diff --git a/.gitignore b/.gitignore index 5ed7e2f..add77e2 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,6 @@ repo/ .gradle/ .sass-cache/ _site/ - +*.fileTracker.data +*file.data +src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/resources/secretKeyGenerated.text \ No newline at end of file diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePlugin.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePlugin.groovy index c87370c..622a18e 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePlugin.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePlugin.groovy @@ -5,22 +5,22 @@ package org.fundacionjala.gradle.plugins.enforce +import org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager.CredentialAdder +import org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager.CredentialUpdater +import org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor.FilesStatus import org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor.Reset +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Deploy +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Undeploy import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Update import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Upload import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.execute.ApexExecutor +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.managepackage.InstallPackageTask +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.managepackage.UninstallPackageTask import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve.Retrieve import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.unittest.RunTestTask import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.gradle.api.Plugin import org.gradle.api.Project -import org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager.CredentialAdder -import org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager.CredentialUpdater -import org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor.FilesStatus -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Deploy -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment.Undeploy -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.managepackage.InstallPackageTask -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.managepackage.UninstallPackageTask /** * This class creates a Force Plugin that represents an extension to Gradle. diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialEncrypter.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialEncrypter.groovy index c8b0000..c3d8015 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialEncrypter.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialEncrypter.groovy @@ -6,8 +6,8 @@ package org.fundacionjala.gradle.plugins.enforce.credentialmanagement import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException -import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.utils.CharsetUtil +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import sun.misc.BASE64Decoder import javax.crypto.Cipher diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManager.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManager.groovy index 44c8470..13cd50f 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManager.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManager.groovy @@ -5,11 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.credentialmanagement -import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException -import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import groovy.json.JsonBuilder import groovy.json.JsonSlurper import groovy.json.internal.LazyMap +import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential /** * Reads and writes credentials in credentials file diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerInput.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerInput.groovy index 1a0a2b9..3a0176a 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerInput.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerInput.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.credentialmanagement -import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException import groovy.json.JsonSlurper import groovy.json.internal.LazyMap +import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.wsc.Credential diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentComparable.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentComparable.groovy new file mode 100644 index 0000000..f567593 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentComparable.groovy @@ -0,0 +1,5 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +public interface ComponentComparable { + ResultTracker compare(T componentTracker) +} \ No newline at end of file diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHash.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHash.groovy new file mode 100644 index 0000000..bf05808 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHash.groovy @@ -0,0 +1,38 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +public class ComponentHash implements ComponentComparable { + String fileName + String hash + + /** + * Sets component name and component hash + * @param fileName is a component name + * @param hash is a hash of a component + */ + public ComponentHash(String fileName, String hash) { + this.fileName = fileName + this.hash = hash + } + + /** + * Initializes component name and component hash + */ + public ComponentHash() { + this.hash = "" + this.fileName = "" + } + + /** + * Compares components status + * @param componentHash is the hash of components + * @return an resultTracker with status + */ + public ResultTracker compare(ComponentHash componentHash) { + ResultTracker resultTracker = new ResultTracker() + resultTracker.state = ComponentStates.NOT_CHANGED + if (componentHash.hash != hash) { + resultTracker.state = ComponentStates.CHANGED + } + return resultTracker + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitor.groovy new file mode 100644 index 0000000..f29d1d7 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitor.groovy @@ -0,0 +1,176 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import com.twmacinta.util.MD5 +import org.fundacionjala.gradle.plugins.enforce.utils.Constants +import org.fundacionjala.gradle.plugins.enforce.utils.Util + +import java.nio.file.Paths + +class ComponentMonitor { + private final String FILE_TRACKING = '.fileTracker.data' + public Map currentFileHashCode + public Map recoveryFileHashCode + public String srcProject + public String fileName + ComponentSerializer componentSerializer + + /** + * Sets a source project directory + * Builds a .fileTracker.data path + * Creates and instance of ComponentSerializer class + * Initializes currentHashCode map and recoveryFileHashCode map + * @param srcProject is project directory + */ + public ComponentMonitor(String srcProject) { + this.srcProject = srcProject + this.fileName = Paths.get(srcProject, FILE_TRACKING).toString() + this.componentSerializer = new ComponentSerializer(fileName) + currentFileHashCode = [:] + recoveryFileHashCode = [:] + } + + /** + * Initializes currentHashCode map and recoveryFileHashCode map + */ + public ComponentMonitor() { + currentFileHashCode = [:] + recoveryFileHashCode = [:] + } + + /** + * Gets a map with components that were changed + * @param arrayFiles are components of the project directory + * @return a map of components with their status changed, added or deleted + */ + public Map getComponentChanged(ArrayList arrayFiles) throws Exception { + recoveryFileHashCode = componentSerializer.read() + currentFileHashCode = getComponentsSignature(arrayFiles) + + return getFilesChanged(recoveryFileHashCode, currentFileHashCode) + } + + /** + * Gets a map with components that were changed + * @param oldFiles is a map of components with their old componentHash + * @param currentFiles is a map of components with their current componentHash + * @return a map of components with their status as changed, added or deleted + */ + public Map getFilesChanged(Map oldFiles, Map currentFiles) { + Map result = [:] + currentFiles.each { String relativePath, ComponentHash currentComponentHash -> + ResultTracker resultTracker + if (!oldFiles.containsKey(relativePath)) { + resultTracker = new ResultTracker(ComponentStates.ADDED) + result.put(relativePath, resultTracker) + } + + if (oldFiles.containsKey(relativePath) && currentFiles.containsKey(relativePath)) { + ComponentHash oldComponentHash = oldFiles.get(relativePath) + resultTracker = oldComponentHash.compare(currentComponentHash) + if(resultTracker.state == ComponentStates.CHANGED) { + result.put(relativePath, resultTracker) + } + } + } + + oldFiles.each { String relativePath, ComponentHash oldComponentHash-> + if(!currentFiles.containsKey(relativePath)) { + ResultTracker resultTracker = new ResultTracker(ComponentStates.DELETED) + result.put(relativePath, resultTracker) + } + } + return result + } + + /** + * Gets components with their componentHash + * @param files is array files + * @return a map of components with their name and its componentHash + */ + public Map getComponentsSignature(ArrayList files) { + Map result = [:] + files.each {File file-> + ComponentHash componentHash + String signature = MD5.asHex(MD5.getHash(file)) + String relativePath = getPathRelative(file) + if (Util.getFileExtension(file) == Constants.OBJECT_EXTENSION) { + ObjectParser objectParser = new ObjectParser() + componentHash = new ObjectHash(relativePath, signature, objectParser.parseByObjectXML(file)) + } else { + componentHash = new ComponentHash(relativePath, signature) + } + result.put(relativePath, componentHash) + } + return result + } + + /** + * Gets a path relative of the file + * @param file is the file that is tracked + * @return is a path relative + */ + public String getPathRelative(File file) { + String nameFile = file.getName() + String folderFile = file.getParentFile().getName() + Paths.get(srcProject, folderFile, nameFile).toString() + } + + public void setSrcProject(String srcProject) { + fileName = Paths.get(srcProject, FILE_TRACKING).toString() + this.srcProject = srcProject + } + + /** + * Verify if file directory exists + * @return boolean result of file(pathFile).exists + */ + public boolean verifyFileMap() { + return new File(fileName).exists() + } + + /** + * Start file monitor + * @param arrayFiles create a file tracking according array files + */ + public void saveCurrentComponents(ArrayList arrayFiles) { + currentFileHashCode = getComponentsSignature(arrayFiles) + componentSerializer.save(currentFileHashCode) + } + + /** + * Update changed value hasCode file + * @throws IOException if no cant write in the disk + */ + public Map getFoldersFiltered(ArrayList folders, Map mapFilesChanged) { + Map foldersFiltered = [:] + + mapFilesChanged.each { fileName, resultTracker -> + + String parentFile = new File(fileName).getParentFile().getName() + folders.each { nameFolder -> + + if (parentFile == nameFolder) { + foldersFiltered.put(fileName, resultTracker) + } + } + } + + return foldersFiltered + } + + /** + * Save only elements changed in the map + * @param mapFileChanged is the files changed + */ + public void saveMapUpdated(Map mapFileChanged) { + mapFileChanged.each { String fileName, ResultTracker resultTracker -> + if (resultTracker.state == ComponentStates.DELETED) { + recoveryFileHashCode.remove(fileName) + } + else { + recoveryFileHashCode.put(fileName, currentFileHashCode.get(fileName)) + } + } + componentSerializer.save(recoveryFileHashCode) + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializer.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializer.groovy new file mode 100644 index 0000000..29a3b0d --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializer.groovy @@ -0,0 +1,98 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import groovy.json.JsonBuilder +import groovy.json.JsonSlurper +import groovy.json.StringEscapeUtils +import groovy.json.internal.LazyMap +import org.fundacionjala.gradle.plugins.enforce.utils.Util + +public class ComponentSerializer implements Serializable{ + public String sourcePath + private final String BACK_SLASH = "\\\\" + private final String DOUBLE_BACK_SLASH = "\\\\\\\\" + private final String FILE_NAME_LABEL = 'fileName' + private final String HASH_LABEL = 'hash' + private final String SUB_COMPONENT_LABEL = 'subComponents' + + public ComponentSerializer(String sourcePath) { + this.sourcePath = sourcePath + } + + /** + * Saves a map into .fileTracker.data file + * @param components is map with filName and its componentHash + */ + void save(Map components) throws IOException { + File fileTracker = new File(sourcePath) + JsonBuilder jsonBuilder = new JsonBuilder() + jsonBuilder(components) + String content = jsonBuilder.toString().replaceAll(DOUBLE_BACK_SLASH, BACK_SLASH) + content = content.replaceAll(BACK_SLASH, DOUBLE_BACK_SLASH) + fileTracker.text = content + } + + /** + * Reads a .fileTracker.data file from source project + * @return a map with .fileTracker.data file values + */ + public Map read() throws IOException { + Map result = [:] + try { + JsonSlurper jsonSlurper = new JsonSlurper() + jsonSlurper.parseText(new File(sourcePath).text) + result = readJsonTrackerFile() + + } catch (Exception exception) { + result = readOldFormat() + } + return result + } + + /** + * Reads a .fileTracker.data file that has old format + * @return a map with values from .fileTracker.data file + */ + private Map readOldFormat() throws IOException { + Map result + ObjectInputStream ois = new ObjectInputStream(new FileInputStream(sourcePath)) + result = convertToComponentHash((Map) ois.readObject()) + ois.close() + return result + } + + /** + * Converts a map from Map to Map + * @param fileTrackerMap is a map that has filename as key and its hash as value + * @return a map with fileName and its componentHash + */ + private Map convertToComponentHash(Map fileTrackerMap) { + Map result = [:] + fileTrackerMap.each {String fileName, String fileHash -> + ComponentHash componentHash = new ComponentHash(fileName, fileHash) + result.put(fileName, componentHash) + } + return result + } + + /** + * Reads .fileTracker.data file that has a json format. + * @return a map with values from .fileTracker.data file + */ + private Map readJsonTrackerFile() { + Map result = [:] + JsonSlurper jsonSlurper = new JsonSlurper() + LazyMap lazyMap = jsonSlurper.parseText(new File(sourcePath).text) + lazyMap.each { String componentName, LazyMap componentMap -> + String fileName = componentMap.get(FILE_NAME_LABEL) + String fileHash = componentMap.get(HASH_LABEL) + ComponentHash componentHash + if (componentMap.containsKey(SUB_COMPONENT_LABEL)) { + componentHash = new ObjectHash(fileName, fileHash, componentMap.get(SUB_COMPONENT_LABEL) as Map) + } else { + componentHash = new ComponentHash(fileName, fileHash) + } + result.put(fileName, componentHash) + } + return result + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentStates.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentStates.groovy new file mode 100644 index 0000000..2c05c95 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentStates.groovy @@ -0,0 +1,18 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +enum ComponentStates { + CHANGED('Changed'), + ADDED('Added'), + DELETED('Deleted'), + NOT_CHANGED('Not changed') + + ComponentStates(String value) { + this.value = value + } + + private final String value + + public String value() { + return value + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/FileMonitorSerializer.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/FileMonitorSerializer.groovy deleted file mode 100644 index c549983..0000000 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/FileMonitorSerializer.groovy +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Fundacion Jala. All rights reserved. - * Licensed under the MIT license. See LICENSE file in the project root for full license information. - */ - -package org.fundacionjala.gradle.plugins.enforce.filemonitor - -/** - * Get and save a map with information of the file path and hashCode - */ -class FileMonitorSerializer extends TemplateFileMonitor { - /** - * Constructor of default if userInfo not put nameFile - */ - public FileMonitorSerializer(String sourceNameFile) { - super(sourceNameFile) - } - - /** - * Constructor of default if userInfo not put nameFile - */ - public FileMonitorSerializer() { - super() - } - - /** - * Save a map in the file binary - * @param myMap - * @throws IOException - */ - @Override - void saveMap(myMap) throws IOException { - ObjectOutputStream oos - oos = new ObjectOutputStream(new FileOutputStream(nameFile)) - oos.writeObject(myMap) - oos.close() - } - - /** - * Read a map of the file binary - * @param source is the path of the file binary - * @return a Map of hashCode the files - * @throws IOException if cannot write in the disk - */ - @Override - Map readMap(source) throws IOException { - Map recoveryMap - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(source)) - recoveryMap = (Map) ois.readObject() - ois.close() - return recoveryMap - } -} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectHash.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectHash.groovy new file mode 100644 index 0000000..8f130f8 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectHash.groovy @@ -0,0 +1,59 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +/** + * This class represents the state of the object component and its sub components + */ +class ObjectHash extends ComponentHash { + + Map subComponents + + public ObjectHash(String fileName, String hash, Map subComponents) { + super(fileName, hash) + this.subComponents = subComponents + } + + /** + * Compares and returns all changes given two ObjectHash + * @param aomponentHash is a ObjectHash to compare all differences + * @return a ObjectResultTracker if there are changes, contains all changes in its sub components + */ + @Override + public ResultTracker compare(ComponentHash componentHash) { + ObjectResultTracker objectResultTracker = new ObjectResultTracker() + objectResultTracker.state = ComponentStates.NOT_CHANGED + if (componentHash.hash != hash) { + objectResultTracker.state = ComponentStates.CHANGED + ObjectHash objectHash = (ObjectHash) componentHash + objectResultTracker.subComponentsResult = getChangedFields(objectHash) + } + return objectResultTracker + } + + /** + * Returns a map that contains all states of the changes, if the sub component was modified, deleted or added + * @param objectHash is a ObjectHash to find all differences + * @return a Map that contains as key the custom field type/fullName and value + * the hash code of the custom field's content + */ + private Map getChangedFields(ObjectHash objectHash) { + Map result = [:] + objectHash.subComponents.each { String fieldAPIName, String fieldHash -> + if (!this.subComponents.containsKey(fieldAPIName)) { + result.put(fieldAPIName, ComponentStates.ADDED) + } + + if (this.subComponents.containsKey(fieldAPIName) && + !this.subComponents.get(fieldAPIName).toString().equals(fieldHash)) { + result.put(fieldAPIName, ComponentStates.CHANGED) + } + } + + this.subComponents.each { String fieldAPIName, String fieldHash -> + if(!objectHash.subComponents.containsKey(fieldAPIName)) { + result.put(fieldAPIName, ComponentStates.DELETED) + } + } + + return result + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParser.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParser.groovy new file mode 100644 index 0000000..da38bbf --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParser.groovy @@ -0,0 +1,51 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import com.twmacinta.util.MD5 +import groovy.util.slurpersupport.GPathResult + +/** + * This class parses the sub components from object component XML file to a Map + */ +class ObjectParser { + + ArrayList customFields = ['fields', 'fieldSets', 'compactLayouts', 'businessProcesses', 'listViews', + 'recordTypes', 'sharingReasons', 'validationRules', 'webLinks'] + //DOESN'T EXIST fullName + //actionOverrides + //searchLayouts + //sharingRecalculations + + //INVALID + //HistoryRetentionPolicy + + + public ObjectParser() { + + } + + /** + * parses the custom fields from object component in a xml file to a Map as + * key is composed by custom field type / custom field fullName + * value is composed by custom field's content in hash code. + * @param file that contains a object component xml. + * @return a Map with all sub components + */ + public Map parseByObjectXML(File file) { + Map result = [:] + XmlSlurper xmlSlurper = new XmlSlurper() + GPathResult customObject = xmlSlurper.parseText(file.text) + customFields.each {String customField -> + Object fieldValue = customObject.getProperty(customField) + if (!fieldValue.toString().isEmpty()) { + fieldValue.each { subComponent -> + MD5 md5 = new MD5() + md5.Update(subComponent.toString()) + String fieldName = "${customField}/${subComponent.fullName}" + String signature = md5.asHex() + result.put(fieldName, signature) + } + } + } + return result + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTracker.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTracker.groovy new file mode 100644 index 0000000..7489391 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTracker.groovy @@ -0,0 +1,24 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +/** + * This class contains the state when you compare two objectHash objects + * if the state is CHANGED then the subComponentsResult map contains + * the state for all sub Components. + */ +class ObjectResultTracker extends ResultTracker { + Map subComponentsResult + + public ObjectResultTracker(ComponentStates state) { + super(state) + subComponentsResult = [:] + } + + @Override + public String toString() { + String result = ''; + subComponentsResult.each { field, fieldState -> + result += field + ' -> '+ fieldState.value() + '\n\t' + } + return state.value() + '\n\t' + result + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTracker.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTracker.groovy new file mode 100644 index 0000000..28fee15 --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTracker.groovy @@ -0,0 +1,22 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +/** + * This class contains the state when you compare two componentHash objects + */ +class ResultTracker { + + public ComponentStates state + + public ResultTracker() { + + } + + public ResultTracker(ComponentStates state) { + this.state = state + } + + @Override + public String toString() { + return state.value() + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/TemplateFileMonitor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/TemplateFileMonitor.groovy deleted file mode 100644 index e13edfc..0000000 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/TemplateFileMonitor.groovy +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) Fundacion Jala. All rights reserved. - * Licensed under the MIT license. See LICENSE file in the project root for full license information. - */ - -package org.fundacionjala.gradle.plugins.enforce.filemonitor - -import com.twmacinta.util.MD5 - -import java.nio.file.Paths - -/** - * This class is a template class to monitor the files changed in a directory - */ -public abstract class TemplateFileMonitor { - - private final String NEW_FILE = "New file" - private final String FILE_TRACKING = '.fileTracker.data' - public static final String DELETE_FILE = "Deleted file" - public static final String CHANGED_FILE = "Changed file" - - String nameFile - Map currentFileHashCode - Map recoveryFileHashCode - protected Map fileSignatures - Map mapFilesChanged - String srcProject - - - public void setSrcProject(String srcProject) { - nameFile = Paths.get(srcProject, FILE_TRACKING).toString() - this.srcProject = srcProject - } - - /** - * Constructor of default if userInfo not put nameFile - */ - public TemplateFileMonitor(String source) { - nameFile = source - srcProject = Paths.get(source).getParent().toString() - fileSignatures = new HashMap() - mapFilesChanged = new HashMap() - } - - /** - * Constructor of default - */ - public TemplateFileMonitor() { - fileSignatures = new HashMap() - mapFilesChanged = new HashMap() - } - - /** - * Get a state of file - * @return string of file example of files is changed or delete - */ - public static String getStateDelete() { - return DELETE_FILE - } - - /** - * Verify if file directory exists - * @return boolean result of file(pathFile).exists - */ - public boolean verifyFileMap() { - new File(nameFile).exists() - } - - /** - * Loads a signature for each file in the directory and its subdirectories - * @param arrayFiles is a elements Files for calculate codeHas - * @return a Map with file path as key and signature as value of a file - */ - public Map loadSignatureForFilesInDirectory(ArrayList arrayFiles) throws Exception { - arrayFiles.each { - File file -> - String signature = MD5.asHex(MD5.getHash(file)) - String relativePath = getPathRelative(file) - fileSignatures.put(relativePath, signature) - } - return fileSignatures - } - - /** - * Gets a path relative of the file - * @param file is the file that is tracked - * @return is a path relative - */ - public String getPathRelative(File file) { - String nameFile = file.getName() - String folderFile = file.getParentFile().getName() - Paths.get(srcProject, folderFile, nameFile).toString() - } - - /** - * Compared mapFilePros with currentMapFile - * CurrentMapFile iterates and search the items on the map mapFilePros - * If not found is considered as a new file - * @param mapFilePros is a map of file binary - * @param currentMapFile is a map that was created with method loadSignatureForFilesInDirectory - */ - public void findNewFiles(mapFilePros, currentMapFile) { - for (Object entry : currentMapFile.entrySet()) { - Map.Entry thisEntry = (Map.Entry) entry - if (!mapFilePros.get(thisEntry.getKey())) { - mapFilesChanged.put(thisEntry.getKey().toString(), NEW_FILE) - } - } - } - - /** - * Compared mapFilePros with currentMapFile - * CurrentMapFile iterates and search the items on the map - * If found mapFilePros comparing the hashCode if the other is considered modified file - * @param mapFilePros is a map of file binary - * @param currentMapFile is a map that was created with method loadSignatureForFilesInDirectory - */ - public void findChangedFiles(mapFilePros, currentMapFile) { - Object currentElement - - for (Object entry : currentMapFile.entrySet()) { - Map.Entry thisEntry = (Map.Entry) entry - currentElement = mapFilePros.get(thisEntry.getKey()) - if (currentElement && !currentElement.equals(thisEntry.getValue())) { - mapFilesChanged.put(thisEntry.getKey().toString(), CHANGED_FILE) - } - } - } - - /** - * Compared currentMapFile with mapFilePros - * MapFilePros iterates and search the items on the map currentMapFile - * If not found is considered as a delete file - * @param mapFilePros is a map of file binary - * @param currentMapFile is a map that was created with method loadSignatureForFilesInDirectory - */ - public void findDeleteFiles(mapFilePros, currentMapFile) { - for (Object entry : mapFilePros.entrySet()) { - Map.Entry thisEntry = (Map.Entry) entry - if (!currentMapFile.get(thisEntry.getKey())) { - mapFilesChanged.put(thisEntry.getKey().toString(), DELETE_FILE) - } - } - } - - /** - * Get a two maps using methods readMap and loadSignatureForFilesInDirectory then - * These two maps call a method compareMaps - * @param arrayFiles is the array files monitor - * @return a map content a elements different between recoveryFileHashCode and currentFileHashCode - */ - public final Map getFileChangedExclude(ArrayList arrayFiles) throws Exception { - recoveryFileHashCode = readMap(nameFile) - currentFileHashCode = loadSignatureForFilesInDirectory(arrayFiles) - findNewFiles(recoveryFileHashCode, currentFileHashCode) - findChangedFiles(recoveryFileHashCode, currentFileHashCode) - findDeleteFiles(recoveryFileHashCode, currentFileHashCode) - - return mapFilesChanged - } - - /** - * Start file monitor - * @param arrayFiles create a file tracking according array files - */ - public void mapRefresh(ArrayList arrayFiles) { - currentFileHashCode = loadSignatureForFilesInDirectory(arrayFiles) - saveMap(currentFileHashCode) - } - - /** - * Update changed value hasCode file - * @throws IOException if no cant write in the disk - */ - public Map getFoldersFiltered(ArrayList folders, Map mapFilesChanged) { - Map auxiliaryMap = [:] - - mapFilesChanged.each { nameFile, state -> - - String parentFile = new File(nameFile).getParentFile().getName() - folders.each { nameFolder -> - - if (parentFile == nameFolder) { - auxiliaryMap.put(nameFile, state) - } - } - } - - return auxiliaryMap - } - - /** - * Save only elements changed in the map - * @param mapFileChanged is the files changed - */ - public void saveMapUpdated(Map mapFileChanged) { - mapFileChanged.each { fileName, status -> - if (status == DELETE_FILE) { - recoveryFileHashCode.remove(fileName) - } else { - recoveryFileHashCode.put(fileName, currentFileHashCode.get(fileName)) - } - } - saveMap(recoveryFileHashCode) - } - - /** - * Save information about codeHas in the map - * @param myMap it is the map that will be saved - */ - public abstract void saveMap(myMap) throws IOException - - /** - * Get information about codeHas of the files - * @param source is the path of tracking file - * @return a map with information names files and codeHash - */ - public abstract Map readMap(source) throws IOException, ClassNotFoundException -} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/FactoryInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/FactoryInterceptor.groovy index 12040b0..79db433 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/FactoryInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/FactoryInterceptor.groovy @@ -6,14 +6,8 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor import com.jalasoft.sfdc.devtool.interceptor.interceptors.* -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.ObjectInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.WorkflowInterceptor +import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.* import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.ClassInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.ComponentInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.PageInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.TabInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors.TriggerInterceptor /** * Creates a new salesforce component interceptor diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/InterceptorManager.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/InterceptorManager.groovy index 0952cdb..e7045b7 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/InterceptorManager.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/InterceptorManager.groovy @@ -8,15 +8,19 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import groovy.util.logging.Slf4j /** * This class manages all components created from source path */ +@Slf4j class InterceptorManager { Map interceptors List truncatedDirectories = ['classes', 'objects', 'triggers', 'pages', 'components', 'workflows', 'tabs'] List interceptorsToExecute + + /** * Creates a new interceptor management from source path * @param sourcePath the source directory path @@ -102,7 +106,8 @@ class InterceptorManager { * Executes the truncate method of all the component interceptors */ public void executeTruncate() { - this.interceptors.values().each { interceptor -> + this.interceptors.each {String component, MetadataInterceptor interceptor -> + log.debug "----------------------" + component + "----------------------" interceptor.executeInterceptors() } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/MetadataInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/MetadataInterceptor.groovy index bd43f61..b56867b 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/MetadataInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/MetadataInterceptor.groovy @@ -4,10 +4,11 @@ */ package org.fundacionjala.gradle.plugins.enforce.interceptor - +import groovy.util.logging.Slf4j /** * This class provides a skeletal implementation of the interceptor for all metadata types supported */ +@Slf4j abstract class MetadataInterceptor { List interceptorsToExecute List files @@ -59,6 +60,7 @@ abstract class MetadataInterceptor { if (interceptorsToExecute.contains(interceptorName) || (!interceptorsToExecute.contains(interceptorName) && interceptorName.isNumber() && interceptorName.toInteger() == interceptor.hashCode())) { + log.debug "$interceptorName --> $file.name" executeInterceptor(interceptor, file) } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/Component.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/Component.groovy index f062e66..fb78178 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/Component.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/Component.groovy @@ -5,16 +5,42 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.commands +import java.util.regex.Matcher + /** * Implements the truncated algorithm to truncate the component content */ class Component { - public static final String EMPTY_COMPONENT = '' + private final String ATTRIBUTE_REGEX = // + private final String ATTRIBUTE_BY_DEFAULT = "" + private final String NAME_ATTRIBUTE = "name" + private final String COMPONENT_BY_DEFAULT = "%s\n" + private final int INDEX_ATTRIBUTE = 0 /** * A closure to truncate the component content */ Closure execute = { file -> - file.text = EMPTY_COMPONENT + if (!file) { + return + } + String component = file.text + String newAttributes = "" + String attribute = "" + String attributeName = "" + int indexName + int indexIniName + int indexEndName + Matcher attributeMatcher = component =~ ATTRIBUTE_REGEX + attributeMatcher.each { attributeIt -> + attribute = attributeIt[INDEX_ATTRIBUTE] + indexName = attribute.indexOf(NAME_ATTRIBUTE) + indexIniName = attribute.indexOf("\"", indexName) + indexEndName = attribute.indexOf("\"", indexIniName + 1) + attributeName = attribute.substring(indexIniName, indexEndName + 1) + newAttributes += "\n${String.format(ATTRIBUTE_BY_DEFAULT, attributeName)}" + } + + file.text = String.format(COMPONENT_BY_DEFAULT, newAttributes) } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectField.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectField.groovy index 585cc19..cd0c206 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectField.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectField.groovy @@ -28,7 +28,8 @@ class ObjectField { if (!file) { return } - Matcher fieldMatcher = file.text =~ FIELDS_REGEX + String objectField = file.text + Matcher fieldMatcher = objectField =~ FIELDS_REGEX fieldMatcher.each { fieldIt -> String field = fieldIt[FIELD_INDEX] if (field) { @@ -41,8 +42,9 @@ class ObjectField { helpTextMatcher.each { helpTextIt -> newField = newField.replace(helpTextIt[HELP_TEXT_INDEX].toString(), HELP_TEXT_TAG) } - file.text = file.text.replace(field, newField) + objectField = objectField.replace(field, newField) } } + file.text = objectField } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectFormula.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectFormula.groovy index 69b6324..d0f33d7 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectFormula.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectFormula.groovy @@ -27,7 +27,9 @@ class ObjectFormula { */ Closure execute = { file -> if (!file) return - Matcher fieldMatcher = file.text =~ FIELDS_REGEX + + String objectFormula = file.text + Matcher fieldMatcher = objectFormula =~ FIELDS_REGEX fieldMatcher.each { fieldIt-> String field = fieldIt[CONTENT_MATCHED_INDEX] String formula @@ -47,34 +49,35 @@ class ObjectFormula { switch (type) { case FormulaType.PERCENT.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, NUMBER_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.NUMBER.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, NUMBER_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.TIME.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, DATE_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.DATE.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, DATE_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.CURRENCY.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, NUMBER_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.CHECKBOK.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, CHECKBOK_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break case FormulaType.TEXT.value(): replacement = field.replace(formula, String.format(TAG_FORMULA, "\"\"")) - file.text = file.text.replace(target, replacement) + objectFormula = objectFormula.replace(target, replacement) break } } } + file.text = objectFormula } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectWebLink.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectWebLink.groovy index a3f3dfb..8e8f3a5 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectWebLink.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ObjectWebLink.groovy @@ -27,7 +27,8 @@ class ObjectWebLink { */ Closure execute = { file -> if (!file) return - Matcher webLinkMatcher = file.text =~ WEB_LINK_REGEX + String objectWebLink = file.text + Matcher webLinkMatcher = objectWebLink =~ WEB_LINK_REGEX webLinkMatcher.each { webLinkIt-> String webLink = webLinkIt[CONTENT_MATCHED_INDEX] String url @@ -47,15 +48,16 @@ class ObjectWebLink { switch (type) { case LinkType.JAVASCRIPT.value(): replacement = webLink.replace(url, String.format(TAG_URL, URL_JS_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectWebLink = objectWebLink.replace(target, replacement) break case LinkType.URL.value(): replacement = webLink.replace(url, String.format(TAG_URL, URL_BY_DEFAULT)) - file.text = file.text.replace(target, replacement) + objectWebLink = objectWebLink.replace(target, replacement) break } } } + file.text = objectWebLink } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ClassInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ClassInterceptor.groovy index c8a1b51..f8d59db 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ClassInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ClassInterceptor.groovy @@ -5,16 +5,17 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ClassAnnotation import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Class +import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ClassAnnotation import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the classes to truncate */ +@Slf4j class ClassInterceptor extends MetadataInterceptor { private final String DEPRECATE_ANNOTATION = '@deprecated' diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptor.groovy index 2acb573..ca76e9b 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptor.groovy @@ -5,15 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor +import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Component import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the components to truncate */ +@Slf4j class ComponentInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ObjectInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ObjectInterceptor.groovy index 46bedb2..731bef7 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ObjectInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ObjectInterceptor.groovy @@ -5,19 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ObjectField -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ObjectFieldSet -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ObjectFormula -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ObjectActionOverride -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.ObjectWebLink +import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.* import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the objects to truncate */ +@Slf4j class ObjectInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/PageInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/PageInterceptor.groovy index 065d9af..42839d6 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/PageInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/PageInterceptor.groovy @@ -5,15 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor +import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Page import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the pages to truncate */ +@Slf4j class PageInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TabInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TabInterceptor.groovy index ad14b65..6deda9a 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TabInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TabInterceptor.groovy @@ -5,15 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors -import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Tab -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor +import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Tab import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the tabs to truncate */ +@Slf4j class TabInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TriggerInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TriggerInterceptor.groovy index fd40c78..28c7367 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TriggerInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/TriggerInterceptor.groovy @@ -5,15 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor +import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Trigger import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the triggers to truncate */ +@Slf4j class TriggerInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/WorkflowInterceptor.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/WorkflowInterceptor.groovy index 591482d..e2068dd 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/WorkflowInterceptor.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/WorkflowInterceptor.groovy @@ -5,15 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.interceptor.interceptors -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.MetadataInterceptor import org.fundacionjala.gradle.plugins.enforce.interceptor.commands.Workflow import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor - +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import groovy.util.logging.Slf4j /** * Implements methods to manage interceptors and load the workflows to truncate */ +@Slf4j class WorkflowInterceptor extends MetadataInterceptor { /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/DeployMetadata.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/DeployMetadata.groovy index 092075d..3f7a673 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/DeployMetadata.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/DeployMetadata.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.metadata +import com.sforce.soap.metadata.DeployResult import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.soap.MetadataAPI -import com.sforce.soap.metadata.DeployResult /** * Deploys an org using metadata API diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/ForceTask.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/ForceTask.groovy index 06235a0..5ad6b6e 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/ForceTask.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/ForceTask.groovy @@ -5,16 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.tasks -import org.gradle.api.DefaultTask -import org.gradle.api.GradleException -import org.gradle.api.logging.StandardOutputListener -import org.gradle.api.tasks.TaskAction -import org.gradle.logging.internal.LoggingOutputInternal import org.fundacionjala.gradle.plugins.enforce.exceptions.CredentialException import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.DeployException import org.fundacionjala.gradle.plugins.enforce.tasks.exception.GradleDeployException import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.logging.StandardOutputListener +import org.gradle.api.tasks.TaskAction +import org.gradle.logging.internal.LoggingOutputInternal import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FileMonitorTask.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FileMonitorTask.groovy index 9389dfd..4be9452 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FileMonitorTask.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FileMonitorTask.groovy @@ -5,20 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor import org.fundacionjala.gradle.plugins.enforce.tasks.ForceTask -import java.nio.file.Paths - /** * Base of the file monitor tasks */ abstract class FileMonitorTask extends ForceTask { - - private final String FILE_TRACKING = '/.fileTracker.data' - FileMonitorSerializer fileMonitorSerializer + ComponentMonitor componentMonitor public static final String GROUP_FILE_MONITOR_TASK = "File Monitor" - ArrayList fileArray + ArrayList sourceComponents /** * Sets description and group task @@ -34,9 +30,8 @@ abstract class FileMonitorTask extends ForceTask { */ @Override void executeTask() { - def pathFileTracker = Paths.get(projectPath, FILE_TRACKING).toString() - fileMonitorSerializer = new FileMonitorSerializer(pathFileTracker) - fileArray = fileManager.getValidElements(projectPath, excludeFilesToMonitor) + componentMonitor = new ComponentMonitor(projectPath) + sourceComponents = fileManager.getValidElements(projectPath, excludeFilesToMonitor) runTask() } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FilesStatus.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FilesStatus.groovy index 974a531..9e5f029 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FilesStatus.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/FilesStatus.groovy @@ -11,7 +11,6 @@ import java.nio.file.Paths * Create a file tracker and display files status */ class FilesStatus extends FileMonitorTask { - private static final String DESCRIPTION_STATUS = "You can display elements that were changed" Map filesChangedMap @@ -27,12 +26,11 @@ class FilesStatus extends FileMonitorTask { */ @Override void runTask() { - if (fileMonitorSerializer.verifyFileMap()) { - filesChangedMap = fileMonitorSerializer.getFileChangedExclude(fileArray) + if (componentMonitor.verifyFileMap()) { + filesChangedMap = componentMonitor.getComponentChanged(sourceComponents) displayFileChanged() } else { - Map initMapSave = fileMonitorSerializer.loadSignatureForFilesInDirectory(fileArray) - fileMonitorSerializer.saveMap(initMapSave) + componentMonitor.saveCurrentComponents(sourceComponents) } } @@ -46,8 +44,8 @@ class FilesStatus extends FileMonitorTask { println "*********************************************" println " Status Files Changed " println "*********************************************" - filesChangedMap.each { key, value -> - println "${Paths.get(key).getFileName()}${" - "}${value}" + filesChangedMap.each { componentPath, resultTracker -> + println "${Paths.get(componentPath).getFileName()}${" - "}${resultTracker.toString()}" } println "*********************************************" } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/Reset.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/Reset.groovy index e61f2c5..bece37b 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/Reset.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/Reset.groovy @@ -5,12 +5,14 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor +import java.nio.file.Paths + /** * Resets file monitor tracker */ class Reset extends FileMonitorTask{ - private static final String DESCRIPTION_REFRESH = "Reset the file monitor" + private final String FILE_TRACKER_NAME = '.fileTracker.data' /** * Sets description and group task @@ -23,6 +25,15 @@ class Reset extends FileMonitorTask{ @Override void runTask() { - fileMonitorSerializer.mapRefresh(fileArray) + removeFileTracker() + componentMonitor.saveCurrentComponents(sourceComponents) + } + + /** + * Removes .fileTracker.data file form project directory + */ + void removeFileTracker() { + String fileTrackerPath = Paths.get(projectPath, FILE_TRACKER_NAME) + new File(fileTrackerPath).delete() } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/SalesforceTask.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/SalesforceTask.groovy index 042919e..256b945 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/SalesforceTask.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/SalesforceTask.groovy @@ -12,10 +12,10 @@ import org.fundacionjala.gradle.plugins.enforce.tasks.ForceTask import org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager.CredentialParameterValidator import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor import org.fundacionjala.gradle.plugins.enforce.utils.Constants -import org.fundacionjala.gradle.plugins.enforce.wsc.Credential -import org.gradle.api.GradleException import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.gradle.api.GradleException import java.nio.file.Paths @@ -91,6 +91,7 @@ abstract class SalesforceTask extends ForceTask { println("\tLogin type: ${credential.loginFormat}") println("___________________________________________ ") println AnsiColor.ANSI_RESET.value() + logger.debug('after show credentials') } /** @@ -150,7 +151,9 @@ abstract class SalesforceTask extends ForceTask { poll = project.enforce.poll waitTime = project.enforce.waitTime loadCredential() + logger.debug('Finished load credential') fileManager.createDirectory(buildFolderPath) + logger.debug('Created directory at: ' + buildFolderPath) runTask() } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deploy.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deploy.groovy index 94035d9..2a3ec74 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deploy.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deploy.groovy @@ -5,11 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor +import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util -import org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor import java.nio.file.Files import java.nio.file.Paths @@ -21,7 +21,6 @@ import java.nio.file.StandardCopyOption class Deploy extends Deployment { private static final String DESCRIPTION_OF_TASK = 'This task deploys all the project' private final String FOLDERS_DEPLOY = "folders" - private final String FILE_TRACKING = '/.fileTracker.data' private final String FOLDER_DEPLOY = 'deploy' private final String TURN_OFF_TRUNCATE = 'turnOffTruncate' private final String TRUNCATE_DEPRECATE = 'deprecate' @@ -57,6 +56,7 @@ class Deploy extends Deployment { void runTask() { folderDeploy = Paths.get(buildFolderPath, FOLDER_DEPLOY).toString() packagePathDeploy = Paths.get(folderDeploy, PACKAGE_NAME).toString() + logger.debug('Creating folder Deploy at: ' + folderDeploy) createDeploymentDirectory(folderDeploy) if (Util.isValidProperty(project, FOLDERS_DEPLOY)) { deployByFolder() @@ -101,11 +101,14 @@ class Deploy extends Deployment { if (codeTruncateOn) { ArrayList filesToTruncate = excludeFiles(fileManager.getFilesByFolders(projectPath, FOLDERS_TO_TRUNCATE)) Files.copy(Paths.get(projectPath, PACKAGE_NAME), Paths.get(packagePathDeploy), StandardCopyOption.REPLACE_EXISTING) + logger.debug('Copying files to deploy') fileManager.copy(filesToTruncate, folderDeploy) + logger.debug('Generating package') writePackage(packagePathDeploy, filesToTruncate) truncateComponents() componentDeploy.startMessage = DEPLOYING_TRUNCATED_CODE componentDeploy.successMessage = DEPLOYING_TRUNCATED_CODE_SUCCESSFULLY + logger.debug("Deploying to truncate components from: $folderDeploy") executeDeploy(folderDeploy) createDeploymentDirectory(folderDeploy) } @@ -140,8 +143,10 @@ class Deploy extends Deployment { if (deprecateTruncateOn) { interceptorsToExecute = [Interceptor.REMOVE_DEPRECATE.id] interceptorsToExecute += interceptors + logger.debug("Truncating components from: $folderDeploy") truncateComponents(folderDeploy) } + logger.debug("Deploying all components from: $folderDeploy") executeDeploy(folderDeploy) updateFileTracker() } @@ -171,10 +176,11 @@ class Deploy extends Deployment { * Updates a file tracker */ def updateFileTracker() { - String pathFileTracker = Paths.get(projectPath, FILE_TRACKING) - FileMonitorSerializer fileMonitorSerializer = new FileMonitorSerializer(pathFileTracker) - Map initMapSave = fileMonitorSerializer.loadSignatureForFilesInDirectory(fileManager.getValidElements(projectPath, excludeFilesToMonitor)) - fileMonitorSerializer.saveMap(initMapSave) + ComponentMonitor componentMonitor = new ComponentMonitor(projectPath) + logger.debug('Getting components signatures') + Map initMapSave = componentMonitor.getComponentsSignature(fileManager.getValidElements(projectPath, excludeFilesToMonitor)) + logger.debug('Saving initial file tracker') + componentMonitor.componentSerializer.save(initMapSave) } /** @@ -187,6 +193,7 @@ class Deploy extends Deployment { Interceptor.TRUNCATE_PAGES.id, Interceptor.TRUNCATE_TRIGGERS.id, Interceptor.TRUNCATE_WORKFLOWS.id, Interceptor.TRUNCATE_COMPONENTS.id] interceptorsToExecute += interceptors + logger.debug("Truncating components at: $srcPath") truncateComponents(srcPath) } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deployment.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deployment.groovy index 64586a2..5286e02 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deployment.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Deployment.groovy @@ -5,14 +5,14 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment +import org.fundacionjala.gradle.plugins.enforce.interceptor.InterceptorManager import org.fundacionjala.gradle.plugins.enforce.metadata.DeployMetadata +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.SalesforceTask import org.fundacionjala.gradle.plugins.enforce.utils.Constants +import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import org.gradle.api.file.FileTree import org.gradle.api.tasks.bundling.Zip -import org.fundacionjala.gradle.plugins.enforce.interceptor.InterceptorManager -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.SalesforceTask -import org.fundacionjala.gradle.plugins.enforce.utils.Util import java.nio.file.Paths @@ -54,8 +54,10 @@ abstract class Deployment extends SalesforceTask { */ def executeDeploy(String sourcePath) { String fileName = new File(sourcePath).getName() + logger.debug("Crating zip file at: $buildFolderPath/$fileName") String pathZipToDeploy = createZip(sourcePath, buildFolderPath, fileName) componentDeploy.setPath(pathZipToDeploy) + logger.debug('Deploying components') componentDeploy.deploy(poll, waitTime, credential) } @@ -64,10 +66,14 @@ abstract class Deployment extends SalesforceTask { * @param dirToTruncate the directory path to truncate */ def truncateComponents(String dirToTruncate) { + logger.debug('Loading files to truncate') componentManager.loadFiles(dirToTruncate) + logger.debug('Adding interceptors') componentManager.addInterceptors(interceptorsToExecute) componentManager.addInterceptorsRegistered(project.property(Constants.FORCE_EXTENSION).interceptors as Map) + logger.debug('Validating interceptors') componentManager.validateInterceptors() + logger.debug('Executing truncate process') componentManager.executeTruncate() } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Undeploy.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Undeploy.groovy index 5c202a9..dadc7ab 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Undeploy.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Undeploy.groovy @@ -13,9 +13,9 @@ import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponent import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import org.fundacionjala.gradle.plugins.enforce.wsc.rest.QueryBuilder +import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI import org.gradle.api.GradleException import org.gradle.api.file.FileTree -import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI import java.nio.file.Files import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Update.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Update.groovy index 95a8bcc..569c255 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Update.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Update.groovy @@ -5,12 +5,10 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment -import org.fundacionjala.gradle.plugins.enforce.wsc.rest.QueryBuilder -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer -import org.fundacionjala.gradle.plugins.enforce.undeploy.SmartFilesValidator +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentStates import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util -import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageGenerator import java.nio.file.Paths @@ -23,17 +21,12 @@ class Update extends Deployment { private final String DIR_UPDATE_FOLDER = "update" private final String FILE_NAME_DESTRUCTIVE = "destructiveChanges.xml" private final String NOT_FILES_CHANGED = "There are not files changed" - private final String NOT_FILES_CHANGED_IN_FOLDER = "There are not files changed in folders selected" - private SmartFilesValidator smartFilesValidator - private QueryBuilder queryBuilder - public ToolingAPI toolingAPI public String pathUpdate - Map filesChanged - FileMonitorSerializer objSerializer ArrayList filesToCopy ArrayList filesToUpdate String folders ArrayList filesExcludes + PackageGenerator packageGenerator /** * Sets description and group task @@ -42,11 +35,10 @@ class Update extends Deployment { */ Update() { super(DESCRIPTION_OF_TASK, Constants.DEPLOYMENT) - filesChanged = [:] - objSerializer = new FileMonitorSerializer() filesToCopy = new ArrayList() filesToUpdate = new ArrayList() filesExcludes = new ArrayList() + packageGenerator = new PackageGenerator() interceptorsToExecute = [org.fundacionjala.gradle.plugins.enforce.interceptor.Interceptor.REMOVE_DEPRECATE.id] } @@ -61,7 +53,7 @@ class Update extends Deployment { verifyParameter() excludeFilesFromFilesChanged() showFilesChanged() - if (filesChanged.isEmpty()) { + if (packageGenerator.fileTrackerMap.isEmpty()) { logger.quiet(NOT_FILES_CHANGED) return } @@ -71,10 +63,10 @@ class Update extends Deployment { showFilesExcludes() truncate(pathUpdate) executeDeploy(pathUpdate) - objSerializer.saveMapUpdated(filesChanged) + packageGenerator.saveFileTrackerMap() } - def truncate(String pathToTruncate){ + def truncate(String pathToTruncate) { interceptorsToExecute += interceptors truncateComponents(pathToTruncate) } @@ -83,55 +75,27 @@ class Update extends Deployment { * Creates packages to all files which has been changed */ def createPackage() { - filesChanged.each { nameFile, state -> - if (state != FileMonitorSerializer.DELETE_FILE) { + packageGenerator.fileTrackerMap.each { nameFile, resultTracker -> + if (resultTracker.state != ComponentStates.DELETED) { filesToCopy.add(new File(nameFile)) } } - writePackage(Paths.get(pathUpdate, PACKAGE_NAME).toString(), filesToCopy) + packageGenerator.buildPackage(Paths.get(pathUpdate, PACKAGE_NAME).toString()) } /** * Creates package to all files which has been deleted */ def createDestructive() { - def arrayDeletedElements = new ArrayList() - filesChanged.each { nameFile, state -> - if (state == FileMonitorSerializer.DELETE_FILE) { - arrayDeletedElements.add(new File(nameFile)) - } - } - smartFilesValidator = new SmartFilesValidator(getJsonQueries(arrayDeletedElements)) - arrayDeletedElements = smartFilesValidator.filterFilesAccordingOrganization(arrayDeletedElements) - writePackage(Paths.get(pathUpdate, FILE_NAME_DESTRUCTIVE).toString(), arrayDeletedElements) - } - - /** - * Gets queries according files given - * @returns queries on String format - */ - def getJsonQueries(ArrayList files) { - toolingAPI = new ToolingAPI(credential) - queryBuilder = new QueryBuilder() - ArrayList jsonQueries = [] - def queries = queryBuilder.createQueriesFromListOfFiles(files) - queries.each {query -> - jsonQueries.push(toolingAPI.httpAPIClient.executeQuery(query as String)) - } - return jsonQueries + packageGenerator.buildDestructive(Paths.get(pathUpdate, FILE_NAME_DESTRUCTIVE).toString()) } /** * Loads all files which has been changed on filesChanged */ def loadFilesChanged() { - objSerializer.setSrcProject(projectPath) - ArrayList fileArray = fileManager.getValidElements(projectPath, excludeFilesToMonitor) - if (!objSerializer.verifyFileMap()) { - objSerializer.mapRefresh(fileArray) - return - } - filesChanged = objSerializer.getFileChangedExclude(fileArray) + ArrayList validatedFiles = fileManager.getValidElements(projectPath, excludeFilesToMonitor) + packageGenerator.init(projectPath, validatedFiles, credential) } /** @@ -143,18 +107,13 @@ class Update extends Deployment { } if (folders) { - ArrayList invalidFolders = new ArrayList() ArrayList foldersName = folders.split(Constants.COMMA) + ArrayList invalidFolders = Util.getInvalidFolders(foldersName) validateFolders(foldersName) - invalidFolders = Util.getInvalidFolders(foldersName) if (!invalidFolders.empty) { throw new Exception("${Constants.INVALID_FOLDER}: ${invalidFolders}") } - def auxiliaryMap = objSerializer.getFoldersFiltered(foldersName, filesChanged) - if (auxiliaryMap == null) { - throw new Exception(NOT_FILES_CHANGED_IN_FOLDER) - } - filesChanged = auxiliaryMap + packageGenerator.updateFileTrackerMap(foldersName) } } @@ -176,12 +135,12 @@ class Update extends Deployment { * Prints files changed */ def showFilesChanged() { - if (filesChanged.size() > 0) { + if (packageGenerator.fileTrackerMap.size() > 0) { logger.quiet("*********************************************") logger.quiet(" Status Files Changed ") logger.quiet("*********************************************") - filesChanged.each { nameFile, status -> - logger.quiet("${Paths.get(nameFile).getFileName().toString()}${" - "}${status}") + packageGenerator.fileTrackerMap.each { nameFile, status -> + logger.quiet("${Paths.get(nameFile).getFileName().toString()}${" - "}${status.toString()}") } logger.quiet("*********************************************") } @@ -211,22 +170,8 @@ class Update extends Deployment { /** * ExcludeFiles from filesExcludes map */ - private void excludeFilesFromFilesChanged () { - def filesUpdated = new ArrayList() - def filesChangedTemp = filesChanged.clone() - - filesChangedTemp.each {key, value -> - filesUpdated.push(new File(key.toString())) - } - - ArrayList filesFiltered = excludeFiles(filesUpdated) - - filesChangedTemp.each {key, value -> - def fileChanged = new File(key.toString()) - if (!filesFiltered.contains(fileChanged)) { - filesChanged.remove(key.toString()) - filesExcludes.push(fileChanged) - } - } + private void excludeFilesFromFilesChanged() { + ArrayList filesFiltered = excludeFiles(packageGenerator.getFiles()) + filesExcludes = packageGenerator.excludeFiles(filesFiltered) } -} +} \ No newline at end of file diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Upload.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Upload.groovy index a90d25b..cbb0ffc 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Upload.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/Upload.groovy @@ -5,10 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment -import org.gradle.api.file.FileTree -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ResultTracker import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageGenerator +import org.gradle.api.file.FileTree import java.nio.file.Paths @@ -26,9 +27,8 @@ class Upload extends Deployment { public ArrayList specificFilesToUpload public ArrayList filesToUpload - public FileMonitorSerializer objSerializer + public PackageGenerator packageGenerator public String pathUpload - public Map filesChanged public String files public String option = 'y' public final String YES_OPTION = 'y' @@ -40,9 +40,8 @@ class Upload extends Deployment { Upload() { super(DESCRIPTION_OF_TASK, Constants.DEPLOYMENT) specificFilesToUpload = new ArrayList() - objSerializer = new FileMonitorSerializer() + packageGenerator = new PackageGenerator() filesToUpload = new ArrayList() - filesChanged = [:] interceptorsToExecute = [] } @@ -81,15 +80,16 @@ class Upload extends Deployment { * Saves on file monitor the files which has been updated */ void saveMapOfFilesChanged() { - if (filesChanged.isEmpty()) { + if (packageGenerator.fileTrackerMap.isEmpty()) { return } if (specificFilesToUpload.empty) { - objSerializer.saveMapUpdated(filesChanged) + packageGenerator.saveFileTrackerMap() return } - objSerializer.saveMapUpdated(filterMapFilesChanged()) + packageGenerator.fileTrackerMap = filterMapFilesChanged() + packageGenerator.saveFileTrackerMap() } /** @@ -97,26 +97,21 @@ class Upload extends Deployment { * @return */ Map filterMapFilesChanged() { - Map auxiliaryMap = [:] - specificFilesToUpload.each { file -> - if (filesChanged.get(file.toString())) { - auxiliaryMap.put(file.toString(), filesChanged.get(file.toString())) + Map fileChanged = [:] + specificFilesToUpload.each { File file -> + if (packageGenerator.fileTrackerMap.get(file.toString())) { + fileChanged.put(file.toString(), packageGenerator.fileTrackerMap.get(file.toString())) } } - return auxiliaryMap + return fileChanged } /** * Loads all files which has been changed to be updated once user execute upload Task */ void loadFilesChangedToUpload() { - objSerializer.setSrcProject(projectPath) - ArrayList fileArray = fileManager.getValidElements(projectPath, excludeFilesToMonitor) - if (!objSerializer.verifyFileMap()) { - objSerializer.mapRefresh(fileArray) - return - } - filesChanged = objSerializer.getFileChangedExclude(fileArray) + ArrayList validatedFiles = fileManager.getValidElements(projectPath, excludeFilesToMonitor) + packageGenerator.init(projectPath, validatedFiles, credential) } /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieval.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieval.groovy index 41123ca..b6982f3 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieval.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieval.groovy @@ -8,11 +8,11 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve import org.fundacionjala.gradle.plugins.enforce.metadata.RetrieveMetadata import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.SalesforceTask import org.fundacionjala.gradle.plugins.enforce.utils.Constants +import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.ZipFileManager import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.Package import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder -import org.fundacionjala.gradle.plugins.enforce.utils.Util import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieve.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieve.groovy index 910528d..68668ec 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieve.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/Retrieve.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve -import org.fundacionjala.gradle.plugins.enforce.utils.Constants import com.sforce.soap.metadata.PackageTypeMembers import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor +import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTask.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTask.groovy index 16bf7ee..1d329d2 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTask.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTask.groovy @@ -5,23 +5,23 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.unittest +import com.sforce.soap.apex.* +import groovy.json.JsonBuilder +import groovy.json.JsonSlurper +import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.SalesforceTask import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexClasses import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult import org.fundacionjala.gradle.plugins.enforce.unittest.RunTestListener import org.fundacionjala.gradle.plugins.enforce.unittest.TestResultReport import org.fundacionjala.gradle.plugins.enforce.unittest.report.HtmlManager import org.fundacionjala.gradle.plugins.enforce.utils.Constants +import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import com.sforce.soap.apex.* -import groovy.json.JsonBuilder -import groovy.json.JsonSlurper +import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI +import org.fundacionjala.gradle.plugins.enforce.wsc.soap.ApexAPI import org.gradle.api.file.FileTree import org.gradle.api.logging.LogLevel import org.gradle.logging.ProgressLoggerFactory -import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.SalesforceTask -import org.fundacionjala.gradle.plugins.enforce.utils.Util -import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI -import org.fundacionjala.gradle.plugins.enforce.wsc.soap.ApexAPI import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/PackageComponent.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/PackageComponent.groovy index 04847d9..bdd4e08 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/PackageComponent.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/PackageComponent.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.undeploy -import org.gradle.api.GradleException import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import org.fundacionjala.gradle.plugins.enforce.wsc.Connector +import org.gradle.api.GradleException /** * This class represents all components that are in a local org diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidator.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidator.groovy index 45f48ee..faa9dc3 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidator.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidator.groovy @@ -5,12 +5,14 @@ package org.fundacionjala.gradle.plugins.enforce.undeploy -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents -import org.fundacionjala.gradle.plugins.enforce.wsc.rest.QueryBuilder import groovy.json.JsonSlurper import groovy.util.logging.Log import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.fundacionjala.gradle.plugins.enforce.wsc.rest.QueryBuilder +import org.fundacionjala.gradle.plugins.enforce.wsc.rest.ToolingAPI /** * Validates files according salesForce json queries @@ -48,9 +50,11 @@ class SmartFilesValidator { if (json.entityTypeName != null) { files = new ArrayList() for (Object record in json.records) { - files.push(record.Name as String) + String recordName = record.FullName?:record.Name + files.push(recordName) } - queryResult.put(json.entityTypeName as String, files) + String key = json.records.size() > 0 ?json.records[0]['attributes'].type:json.entityTypeName + queryResult.put(key, files) } } } @@ -70,7 +74,7 @@ class SmartFilesValidator { * @param files contains all files to be evaluated * @return files selected */ - public filterFilesAccordingOrganization(ArrayList files) { + public ArrayList filterFilesAccordingOrganization(ArrayList files) { if (files == null) { throw new NullPointerException(String.format(Constants.NULL_PARAM_EXCEPTION, "files")) } @@ -133,4 +137,19 @@ class SmartFilesValidator { foldersSupported.push(MetadataComponents.getDirectoryByName(typeFile)) } } + + /** + * Gets queries according files given + * @returns queries on String format + */ + public static ArrayList getJsonQueries(ArrayList files, Credential credential) { + ToolingAPI toolingAPI = new ToolingAPI(credential) + QueryBuilder queryBuilder = new QueryBuilder() + ArrayList jsonQueries = [] + def queries = queryBuilder.createQueriesFromListOfFiles(files) + queries.each {query -> + jsonQueries.push(toolingAPI.httpAPIClient.executeQuery(query as String)) + } + return jsonQueries + } } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/RunTestListener.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/RunTestListener.groovy index 1b18451..05eaf7e 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/RunTestListener.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/RunTestListener.groovy @@ -5,14 +5,14 @@ package org.fundacionjala.gradle.plugins.enforce.unittest -import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexClasses -import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexTestItem import org.cometd.bayeux.Channel import org.cometd.bayeux.Message import org.cometd.bayeux.client.ClientSessionChannel import org.cometd.bayeux.client.ClientSessionChannel.MessageListener import org.fundacionjala.gradle.plugins.enforce.streaming.StreamingClient import org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.unittest.RunTestTask +import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexClasses +import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexTestItem import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.wsc.soap.ToolingAPI diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReport.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReport.groovy index 1fd7fbe..4bac91b 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReport.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReport.groovy @@ -5,7 +5,6 @@ package org.fundacionjala.gradle.plugins.enforce.unittest -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import groovy.json.JsonSlurper import groovy.xml.MarkupBuilder import groovy.xml.XmlUtil @@ -13,6 +12,7 @@ import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult import org.fundacionjala.gradle.plugins.enforce.unittest.coverage.Component import org.fundacionjala.gradle.plugins.enforce.unittest.coverage.CoverageElement import org.fundacionjala.gradle.plugins.enforce.unittest.report.InformationLoader +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManager.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManager.groovy index e526756..3abacc2 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManager.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManager.groovy @@ -5,11 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.unittest.report -import org.fundacionjala.gradle.plugins.enforce.utils.Constants -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import com.sforce.soap.apex.CodeCoverageResult import groovy.text.SimpleTemplateEngine import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult +import org.fundacionjala.gradle.plugins.enforce.utils.Constants +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import java.nio.file.Paths diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/InformationLoader.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/InformationLoader.groovy index a4da12f..9d44af4 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/InformationLoader.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/InformationLoader.groovy @@ -5,12 +5,12 @@ package org.fundacionjala.gradle.plugins.enforce.unittest.report -import groovy.json.StringEscapeUtils -import org.fundacionjala.gradle.plugins.enforce.utils.Constants import com.sforce.soap.apex.CodeCoverageResult import groovy.json.JsonBuilder import groovy.json.JsonSlurper +import groovy.json.StringEscapeUtils import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult +import org.fundacionjala.gradle.plugins.enforce.utils.Constants /** * Process information to coverage for the report diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Constants.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Constants.groovy index 99f9e34..6bb3a5d 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Constants.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Constants.groovy @@ -33,4 +33,6 @@ public class Constants { public static final String COMMA = "," public static final String POINT = "." public static final String WILDCARD = "*" + + public static final String OBJECT_EXTENSION = 'object' } diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Util.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Util.groovy index 612114a..1cdb2ce 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Util.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/Util.groovy @@ -31,6 +31,24 @@ class Util { fileName.replaceFirst(PATTERN_FILE_EXT, '') } + /** + * Gets a developer name of full name + * @param fullName is a tag of custom field + * @return developerName of custom field + */ + public static String getDeveloperName(String fullName){ + return fullName.substring(fullName.indexOf('.') + 1, fullName.length() - 7) + } + + /** + * Gets a developerName of member + * @param member is member tag of package xml file + * @return developerName of custom field + */ + public static String getDeveloperNameByMember(String member) { + return member.substring(member.indexOf('.') + 1, member.length() - 3) + } + /** * Verifies if the property exist and if it is not empty string * @param name the property typeName @@ -160,7 +178,7 @@ class Util { public static ArrayList getInvalidFolders(ArrayList foldersName) { ArrayList invalidFolders = new ArrayList() foldersName.each { String folderName -> - if (!MetadataComponents.validFolder(folderName)) { + if (!MetadataComponents.validFolder(folderName) || folderName.contains('.')) { invalidFolders.push(folderName) } } @@ -176,8 +194,10 @@ class Util { ArrayList emptyFolders = new ArrayList() foldersName.each { String folderName -> File file = new File(Paths.get(projectPath, folderName).toString()) - if (file.exists() && file.list().length == 0) { - emptyFolders.push(folderName) + if (file.isDirectory()) { + if (file.exists() && file.list().length == 0 ) { + emptyFolders.push(folderName) + } } } return emptyFolders diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponents.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponents.groovy index bdc581e..62dfec4 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponents.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponents.groovy @@ -64,7 +64,17 @@ public enum MetadataComponents { TRIGGERS("ApexTrigger", "trigger", "triggers"), PROFILES("Profile", "profile", "profiles"), TABS("CustomTab", "tab", "tabs"), - TRANSLATIONS("Translations", "translation", "translations") + TRANSLATIONS("Translations", "translation", "translations"), + FIELDS("CustomField", "sbc", "fields"), + COMPACTLAYOUTS("CompactLayout", "sbc", "compactLayouts"), + RECORDTYPES("RecordType", "sbc", "recordTypes"), + VALIDATIONRULES("ValidationRule", "sbc", "validationRules"), + BUSINESSPROCESSES("BusinessProcess", "sbc", "businessProcesses"), + FIELDSETS("FieldSet", "sbc", "fieldSets"), + LISTVIEWS("ListView", "sbc", "listViews"), + SHARINGREASON("SharingReason", "sbc", "SharingReason"), + OBJECTWEBLINKS("Weblink", "sbc", "webLinks"), + CUSTOMPERMISSIONS("CustomPermission", "customPermission", "customPermissions") public final static Map COMPONENT; @@ -102,6 +112,11 @@ public enum MetadataComponents { return COMPONENT.get(name.toUpperCase()); } + /** + * Gets a MetadataComponent by folder + * @param folder is a component folder + * @return a MetadataComponent + */ public static MetadataComponents getComponentByFolder(String folder) { MetadataComponents metadataComponent @@ -114,6 +129,28 @@ public enum MetadataComponents { return metadataComponent } + /** + * Gets a MetadataComponent by name + * @param name is component name + * @return a MetadataComponent object + */ + public static MetadataComponents getComponentByName(String name) { + + MetadataComponents metadataComponent + for (MetadataComponents component : values()) { + if (component.getTypeName() == name) { + metadataComponent = component + break + } + } + return metadataComponent + } + + /** + * Gets a extension of component by folder + * @param folder is a component folder + * @return a extension of component + */ public static String getExtensionByFolder(String folder) { String extensionByFolder @@ -126,6 +163,11 @@ public enum MetadataComponents { return extensionByFolder } + /** + * Gets a extension of component by name + * @param name is component name + * @return a extension o component + */ public static String getExtensionByName(String name) { String extensionByName @@ -138,6 +180,11 @@ public enum MetadataComponents { return extensionByName } + /** + * Gets a directory of component by name + * @param name is a component name + * @return a directory of component + */ public static String getDirectoryByName(String name) { String directory @@ -150,6 +197,11 @@ public enum MetadataComponents { return directory } + /** + * Validates a component extension + * @param extension is a component extension + * @return true if extension is valid + */ public static boolean validExtension(String extension) { for (MetadataComponents input : values()) { if (input.getExtension() == extension) { @@ -159,6 +211,11 @@ public enum MetadataComponents { return false } + /** + * Validates a component folder + * @param folderName is a component folder + * @return true if folder is valid + */ public static boolean validFolder(String folderName) { for (MetadataComponents input : values()) { if (input.name() == folderName.toUpperCase()) { diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageBuilder.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageBuilder.groovy index 93f044a..2686b5f 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageBuilder.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageBuilder.groovy @@ -5,8 +5,6 @@ package org.fundacionjala.gradle.plugins.enforce.utils.salesforce -import org.fundacionjala.gradle.plugins.enforce.utils.Constants -import org.fundacionjala.gradle.plugins.enforce.wsc.Connector import com.sforce.soap.metadata.PackageTypeMembers import groovy.util.logging.Log import groovy.util.slurpersupport.GPathResult @@ -14,7 +12,9 @@ import groovy.xml.DOMBuilder import groovy.xml.MarkupBuilder import groovy.xml.XmlUtil import groovy.xml.dom.DOMCategory +import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util +import org.fundacionjala.gradle.plugins.enforce.wsc.Connector import org.w3c.dom.Document import org.w3c.dom.Element diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGenerator.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGenerator.groovy new file mode 100644 index 0000000..7ca994d --- /dev/null +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGenerator.groovy @@ -0,0 +1,119 @@ +package org.fundacionjala.gradle.plugins.enforce.utils.salesforce + +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentStates +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ObjectResultTracker +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ResultTracker +import org.fundacionjala.gradle.plugins.enforce.undeploy.SmartFilesValidator +import org.fundacionjala.gradle.plugins.enforce.utils.Util +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential + +import java.nio.file.Paths + +class PackageGenerator { + PackageBuilder packageBuilder + ComponentMonitor componentMonitor + Map fileTrackerMap + SmartFilesValidator smartFilesValidator + Credential credential + + public PackageGenerator() { + packageBuilder = new PackageBuilder() + componentMonitor = new ComponentMonitor() + } + + public void init(String projectPath, ArrayList files, Credential credential) { + this.credential = credential + componentMonitor = new ComponentMonitor(projectPath) + if (!componentMonitor.verifyFileMap()) { + componentMonitor.saveCurrentComponents(files) + return + } + fileTrackerMap = componentMonitor.getComponentChanged(files) + } + + public ArrayList getFiles() { + ArrayList files = [] + fileTrackerMap.each { fileName, resultTracker -> + files.add(new File(fileName)) + } + return files + } + + public void buildPackage(String path) { + FileWriter fileWriter = new FileWriter(path) + this.buildPackage(fileWriter) + } + + public void saveFileTrackerMap(){ + componentMonitor.saveMapUpdated(fileTrackerMap) + } + + public void buildDestructive(String path) { + FileWriter fileWriter = new FileWriter(path) + this.buildDestructive(fileWriter) + } + + public ArrayList getFiles(ComponentStates status) { + ArrayList filesPackage = [] + fileTrackerMap.each { fileName, resultTracker -> + if (resultTracker.state == status) { + filesPackage.add(new File(fileName)) + } + } + return filesPackage + } + + public ArrayList getSubComponents(ComponentStates subComponentStatus) { + ArrayList filesResult = [] + File file + fileTrackerMap.each { fileName, resultTracker -> + if (resultTracker instanceof ObjectResultTracker && resultTracker.state == ComponentStates.CHANGED) { + resultTracker.subComponentsResult.each { subComponentName, statusField -> + if (statusField == subComponentStatus) { + file = new File("${Paths.get(subComponentName).parent.fileName}/${Util.getFileName(Paths.get(fileName).fileName.toString())}.${Paths.get(subComponentName).fileName}.sbc") + filesResult.add(file) + } + } + } + } + return filesResult + } + + public void buildPackage(Writer writer) { + ArrayList files = getFiles(ComponentStates.ADDED) + getFiles(ComponentStates.CHANGED) + getSubComponents(ComponentStates.ADDED) + getSubComponents(ComponentStates.CHANGED) + packageBuilder.createPackage(files) + packageBuilder.write(writer) + } + + public void buildDestructive(Writer writer){ + ArrayList files = getFiles(ComponentStates.DELETED) + getSubComponents(ComponentStates.DELETED) + smartFilesValidator = new SmartFilesValidator(SmartFilesValidator.getJsonQueries(files, credential)) + buildDestructive(writer, smartFilesValidator) + } + + public void buildDestructive(Writer writer, SmartFilesValidator smartFilesValidator) { + ArrayList files = getFiles(ComponentStates.DELETED) + getSubComponents(ComponentStates.DELETED) + files = smartFilesValidator.filterFilesAccordingOrganization(files) + + packageBuilder.createPackage(files) + packageBuilder.write(writer) + } + + public void updateFileTrackerMap(ArrayList folders) { + fileTrackerMap = componentMonitor.getFoldersFiltered(folders, fileTrackerMap) + } + + public ArrayList excludeFiles(ArrayList files) { + Map fileTrackerMapClone = fileTrackerMap.clone() as Map + ArrayList excludedFiles = [] + fileTrackerMapClone.each { fileName, resultTracker -> + def fileChanged = new File(fileName.toString()) + if (!files.contains(fileChanged)) { + fileTrackerMap.remove(fileName.toString()) + excludedFiles.push(fileChanged) + } + } + return excludedFiles + } +} diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/HttpAPIClient.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/HttpAPIClient.groovy index 31bdcae..d1bfdb1 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/HttpAPIClient.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/HttpAPIClient.groovy @@ -6,6 +6,7 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.rest import groovyx.net.http.HTTPBuilder + import static groovyx.net.http.ContentType.JSON import static groovyx.net.http.ContentType.TEXT import static groovyx.net.http.Method.GET @@ -46,7 +47,6 @@ class HttpAPIClient { * @return the result from server in JSON format */ public String executeQuery(String soql) { - String resultQuery = "" HTTPBuilder http = new HTTPBuilder(getEndPoint(host)) http.request( GET, JSON ) { diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilder.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilder.groovy index 55774c4..013cce3 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilder.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilder.groovy @@ -5,10 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.rest -import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents +import com.sforce.soap.metadata.PackageTypeMembers import groovy.util.logging.Log import org.fundacionjala.gradle.plugins.enforce.utils.Constants import org.fundacionjala.gradle.plugins.enforce.utils.Util +import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.MetadataComponents import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder /** @@ -18,11 +19,14 @@ import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder class QueryBuilder { private final String SELECT_NAME = 'SELECT Name FROM' + private final String SELECT_FULL_NAME = 'SELECT FullName FROM' private final String WHERE_NAME = 'WHERE Name =' + private final String WHERE_FULL_NAME = 'WHERE DeveloperName =' private final String THERE_IS_NOT_PACKAGE = "There isn't a package xml file in this path: " public static final ArrayList defaultComponents = ['ApexClass', 'ApexComponent', 'ApexPage', 'ApexTrigger', 'StaticResource', - 'Profile', 'EmailTemplate'] + 'Profile', 'EmailTemplate', 'CustomField', 'CompactLayout', 'RecordType','ValidationRule'] + public static final ArrayList defaultSubComponents = ['CustomField', 'CompactLayout', 'RecordType','ValidationRule'] /** * Gets queries of components from package xml file * @param packagePath is type String @@ -33,9 +37,18 @@ class QueryBuilder { throw new Exception("${THERE_IS_NOT_PACKAGE}${packagePath}") } ArrayList queries = new ArrayList() - getComponents(new FileReader(packagePath)).each { component -> - if (isDefaultComponent(component)) { - queries.add("${'SELECT Name FROM'} ${component}") + getComponents(new FileReader(packagePath)).each { typeMembers -> + if(defaultSubComponents.contains(typeMembers.name)) { + typeMembers.members.each { member -> + if (member != '*') { + queries.add("""${SELECT_FULL_NAME} ${typeMembers.name} ${WHERE_FULL_NAME} '${ + Util.getDeveloperNameByMember(member) + }'""") + } + } + } else + if (isDefaultComponent(typeMembers.name)) { + queries.add("${SELECT_NAME} ${typeMembers.name}") } } return queries @@ -56,9 +69,13 @@ class QueryBuilder { String folderName = file.getParentFile().getName() MetadataComponents component = MetadataComponents.getComponentByFolder(folderName) if (component && isDefaultComponent(component.getTypeName())) { - queries.add("""${SELECT_NAME} ${component.getTypeName()} ${WHERE_NAME} '${ - Util.getFileName(file.getName()) - }'""") + String query = component.getExtension() != 'sbc'? + """${SELECT_NAME} ${component.getTypeName()} ${WHERE_NAME} '${ + Util.getFileName(file.getName())}'""" : + """${SELECT_FULL_NAME} ${component.getTypeName()} ${WHERE_FULL_NAME} '${ + Util.getDeveloperName(file.getName()) + }'""" + queries.add(query) } else { invalidFolders.add(folderName) } @@ -84,14 +101,10 @@ class QueryBuilder { * @param reader is type Reader * @return arrayList with sales force's components */ - public ArrayList getComponents(Reader reader) { + public ArrayList getComponents(Reader reader) { PackageBuilder packageBuilder = new PackageBuilder() packageBuilder.read(reader) - ArrayList components = new ArrayList() - packageBuilder.metaPackage.types.each { type -> - components.add(type.name) - } - return components + return packageBuilder.metaPackage.types } /** diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/ToolingAPI.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/ToolingAPI.groovy index f259243..acdd51c 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/ToolingAPI.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/ToolingAPI.groovy @@ -5,11 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.rest -import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexTestItem +import groovy.json.JsonSlurper import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult +import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexTestItem import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI -import groovy.json.JsonSlurper /** * A wrapper around http client that execute queries diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexAPI.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexAPI.groovy index 6d6605a..c99c307 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexAPI.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexAPI.groovy @@ -5,11 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.soap +import com.sforce.soap.apex.* +import com.sforce.ws.ConnectionException import org.fundacionjala.gradle.plugins.enforce.wsc.Connector import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI -import com.sforce.soap.apex.* -import com.sforce.ws.ConnectionException /** * This class wraps Apex Api and exposes the WSDL methods diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataAPI.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataAPI.groovy index 5a68825..ef1b33b 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataAPI.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataAPI.groovy @@ -5,12 +5,12 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.soap -import org.fundacionjala.gradle.plugins.enforce.wsc.InspectorResults import com.sforce.soap.metadata.* import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.DeployException import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.InfoDeploy import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI +import org.fundacionjala.gradle.plugins.enforce.wsc.InspectorResults /** * This class wraps Metadata Api and exposes WSDL methods diff --git a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ToolingAPI.groovy b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ToolingAPI.groovy index 94053e9..0783366 100644 --- a/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ToolingAPI.groovy +++ b/src/main/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ToolingAPI.groovy @@ -5,13 +5,13 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.soap +import com.sforce.soap.tooling.* +import com.sforce.ws.ConnectionException import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexTestItem import org.fundacionjala.gradle.plugins.enforce.wsc.Connector import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI -import com.sforce.soap.tooling.* -import com.sforce.ws.ConnectionException /** * A wrapper around soap client that execute queries diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePluginTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePluginTest.groovy index d6b47ce..fc6e63b 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePluginTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/EnforcePluginTest.groovy @@ -5,12 +5,11 @@ package org.fundacionjala.gradle.plugins.enforce +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder -import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import spock.lang.Specification - class EnforcePluginTest extends Specification { def 'force extensions exist'() { diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManagerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManagerTest.groovy index e734193..35c9a3b 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManagerTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialFileManagerTest.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.credentialmanagement +import groovy.json.JsonSlurper import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType -import groovy.json.JsonSlurper import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerTest.groovy index 06fe1bb..530d4e9 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/credentialmanagement/CredentialManagerTest.groovy @@ -5,9 +5,9 @@ package org.fundacionjala.gradle.plugins.enforce.credentialmanagement -import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import groovy.json.JsonSlurper import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHashTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHashTest.groovy new file mode 100644 index 0000000..0dfbfdc --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentHashTest.groovy @@ -0,0 +1,39 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +class ComponentHashTest extends Specification { + + @Shared + ComponentHash componentTracker + + def setup() { + componentTracker = new ComponentHash() + } + + def "Test should be Initialize ComponentTracker object"() { + expect: + componentTracker instanceof ComponentHash + } + + def "Test should be able to comparate a component tracker if It has changed" () { + given: + ComponentHash componentTrackerOld = new ComponentHash('src/classes/Class1.cls', 'lkiujhytgfr') + ComponentHash componentTrackerNew = new ComponentHash('src/classes/Class1.cls', 'qweasdzxcrt') + when: + ResultTracker resultTracker = componentTrackerOld.compare(componentTrackerNew) + then: + resultTracker.state == ComponentStates.CHANGED + } + + def "Test should be able to comparate a component tracker if It hasn't changed" () { + given: + ComponentHash componentTrackerOld = new ComponentHash('src/classes/Class1.cls', 'lkiujhytgfr') + ComponentHash componentTrackerNew = new ComponentHash('src/classes/Class1.cls', 'lkiujhytgfr') + when: + ResultTracker resultTracker = componentTrackerOld.compare(componentTrackerNew) + then: + resultTracker.state == ComponentStates.NOT_CHANGED + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitorTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitorTest.groovy new file mode 100644 index 0000000..a282f13 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentMonitorTest.groovy @@ -0,0 +1,459 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import com.twmacinta.util.MD5 +import groovy.util.slurpersupport.GPathResult +import groovy.util.slurpersupport.NodeChild +import groovy.xml.StreamingMarkupBuilder +import groovy.xml.XmlUtil +import spock.lang.Shared +import spock.lang.Specification + +import java.nio.file.Paths + +class ComponentMonitorTest extends Specification{ + + @Shared + ComponentMonitor componentMonitor + + @Shared + Map oldFiles = [:] + + @Shared + Map currentFiles = [:] + + @Shared + String srcProjectPath = Paths.get(System.getProperty("user.dir"), "src", "test", "groovy", "org", "fundacionjala", "gradle", + "plugins","enforce", "filemonitor", "resources").toString() + + @Shared + String fileNameClass = 'src/classes/Class1.cls' + + @Shared + Map subComponents + + def setup() { + subComponents = [:] + componentMonitor = new ComponentMonitor('resources') + ComponentHash oldClassTracker = new ComponentHash() + oldClassTracker.hash = 'qweasdzxc' + ComponentHash currentClassTracker = new ComponentHash() + currentClassTracker.hash = 'rtyfghvbn' + oldFiles.put(fileNameClass, oldClassTracker) + currentFiles.put(fileNameClass, currentClassTracker) + def fileTrackerPath = Paths.get(srcProjectPath, '.fileTracker.data').toString() + ComponentSerializer componentSerializer = new ComponentSerializer(fileTrackerPath) + componentMonitor.componentSerializer = componentSerializer + } + + def "Test should return a map with files changed" () { + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + result.containsKey(fileNameClass) + result.get(fileNameClass).state == ComponentStates.CHANGED + } + + def "Test should return a map with files were added" () { + given: + String newClassPath = 'src/classes/NewClass.cls' + currentFiles.put(newClassPath, new ComponentHash(newClassPath, 'akshdkjashdkj')) + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + result.containsKey(newClassPath) + result.get(newClassPath).state == ComponentStates.ADDED + } + + def "Test should return a map with files were deleted" () { + given: + String deletedClassPath = 'src/classes/DeletedClass.cls' + oldFiles.put(deletedClassPath, new ComponentHash(deletedClassPath, 'akshdkjashdkj')) + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + result.containsKey(deletedClassPath) + result.get(deletedClassPath).state == ComponentStates.DELETED + } + + def "Test should return a map with updated, added and deleted files" () { + given: + String updateClassPath = 'src/classes/UpdatedClass.cls' + String newClassPath = 'src/classes/NewClass.cls' + String deletedClassPath = 'src/classes/DeletedClass.cls' + oldFiles.put(updateClassPath, new ComponentHash(updateClassPath, 'oldClassHash')) + currentFiles.put(updateClassPath, new ComponentHash(updateClassPath, 'updatedClassHash')) + currentFiles.put(newClassPath, new ComponentHash(newClassPath, 'newClassHash')) + oldFiles.put(deletedClassPath, new ComponentHash(deletedClassPath, 'deletedClassHash')) + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + result.containsKey(updateClassPath) + result.get(updateClassPath).state == ComponentStates.CHANGED + + result.containsKey(deletedClassPath) + result.get(deletedClassPath).state == ComponentStates.DELETED + + result.containsKey(newClassPath) + result.get(newClassPath).state == ComponentStates.ADDED + } + + def "Test shouldn't save the files that weren't updated, added or deleted" () { + given: + String classPath = 'src/classes/NotChangedClass.cls' + ComponentHash componentTracker = new ComponentHash(classPath, 'sameHash') + oldFiles.put(classPath, componentTracker) + currentFiles.put(classPath, componentTracker) + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + !result.containsKey(classPath) + } + + def "Test should return a map that only contains the updated, deleted and added ObjectTrackers" () { + given: + String objectPath = 'src/objects/Object1__c.object' + ObjectHash objectTracker = new ObjectHash(objectPath, 'filedHash', subComponents) + oldFiles.put(objectPath, objectTracker) + currentFiles.put(objectPath, objectTracker) + when: + Map result = componentMonitor.getFilesChanged(oldFiles, currentFiles) + then: + !result.containsKey(objectPath) + } + + def "Test should return a map with components and their hash value" () { + given: + String firstFile = Paths.get(srcProjectPath, 'classes', 'Class1.cls') + String secondFile = Paths.get(srcProjectPath, 'classes', 'Class2.cls') + ArrayList files = [new File(firstFile), new File(secondFile)] + def class1Hash = MD5.asHex(MD5.getHash(files[0])) + def class2Hash = MD5.asHex(MD5.getHash(files[1])) + componentMonitor.srcProject = 'resources' + when: + Map result = componentMonitor.getComponentsSignature(files) + then: + result.containsKey(Paths.get('resources', 'classes','Class1.cls').toString()) + result.containsKey(Paths.get('resources', 'classes','Class2.cls').toString()) + result.get(Paths.get('resources', 'classes','Class1.cls').toString()).hash == class1Hash + result.get(Paths.get('resources', 'classes','Class2.cls').toString()).hash == class2Hash + } + + def "Test should have the values as instance of ObjectTracker" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + ArrayList files = [new File(object1), new File(object2)] + componentMonitor.srcProject = 'resources' + when: + Map result = componentMonitor.getComponentsSignature(files) + then: + result.containsKey(Paths.get('resources','objects', 'Object1__c.object').toString()) + result.containsKey(Paths.get('resources','objects', 'Object2__c.object').toString()) + result.get(Paths.get('resources','objects', 'Object1__c.object').toString()) instanceof ObjectHash + result.get(Paths.get('resources','objects', 'Object2__c.object').toString()) instanceof ObjectHash + } + + def "Test should return a map with fields and their hash value" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + ArrayList files = [new File(object1), new File(object2)] + componentMonitor.srcProject = 'resources' + when: + Map result = componentMonitor.getComponentsSignature(files) + then: + result.containsKey(Paths.get('resources','objects', 'Object1__c.object').toString()) + result.containsKey(Paths.get('resources','objects', 'Object2__c.object').toString()) + result.get(Paths.get('resources','objects', 'Object1__c.object').toString()).subComponents.containsKey('fields/Field1__c') + result.get(Paths.get('resources','objects', 'Object2__c.object').toString()).subComponents.containsKey('fields/Field1__c') + } + + def "Test should return a map without changes" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + ArrayList files = [new File(object1), new File(object2)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + componentMonitor.componentSerializer.save(componentsHash) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + result.isEmpty() + } + + def "Test should return a map with files that have had deleted" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + ArrayList files = [new File(object1), new File(object2)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + ComponentSerializer componentSerializer = new ComponentSerializer('resources') + componentSerializer.save(componentsHash) + files.remove(0) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + result.containsKey(Paths.get('resources','objects', 'Object1__c.object').toString()) + result.get(Paths.get('resources','objects', 'Object1__c.object').toString()).state == ComponentStates.DELETED + } + + def "Test should return a map with files that have had added" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + def everNoteObject = Paths.get(srcProjectPath, 'objects', 'Evernote__Contact_Note__c.object').toString() + ArrayList files = [new File(object1), new File(object2)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + ComponentSerializer componentSerializer = new ComponentSerializer('resources') + componentSerializer.save(componentsHash) + files.add(new File(everNoteObject)) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + String everNoteObjectPath = Paths.get('resources', 'objects', 'Evernote__Contact_Note__c.object') + result.containsKey(everNoteObjectPath) + result.get(everNoteObjectPath).state == ComponentStates.ADDED + } + + def "Test should return a map with files that have had changed" () { + given: + def everNoteChanged = Paths.get(srcProjectPath, 'objects', 'EverNoteChanged__c.object').toString() + def object2 = Paths.get(srcProjectPath, 'objects', 'Object2__c.object').toString() + def everNoteChangedContent = new File(Paths.get(srcProjectPath, 'objects', 'Evernote__Contact_Note__c.object').toString()).text + new File(everNoteChanged).write(everNoteChangedContent) + ArrayList files = [new File(everNoteChanged), new File(object2)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + componentMonitor.componentSerializer.save(componentsHash) + XmlSlurper xmlSlurper = new XmlSlurper() + GPathResult objectParsed = xmlSlurper.parseText(new File(everNoteChanged).text) + objectParsed.enableEnhancedLookup = true + XmlUtil xmlUtil = new XmlUtil() + String xmlString = xmlUtil.serialize(objectParsed) + new File(everNoteChanged).write(xmlString) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + String everNoteChangedPath = Paths.get('resources', 'objects', 'EverNoteChanged__c.object') + result.containsKey(everNoteChangedPath) + result.get(everNoteChangedPath).state == ComponentStates.CHANGED + } + + def "Test should return a map with fields that have had deleted" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object1FieldDeleted = Paths.get(srcProjectPath, 'objects', 'Object1FieldDeleted__c.object').toString() + def object1Content = new File(object1).text + File object1FieldDeletedFile = new File(object1FieldDeleted) + object1FieldDeletedFile.write(object1Content) + ArrayList files = [new File(object1), new File(object1FieldDeleted)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + componentMonitor.componentSerializer.save(componentsHash) + def xmlSlurper = new XmlSlurper() + def objectParsed = xmlSlurper.parse(object1FieldDeletedFile) + def list = objectParsed.fields.list() + list.remove(0) + objectParsed.fields = list + object1FieldDeletedFile.withWriter { outWriter -> + XmlUtil.serialize( new StreamingMarkupBuilder().bind{ mkp.yield objectParsed }, outWriter ) + } + when: + Map result = componentMonitor.getComponentChanged(files) + then: + String objectFieldDeleted = Paths.get('resources', 'objects', 'Object1FieldDeleted__c.object') + result.containsKey(objectFieldDeleted) + result.get(objectFieldDeleted).state == ComponentStates.CHANGED + result.get(objectFieldDeleted).subComponentsResult.containsKey('fields/Field1__c') + result.get(objectFieldDeleted).subComponentsResult.get('fields/Field1__c') == ComponentStates.DELETED + } + + def "Test should return a map with fields that have had added" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def object1FieldAdded = Paths.get(srcProjectPath, 'objects', 'Object1FieldAdded__c.object').toString() + def object1Content = new File(object1).text + new File(object1FieldAdded).write(object1Content) + ArrayList files = [new File(object1), new File(object1FieldAdded)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + componentMonitor.componentSerializer.save(componentsHash) + def xmlSlurper = new XmlSlurper() + def objectParsed = xmlSlurper.parse(new File(object1FieldAdded)) + def fieldSetValue = "${'Enforce_Fieldset'}${'Enforce_Fieldset'}" + NodeChild newNode = new XmlSlurper().parseText(fieldSetValue) + objectParsed.appendNode(newNode) + XmlUtil xmlUtil = new XmlUtil() + String xmlString = xmlUtil.serialize(objectParsed) + new File(object1FieldAdded).write(xmlString) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + String object1FieldAddedPath = Paths.get('resources', 'objects', 'Object1FieldAdded__c.object') + result.containsKey(object1FieldAddedPath) + result.get(object1FieldAddedPath).state == ComponentStates.CHANGED + result.get(object1FieldAddedPath).subComponentsResult.containsKey('fieldSets/Enforce_Fieldset') + result.get(object1FieldAddedPath).subComponentsResult.get('fieldSets/Enforce_Fieldset') == ComponentStates.ADDED + } + + def "Test should return a map with fields that have had changed" () { + given: + def object1 = Paths.get(srcProjectPath, 'objects', 'Object1__c.object').toString() + def objectFieldChanged = Paths.get(srcProjectPath, 'objects', 'Object1FieldChanged__c.object').toString() + def object1Content = new File(object1).text + new File(objectFieldChanged).write(object1Content) + ArrayList files = [new File(object1), new File(objectFieldChanged)] + Map componentsHash = componentMonitor.getComponentsSignature(files) + componentMonitor.componentSerializer.save(componentsHash) + def xmlSlurper = new XmlSlurper() + def objectParsed = xmlSlurper.parse(new File(objectFieldChanged)) + objectParsed.fields[0].length = 5 + XmlUtil xmlUtil = new XmlUtil() + String xmlString = xmlUtil.serialize(objectParsed) + new File(objectFieldChanged).write(xmlString) + when: + Map result = componentMonitor.getComponentChanged(files) + then: + String object1FieldChangedPath = Paths.get('resources', 'objects', 'Object1FieldChanged__c.object') + result.containsKey(object1FieldChangedPath) + result.get(object1FieldChangedPath).state == ComponentStates.CHANGED + result.get(object1FieldChangedPath).subComponentsResult.containsKey('fields/Field1__c') + result.get(object1FieldChangedPath).subComponentsResult.get('fields/Field1__c') == ComponentStates.CHANGED + } + + def "Test select files changed according folders"() { + given: + def arrayFolders = ["classes"] + def mapFilesChanged = ["classes/class1.cls": "file Changed", "triggers/trigger1.trigger": "file Changed"] + when: + def mapResult = componentMonitor.getFoldersFiltered(arrayFolders, mapFilesChanged) + then: + mapResult == ["classes/class1.cls": "file Changed"] + } + + def "Test verify exist map"() { + when: + String fileTrackerFile = Paths.get(srcProjectPath, '.fileTrackerTest.data') + new File(fileTrackerFile).write('test') + componentMonitor.fileName = fileTrackerFile + then: + componentMonitor.verifyFileMap() + new File(fileTrackerFile).delete() + } + + def "Test verify not exist map "() { + when: + String fileTrackerFile = Paths.get(srcProjectPath, '.fileTrackerTest.data') + componentMonitor.fileName = fileTrackerFile + then: + !componentMonitor.verifyFileMap() + } + + def "Test set a project path"() { + given: + def sourceProject = "src" + def fileName = '.fileTracker.data' + when: + componentMonitor.setSrcProject(sourceProject) + then: + componentMonitor.srcProject == sourceProject + componentMonitor.fileName == Paths.get(sourceProject, fileName).toString() + } + + def "Test get relative path"() { + given: + File fileRelativePath = new File("user/project/src/class/class1") + when: + def relativePath = componentMonitor.getPathRelative(fileRelativePath) + then: + relativePath == Paths.get("resources", "class", "class1").toString() + } + + def "Test should update the map with subComponents"() { + given: + String class1Path = Paths.get('src', 'classes', 'Class1.cls') + String class2Path = Paths.get('src', 'classes', 'Class2.cls') + String class3Path = Paths.get('src', 'classes', 'Class3.cls') + String newClassPath = Paths.get('src', 'classes', 'NewClass.cls') + Map recoveryFileHashCode = [:] + recoveryFileHashCode.put(class1Path, new ComponentHash(class1Path, 'hashClass1')) + recoveryFileHashCode.put(class2Path, new ComponentHash(class1Path, 'hashClass2')) + recoveryFileHashCode.put(class3Path, new ComponentHash(class1Path, 'hashClass3')) + + Map currentFileHashCode = [:] + currentFileHashCode.put(class1Path, new ComponentHash(newClassPath,'hashClassChanged')) + currentFileHashCode.put(newClassPath, new ComponentHash(newClassPath,'hashNewClass')) + currentFileHashCode.put(class3Path, new ComponentHash(newClassPath,'hashClass3')) + + + Map mapFilesChanged = [:] + mapFilesChanged.put(class1Path, new ResultTracker(ComponentStates.CHANGED)) + mapFilesChanged.put(class2Path, new ResultTracker(ComponentStates.DELETED)) + mapFilesChanged.put(newClassPath, new ResultTracker(ComponentStates.ADDED)) + + componentMonitor.recoveryFileHashCode = recoveryFileHashCode + componentMonitor.currentFileHashCode = currentFileHashCode + + when: + componentMonitor.saveMapUpdated(mapFilesChanged) + then: + !componentMonitor.recoveryFileHashCode.containsKey(class2Path) + componentMonitor.recoveryFileHashCode.containsKey(class1Path) + componentMonitor.recoveryFileHashCode.containsKey(class3Path) + componentMonitor.recoveryFileHashCode.containsKey(newClassPath) + componentMonitor.recoveryFileHashCode.get(class1Path).hash == 'hashClassChanged' + componentMonitor.recoveryFileHashCode.get(class3Path).hash == 'hashClass3' + componentMonitor.recoveryFileHashCode.get(newClassPath).hash == 'hashNewClass' + } + + def "Test should update the map to save it "() { + given: + String object1Path = Paths.get('src', 'objects', 'object1__c.object') + Map recoveryFileHashCode = [:] + Map subComponentsRecovery = [:] + subComponentsRecovery.put('fields/Field1__c', 'field1Hash') + subComponentsRecovery.put('fields/Field2__c', 'field2Hash') + subComponentsRecovery.put('fields/Field3__c', 'field3Hash') + recoveryFileHashCode.put(object1Path, new ObjectHash(object1Path, 'ObjectHash', subComponentsRecovery)) + + Map currentFileHashCode = [:] + Map subComponentsCurrent = [:] + subComponentsCurrent.put('fields/Field1__c', 'field1HashChanged') + subComponentsCurrent.put('fields/Field3__c', 'field3Hash') + subComponentsCurrent.put('fields/Field4__c', 'field4Hash') + currentFileHashCode.put(object1Path, new ObjectHash(object1Path, 'objectHashChanged', subComponentsCurrent)) + + + Map mapFilesChanged = [:] + Map objectResultSubComponents = [:] + objectResultSubComponents.put('fields/Field1__c', ComponentStates.CHANGED) + objectResultSubComponents.put('fields/Field2__c', ComponentStates.DELETED) + objectResultSubComponents.put('fields/Field4__c', ComponentStates.ADDED) + ObjectResultTracker objectResultTracker = new ObjectResultTracker(ComponentStates.CHANGED) + objectResultTracker.subComponentsResult = objectResultSubComponents + mapFilesChanged.put(object1Path, objectResultTracker) + + componentMonitor.recoveryFileHashCode = recoveryFileHashCode + componentMonitor.currentFileHashCode = currentFileHashCode + + when: + componentMonitor.saveMapUpdated(mapFilesChanged) + then: + componentMonitor.recoveryFileHashCode.containsKey(object1Path) + componentMonitor.recoveryFileHashCode.get(object1Path).hash == 'objectHashChanged' + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.containsKey('fields/Field1__c') + !componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.containsKey('fields/Field2__c') + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.containsKey('fields/Field3__c') + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.containsKey('fields/Field4__c') + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.get('fields/Field1__c') == 'field1HashChanged' + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.get('fields/Field3__c') == 'field3Hash' + componentMonitor.recoveryFileHashCode.get(object1Path).subComponents.get('fields/Field4__c') == 'field4Hash' + + + } + + def cleanupSpec() { + new File(Paths.get(srcProjectPath, 'objects', 'EverNoteChanged__c.object').toString()).delete() + new File(Paths.get(srcProjectPath, 'objects', 'Object1FieldDeleted__c.object').toString()).delete() + new File(Paths.get(srcProjectPath, 'objects', 'Object1FieldAdded__c.object').toString()).delete() + new File(Paths.get(srcProjectPath, 'objects', 'Object1FieldChanged__c.object').toString()).delete() + new File(Paths.get('resources').toString()).delete() + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializerTest.groovy new file mode 100644 index 0000000..0b70923 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ComponentSerializerTest.groovy @@ -0,0 +1,101 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +import java.nio.file.Paths + +class ComponentSerializerTest extends Specification { + + @Shared + ComponentSerializer componentSerializer + + @Shared + String srcProjectPath = Paths.get(System.getProperty("user.dir"), "src", "test", "groovy", "org", "fundacionjala", "gradle", + "plugins","enforce", "filemonitor", "resources").toString() + @Shared + Map subComponents + + @Shared + String fileName + + def setup() { + fileName = Paths.get(srcProjectPath, '.fileTracker.data') + subComponents = [:] + componentSerializer = new ComponentSerializer(fileName) + } + + def "Test Should be Initialize ComponentManager object"() { + expect: + componentSerializer instanceof ComponentSerializer + } + + def "Test should save a Map object in a .fileTracker.data file" () { + given: + Map components = [:] + components.put('src/classes/Class1.cls', new ComponentHash('src/classes/Class1.cls', 'classHash')) + components.put('src/classes/Object1__c.object', new ObjectHash('src/classes/Object1__c.object', 'objectHash', subComponents)) + when: + componentSerializer.save(components) + then: + new File(fileName).exists() + new File(fileName).size() > 0 + } + + def "Test should read a .fileTracker.data file and returns a Map object" () { + given: + Map components = [:] + components.put('src/classes/Class1.cls', new ComponentHash('src/classes/Class1.cls', 'classHash')) + components.put('src/classes/Object1__c.object', new ObjectHash('src/classes/Object1__c.object', 'objectHash', subComponents)) + when: + componentSerializer.save(components) + Map result = componentSerializer.read() + then: + result.size() == components.size() + result.each {String relativePath, ComponentHash componentTracker -> + components.get(relativePath).hash == componentTracker.hash + } + } + + def "Test should read a .fileTracker.data oldFormat file and returns a Map object" () { + given: + Map components = [:] + String fileNameTest = Paths.get(srcProjectPath, '.fileTrackerOldFormat.data') + componentSerializer = new ComponentSerializer(fileNameTest) + components.put('src/classes/Class1.cls', 'Class1Hash') + components.put('src/classes/Object1__c.object', 'Object1Hash') + ObjectOutputStream oos + oos = new ObjectOutputStream(new FileOutputStream(fileNameTest)) + oos.writeObject(components) + oos.close() + when: + Map result = componentSerializer.read() + then: + result.containsKey('src/classes/Class1.cls') + result.containsKey('src/classes/Object1__c.object') + result.get('src/classes/Class1.cls').hash == 'Class1Hash' + result.get('src/classes/Object1__c.object').hash == 'Object1Hash' + } + + def "Test should read a .fileTracker.data new format file and returns a Map object" () { + given: + Map components = [:] + String fileNameTest = Paths.get(srcProjectPath, '.fileTrackerOldFormat.data') + componentSerializer = new ComponentSerializer(fileNameTest) + components.put('src/classes/Class1.cls', new ComponentHash('src/classes/Class1.cls', 'classHash')) + components.put('src/classes/Object1__c.object', new ObjectHash('src/classes/Object1__c.object', 'objectHash', subComponents)) + when: + componentSerializer.save(components) + Map result = componentSerializer.read() + then: + result.containsKey('src/classes/Class1.cls') + result.containsKey('src/classes/Object1__c.object') + result.get('src/classes/Class1.cls').hash == 'classHash' + result.get('src/classes/Object1__c.object').hash == 'objectHash' + } + + def cleanupSpec() { + new File(fileName).delete() + new File(Paths.get(srcProjectPath, '.fileTrackerOldFormat.data').toString()).delete() + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParserTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParserTest.groovy new file mode 100644 index 0000000..ccf7af7 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectParserTest.groovy @@ -0,0 +1,54 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +import java.nio.file.Paths + +class ObjectParserTest extends Specification { + + @Shared + ObjectParser objectParser + + @Shared + String srcProjectPath = Paths.get(System.getProperty("user.dir"), "src", "test", "groovy", "org", "fundacionjala", "gradle", + "plugins","enforce", "filemonitor", "resources").toString() + + def setup() { + objectParser = new ObjectParser() + } + + def "Test should be an instance of ObjectParser" () { + expect: + objectParser instanceof ObjectParser + } + + def "Test should return an ObjectTracker that contain a map with field name and its hash" () { + given: + String objectPath = Paths.get(srcProjectPath, 'objects', 'Object1__c.object') + String field1__cHash = 'b8535e7f90c928ae8f6c7606367fbaf1' + when: + Map result = objectParser.parseByObjectXML(new File (objectPath)) + then: + result.containsKey('fields/Field1__c') + result.get('fields/Field1__c') == field1__cHash + } + + def "Test should return ObjectTracker that contain a map with fields name and their hash" () { + given: + String objectPath = Paths.get(srcProjectPath, 'objects', 'Evernote__Contact_Note__c.object') + String enforce_FieldsetHash = '1f2148ab348e55398083d8e8775250a7' + String enforce_Number_Field__c = '9f150323f784c692936aedd92cd69914' + String enforce_User__c = 'c3bcafaeddf610a4c6950760399877fa' + when: + Map result = objectParser.parseByObjectXML(new File (objectPath)) + then: + result.containsKey('fieldSets/Enforce_Fieldset') + result.containsKey('fields/Enforce_Number_Field__c') + result.containsKey('fields/Enforce_User__c') + + result.get('fieldSets/Enforce_Fieldset') == enforce_FieldsetHash + result.get('fields/Enforce_Number_Field__c') == enforce_Number_Field__c + result.get('fields/Enforce_User__c') == enforce_User__c + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTrackerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTrackerTest.groovy new file mode 100644 index 0000000..b2e5839 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectResultTrackerTest.groovy @@ -0,0 +1,19 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +class ObjectResultTrackerTest extends Specification { + + @Shared + ObjectResultTracker objectResultTracker + + def setup() { + objectResultTracker = new ObjectResultTracker() + } + + def "Test should be an instance of ObjectResult" () { + expect: + objectResultTracker instanceof ObjectResultTracker + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectTrackerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectTrackerTest.groovy new file mode 100644 index 0000000..2644e61 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ObjectTrackerTest.groovy @@ -0,0 +1,119 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +class ObjectTrackerTest extends Specification { + + @Shared + ObjectHash oldObjectTracker + + @Shared + ObjectHash currentObjectTracker + + @Shared + Map subComponents + + def setup() { + subComponents = [:] + oldObjectTracker = new ObjectHash('fieldAPIName', 'fileHash',subComponents) + oldObjectTracker.subComponents = ['fieldAPIName':'fieldHash'] + currentObjectTracker = new ObjectHash('fieldAPIName', 'fileHashDifferent', subComponents) + currentObjectTracker.subComponents = ['fieldAPIName':'fieldHashDifferent'] + } + + def "Test should be instance of ObjectTracker"() { + expect: + oldObjectTracker instanceof ObjectHash + } + + def "Test should return an instance of ObjectResultTracker" () { + given: + ObjectHash currentObjectTracker = new ObjectHash('src/classes/Class1.cls', 'fileHash', subComponents) + when: + ResultTracker resultTracker = oldObjectTracker.compare(currentObjectTracker) + then: + resultTracker instanceof ObjectResultTracker + } + + def "Test should be able to compare a component tracker if It has changed" () { + when: + ResultTracker resultTracker = oldObjectTracker.compare(currentObjectTracker) + then: + resultTracker.state == ComponentStates.CHANGED + } + + def "Test should be able to comparate a component tracker if It hasn't changed" () { + given: + ObjectHash oldObjectTracker = new ObjectHash('src/classes/Class1.cls', 'lkiujhytgfr',subComponents) + ObjectHash currentObjectTracker = new ObjectHash('src/classes/Class1.cls', 'lkiujhytgfr', subComponents) + when: + ResultTracker resultTracker = oldObjectTracker.compare(currentObjectTracker) + then: + resultTracker.state == ComponentStates.NOT_CHANGED + } + + def "Test should return ResultTracker with a map that contains fields changed in a ObjectTracker" () { + when: + ObjectResultTracker objectResultTracker = (ObjectResultTracker)oldObjectTracker.compare(currentObjectTracker) + then: + objectResultTracker.state == ComponentStates.CHANGED + objectResultTracker.subComponentsResult.containsKey('fieldAPIName') + objectResultTracker.subComponentsResult.get('fieldAPIName') == ComponentStates.CHANGED + } + + def "Test should return ResultTracker with a map that contains fields added in a ObjectTracker" () { + given: + String addedFieldAPIName = 'addedFieldAPiName' + currentObjectTracker.subComponents.put(addedFieldAPIName, 'fieldHashAdded') + when: + ObjectResultTracker objectResultTracker = (ObjectResultTracker)oldObjectTracker.compare(currentObjectTracker) + then: + objectResultTracker.state == ComponentStates.CHANGED + objectResultTracker.subComponentsResult.containsKey(addedFieldAPIName) + objectResultTracker.subComponentsResult.get(addedFieldAPIName) == ComponentStates.ADDED + } + + def "Test should return ResultTracker with a map that contains fields deleted in a ObjectTracker" () { + given: + currentObjectTracker.subComponents.remove('fieldAPIName') + when: + ObjectResultTracker objectResultTracker = (ObjectResultTracker)oldObjectTracker.compare(currentObjectTracker) + then: + objectResultTracker.state == ComponentStates.CHANGED + objectResultTracker.subComponentsResult.containsKey('fieldAPIName') + objectResultTracker.subComponentsResult.get('fieldAPIName') == ComponentStates.DELETED + } + + def "Test shouldn't return ResultTracker with a map that contains fields deleted in a ObjectTracker" () { + given: + currentObjectTracker.subComponents.put('notChangedFieldName', 'notChangeHash') + oldObjectTracker.subComponents.put('notChangedFieldName', 'notChangeHash') + when: + ObjectResultTracker objectResultTracker = (ObjectResultTracker)oldObjectTracker.compare(currentObjectTracker) + then: + !objectResultTracker.subComponentsResult.containsKey('notChangedFieldName') + } + + def "Test should return a ResultTracker with a map that contains fields deleted, updated and added in a ObjectTracker" () { + given: + String addedFieldAPIName = 'addedFieldAPiName' + String deletedFieldAPIName = 'fieldAPIName' + String updatedFieldAPIName = 'updatedFieldAPiName' + currentObjectTracker.subComponents.put(addedFieldAPIName, 'fieldHashAdded') + currentObjectTracker.subComponents.put(updatedFieldAPIName, 'fieldHash') + oldObjectTracker.subComponents.put(updatedFieldAPIName, 'fieldHashDifferent') + currentObjectTracker.subComponents.remove(deletedFieldAPIName) + when: + ObjectResultTracker objectResultTracker = (ObjectResultTracker)oldObjectTracker.compare(currentObjectTracker) + then: + objectResultTracker.subComponentsResult.containsKey(addedFieldAPIName) + objectResultTracker.subComponentsResult.get(addedFieldAPIName) == ComponentStates.ADDED + + objectResultTracker.subComponentsResult.containsKey(updatedFieldAPIName) + objectResultTracker.subComponentsResult.get(updatedFieldAPIName) == ComponentStates.CHANGED + + objectResultTracker.subComponentsResult.containsKey(deletedFieldAPIName) + objectResultTracker.subComponentsResult.get(deletedFieldAPIName) == ComponentStates.DELETED + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTrackerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTrackerTest.groovy new file mode 100644 index 0000000..eccbf2e --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/ResultTrackerTest.groovy @@ -0,0 +1,26 @@ +package org.fundacionjala.gradle.plugins.enforce.filemonitor + +import spock.lang.Shared +import spock.lang.Specification + +class ResultTrackerTest extends Specification { + + @Shared + ResultTracker resultTracker + + def setup() { + resultTracker = new ResultTracker() + } + + def "Test should be an instance of ResultTracker" () { + expect: + resultTracker instanceof ResultTracker + } + + def "Test should verify if the state is saved in the ResultTracker object" () { + when: + ResultTracker result = new ResultTracker(ComponentStates.ADDED) + then: + result.state == ComponentStates.ADDED + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/SerializerMonitorFilesTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/SerializerMonitorFilesTest.groovy deleted file mode 100644 index 434b081..0000000 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/SerializerMonitorFilesTest.groovy +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) Fundacion Jala. All rights reserved. - * Licensed under the MIT license. See LICENSE file in the project root for full license information. - */ - -package org.fundacionjala.gradle.plugins.enforce.filemonitor - -import spock.lang.Shared -import spock.lang.Specification - -import java.nio.file.Paths - - -class SerializerMonitorFilesTest extends Specification { - - @Shared - def SRC_PATH = System.getProperty("user.dir") + "/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/resources" - - @Shared - File file1 - - @Shared - File file2 - - @Shared - private Map mapFileChanged - - @Shared - FileMonitorSerializer serializerMonitorFiles - - @Shared - ArrayList arrayFiles - - @Shared - String relativePath = "./resources" - - @Shared - String NAME_FILE_TRACKER = "./file.data" - - def setup() { - serializerMonitorFiles = Spy(FileMonitorSerializer, constructorArgs: [NAME_FILE_TRACKER]) - arrayFiles = new ArrayList() - file1 = new File(Paths.get(SRC_PATH, "/one.txt").toString()) - file2 = new File(Paths.get(SRC_PATH, "/two.txt").toString()) - - mapFileChanged = new HashMap() - mapFileChanged.put(Paths.get(relativePath, "/one.txt").toString(), "123dasd") - mapFileChanged.put(Paths.get(relativePath, "/two.txt").toString(), "059e0d992ee883bd390612888db75b03") - } - - def "Test set a project path"() { - given: - def sourceProject = "src" - def fileName = '.fileTracker.data' - when: - serializerMonitorFiles.setSrcProject(sourceProject) - then: - serializerMonitorFiles.srcProject == sourceProject - serializerMonitorFiles.nameFile == Paths.get(sourceProject, fileName).toString() - } - - def "Test using no parameters constructor"() { - - when: - FileMonitorSerializer fileMonitorSerializer = new FileMonitorSerializer() - then: - fileMonitorSerializer instanceof FileMonitorSerializer - fileMonitorSerializer instanceof TemplateFileMonitor - } - - def "Test load Signature for files in directory"() { - given: - Map signatureFileMap - when: - arrayFiles.push(file1) - arrayFiles.push(file2) - signatureFileMap = serializerMonitorFiles.loadSignatureForFilesInDirectory(arrayFiles) - then: - 2 == signatureFileMap.size() - signatureFileMap.get(Paths.get(relativePath, "/one.txt").toString()) == "87ee732d831690f45b8606b1547bd09e" - signatureFileMap.get(Paths.get(relativePath, "/two.txt").toString()) == "059e0d992ee883bd390612888db75b03" - } - - def "Test get file changed"() { - given: - Map MapMock = new HashMap() - MapMock.put(Paths.get(relativePath, "/one.txt").toString(), "Changed file") - arrayFiles.push(file1) - arrayFiles.push(file2) - when: - def mapResult = serializerMonitorFiles.getFileChangedExclude(arrayFiles) - then: - 1 * serializerMonitorFiles.readMap(NAME_FILE_TRACKER) >> mapFileChanged - MapMock == mapResult - } - - def "Test save and read map "() { - given: - def path = System.getProperty("user.dir") + "/src/file.data" - serializerMonitorFiles.setNameFile(path) - File fileMap = new File(path) - arrayFiles.push(file1) - arrayFiles.push(file2) - Map mapLoader = serializerMonitorFiles.loadSignatureForFilesInDirectory(arrayFiles) - Map recoveryMap - when: - serializerMonitorFiles.saveMap(mapLoader) - recoveryMap = serializerMonitorFiles.readMap(path) - then: - serializerMonitorFiles.verifyFileMap() - recoveryMap == mapLoader - fileMap.delete() - } - - def "Test state delete"() { - given: - def state - when: - state = "Deleted file" - then: - state == serializerMonitorFiles.getStateDelete() - } - - def "Test get relative path"() { - given: - File fileRelativePath = new File("user/project/src/class/class1") - when: - def relativePath = serializerMonitorFiles.getPathRelative(fileRelativePath) - then: - relativePath == Paths.get(".", "class", "class1").toString() - } - - def "Test new File"() { - given: - Map mapFilePros = ["src/class/class1.cls": "123456789"] - Map mapCurrent = ["src/class/class1.cls": "123456789", "src/class/class2.cls": "1234567890"] - when: - serializerMonitorFiles.findNewFiles(mapFilePros, mapCurrent) - then: - serializerMonitorFiles.mapFilesChanged == ["src/class/class2.cls": "New file"] - } - - def "Test new File not exits"() { - given: - Map mapFilePros = ["src/class/class1.cls": "123456789"] - Map mapCurrent = [:] - when: - serializerMonitorFiles.findNewFiles(mapFilePros, mapCurrent) - then: - serializerMonitorFiles.mapFilesChanged == [:] - } - - def "Test changed File"() { - given: - Map mapFilePros = ["src/class/class1.cls": "123456789"] - Map mapCurrent = ["src/class/class1.cls": "1234567890"] - when: - serializerMonitorFiles.findChangedFiles(mapFilePros, mapCurrent) - then: - serializerMonitorFiles.mapFilesChanged == ["src/class/class1.cls": "Changed file"] - } - - def "Test deleted File"() { - given: - Map mapFilePros = ["src/class/class1.cls": "123456789", "src/class/class2.cls": "1234567890"] - Map mapCurrent = ["src/class/class1.cls": "123456789"] - when: - serializerMonitorFiles.findDeleteFiles(mapFilePros, mapCurrent) - then: - serializerMonitorFiles.mapFilesChanged == ["src/class/class2.cls": "Deleted file"] - } - - def "Test verify exist map"() { - when: - serializerMonitorFiles.setNameFile(SRC_PATH + "/file.data") - then: - true == serializerMonitorFiles.verifyFileMap() - } - - def "Test verify not exist map "() { - when: - serializerMonitorFiles.setNameFile(SRC_PATH + "/file1.data") - then: - false == serializerMonitorFiles.verifyFileMap() - } - - def "Test select files changed according folders"() { - given: - def arrayFolders = ["classes"] - def mapFilesChanged = ["classes/class1.cls": "file Changed", "triggers/trigger1.trigger": "file Changed"] - when: - def mapResult = serializerMonitorFiles.getFoldersFiltered(arrayFolders, mapFilesChanged) - then: - mapResult == ["classes/class1.cls": "file Changed"] - } - - def "Test should update the map to save it "() { - given: - Map recoveryMap = ["class1.cls": "123", "class2.cls": "345", "class3.cls": "789"] - serializerMonitorFiles.setRecoveryFileHashCode(recoveryMap) - Map currentMap = ["class1.cls": "123", "class2.cls": "999"] - serializerMonitorFiles.setCurrentFileHashCode(currentMap) - Map mapFileChanged = ["class1.cls": "123", "class2.cls": "file_changed", "class3.cls": serializerMonitorFiles.getStateDelete()] - when: - serializerMonitorFiles.saveMapUpdated(mapFileChanged) - then: - serializerMonitorFiles.recoveryFileHashCode == ["class1.cls": "123", "class2.cls": "999"] - } -} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/resources/objects/Evernote__Contact_Note__c.object b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/resources/objects/Evernote__Contact_Note__c.object new file mode 100644 index 0000000..c40531e --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/filemonitor/resources/objects/Evernote__Contact_Note__c.object @@ -0,0 +1,51 @@ + + + false + + Enforce_Fieldset + Enforce_Fieldset + + Name + false + false + + + Enforce_Number_Field__c + false + false + + + Enforce_User__c + false + false + + + CreatedById + false + false + + + + + Enforce_Number_Field__c + false + + 18 + false + 0 + false + Number + false + + + Enforce_User__c + SetNull + false + + User + Contact_Notes + false + false + Lookup + + diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ComponentTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ComponentTest.groovy index 0a6dba0..7d1858c 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ComponentTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/commands/ComponentTest.groovy @@ -34,15 +34,29 @@ class ComponentTest extends Specification { } - def "Should truncate a component"() { - setup: - File file = new File("${TRUNCATED_PATH}/Component1.component") + def "Should truncate a simple component"() { + given: + def expectedContent = '''\n''' + File file = new File("${TRUNCATED_PATH}/ComponentContent.component") when: componentContent.execute(file) then: - file.text == Component.EMPTY_COMPONENT + file.text.replaceAll("\\s*","") == expectedContent.replaceAll("\\s*","") + } + def "Should truncate a component with attributes"() { + given: + def expectedContent = ''' + + + +''' + File file = new File("${TRUNCATED_PATH}/NewComponentContent.component") + when: + componentContent.execute(file) + then: + true + file.text.replaceAll("\\s*","") == expectedContent.replaceAll("\\s*","") } - def cleanupSpec() { new File(TRUNCATED_PATH).deleteDir() } diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptorTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptorTest.groovy index 7d3717f..bed6c0c 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptorTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/interceptors/ComponentInterceptorTest.groovy @@ -24,7 +24,7 @@ class ComponentInterceptorTest extends Specification { when: componentInterceptor.loadFiles(path) then: - componentInterceptor.files.size() == 1 + componentInterceptor.files.size() == 2 } } diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/ComponentContent.component b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/ComponentContent.component index ba21dc2..ba208d9 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/ComponentContent.component +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/ComponentContent.component @@ -1,6 +1,4 @@

Congratulations

-This is your new Component -
\ No newline at end of file diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/NewComponentContent.component b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/NewComponentContent.component new file mode 100644 index 0000000..68f1b36 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/interceptor/resources/components/NewComponentContent.component @@ -0,0 +1,8 @@ + + + + + + + \ No newline at end of file diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/RetrieveMetadataTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/RetrieveMetadataTest.groovy index 65ac4f3..0f59358 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/RetrieveMetadataTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/metadata/RetrieveMetadataTest.groovy @@ -5,10 +5,10 @@ package org.fundacionjala.gradle.plugins.enforce.metadata -import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import com.sforce.soap.metadata.RetrieveMessage import com.sforce.soap.metadata.RetrieveResult import com.sforce.soap.metadata.RetrieveStatus +import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.Package import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialAdderTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialAdderTest.groovy index 7f8204e..6a339ee 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialAdderTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialAdderTest.groovy @@ -5,10 +5,10 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager -import org.gradle.api.Project -import org.gradle.testfixtures.ProjectBuilder import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.gradle.api.Project +import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialUpdaterTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialUpdaterTest.groovy index 1111c51..a086d08 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialUpdaterTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/CredentialUpdaterTest.groovy @@ -5,10 +5,10 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.credentialmanager -import org.gradle.api.Project -import org.gradle.testfixtures.ProjectBuilder import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.gradle.api.Project +import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/resources/secretKeyGenerated.text b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/resources/secretKeyGenerated.text deleted file mode 100644 index 773a628..0000000 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/credentialmanager/resources/secretKeyGenerated.text +++ /dev/null @@ -1 +0,0 @@ -N2MwNTA3M2MzMTdlQ09ERA== \ No newline at end of file diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/ResetTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/ResetTest.groovy index 4e6a3be..601187e 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/ResetTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/filemonitor/ResetTest.groovy @@ -6,12 +6,13 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.filemonitor import com.twmacinta.util.MD5 -import org.gradle.testfixtures.ProjectBuilder +import groovy.json.JsonSlurper import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor +import org.gradle.api.Project +import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared import spock.lang.Specification -import org.gradle.api.Project import java.nio.file.Paths @@ -44,18 +45,30 @@ class ResetTest extends Specification { fileWriter.write('test') def pathFileTracker = Paths.get(SRC_PATH, 'src', '.fileTracker.data').toString() new File(pathFileTracker).createNewFile() - instanceReset.fileArray = [new File(class1Path)] - instanceReset.fileMonitorSerializer = new FileMonitorSerializer(pathFileTracker) + instanceReset.sourceComponents = [new File(class1Path)] + instanceReset.componentMonitor = new ComponentMonitor(Paths.get(SRC_PATH, 'src').toString()) def signature = MD5.asHex(MD5.getHash(new File(class1Path))) when: instanceReset.runTask() fileWriter.write('new change') fileWriter.close() then: - instanceReset.fileMonitorSerializer.readMap(pathFileTracker).get(class1Path) == signature + instanceReset.componentMonitor.componentSerializer.read().get(class1Path).hash == signature + } + + def "Test should delete a old fileTracker file and create a new fileTracker with jsonFormat" () { + given: + String fileTrackerPath = Paths.get(SRC_PATH, '.fileTracker.data') + new File(fileTrackerPath).write('components tracked') + instanceReset.projectPath = SRC_PATH + when: + instanceReset.removeFileTracker() + then: + !new File(fileTrackerPath).exists() } def cleanupSpec() { - new File(Paths.get(SRC_PATH).toString()).deleteDir() + new File(Paths.get(SRC_PATH).toString()).deleteDir() + } } diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/DeployTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/DeployTest.groovy index 5622de1..0dba971 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/DeployTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/DeployTest.groovy @@ -5,13 +5,13 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment +import org.custommonkey.xmlunit.Diff +import org.custommonkey.xmlunit.XMLUnit import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.metadata.DeployMetadata import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType -import org.custommonkey.xmlunit.Diff -import org.custommonkey.xmlunit.XMLUnit import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UndeployTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UndeployTest.groovy index 6cd0fe1..ba72ffe 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UndeployTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UndeployTest.groovy @@ -5,18 +5,18 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment -import org.fundacionjala.gradle.plugins.enforce.undeploy.PackageComponent import org.custommonkey.xmlunit.Diff import org.custommonkey.xmlunit.XMLUnit -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.testfixtures.ProjectBuilder import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.metadata.DeployMetadata +import org.fundacionjala.gradle.plugins.enforce.undeploy.PackageComponent import org.fundacionjala.gradle.plugins.enforce.undeploy.SmartFilesValidator import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared import spock.lang.Specification @@ -181,8 +181,8 @@ class UndeployTest extends Specification { undeployInstance.unDeployPackagePath = unDeployPath undeployInstance.credential = credential when: - def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1"},{"Name" : "Class2"}]""" - def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger2"}]""" + def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1","attributes":{"type":"ApexClass"}},{"Name" : "Class2", "attributes":{"type":"ApexClass"}}]""" + def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger2", "attributes":{"type":"ApexTrigger"}}]""" def jsonArrays = new ArrayList() jsonArrays.push(jsonString1) jsonArrays.push(jsonString2) diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UpdateTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UpdateTest.groovy index 9714cfb..d51d93b 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UpdateTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UpdateTest.groovy @@ -5,14 +5,17 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment +import org.custommonkey.xmlunit.Diff +import org.custommonkey.xmlunit.XMLUnit import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentSerializer +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentStates +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ResultTracker import org.fundacionjala.gradle.plugins.enforce.metadata.DeployMetadata import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType -import org.custommonkey.xmlunit.Diff -import org.custommonkey.xmlunit.XMLUnit import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder import spock.lang.Shared @@ -29,11 +32,17 @@ class UpdateTest extends Specification { @Shared def SRC_PATH = Paths.get(System.getProperty("user.dir"), "src", "test", "groovy", "org", - "fundacionjala", "gradle", "plugins","enforce","tasks", "salesforce", "resources").toString() + "fundacionjala", "gradle", "plugins","enforce","tasks", "salesforce", "resources").toString() @Shared Credential credential + @Shared + ComponentSerializer componentSerializer + + @Shared + ComponentMonitor componentMonitor + def setup() { project = ProjectBuilder.builder().build() project.apply(plugin: EnforcePlugin) @@ -42,10 +51,10 @@ class UpdateTest extends Specification { updateInstance.fileManager = new ManagementFile(SRC_PATH) updateInstance.createDeploymentDirectory(Paths.get(SRC_PATH, 'build').toString()) updateInstance.createDeploymentDirectory(Paths.get(SRC_PATH, 'build', 'update').toString()) - FileMonitorSerializer fileMonitorSerializer = new FileMonitorSerializer() - fileMonitorSerializer.setSrcProject(SRC_PATH) + def fileTrackerPath = Paths.get(SRC_PATH,'.fileTracker.data').toString() + componentSerializer = new ComponentSerializer(fileTrackerPath) + componentMonitor = new ComponentMonitor(SRC_PATH) def class1 = new File(Paths.get(SRC_PATH, 'classes', 'class1.cls').toString()) - def object = new File(Paths.get(SRC_PATH, 'objects', 'object1.object').toString()) def class1Cls = new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls').toString()) def class1ClsXml = new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls-meta.xml').toString()) @@ -54,8 +63,8 @@ class UpdateTest extends Specification { def trigger = new File(Paths.get(SRC_PATH, 'src', 'triggers', 'Trigger1.trigger').toString()) def triggerXml = new File(Paths.get(SRC_PATH, 'src', 'triggers', 'Trigger1.trigger-meta.xml').toString()) - def mapMock = fileMonitorSerializer.loadSignatureForFilesInDirectory([class1, object, class1Cls, class1ClsXml, object1__c, object1__c, account, trigger, triggerXml]) - fileMonitorSerializer.saveMap(mapMock) + def mapMock = componentMonitor.getComponentsSignature([class1, class1Cls, class1ClsXml, object1__c, object1__c, account, trigger, triggerXml]) + componentSerializer.save(mapMock) credential = new Credential() credential.id = 'id' @@ -68,45 +77,45 @@ class UpdateTest extends Specification { def "Test should show files changed" () { given: - updateInstance.filesChanged = ["two.txt":"New file"] + updateInstance.packageGenerator.fileTrackerMap = ["two.txt":"New file"] when: - def stdOut = System.out - def os = new ByteArrayOutputStream() - System.out = new PrintStream(os) + def stdOut = System.out + def os = new ByteArrayOutputStream() + System.out = new PrintStream(os) - updateInstance.showFilesChanged() - def array = os.toByteArray() - def is = new ByteArrayInputStream(array) - System.out = stdOut - def lineAux = is.readLines() + updateInstance.showFilesChanged() + def array = os.toByteArray() + def is = new ByteArrayInputStream(array) + System.out = stdOut + def lineAux = is.readLines() then: - lineAux[0].contains("*********************************************") - lineAux[1].contains(" Status Files Changed ") - lineAux[2].contains("*********************************************") - lineAux[3].contains("two.txt - New file") - lineAux[4].contains("*********************************************") + lineAux[0].contains("*********************************************") + lineAux[1].contains(" Status Files Changed ") + lineAux[2].contains("*********************************************") + lineAux[3].contains("two.txt - New file") + lineAux[4].contains("*********************************************") } def "Test should show nothing" () { given: - updateInstance.filesChanged = [:] + updateInstance.packageGenerator.fileTrackerMap = [:] when: - def stdOut = System.out - def os = new ByteArrayOutputStream() - System.out = new PrintStream(os) - updateInstance.showFilesChanged() - def array = os.toByteArray() - def is = new ByteArrayInputStream(array) - System.out = stdOut - def lineAux = is.readLines() + def stdOut = System.out + def os = new ByteArrayOutputStream() + System.out = new PrintStream(os) + updateInstance.showFilesChanged() + def array = os.toByteArray() + def is = new ByteArrayInputStream(array) + System.out = stdOut + def lineAux = is.readLines() then: - lineAux == [] + lineAux == [] } def "Test should create a package XML file" () { given: - updateInstance.filesChanged = ['classes/Class1.cls':"New file"] + updateInstance.packageGenerator.fileTrackerMap = ['classes/Class1.cls':new ResultTracker(ComponentStates.ADDED)] updateInstance.pathUpdate = Paths.get(SRC_PATH, 'build', 'update').toString() updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() when: @@ -117,7 +126,7 @@ class UpdateTest extends Specification { def "Test should create a package XML file empty if status is deleted" () { given: - updateInstance.filesChanged = ['Class1.cls':"Deleted file"] + updateInstance.packageGenerator.fileTrackerMap = ['classes/Class1.cls':new ResultTracker(ComponentStates.ADDED)] updateInstance.pathUpdate = Paths.get(SRC_PATH, 'build', 'update').toString() updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() when: @@ -128,7 +137,7 @@ class UpdateTest extends Specification { def "Test should create a package empty" () { given: - updateInstance.filesChanged = [:] + updateInstance.packageGenerator.fileTrackerMap = [:] updateInstance.pathUpdate = Paths.get(SRC_PATH, 'build', 'update').toString() updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() when: @@ -139,10 +148,11 @@ class UpdateTest extends Specification { def "Test should create a destructive XML file" () { given: - updateInstance.filesChanged = ['classes/Class1.cls':"Deleted file"] + updateInstance.packageGenerator.fileTrackerMap = ['classes/Class1.cls':new ResultTracker(ComponentStates.DELETED)] updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() updateInstance.pathUpdate = Paths.get(SRC_PATH, 'build', 'update').toString() updateInstance.credential = credential + updateInstance.packageGenerator.credential = credential when: updateInstance.createDestructive() then: @@ -152,16 +162,18 @@ class UpdateTest extends Specification { def "Test should load new file" () { given: updateInstance.projectPath = SRC_PATH - updateInstance.objSerializer = new FileMonitorSerializer() - def newFilePath = Paths.get(SRC_PATH, 'classes', 'class2.cls').toString() + updateInstance.packageGenerator.componentMonitor = new ComponentMonitor(SRC_PATH) + def newFilePath = Paths.get(SRC_PATH, 'classes', 'Class2.cls').toString() FileWriter newFile = new FileWriter(newFilePath) newFile.write('test') newFile.close() + updateInstance.credential = credential when: updateInstance.loadFilesChanged() then: - updateInstance.filesChanged.get(newFilePath) == "New file" - updateInstance.filesChanged.containsKey(newFilePath) == true + updateInstance.packageGenerator.fileTrackerMap.containsKey(newFilePath) + updateInstance.packageGenerator.fileTrackerMap.get(newFilePath).state == ComponentStates.ADDED + } def "Test should copy changed files" () { @@ -180,7 +192,7 @@ class UpdateTest extends Specification { given: updateInstance.buildFolderPath = Paths.get(SRC_PATH, 'build').toString() updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() - updateInstance.filesChanged = [:] + updateInstance.packageGenerator.fileTrackerMap = [:] updateInstance.componentDeploy = new DeployMetadata() updateInstance.poll = 200 updateInstance.waitTime = 10 @@ -200,15 +212,15 @@ class UpdateTest extends Specification { def "Integration test should update (New file)"() { given: - FileMonitorSerializer fileMonitorSerializer = new FileMonitorSerializer() - fileMonitorSerializer.setSrcProject(Paths.get(SRC_PATH, 'src').toString()) + updateInstance.packageGenerator.fileTrackerMap = [:] def class1Cls = new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls').toString()) def object1__c = new File(Paths.get(SRC_PATH, 'src', 'objects', 'Object1__c.object').toString()) def account = new File(Paths.get(SRC_PATH, 'src', 'objects', 'Account.object').toString()) def trigger = new File(Paths.get(SRC_PATH, 'src', 'triggers', 'Trigger1.trigger').toString()) - def mapMock = fileMonitorSerializer.loadSignatureForFilesInDirectory([class1Cls, object1__c, account, trigger]) - fileMonitorSerializer.saveMap(mapMock) - + componentMonitor.srcProject = Paths.get(SRC_PATH,'src').toString() + componentSerializer.sourcePath = Paths.get(SRC_PATH,'src','.fileTracker.data').toString() + def mapMock = componentMonitor.getComponentsSignature([class1Cls, object1__c, account, trigger]) + componentSerializer.save(mapMock) updateInstance.buildFolderPath = Paths.get(SRC_PATH, 'build').toString() updateInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() def newFilePath = Paths.get(SRC_PATH, 'src', 'classes', 'Class2.cls').toString() @@ -227,7 +239,6 @@ class UpdateTest extends Specification { updateInstance.credential = credential def packageExpect = "${""}${""}${"Class2ApexClass32.0"}" def destructiveExpect = "${""}${""}${"32.0"}${""}" - when: updateInstance.runTask() def packageXml = new File(Paths.get(SRC_PATH, 'build', 'update', 'package.xml').toString()).text @@ -242,12 +253,12 @@ class UpdateTest extends Specification { destructiveXmlDifference.similar() classXmlDifference.similar() class2Content == new File(Paths.get(SRC_PATH, 'build', 'update', 'classes', 'Class2.cls').toString()).text - } - + } def cleanupSpec() { new File(Paths.get(SRC_PATH, 'build').toString()).deleteDir() - new File(Paths.get(SRC_PATH, 'classes', 'class2.cls').toString()).delete() + new File(Paths.get(SRC_PATH, 'classes', 'Class2.cls').toString()).delete() new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class2.cls').toString()).delete() new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class2.cls-meta.xml').toString()).delete() + new File(Paths.get(SRC_PATH, 'src', '.fileTracker.data').toString()).delete() } -} +} \ No newline at end of file diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UploadTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UploadTest.groovy index b6fef33..6eee348 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UploadTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/deployment/UploadTest.groovy @@ -5,14 +5,15 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.deployment -import org.fundacionjala.gradle.plugins.enforce.filemonitor.FileMonitorSerializer +import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentStates +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ResultTracker +import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile +import org.fundacionjala.gradle.plugins.enforce.utils.Util import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder -import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin -import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile -import org.fundacionjala.gradle.plugins.enforce.utils.Util import spock.lang.Shared import spock.lang.Specification @@ -30,8 +31,8 @@ class UploadTest extends Specification { @Shared def SRC_PATH = Paths.get(System.getProperty("user.dir"), "src", "test", "groovy", "org", - "fundacionjala", "gradle", "plugins","enforce", - "tasks", "salesforce", "resources").toString() + "fundacionjala", "gradle", "plugins", "enforce", + "tasks", "salesforce", "resources").toString() @Shared Credential credential @@ -53,7 +54,7 @@ class UploadTest extends Specification { credential.type = 'normal' } - def "Test shouldn't create a package xml file if specificFilesToUpload Array is empty " () { + def "Test shouldn't create a package xml file if specificFilesToUpload Array is empty "() { given: uploadInstance.pathUpload = Paths.get(SRC_PATH, 'build').toString() uploadInstance.specificFilesToUpload = [] @@ -63,7 +64,7 @@ class UploadTest extends Specification { !new File(Paths.get(SRC_PATH, 'build', 'package.xml').toString()).exists() } - def "Test should create a package xml file" () { + def "Test should create a package xml file"() { given: uploadInstance.pathUpload = Paths.get(SRC_PATH, 'build').toString() uploadInstance.specificFilesToUpload = [new File(Paths.get(SRC_PATH, "src", "classes", "Class1.cls").toString()), @@ -76,7 +77,7 @@ class UploadTest extends Specification { new File(Paths.get(SRC_PATH, 'build', 'package.xml').toString()).exists() } - def "Test should copy files to upload" () { + def "Test should copy files to upload"() { given: uploadInstance.pathUpload = Paths.get(SRC_PATH, 'build').toString() uploadInstance.specificFilesToUpload = [new File(Paths.get(SRC_PATH, "src", "classes", "Class1.cls").toString()), @@ -85,84 +86,44 @@ class UploadTest extends Specification { when: uploadInstance.copyFilesToUpload() then: - new File(Paths.get(SRC_PATH, 'build', "classes", "Class1.cls").toString()).exists() - new File(Paths.get(SRC_PATH, 'build', "classes", "Class1.cls-meta.xml").toString()).exists() - new File(Paths.get(SRC_PATH, 'build', "objects", "Object1__c.object").toString()).exists() + new File(Paths.get(SRC_PATH, 'build', "classes", "Class1.cls").toString()).exists() + new File(Paths.get(SRC_PATH, 'build', "classes", "Class1.cls-meta.xml").toString()).exists() + new File(Paths.get(SRC_PATH, 'build', "objects", "Object1__c.object").toString()).exists() } - def "Test should return a map with changed files" () { + def "Test should return a map with changed files"() { given: def changedFilePath = Paths.get(SRC_PATH, "classes", "class1.cls").toString() uploadInstance.specificFilesToUpload = [new File(changedFilePath), new File(Paths.get(SRC_PATH, "classes", "class1.cls-meta.xml").toString()), new File(Paths.get(SRC_PATH, "objects", "object1.object").toString())] - uploadInstance.filesChanged.put(changedFilePath, "New file") + uploadInstance.packageGenerator.fileTrackerMap = [:] + uploadInstance.packageGenerator.fileTrackerMap.put(changedFilePath, new ResultTracker(ComponentStates.ADDED)) def filesChangedExpect = [:] - filesChangedExpect.put(changedFilePath, "New file") + filesChangedExpect.put(changedFilePath, new ResultTracker(ComponentStates.ADDED)) when: def filesChangedToUpload = uploadInstance.filterMapFilesChanged() then: - filesChangedToUpload == filesChangedExpect + filesChangedToUpload.containsKey(changedFilePath) + filesChangedExpect.containsKey(changedFilePath) + filesChangedToUpload.get(changedFilePath).state == filesChangedExpect.get(changedFilePath).state } - def "Test should return a empty Map if there isn't changed file" () { + def "Test should return a empty Map if there isn't changed file"() { given: def changedFilePath = Paths.get(SRC_PATH, "classes", "class2.cls").toString() uploadInstance.specificFilesToUpload = [new File(Paths.get(SRC_PATH, "classes", "class1.cls").toString()), new File(Paths.get(SRC_PATH, "classes", "class1.cls-meta.xml").toString()), new File(Paths.get(SRC_PATH, "objects", "object1.object").toString())] - uploadInstance.filesChanged.put(changedFilePath, "") + uploadInstance.packageGenerator.fileTrackerMap = [:] + uploadInstance.packageGenerator.fileTrackerMap.put(changedFilePath, "") when: def filesChangedToUpload = uploadInstance.filterMapFilesChanged() then: filesChangedToUpload == [:] } - def "Test should save in a map changed files" () { - given: - uploadInstance.objSerializer = new FileMonitorSerializer() - def changedFilePath = Paths.get(SRC_PATH, "src", "classes", "Class1.cls").toString() - uploadInstance.specificFilesToUpload = [new File(Paths.get(SRC_PATH, "src", "classes", "Class1.cls").toString()), - new File(Paths.get(SRC_PATH, "src", "classes", "Class1.cls-meta.xml").toString()), - new File(Paths.get(SRC_PATH, "src", "objects", "Object1__c.object").toString())] - uploadInstance.filesChanged.put(changedFilePath, "Changed file") - uploadInstance.objSerializer.recoveryFileHashCode = [:] - uploadInstance.objSerializer.currentFileHashCode = [:] - uploadInstance.objSerializer.currentFileHashCode.put(changedFilePath, "Changed file") - uploadInstance.objSerializer.nameFile = Paths.get(SRC_PATH, '.fileTracker.data').toString() - when: - uploadInstance.saveMapOfFilesChanged() - then: - uploadInstance.objSerializer.recoveryFileHashCode == uploadInstance.filterMapFilesChanged() - } - - def "Test shouldn't save anything if filesChanged is empty " () { - given: - uploadInstance.filesChanged = [:] - uploadInstance.objSerializer = new FileMonitorSerializer() - when: - uploadInstance.saveMapOfFilesChanged() - then: - uploadInstance.objSerializer.recoveryFileHashCode == null - } - - def "Test should save in a map changed files if specificFilesToUpload map is empty" () { - given: - uploadInstance.objSerializer = new FileMonitorSerializer() - def changedFilePath = Paths.get(SRC_PATH, "src", "classes", "Class1.cls").toString() - uploadInstance.specificFilesToUpload = [] - uploadInstance.filesChanged.put(changedFilePath, "Changed file") - uploadInstance.objSerializer.recoveryFileHashCode = [:] - uploadInstance.objSerializer.currentFileHashCode = [:] - uploadInstance.objSerializer.currentFileHashCode.put(changedFilePath, "Changed file") - uploadInstance.objSerializer.nameFile = Paths.get(SRC_PATH, '.fileTracker.data').toString() - when: - uploadInstance.saveMapOfFilesChanged() - then: - uploadInstance.objSerializer.recoveryFileHashCode == uploadInstance.filesChanged - } - - def "Test should return an exception if there is a invalid folder" () { + def "Test should return an exception if there is a invalid folder"() { given: def foldersName = ['classes', 'invalid'] when: @@ -171,16 +132,16 @@ class UploadTest extends Specification { thrown(Exception) } - def "Test should return an exception if there is a invalid file" () { + def "Test should return an exception if there is a invalid file"() { given: - def filesName = ["classes${File.separator}Class1.txy","triggers${File.separator}TriggerOne.trigger"] + def filesName = ["classes${File.separator}Class1.txy", "triggers${File.separator}TriggerOne.trigger"] when: uploadInstance.validateFiles(filesName) then: thrown(Exception) } - def "Test should fill specificFilesToUpload with files sent" () { + def "Test should fill specificFilesToUpload with files sent"() { given: uploadInstance.files = "classes${File.separator}class1.cls,objects${File.separator}Object1__c.object" uploadInstance.projectPath = SRC_PATH @@ -193,7 +154,7 @@ class UploadTest extends Specification { uploadInstance.specificFilesToUpload.sort() == [classFile, objectFile, classFileXml].sort() } - def "Test should fill specificFilesToUpload with folders sent" () { + def "Test should fill specificFilesToUpload with folders sent"() { given: uploadInstance.files = 'classes,triggers' uploadInstance.projectPath = SRC_PATH @@ -207,7 +168,7 @@ class UploadTest extends Specification { uploadInstance.specificFilesToUpload.sort() == [classFile, triggerFile, classFileXml, triggerFileXml].sort() } - def "Test should fill specificFilesToUpload with folders and files sent" () { + def "Test should fill specificFilesToUpload with folders and files sent"() { given: uploadInstance.files = "classes,triggers${File.separator}LunesTrigger.trigger" uploadInstance.projectPath = SRC_PATH @@ -221,9 +182,9 @@ class UploadTest extends Specification { uploadInstance.specificFilesToUpload.sort() == [classFile, triggerFile, classFileXml, triggerFileXml].sort() } - def "Test should fill specificFilesToUpload array following a wildcard sent '*/class1.cls,objects/Object1__c.object' " () { + def "Test should fill specificFilesToUpload array following a wildcard sent '*/class1.cls,objects/Object1__c.object' "() { given: - uploadInstance.files ="*${File.separator}class1.cls,objects${File.separator}Object1__c.object" + uploadInstance.files = "*${File.separator}class1.cls,objects${File.separator}Object1__c.object" uploadInstance.projectPath = SRC_PATH when: uploadInstance.loadParameter() @@ -234,39 +195,39 @@ class UploadTest extends Specification { uploadInstance.specificFilesToUpload.sort() == [classFile, objectFile, classFileXml].sort() } - def "Test should fill specificFilesToUpload array following a wildcard sent 'objects/*.object' " () { + def "Test should fill specificFilesToUpload array following a wildcard sent 'objects/*.object' "() { given: - uploadInstance.files ="objects${File.separator}*.object" + uploadInstance.files = "objects${File.separator}*.object" uploadInstance.projectPath = SRC_PATH + new File(Paths.get(SRC_PATH, 'objects', 'object1.object').toString()) when: uploadInstance.loadParameter() then: uploadInstance.specificFilesToUpload.sort() == [new File(Paths.get(SRC_PATH, 'objects', 'Account.object').toString()), - new File(Paths.get(SRC_PATH, 'objects', 'object1.object').toString()), new File(Paths.get(SRC_PATH, 'objects', 'Object1__c.object').toString()), new File(Paths.get(SRC_PATH, 'objects', 'Object2__c.object').toString())].sort() } - def "Test should fill specificFilesToUpload array following a wildcard sent '**/*Account*/**' " () { + def "Test should fill specificFilesToUpload array following a wildcard sent '**/*Account*/**' "() { given: - uploadInstance.files ="**${File.separator}*Account*${File.separator}**" + uploadInstance.files = "**${File.separator}*Account*${File.separator}**" uploadInstance.projectPath = SRC_PATH when: uploadInstance.loadParameter() then: uploadInstance.specificFilesToUpload.sort() == [new File(Paths.get(SRC_PATH, 'objects', 'Account.object').toString()), - new File(Paths.get(SRC_PATH, 'src', 'objects', 'Account.object').toString())].sort() + new File(Paths.get(SRC_PATH, 'src', 'objects', 'Account.object').toString())].sort() } - def "Test should fill specificFilesToUpload array following a wildcard sent '**/*.cls' " () { + def "Test should fill specificFilesToUpload array following a wildcard sent '**/*.cls' "() { given: - uploadInstance.files ="**${File.separator}*.cls" + uploadInstance.files = "**${File.separator}*.cls" uploadInstance.projectPath = Paths.get(SRC_PATH, 'src').toString() when: uploadInstance.loadParameter() then: uploadInstance.specificFilesToUpload.sort() == [new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls').toString()), - new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls-meta.xml').toString())].sort() + new File(Paths.get(SRC_PATH, 'src', 'classes', 'Class1.cls-meta.xml').toString())].sort() } def cleanupSpec() { diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/.fileTracker.data b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/.fileTracker.data deleted file mode 100644 index 1a8bbee..0000000 Binary files a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/.fileTracker.data and /dev/null differ diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/objects/object1.object b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/objects/object1.object deleted file mode 100644 index e69de29..0000000 diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/src/.fileTracker.data b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/src/.fileTracker.data deleted file mode 100644 index 8467a25..0000000 Binary files a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/resources/src/.fileTracker.data and /dev/null differ diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/RetrieveTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/RetrieveTest.groovy index 7590a44..3421551 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/RetrieveTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/retrieve/RetrieveTest.groovy @@ -5,16 +5,16 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve +import org.custommonkey.xmlunit.Diff +import org.custommonkey.xmlunit.XMLUnit +import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.fundacionjala.gradle.plugins.enforce.credentialmanagement.CredentialManager import org.fundacionjala.gradle.plugins.enforce.undeploy.PackageComponent +import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType -import org.custommonkey.xmlunit.Diff -import org.custommonkey.xmlunit.XMLUnit import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder -import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin -import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile import spock.lang.Shared import java.nio.file.Paths diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTaskTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTaskTest.groovy index 240d089..7007c8a 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTaskTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/tasks/salesforce/unittest/RunTestTaskTest.groovy @@ -5,16 +5,15 @@ package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.unittest +import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import org.gradle.api.Project import org.gradle.api.Task import org.gradle.testfixtures.ProjectBuilder -import org.fundacionjala.gradle.plugins.enforce.EnforcePlugin import spock.lang.Shared import spock.lang.Specification import java.nio.file.Paths - class RunTestTaskTest extends Specification { static final RUN_TEST_TASK_NAME = "runTest" @Shared diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidatorTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidatorTest.groovy index 4e2bca9..4999245 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidatorTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/undeploy/SmartFilesValidatorTest.groovy @@ -30,8 +30,8 @@ class SmartFilesValidatorTest extends Specification { def "Test should create a json format since string" () { given: - def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1"},{"Name" : "Class2"}]""" - def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1"},{"Name" : "Trigger2"}]""" + def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1","attributes":{"type":"ApexClass"}},{"Name" : "Class2", "attributes":{"type":"ApexClass"}}]""" + def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1", "attributes":{"type":"Trigger"}},{"Name" : "Trigger2", "attributes":{"type":"Trigger"}}]""" def jsonArrays = new ArrayList() jsonArrays.push(jsonString1) jsonArrays.push(jsonString2) @@ -43,8 +43,8 @@ class SmartFilesValidatorTest extends Specification { def "Test should fill a map with thw files on org" () { given: - def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1"},{"Name" : "Class2"}]""" - def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1"},{"Name" : "Trigger2"}]""" + def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1","attributes":{"type":"ApexClass"}},{"Name" : "Class2", "attributes":{"type":"ApexClass"}}]""" + def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1", "attributes":{"type":"ApexTrigger"}},{"Name" : "Trigger2", "attributes":{"type":"ApexTrigger"}}]""" def jsonArrays = new ArrayList() jsonArrays.push(jsonString1) jsonArrays.push(jsonString2) @@ -57,8 +57,8 @@ class SmartFilesValidatorTest extends Specification { def "Test should return only files that exist in organization" () { given: - def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1"},{"Name" : "Class2"}]""" - def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1"},{"Name" : "Trigger2"}]""" + def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1","attributes":{"type":"ApexClass"}},{"Name" : "Class2", "attributes":{"type":"ApexClass"}}]""" + def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1", "attributes":{"type":"ApexTrigger"}},{"Name" : "Trigger2", "attributes":{"type":"ApexTrigger"}}]""" def jsonArrays = new ArrayList() jsonArrays.push(jsonString1) jsonArrays.push(jsonString2) @@ -79,9 +79,9 @@ class SmartFilesValidatorTest extends Specification { def "Test should verify if profile is accepted" () { given: - def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1"},{"Name" : "Class2"}]""" - def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1"},{"Name" : "Trigger2"}]""" - def jsonString3 = """{"entityTypeName":"Profile","records": [{"Name" : "Profile__custom"}]""" + def jsonString1 = """{"entityTypeName":"ApexClass","records": [{"Name" : "Class1","attributes":{"type":"ApexClass"}},{"Name" : "Class2", "attributes":{"type":"ApexClass"}}]""" + def jsonString2 = """{"entityTypeName":"ApexTrigger","records": [{"Name" : "Trigger1", "attributes":{"type":"ApexTrigger"}},{"Name" : "Trigger2", "attributes":{"type":"ApexTrigger"}}]""" + def jsonString3 = """{"entityTypeName":"Profile","records": [{"Name" : "Profile__custom", "attributes":{"type":"Profile"}}]""" def jsonArrays = new ArrayList() jsonArrays.push(jsonString1) jsonArrays.push(jsonString2) diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReportTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReportTest.groovy index d0936c0..ab4b703 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReportTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/TestResultReportTest.groovy @@ -5,10 +5,10 @@ package org.fundacionjala.gradle.plugins.enforce.unittest -import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult -import org.fundacionjala.gradle.plugins.enforce.unittest.coverage.Component import org.custommonkey.xmlunit.Diff import org.custommonkey.xmlunit.XMLUnit +import org.fundacionjala.gradle.plugins.enforce.unittest.Apex.ApexRunTestResult +import org.fundacionjala.gradle.plugins.enforce.unittest.coverage.Component import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/htmlManagerTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManagerTest.groovy similarity index 100% rename from src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/htmlManagerTest.groovy rename to src/test/groovy/org/fundacionjala/gradle/plugins/enforce/unittest/report/HtmlManagerTest.groovy diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/UtilTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/UtilTest.groovy index f8379c6..179f4bf 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/UtilTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/UtilTest.groovy @@ -134,6 +134,20 @@ class UtilTest extends Specification { macAddress.size() == 12 } + def "Test should get developerName from a fullName" () { + when: + def developerName = Util.getDeveloperName('TwilioConfig__c.AuthTokenAPI__c.sbc') + then: + developerName == 'AuthTokenAPI' + } + + def "Test should get developerName from a member" () { + when: + def developerName = Util.getDeveloperNameByMember('TwilioConfig__c.AuthTokenAPI__c') + then: + developerName == 'AuthTokenAPI' + } + def cleanupSpec() { new File(Paths.get(resourcesPath, 'triggers').toString()).deleteDir() } diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponentsTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponentsTest.groovy index 91ad034..b66de5c 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponentsTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/MetadataComponentsTest.groovy @@ -64,10 +64,17 @@ class MetadataComponentsTest extends Specification { def "Test enum name is equals to directory name"() { expect: MetadataComponents.COMPONENT.each {key, value-> - assert key == value.directory.toUpperCase() + if(value.extension != 'sbc') { + assert key == value.directory.toUpperCase() + } } } + def "Test get a CustomPermission extension"() { + expect: + MetadataComponents.getComponent("customPermissions").getExtension() == "customPermission" + } + def "Test a component by folder"() { expect: MetadataComponents.getComponentByFolder("classes").typeName == "ApexClass" diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGeneratorTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGeneratorTest.groovy new file mode 100644 index 0000000..abdfbe2 --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/salesforce/PackageGeneratorTest.groovy @@ -0,0 +1,177 @@ +package org.fundacionjala.gradle.plugins.enforce.utils.salesforce + +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentMonitor +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ComponentStates +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ObjectResultTracker +import org.fundacionjala.gradle.plugins.enforce.filemonitor.ResultTracker +import org.fundacionjala.gradle.plugins.enforce.undeploy.SmartFilesValidator +import spock.lang.Shared +import spock.lang.Specification + +class PackageGeneratorTest extends Specification { + @Shared + String ROOT_PATH = System.properties['user.dir'] + + @Shared + String RESOURCE_PATH = "${ROOT_PATH}/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/utils/resources" + + def "Test should build a package from new and changed files"() { + given: + PackageGenerator packageGenerator = new PackageGenerator() + Map fileTrackerMap = [:] + def newFilePath1 = "classes/File.cls" + def newFilePath2 = "classes/Util.cls" + def newFilePath3 = "objects/ObjectFile.object" + def newFilePath4 = "objects/ObjectUtil.object" + fileTrackerMap.put(newFilePath1, new ResultTracker(ComponentStates.ADDED)) + fileTrackerMap.put(newFilePath2, new ResultTracker(ComponentStates.CHANGED)) + fileTrackerMap.put(newFilePath3, new ObjectResultTracker(ComponentStates.ADDED)) + fileTrackerMap.put(newFilePath4, new ObjectResultTracker(ComponentStates.CHANGED)) + packageGenerator.fileTrackerMap = fileTrackerMap + def stringWriter = new StringWriter() + when: + packageGenerator.buildPackage(stringWriter) + then: + packageGenerator.packageBuilder.metaPackage.types[0].members[0] == "File" + packageGenerator.packageBuilder.metaPackage.types[0].members[1] == "Util" + packageGenerator.packageBuilder.metaPackage.types[0].name == "ApexClass" + packageGenerator.packageBuilder.metaPackage.types[1].members[0] == "ObjectFile" + packageGenerator.packageBuilder.metaPackage.types[1].members[1] == "ObjectUtil" + packageGenerator.packageBuilder.metaPackage.types[1].name == "CustomObject" + } + + def "Test should get the subcomponentes according to status field"() { + given: + PackageGenerator packageGenerator = new PackageGenerator() + packageGenerator.componentMonitor = Mock(ComponentMonitor) + + def newFilePathObject1 = "objects/ObjectFile.object" + def newFilePathObject2 = "objects/ObjectUtil.object" + + Map subComponentResult1 = [:] + subComponentResult1.put("fields/fieldOne",ComponentStates.CHANGED) + subComponentResult1.put("fields/fieldTwo",ComponentStates.ADDED) + subComponentResult1.put("fields/fieldThree",ComponentStates.CHANGED) + + ObjectResultTracker objectResultTracker1 = new ObjectResultTracker(ComponentStates.CHANGED) + objectResultTracker1.subComponentsResult = subComponentResult1; + + Map subComponentResult2 = [:] + subComponentResult2.put("fields/fieldFour",ComponentStates.CHANGED) + subComponentResult2.put("fields/fieldFive",ComponentStates.ADDED) + + ObjectResultTracker objectResultTracker2 = new ObjectResultTracker(ComponentStates.CHANGED) + objectResultTracker2.subComponentsResult = subComponentResult2 + + Map fileTrackerMap = [:] + fileTrackerMap.put(newFilePathObject1,objectResultTracker1) + fileTrackerMap.put(newFilePathObject2,objectResultTracker2) + + packageGenerator.fileTrackerMap = fileTrackerMap + + when: + def fieldsAdded = packageGenerator.getSubComponents(ComponentStates.ADDED) + def fieldsChanged = packageGenerator.getSubComponents(ComponentStates.CHANGED) + + then: + fieldsAdded[0].name == "ObjectFile.fieldTwo.sbc" + fieldsAdded[1].name == "ObjectUtil.fieldFive.sbc" + + fieldsChanged[0].name == "ObjectFile.fieldOne.sbc" + fieldsChanged[1].name == "ObjectFile.fieldThree.sbc" + fieldsChanged[2].name == "ObjectUtil.fieldFour.sbc" + } + + def "Test should build a package for subcomponents"() { + given: + PackageGenerator packageGenerator = new PackageGenerator() + Map fileTrackerMap = [:] + def newFilePathAdded = "classes/File.cls" + def newFilePathAdded2 = "classes/Util.cls" + def newObjectPathChanged = "objects/ObjectFile.object" + def newObjectPathAdded = "objects/ObjectUtil.object" + fileTrackerMap.put(newFilePathAdded, new ResultTracker(ComponentStates.ADDED)) + fileTrackerMap.put(newFilePathAdded2, new ResultTracker(ComponentStates.CHANGED)) + + Map subComponentResult = [:] + subComponentResult.put("fields/fieldOne",ComponentStates.CHANGED) + subComponentResult.put("fields/fieldTwo",ComponentStates.ADDED) + subComponentResult.put("fields/fieldThree",ComponentStates.CHANGED) + + ObjectResultTracker objectResultTrackerChanged = new ObjectResultTracker(ComponentStates.CHANGED) + objectResultTrackerChanged.subComponentsResult = subComponentResult + fileTrackerMap.put(newObjectPathChanged, objectResultTrackerChanged) + fileTrackerMap.put(newObjectPathAdded , new ObjectResultTracker(ComponentStates.ADDED)) + + packageGenerator.fileTrackerMap = fileTrackerMap + def stringWriter = new StringWriter() + + when: + packageGenerator.buildPackage(stringWriter) + + then: + packageGenerator.packageBuilder.metaPackage.types[0].members[0] == "File" + packageGenerator.packageBuilder.metaPackage.types[0].members[1] == "Util" + packageGenerator.packageBuilder.metaPackage.types[0].name == "ApexClass" + packageGenerator.packageBuilder.metaPackage.types[1].members[0] == "ObjectUtil" + packageGenerator.packageBuilder.metaPackage.types[1].members[1] == "ObjectFile" + packageGenerator.packageBuilder.metaPackage.types[1].name == "CustomObject" + + packageGenerator.packageBuilder.metaPackage.types[2].members[0] == "ObjectFile.fieldTwo" + packageGenerator.packageBuilder.metaPackage.types[2].members[1] == "ObjectFile.fieldOne" + packageGenerator.packageBuilder.metaPackage.types[2].members[2] == "ObjectFile.fieldThree" + packageGenerator.packageBuilder.metaPackage.types[2].name == "CustomField" + } + + def "Test should build a package from deleted files"() { + given: + PackageGenerator packageGenerator = new PackageGenerator() + SmartFilesValidator smartFilesValidator = Mock(SmartFilesValidator) + + Map subComponentResult = [:] + subComponentResult.put("fields/fieldOne",ComponentStates.DELETED) + subComponentResult.put("fields/fieldTwo",ComponentStates.DELETED) + + + ObjectResultTracker objectResultTracker = new ObjectResultTracker(ComponentStates.CHANGED); + objectResultTracker.subComponentsResult = subComponentResult; + + def newFilePath = "classes/File.cls" + def newObjectPathChanged = "objects/ObjectFileChanged.object" + def newObjectPathDeleted = "objects/ObjectFileDeleted.object" + Map fileTrackerMap = [:] + fileTrackerMap.put(newFilePath, new ResultTracker(ComponentStates.DELETED)) + fileTrackerMap.put(newObjectPathDeleted, new ResultTracker(ComponentStates.DELETED)) + fileTrackerMap.put(newObjectPathChanged, objectResultTracker) + packageGenerator.fileTrackerMap = fileTrackerMap + smartFilesValidator.filterFilesAccordingOrganization(_) >> packageGenerator.getFiles(ComponentStates.DELETED) + packageGenerator.getSubComponents(ComponentStates.DELETED) + def stringWriter = new StringWriter() + + when: + packageGenerator.buildDestructive(stringWriter, smartFilesValidator) + + then: + packageGenerator.packageBuilder.metaPackage.types[0].members[0] == "File" + packageGenerator.packageBuilder.metaPackage.types[0].name == "ApexClass" + packageGenerator.packageBuilder.metaPackage.types[1].members[0] == "ObjectFileDeleted" + packageGenerator.packageBuilder.metaPackage.types[1].name == "CustomObject" + + packageGenerator.packageBuilder.metaPackage.types[2].members[0] == "ObjectFileChanged.fieldOne" + packageGenerator.packageBuilder.metaPackage.types[2].members[1] == "ObjectFileChanged.fieldTwo" + packageGenerator.packageBuilder.metaPackage.types[2].name == "CustomField" + + } + + def "Test should exclude a file called Class1.cls from fileTrackerMap"() { + given: + PackageGenerator packageGenerator = new PackageGenerator() + Map fileTrackerMap = ['classes/Class1.cls': new ResultTracker(ComponentStates.ADDED), + 'classes/Class2.cls': new ResultTracker(ComponentStates.CHANGED)] + packageGenerator.fileTrackerMap = fileTrackerMap + ArrayList files = [new File('classes/Class2.cls')] + when: + ArrayList result = packageGenerator.excludeFiles(files) + then: + result == [new File('classes/Class1.cls')] + } +} diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/resources/packageWithFields.xml b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/resources/packageWithFields.xml new file mode 100644 index 0000000..25cffac --- /dev/null +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/resources/packageWithFields.xml @@ -0,0 +1,18 @@ + + + * + ApexClass + + + Component1__c.component + Component2__c.component + ApexComponent + + + Object5__c.Field11__c + Object5__c.Field22__c + Object5__c.Field33__c + CustomField + + 32.0 + diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilderTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilderTest.groovy index 12b92de..3f1c62a 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilderTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/rest/QueryBuilderTest.groovy @@ -42,8 +42,30 @@ class QueryBuilderTest extends Specification { def packagePath = Paths.get(wscPath, 'resources', 'packageTest.xml').toString() when: def componentsObtained = queryBuilder.getComponents(new FileReader(packagePath)) + def componentsName = new ArrayList() + componentsObtained.each { component -> + componentsName.add(component.name) + } + componentsName = componentsName.sort() then: - componentsObtained.sort() == ['ApexClass', 'ApexComponent', 'ApexPage', 'ApexTrigger', 'CustomObject', 'StaticResource'].sort() + componentsName.get(0) == 'ApexClass' + componentsName.get(1) == 'ApexComponent' + componentsName.get(2) == 'ApexPage' + componentsName.get(3) == 'ApexTrigger' + componentsName.get(4) == 'CustomObject' + componentsName.get(5) == 'StaticResource' + } + + def "Test should return an array with queries that have fields" () { + given: + def packagePath = Paths.get(wscPath, 'resources', 'packageWithFields.xml').toString() + when: + def queries = queryBuilder.createQueryFromPackage(packagePath) + then: + queries.sort() == ['SELECT Name FROM ApexClass', 'SELECT Name FROM ApexComponent', + "${'SELECT FullName FROM CustomField WHERE DeveloperName = '}${"'Field11'"}", + "${'SELECT FullName FROM CustomField WHERE DeveloperName = '}${"'Field22'"}", + "${'SELECT FullName FROM CustomField WHERE DeveloperName = '}${"'Field33'"}",].sort() } def "Test should return an array with queries" () { diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexApiTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexApiTest.groovy index f2061c1..1e77103 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexApiTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/ApexApiTest.groovy @@ -5,7 +5,6 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.soap -import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import com.sforce.soap.apex.DebuggingInfo_element import com.sforce.soap.apex.ExecuteAnonymousResult import com.sforce.soap.apex.SoapConnection @@ -15,6 +14,7 @@ import com.sforce.soap.partner.PartnerConnection import org.fundacionjala.gradle.plugins.enforce.wsc.Connector import org.fundacionjala.gradle.plugins.enforce.wsc.Credential import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI +import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import spock.lang.Shared import spock.lang.Specification diff --git a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataApiTest.groovy b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataApiTest.groovy index 0ff1f4c..b6bfba1 100644 --- a/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataApiTest.groovy +++ b/src/test/groovy/org/fundacionjala/gradle/plugins/enforce/wsc/soap/MetadataApiTest.groovy @@ -5,18 +5,18 @@ package org.fundacionjala.gradle.plugins.enforce.wsc.soap -import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.DeployException -import org.fundacionjala.gradle.plugins.enforce.wsc.Credential -import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI -import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import com.sforce.soap.metadata.DeployDetails import com.sforce.soap.metadata.DeployMessage import com.sforce.soap.metadata.DeployResult import com.sforce.soap.partner.GetUserInfoResult import com.sforce.soap.partner.LoginResult import com.sforce.soap.partner.PartnerConnection +import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.DeployException import org.fundacionjala.gradle.plugins.enforce.exceptions.deploy.InfoDeploy import org.fundacionjala.gradle.plugins.enforce.wsc.Connector +import org.fundacionjala.gradle.plugins.enforce.wsc.Credential +import org.fundacionjala.gradle.plugins.enforce.wsc.ForceAPI +import org.fundacionjala.gradle.plugins.enforce.wsc.LoginType import spock.lang.Shared import spock.lang.Specification