From 734ddbae7a220d6ccc7616a900fd5359fffa3577 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Fri, 18 Nov 2022 10:34:59 +0000 Subject: [PATCH 01/28] #291 initial commit --- copado-function/app/Init.fn.js | 47 +++++++--- copado-function/app/common/Util.js | 6 +- copado-function/app/config/Init.config | 20 +++++ copado-function/dist/Commit.fn.js | 14 +-- copado-function/dist/Deploy.fn.js | 26 +++--- copado-function/dist/Init.fn.js | 53 ++++++++---- copado-function/dist/Retrieve.fn.js | 12 +-- copado-function/docs/documentation.md | 113 +++++++------------------ 8 files changed, 151 insertions(+), 140 deletions(-) create mode 100644 copado-function/app/config/Init.config diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index c2e7ccb..0246018 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -7,16 +7,22 @@ const Util = require('./common/Util'); const Copado = require('./common/Copado'); // credentials -CONFIG.credentialNameSource = process.env.credentialNameSource; +CONFIG.credentialNameSource = process.env.credentialName; CONFIG.credentialNameTarget = null; -CONFIG.credentials = process.env.credentials; +CONFIG.client_id = process.env.client_id; +CONFIG.client_secret = process.env.client_secret; +CONFIG.auth_url = process.env.auth_url; +CONFIG.account_id = process.env.account_id; +CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; +CONFIG.gitEmail = process.env.gitEmail; + // generic CONFIG.configFilePath = null; CONFIG.repoUrl = process.env.repoUrl; CONFIG.debug = process.env.debug === 'true' ? true : false; CONFIG.installMcdevLocally = process.env.installMcdevLocally === 'true' ? true : false; CONFIG.mainBranch = null; -CONFIG.mcdevVersion = null; +CONFIG.mcdevVersion = process.env.mcdev_version; // this will only be needed if installMcdevLocally=true CONFIG.metadataFilePath = null; // do not change - LWC depends on it! // not needed in this case, previous value: 'mcmetadata.json' CONFIG.source_mid = null; CONFIG.tmpDirectory = '../tmp'; @@ -54,10 +60,19 @@ async function run() { Log.debug(''); Log.debug('Parameters'); Log.debug('==================='); + // if one of the elements present in the array are undefined, this error will be triggered + if ([CONFIG.client_id, CONFIG.client_secret, CONFIG.auth_url, CONFIG.account_id].includes()) { + Log.error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + throw new Error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + } try { CONFIG.credentials = JSON.parse(CONFIG.credentials); } catch (ex) { - Log.error('Could not parse credentials'); + Log.error(`Could not parse credentials: ${CONFIG.credentials}`); throw ex; } Log.debug(CONFIG); @@ -80,20 +95,28 @@ async function run() { Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); // prevent git errors down the road try { - Util.execCommand(null, ['git config --global --add safe.directory /tmp']); + Util.execCommand(null, [ + 'git config --global --add safe.directory ' + resolve(CONFIG.tmpDirectory), + ]); } catch { - try { - Util.execCommand(null, [ - 'git config --global --add safe.directory ' + resolve(CONFIG.tmpDirectory), - ]); - } catch { - Log.error('Could not set tmp directoy as safe directory'); - } + Log.error('Could not set tmp directoy as safe directory'); } + // actually change working directory process.chdir(CONFIG.tmpDirectory); Log.debug(process.cwd()); + try { + Log.info(''); + Log.info('Adding git email'); + Log.info('==================='); + Util.execCommand(null, [`git config --global user.email "${CONFIG.gitEmail}"`]); + Log.info(''); + } catch (ex) { + Log.error('adding git email failed: ' + ex.message); + throw ex; + } + try { Log.info(''); Log.info('Preparing'); diff --git a/copado-function/app/common/Util.js b/copado-function/app/common/Util.js index b0837d9..3ae95f8 100644 --- a/copado-function/app/common/Util.js +++ b/copado-function/app/common/Util.js @@ -127,13 +127,13 @@ class Util { 'Completed installing Accenture SFMC DevTools' ); return; // we're done here + } else if (!CONFIG.mcdevVersion) { + Log.error('Please specify mcdev_version in pipeline & environment settings'); + throw new Error('Please specify mcdev_version in pipeline & environment settings'); } else if (CONFIG.mcdevVersion.charAt(0) === '#') { // assume branch of mcdev's git repo shall be loaded installer = `accenture/sfmc-devtools${CONFIG.mcdevVersion}`; - } else if (!CONFIG.mcdevVersion) { - Log.error('Please specify mcdev_version in pipeline & environment settings'); - throw new Error('Please specify mcdev_version in pipeline & environment settings'); } else { // default, install via npm at specified version installer = `mcdev@${CONFIG.mcdevVersion}`; diff --git a/copado-function/app/config/Init.config b/copado-function/app/config/Init.config new file mode 100644 index 0000000..ec58998 --- /dev/null +++ b/copado-function/app/config/Init.config @@ -0,0 +1,20 @@ +# Details +* [Function Name] (Marketing Cloud Init) +* [API Name] (MC_Init) +* [Type] (Custom) +* [Description] (Initializes mcdev in an empty Marketing Cloud Repository) + +# Configuration +* [Image name] (0onz6fxsbyolcopmojdzlxa5vzgsts-sfmc-devtools:v1.0) (backup:copado-multicloud-git-utils:v1) +* [Timeout] (10) +* [Worker Size] (S) + +# Parameters needs to be configured for Marketing Cloud init function +* credentialName ({...}) // por o nome? +* client_id ({...}) // não sei onde por ainda +* client_secret ({...}) // não sei onde por ainda +* auth_url ({...}) // não sei onde por ainda +* account_id ({...}) // não sei onde por ainda +* repoUrl ({...}) // não sei onde por ainda +* [debug] ({...}) // não sei onde por ainda +* [installMcdevLocally] ({...}) // não sei onde por ainda \ No newline at end of file diff --git a/copado-function/dist/Commit.fn.js b/copado-function/dist/Commit.fn.js index 4a77f84..e3e2626 100644 --- a/copado-function/dist/Commit.fn.js +++ b/copado-function/dist/Commit.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-16T10:43:40.729Z) + * mcdev-copado v1.1.2 (built 2022-11-18T10:11:13.474Z) * Function: Commit.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -78,7 +78,7 @@ var require_Util = __commonJS({ "use strict"; var fs = require("fs"); var execSync = require("child_process").execSync; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = class { @@ -150,11 +150,11 @@ var require_Util = __commonJS({ "Completed installing Accenture SFMC DevTools" ); return; - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else if (!CONFIG2.mcdevVersion) { Log2.error("Please specify mcdev_version in pipeline & environment settings"); throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else { installer = `mcdev@${CONFIG2.mcdevVersion}`; } @@ -246,7 +246,7 @@ var require_Copado = __commonJS({ "use strict"; var fs = require("fs"); var exec = require("child_process").exec; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { @@ -344,7 +344,7 @@ var require_Commit = __commonJS({ "use strict"; var fs = require("fs"); var execSync = require("child_process").execSync; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = require_Util(); @@ -422,7 +422,7 @@ var require_Commit = __commonJS({ // Commit.fn.js var resolve = require("path").resolve; -var TYPES = require_mcdev_copado_d(); +var TYPE = require_mcdev_copado_d(); var CONFIG = require_Config(); var Log = require_Log(); var Util = require_Util(); diff --git a/copado-function/dist/Deploy.fn.js b/copado-function/dist/Deploy.fn.js index 061f1c4..88ba981 100644 --- a/copado-function/dist/Deploy.fn.js +++ b/copado-function/dist/Deploy.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-16T10:43:40.773Z) + * mcdev-copado v1.1.2 (built 2022-11-18T10:11:13.522Z) * Function: Deploy.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -78,7 +78,7 @@ var require_Util = __commonJS({ "use strict"; var fs2 = require("fs"); var execSync2 = require("child_process").execSync; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = class { @@ -150,11 +150,11 @@ var require_Util = __commonJS({ "Completed installing Accenture SFMC DevTools" ); return; - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else if (!CONFIG2.mcdevVersion) { Log2.error("Please specify mcdev_version in pipeline & environment settings"); throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else { installer = `mcdev@${CONFIG2.mcdevVersion}`; } @@ -246,7 +246,7 @@ var require_Copado = __commonJS({ "use strict"; var fs2 = require("fs"); var exec = require("child_process").exec; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { @@ -344,7 +344,7 @@ var require_Commit = __commonJS({ "use strict"; var fs2 = require("fs"); var execSync2 = require("child_process").execSync; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = require_Util(); @@ -424,7 +424,7 @@ var require_Commit = __commonJS({ var fs = require("fs"); var execSync = require("child_process").execSync; var resolve = require("path").resolve; -var TYPES = require_mcdev_copado_d(); +var TYPE = require_mcdev_copado_d(); var CONFIG = require_Config(); var Log = require_Log(); var Util = require_Util(); @@ -811,12 +811,12 @@ var Deploy = class { config.marketList[deploySourceList][sourceBU] = "source"; config.marketList[deployTargetList][targetBU] = "target"; } - console.log( - "config.options.deployment.sourceTargetMapping", - config.options.deployment.sourceTargetMapping - ); - console.log("config.markets", config.markets); - console.log("config.marketList", JSON.stringify(config.marketList)); + Log.debug("config.options.deployment.sourceTargetMapping"); + Log.debug(config.options.deployment.sourceTargetMapping); + Log.debug("config.markets"); + Log.debug(config.markets); + Log.debug("config.marketList"); + Log.debug(JSON.stringify(config.marketList)); try { fs.renameSync(CONFIG.configFilePath, CONFIG.configFilePath + ".BAK"); Util.saveJsonFile(CONFIG.configFilePath, config, "utf8"); diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 02aafc0..34ebb27 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-16T15:41:41.002Z) + * mcdev-copado v1.1.2 (built 2022-11-18T10:11:13.569Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -78,7 +78,7 @@ var require_Util = __commonJS({ "use strict"; var fs = require("fs"); var execSync = require("child_process").execSync; - var TYPES = require_mcdev_copado_d(); + var TYPE = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = class { @@ -150,11 +150,11 @@ var require_Util = __commonJS({ "Completed installing Accenture SFMC DevTools" ); return; - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else if (!CONFIG2.mcdevVersion) { Log2.error("Please specify mcdev_version in pipeline & environment settings"); throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else { installer = `mcdev@${CONFIG2.mcdevVersion}`; } @@ -246,7 +246,7 @@ var require_Copado = __commonJS({ "use strict"; var fs = require("fs"); var exec = require("child_process").exec; - var TYPES = require_mcdev_copado_d(); + var TYPE = require_mcdev_copado_d(); var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { @@ -344,15 +344,20 @@ var CONFIG = require_Config(); var Log = require_Log(); var Util = require_Util(); var Copado = require_Copado(); -CONFIG.credentialNameSource = process.env.credentialNameSource; +CONFIG.credentialNameSource = process.env.credentialName; CONFIG.credentialNameTarget = null; -CONFIG.credentials = process.env.credentials; +CONFIG.client_id = process.env.client_id; +CONFIG.client_secret = process.env.client_secret; +CONFIG.auth_url = process.env.auth_url; +CONFIG.account_id = process.env.account_id; +CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; +CONFIG.gitEmail = process.env.gitEmail; CONFIG.configFilePath = null; CONFIG.repoUrl = process.env.repoUrl; CONFIG.debug = process.env.debug === "true" ? true : false; CONFIG.installMcdevLocally = process.env.installMcdevLocally === "true" ? true : false; CONFIG.mainBranch = null; -CONFIG.mcdevVersion = null; +CONFIG.mcdevVersion = process.env.mcdev_version; CONFIG.metadataFilePath = null; CONFIG.source_mid = null; CONFIG.tmpDirectory = "../tmp"; @@ -381,10 +386,18 @@ async function run() { Log.debug(""); Log.debug("Parameters"); Log.debug("==================="); + if ([CONFIG.client_id, CONFIG.client_secret, CONFIG.auth_url, CONFIG.account_id].includes()) { + Log.error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + throw new Error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + } try { CONFIG.credentials = JSON.parse(CONFIG.credentials); } catch (ex) { - Log.error("Could not parse credentials"); + Log.error(`Could not parse credentials: ${CONFIG.credentials}`); throw ex; } Log.debug(CONFIG); @@ -402,18 +415,24 @@ async function run() { } Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); try { - Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + Util.execCommand(null, [ + "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) + ]); } catch { - try { - Util.execCommand(null, [ - "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) - ]); - } catch { - Log.error("Could not set tmp directoy as safe directory"); - } + Log.error("Could not set tmp directoy as safe directory"); } process.chdir(CONFIG.tmpDirectory); Log.debug(process.cwd()); + try { + Log.info(""); + Log.info("Adding git email"); + Log.info("==================="); + Util.execCommand(null, [`git config --global user.email "${CONFIG.gitEmail}"`]); + Log.info(""); + } catch (ex) { + Log.error("adding git email failed: " + ex.message); + throw ex; + } try { Log.info(""); Log.info("Preparing"); diff --git a/copado-function/dist/Retrieve.fn.js b/copado-function/dist/Retrieve.fn.js index 05e940d..c567df7 100644 --- a/copado-function/dist/Retrieve.fn.js +++ b/copado-function/dist/Retrieve.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-16T10:43:39.840Z) + * mcdev-copado v1.1.2 (built 2022-11-18T10:11:12.296Z) * Function: Retrieve.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -79,7 +79,7 @@ var require_Util = __commonJS({ "use strict"; var fs2 = require("fs"); var execSync = require("child_process").execSync; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var CONFIG2 = require_Config(); var Log2 = require_Log(); var Util2 = class { @@ -151,11 +151,11 @@ var require_Util = __commonJS({ "Completed installing Accenture SFMC DevTools" ); return; - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else if (!CONFIG2.mcdevVersion) { Log2.error("Please specify mcdev_version in pipeline & environment settings"); throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; } else { installer = `mcdev@${CONFIG2.mcdevVersion}`; } @@ -247,7 +247,7 @@ var require_Copado = __commonJS({ "use strict"; var fs2 = require("fs"); var exec = require("child_process").exec; - var TYPES2 = require_mcdev_copado_d(); + var TYPE2 = require_mcdev_copado_d(); var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { @@ -342,7 +342,7 @@ var require_Copado = __commonJS({ // Retrieve.fn.js var fs = require("fs"); var resolve = require("path").resolve; -var TYPES = require_mcdev_copado_d(); +var TYPE = require_mcdev_copado_d(); var CONFIG = require_Config(); var Log = require_Log(); var Util = require_Util(); diff --git a/copado-function/docs/documentation.md b/copado-function/docs/documentation.md index 55c000f..400f651 100644 --- a/copado-function/docs/documentation.md +++ b/copado-function/docs/documentation.md @@ -41,12 +41,6 @@ ## Typedefs
-
MetadataItem : object
-
-
EnvChildVar : object
-
-
CommitSelection : object
-
EnvChildVar : object
CommitSelection : object
@@ -67,7 +61,7 @@ handles downloading metadata * [.retrieveAndCommit(targetBU, commitSelectionArr)](#Deploy.retrieveAndCommit) ⇒ Array.<string> * [.commit([commitMsgLines])](#Deploy.commit) ⇒ Array.<string> * [.getCommitMessage(targetBU, commitSelectionArr)](#Deploy.getCommitMessage) ⇒ Array.<string> - * [._convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU)](#Deploy._convertCommitToDeltaPkgItems) ⇒ Array.<TYPES.DeltaPkgItem> + * [._convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU)](#Deploy._convertCommitToDeltaPkgItems) ⇒ Array.<TYPE.DeltaPkgItem> * [.getDeployFolder()](#Deploy.getDeployFolder) ⇒ string * [.updateMarketLists(sourceBU, targetBU, marketVariables)](#Deploy.updateMarketLists) ⇒ void * [.createDeltaPackage(deployFolder, commitSelectionArr, sourceBU)](#Deploy.createDeltaPackage) ⇒ Promise.<boolean> @@ -88,7 +82,7 @@ retrieve the new values into the targets folder so it can be commited later. | Param | Type | Description | | --- | --- | --- | | targetBU | string | buname of source BU | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of committed components based on user selection | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of committed components based on user selection | @@ -113,19 +107,19 @@ helper for Deploy.retrieveAndCommit that creates a multi-line commit msg | Param | Type | Description | | --- | --- | --- | | targetBU | string | name of BU we deployed to incl. credential name | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of committed components based on user selection | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of committed components based on user selection | -### Deploy.\_convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU) ⇒ Array.<TYPES.DeltaPkgItem> +### Deploy.\_convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU) ⇒ Array.<TYPE.DeltaPkgItem> convert CommitSelection[] to DeltaPkgItem[] **Kind**: static method of [Deploy](#Deploy) -**Returns**: Array.<TYPES.DeltaPkgItem> - format required by mcdev.createDeltaPkg +**Returns**: Array.<TYPE.DeltaPkgItem> - format required by mcdev.createDeltaPkg | Param | Type | Description | | --- | --- | --- | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of committed components based on user selection | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of committed components based on user selection | | sourceBU | string | buname of source BU | @@ -158,7 +152,7 @@ return whether the delta package is empty or not | Param | Type | Description | | --- | --- | --- | | deployFolder | string | path | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of committed components based on user selection | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of committed components based on user selection | | sourceBU | string | buname of source BU | @@ -197,7 +191,7 @@ In case of errors, the deployment is not stopped. | Param | Type | Description | | --- | --- | --- | | bu | string | name of BU | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of committed components based on user selection | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of committed components based on user selection | | deployResult | object | result of deployment | @@ -221,7 +215,7 @@ applies market values of target onto name and key of commitSelectionArr | Param | Type | Description | | --- | --- | --- | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of items to be added | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of items to be added | @@ -281,7 +275,7 @@ sure we have only components that really exist in the BU. | Param | Type | Description | | --- | --- | --- | | sourceBU | string | specific subfolder for downloads | -| commitSelectionArr | Array.<TYPES.CommitSelection> | list of items to be added | +| commitSelectionArr | Array.<TYPE.CommitSelection> | list of items to be added | @@ -318,7 +312,7 @@ methods to handle interaction with the copado platform * [.attachJson(localPath, [parentSfid], [async], [preMsg])](#Copado.attachJson) ⇒ void * [.attachLog(localPath)](#Copado.attachLog) ⇒ Promise.<void> * [._downloadFile(fileSFID, [preMsg])](#Copado._downloadFile) ⇒ void - * [.getJsonFile(fileSFID, fileName, [preMsg])](#Copado.getJsonFile) ⇒ Array.<TYPES.CommitSelection> + * [.getJsonFile(fileSFID, fileName, [preMsg])](#Copado.getJsonFile) ⇒ Array.<TYPE.CommitSelection> * [.checkoutSrc(workingBranch, [createBranch])](#Copado.checkoutSrc) ⇒ void * [.deleteBranch(featureBranch)](#Copado.deleteBranch) ⇒ void * [.uploadToolLogs()](#Copado.uploadToolLogs) ⇒ Promise.<void> @@ -374,11 +368,11 @@ download file to CWD with the name that was stored in Salesforce -### Copado.getJsonFile(fileSFID, fileName, [preMsg]) ⇒ Array.<TYPES.CommitSelection> +### Copado.getJsonFile(fileSFID, fileName, [preMsg]) ⇒ Array.<TYPE.CommitSelection> downloads & parses JSON file from Salesforce **Kind**: static method of [Copado](#Copado) -**Returns**: Array.<TYPES.CommitSelection> - commitSelectionArr +**Returns**: Array.<TYPE.CommitSelection> - commitSelectionArr | Param | Type | Description | | --- | --- | --- | @@ -616,7 +610,7 @@ helper that converts the copado-internal format for "environment variables" into | Param | Type | Description | | --- | --- | --- | -| envVarArr | Array.<TYPES.EnvVar> | - | +| envVarArr | Array.<TYPE.EnvVar> | - | @@ -628,7 +622,7 @@ helper that converts the copado-internal format for "environment variables" into | Param | Type | Description | | --- | --- | --- | -| envChildVarArr | Array.<TYPES.EnvChildVar> | - | +| envChildVarArr | Array.<TYPE.EnvChildVar> | - | @@ -651,16 +645,16 @@ main method that combines runs this function **Kind**: global function * [run()](#run) ⇒ void - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) @@ -670,16 +664,16 @@ main method that combines runs this function **Kind**: global function * [run()](#run) ⇒ void - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) @@ -689,16 +683,16 @@ main method that combines runs this function **Kind**: global function * [run()](#run) ⇒ void - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) @@ -708,62 +702,17 @@ main method that combines runs this function **Kind**: global function * [run()](#run) ⇒ void - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> - * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPES.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> + * [~commitSelectionArr](#run..commitSelectionArr) : Array.<TYPE.CommitSelection> -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) -### run~commitSelectionArr : Array.<TYPES.CommitSelection> +### run~commitSelectionArr : Array.<TYPE.CommitSelection> **Kind**: inner property of [run](#run) - - -## MetadataItem : object -**Kind**: global typedef -**Properties** - -| Name | Type | Description | -| --- | --- | --- | -| n | string | Name | -| k | string | Key (Customer Key / External Key) | -| t | string | metadata type | -| [cd] | string | created date | -| [cb] | string | created by name | -| [ld] | string | last modified date | -| [lb] | string | last modified by name | - - - -## EnvChildVar : object -**Kind**: global typedef -**Properties** - -| Name | Type | Description | -| --- | --- | --- | -| value | string | variable value | -| scope | string | ? | -| name | string | variable name | -| environmentVariables | Array.<EnvVar> | list of environment variables | -| environmentName | string | name of environment in Copado | - - - -## CommitSelection : object -**Kind**: global typedef -**Properties** - -| Name | Type | Description | -| --- | --- | --- | -| t | string | type | -| n | string | name | -| m | string | ??? | -| j | string | json string with exta info | -| c | 'sfmc' | system | -| a | 'add' | action | - ## EnvChildVar : object From 42d072b8188af5f82b1f8f4fdbc2f824ed9daf83 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Fri, 18 Nov 2022 15:58:01 +0000 Subject: [PATCH 02/28] #296 added user.email and user.name values in process envs and its logic to set the user.email and user.name in global gitconfig --- copado-function/app/Init.fn.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 0246018..4d62555 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -26,6 +26,9 @@ CONFIG.mcdevVersion = process.env.mcdev_version; // this will only be needed if CONFIG.metadataFilePath = null; // do not change - LWC depends on it! // not needed in this case, previous value: 'mcmetadata.json' CONFIG.source_mid = null; CONFIG.tmpDirectory = '../tmp'; +CONFIG.userEmail = process.env.git_email; +CONFIG.userName = process.env.git_name; + // retrieve CONFIG.source_sfid = null; // commit @@ -108,15 +111,17 @@ async function run() { try { Log.info(''); - Log.info('Adding git email'); + Log.info('Adding git email and name'); Log.info('==================='); - Util.execCommand(null, [`git config --global user.email "${CONFIG.gitEmail}"`]); Log.info(''); + Util.execCommand(null, [ + `git config --global user.email "${CONFIG.userEmail}"`, + `git config --global user.name "${CONFIG.userName}"`, + ]); } catch (ex) { - Log.error('adding git email failed: ' + ex.message); + Log.error('adding git email and name failed: ' + ex.message); throw ex; } - try { Log.info(''); Log.info('Preparing'); From 59f504154723661c52a5c8d2dddf1f94afcedb74 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Fri, 18 Nov 2022 15:59:28 +0000 Subject: [PATCH 03/28] #296 removed CONFIG variable not needed --- copado-function/app/Init.fn.js | 1 - 1 file changed, 1 deletion(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 4d62555..303c67f 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -14,7 +14,6 @@ CONFIG.client_secret = process.env.client_secret; CONFIG.auth_url = process.env.auth_url; CONFIG.account_id = process.env.account_id; CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; -CONFIG.gitEmail = process.env.gitEmail; // generic CONFIG.configFilePath = null; From a2d0c73ce7963096579133810bcb1266b66ee825 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Fri, 18 Nov 2022 16:05:40 +0000 Subject: [PATCH 04/28] #296 added user.email and user.name values in process envs and its logic to set the user.email and user.name in global gitconfig (dist script) --- copado-function/dist/Init.fn.js | 780 ++++++++++++++++---------------- 1 file changed, 381 insertions(+), 399 deletions(-) diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 4f4f574..3a0a2ab 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,364 +1,341 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-17T12:49:31.721Z) + * mcdev-copado v1.1.2 (built 2022-11-18T15:41:44.283Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme * Support: https://github.com/Accenture/sfmc-devtools-copado/issues * Git-Repository: https://github.com/Accenture/sfmc-devtools-copado.git * Copyright (c) 2022 Accenture. MIT licensed - */ +*/ + var __getOwnPropNames = Object.getOwnPropertyNames; -var __commonJS = (cb, mod) => - function __require() { - return ( - mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), - mod.exports - ); - }; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; // common/Config.js var require_Config = __commonJS({ - "common/Config.js"(exports, module2) { - module2.exports = {}; - } + "common/Config.js"(exports, module2) { + module2.exports = {}; + } }); // common/Log.js var require_Log = __commonJS({ - "common/Log.js"(exports, module2) { - "use strict"; - var execSync = require("child_process").execSync; - var CONFIG2 = require_Config(); - var Log2 = class { - static debug(msg) { - if (CONFIG2.debug) { - console.log("DEBUG:", msg); - } - } - static warn(msg) { - console.log("\u26A0", msg); - } - static info(msg) { - console.log(msg); - } - static error(error, msg = "Error") { - console.log("\u274C", error); - error = JSON.stringify(error); - msg = JSON.stringify(msg); - execSync(`copado --error-message ${error} --progress ${msg}`); - } - static result(json, msg = "Result attached") { - if (typeof json !== "string") { - json = JSON.stringify(json); - } - console.log("\u2705", json); - json = JSON.stringify(`${msg}: ${json}`); - msg = JSON.stringify(msg); - execSync(`copado --result-data ${json} --progress ${msg}`); - } - static progress(msg) { - msg = JSON.stringify(msg); - execSync(`copado --progress ${msg}`); - } - }; - module2.exports = Log2; - } + "common/Log.js"(exports, module2) { + "use strict"; + var execSync = require("child_process").execSync; + var CONFIG2 = require_Config(); + var Log2 = class { + static debug(msg) { + if (CONFIG2.debug) { + console.log("DEBUG:", msg); + } + } + static warn(msg) { + console.log("\u26A0", msg); + } + static info(msg) { + console.log(msg); + } + static error(error, msg = "Error") { + console.log("\u274C", error); + error = JSON.stringify(error); + msg = JSON.stringify(msg); + execSync(`copado --error-message ${error} --progress ${msg}`); + } + static result(json, msg = "Result attached") { + if (typeof json !== "string") { + json = JSON.stringify(json); + } + console.log("\u2705", json); + json = JSON.stringify(`${msg}: ${json}`); + msg = JSON.stringify(msg); + execSync(`copado --result-data ${json} --progress ${msg}`); + } + static progress(msg) { + msg = JSON.stringify(msg); + execSync(`copado --progress ${msg}`); + } + }; + module2.exports = Log2; + } }); // types/mcdev-copado.d.js var require_mcdev_copado_d = __commonJS({ - "types/mcdev-copado.d.js"(exports, module2) { - module2.exports = {}; - } + "types/mcdev-copado.d.js"(exports, module2) { + module2.exports = {}; + } }); // common/Util.js var require_Util = __commonJS({ - "common/Util.js"(exports, module2) { - "use strict"; - var fs = require("fs"); - var execSync = require("child_process").execSync; - var TYPE = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = class { - static saveJsonFile(localPath, jsObj, beautify) { - const jsonString = beautify - ? JSON.stringify(jsObj, null, 4) - : JSON.stringify(jsObj); - fs.writeFileSync(localPath, jsonString, "utf8"); - } - static push(destinationBranch) { - Util2.execCommand( - `Pushing updates to ${destinationBranch} branch`, - ['git push origin "' + destinationBranch + '"'], - "Completed pushing branch" - ); - } - static execCommand(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - if (null != postMsg) { - Log2.debug("\u2714\uFE0F " + postMsg); - } - } - static execCommandReturnStatus(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - let exitCode = null; - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - exitCode = 0; - } catch (ex) { - Log2.warn("\u274C " + ex.status + ": " + ex.message); - exitCode = ex.status; - return exitCode; - } - if (null != postMsg) { - Log2.progress("\u2714\uFE0F " + postMsg); - } - return exitCode; - } - static provideMCDevTools() { - if (fs.existsSync("package.json")) { - Log2.debug("package.json found, assuming npm was already initialized"); - } else { - Util2.execCommand( - "Initializing npm", - ["npm init -y"], - "Completed initializing NPM" - ); - } - let installer; - if (!CONFIG2.installMcdevLocally) { - Util2.execCommand( - `Initializing Accenture SFMC DevTools (packaged version)`, - [ - `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, - "mcdev --version" - ], - "Completed installing Accenture SFMC DevTools" - ); - return; - } else if (!CONFIG2.mcdevVersion) { - Log2.error("Please specify mcdev_version in pipeline & environment settings"); - throw new Error( - "Please specify mcdev_version in pipeline & environment settings" - ); - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; - } else { - installer = `mcdev@${CONFIG2.mcdevVersion}`; - } - Util2.execCommand( - `Initializing Accenture SFMC DevTools (${installer})`, - [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], - "Completed installing Accenture SFMC DevTools" - ); - } - static provideMCDevCredentials(credentials) { - Log2.info("Provide authentication"); - Util2.saveJsonFile(".mcdev-auth.json", credentials, true); - } - static convertSourceProperties(properties) { - const response = {}; - for (const item of properties) { - response[item.copado__API_Name__c] = item.copado__Value__c; - } - return response; - } - static convertEnvVariables(envVariables) { - Object.keys(envVariables).map((key) => { - if (key.endsWith("Children")) { - envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); - } else { - envVariables[key] = Util2._convertEnvVars(envVariables[key]); - } - }); - } - static _convertEnvVars(envVarArr) { - if (!envVarArr) { - return envVarArr; - } - if (typeof envVarArr === "string") { - envVarArr = JSON.parse(envVarArr); - } - const response = {}; - for (const item of envVarArr) { - response[item.name] = item.value; - } - return response; - } - static _convertEnvChildVars(envChildVarArr) { - if (!envChildVarArr) { - return envChildVarArr; - } - if (typeof envChildVarArr === "string") { - envChildVarArr = JSON.parse(envChildVarArr); - } - const response = {}; - for (const item of envChildVarArr) { - response[item.id] = Util2._convertEnvVars(item.environmentVariables); - } - return response; - } - static getBuName(credName, mid) { - let credBuName; - if (!credName) { - throw new Error('System Property "credentialName" not set'); - } - if (!mid) { - throw new Error('System Property "mid" not set'); - } - if (!fs.existsSync(CONFIG2.configFilePath)) { - throw new Error("Could not find config file " + CONFIG2.configFilePath); - } - const config = JSON.parse(fs.readFileSync(CONFIG2.configFilePath, "utf8")); - if (config.credentials[credName] && config.credentials[credName].businessUnits) { - const myBuNameArr = Object.keys( - config.credentials[credName].businessUnits - ).filter((buName) => config.credentials[credName].businessUnits[buName] == mid); - if (myBuNameArr.length === 1) { - Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); - credBuName = credName + "/" + myBuNameArr[0]; - } else { - throw new Error(`MID ${mid} not found for ${credName}`); - } - } - return credBuName; - } - }; - module2.exports = Util2; - } + "common/Util.js"(exports, module2) { + "use strict"; + var fs = require("fs"); + var execSync = require("child_process").execSync; + var TYPE = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = class { + static saveJsonFile(localPath, jsObj, beautify) { + const jsonString = beautify ? JSON.stringify(jsObj, null, 4) : JSON.stringify(jsObj); + fs.writeFileSync(localPath, jsonString, "utf8"); + } + static push(destinationBranch) { + Util2.execCommand( + `Pushing updates to ${destinationBranch} branch`, + ['git push origin "' + destinationBranch + '"'], + "Completed pushing branch" + ); + } + static execCommand(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + if (null != postMsg) { + Log2.debug("\u2714\uFE0F " + postMsg); + } + } + static execCommandReturnStatus(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + let exitCode = null; + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + exitCode = 0; + } catch (ex) { + Log2.warn("\u274C " + ex.status + ": " + ex.message); + exitCode = ex.status; + return exitCode; + } + if (null != postMsg) { + Log2.progress("\u2714\uFE0F " + postMsg); + } + return exitCode; + } + static provideMCDevTools() { + if (fs.existsSync("package.json")) { + Log2.debug("package.json found, assuming npm was already initialized"); + } else { + Util2.execCommand("Initializing npm", ["npm init -y"], "Completed initializing NPM"); + } + let installer; + if (!CONFIG2.installMcdevLocally) { + Util2.execCommand( + `Initializing Accenture SFMC DevTools (packaged version)`, + [ + `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, + "mcdev --version" + ], + "Completed installing Accenture SFMC DevTools" + ); + return; + } else if (!CONFIG2.mcdevVersion) { + Log2.error("Please specify mcdev_version in pipeline & environment settings"); + throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; + } else { + installer = `mcdev@${CONFIG2.mcdevVersion}`; + } + Util2.execCommand( + `Initializing Accenture SFMC DevTools (${installer})`, + [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], + "Completed installing Accenture SFMC DevTools" + ); + } + static provideMCDevCredentials(credentials) { + Log2.info("Provide authentication"); + Util2.saveJsonFile(".mcdev-auth.json", credentials, true); + } + static convertSourceProperties(properties) { + const response = {}; + for (const item of properties) { + response[item.copado__API_Name__c] = item.copado__Value__c; + } + return response; + } + static convertEnvVariables(envVariables) { + Object.keys(envVariables).map((key) => { + if (key.endsWith("Children")) { + envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); + } else { + envVariables[key] = Util2._convertEnvVars(envVariables[key]); + } + }); + } + static _convertEnvVars(envVarArr) { + if (!envVarArr) { + return envVarArr; + } + if (typeof envVarArr === "string") { + envVarArr = JSON.parse(envVarArr); + } + const response = {}; + for (const item of envVarArr) { + response[item.name] = item.value; + } + return response; + } + static _convertEnvChildVars(envChildVarArr) { + if (!envChildVarArr) { + return envChildVarArr; + } + if (typeof envChildVarArr === "string") { + envChildVarArr = JSON.parse(envChildVarArr); + } + const response = {}; + for (const item of envChildVarArr) { + response[item.id] = Util2._convertEnvVars(item.environmentVariables); + } + return response; + } + static getBuName(credName, mid) { + let credBuName; + if (!credName) { + throw new Error('System Property "credentialName" not set'); + } + if (!mid) { + throw new Error('System Property "mid" not set'); + } + if (!fs.existsSync(CONFIG2.configFilePath)) { + throw new Error("Could not find config file " + CONFIG2.configFilePath); + } + const config = JSON.parse(fs.readFileSync(CONFIG2.configFilePath, "utf8")); + if (config.credentials[credName] && config.credentials[credName].businessUnits) { + const myBuNameArr = Object.keys(config.credentials[credName].businessUnits).filter( + (buName) => config.credentials[credName].businessUnits[buName] == mid + ); + if (myBuNameArr.length === 1) { + Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); + credBuName = credName + "/" + myBuNameArr[0]; + } else { + throw new Error(`MID ${mid} not found for ${credName}`); + } + } + return credBuName; + } + }; + module2.exports = Util2; + } }); // common/Copado.js var require_Copado = __commonJS({ - "common/Copado.js"(exports, module2) { - "use strict"; - var fs = require("fs"); - var exec = require("child_process").exec; - var TYPE = require_mcdev_copado_d(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Copado2 = class { - static mcdevInit(credentials, credentialName, url) { - Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` - ], - "Mcdev initialized!" - ); - } - static attachJson(localPath, parentSfid, async = false, preMsg) { - Copado2._attachFile(localPath, async, parentSfid, preMsg); - } - static async attachLog(localPath) { - Copado2._attachFile(localPath, true); - } - static _attachFile( - localPath, - async = false, - parentSfid, - preMsg, - postMsg = "Completed uploading file" - ) { - const command = - `copado --uploadfile "${localPath}"` + - (parentSfid ? ` --parentid "${parentSfid}"` : ""); - if (async) { - Log2.debug("\u26A1 " + command); - try { - exec(command); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - } else { - if (!preMsg) { - preMsg = "Uploading file " + localPath; - if (parentSfid) { - preMsg += ` to ${parentSfid}`; - } - } - Util2.execCommand(preMsg, [command], postMsg); - } - } - static _downloadFile(fileSFID, preMsg) { - if (fileSFID) { - if (!preMsg) { - preMsg = `Download ${fileSFID}.`; - } - Util2.execCommand( - preMsg, - `copado --downloadfiles "${fileSFID}"`, - "Completed download" - ); - } else { - throw new Error("fileSalesforceId is not set"); - } - } - static getJsonFile(fileSFID, fileName, preMsg) { - Copado2._downloadFile(fileSFID, preMsg); - return JSON.parse(fs.readFileSync(fileName, "utf8")); - } - static checkoutSrc(workingBranch, createBranch = false) { - Util2.execCommand( - `Switching to ${workingBranch} branch`, - [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], - "Completed creating/checking out branch" - ); - } - static deleteBranch(featureBranch) { - Util2.execCommand( - `Deleting branch ${featureBranch} on server`, - [`git push origin --delete ${featureBranch}`], - "Completed deleting server branch " + featureBranch - ); - Util2.execCommand( - `Deleting branch ${featureBranch} locally`, - [`git branch --delete --force ${featureBranch}`], - "Completed deleting local branch " + featureBranch - ); - } - static async uploadToolLogs() { - Log2.debug("Getting mcdev logs"); - try { - const logsAttached = []; - for (const file of fs.readdirSync("logs")) { - Log2.debug("- " + file); - logsAttached.push(Copado2.attachLog("logs/" + file)); - } - const response = await Promise.all(logsAttached); - Log2.debug("Attached mcdev logs"); - return response; - } catch (ex) { - Log2.debug("attaching mcdev logs failed:" + ex.message); - } + "common/Copado.js"(exports, module2) { + "use strict"; + var fs = require("fs"); + var exec = require("child_process").exec; + var TYPE = require_mcdev_copado_d(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Copado2 = class { + static mcdevInit(credentials, credentialName, url) { + Util2.execCommand( + `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, + [ + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` + ], + "Mcdev initialized!" + ); + } + static attachJson(localPath, parentSfid, async = false, preMsg) { + Copado2._attachFile(localPath, async, parentSfid, preMsg); + } + static async attachLog(localPath) { + Copado2._attachFile(localPath, true); + } + static _attachFile(localPath, async = false, parentSfid, preMsg, postMsg = "Completed uploading file") { + const command = `copado --uploadfile "${localPath}"` + (parentSfid ? ` --parentid "${parentSfid}"` : ""); + if (async) { + Log2.debug("\u26A1 " + command); + try { + exec(command); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + } else { + if (!preMsg) { + preMsg = "Uploading file " + localPath; + if (parentSfid) { + preMsg += ` to ${parentSfid}`; } - }; - module2.exports = Copado2; - } + } + Util2.execCommand(preMsg, [command], postMsg); + } + } + static _downloadFile(fileSFID, preMsg) { + if (fileSFID) { + if (!preMsg) { + preMsg = `Download ${fileSFID}.`; + } + Util2.execCommand(preMsg, `copado --downloadfiles "${fileSFID}"`, "Completed download"); + } else { + throw new Error("fileSalesforceId is not set"); + } + } + static getJsonFile(fileSFID, fileName, preMsg) { + Copado2._downloadFile(fileSFID, preMsg); + return JSON.parse(fs.readFileSync(fileName, "utf8")); + } + static checkoutSrc(workingBranch, createBranch = false) { + Util2.execCommand( + `Switching to ${workingBranch} branch`, + [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], + "Completed creating/checking out branch" + ); + } + static deleteBranch(featureBranch) { + Util2.execCommand( + `Deleting branch ${featureBranch} on server`, + [`git push origin --delete ${featureBranch}`], + "Completed deleting server branch " + featureBranch + ); + Util2.execCommand( + `Deleting branch ${featureBranch} locally`, + [`git branch --delete --force ${featureBranch}`], + "Completed deleting local branch " + featureBranch + ); + } + static async uploadToolLogs() { + Log2.debug("Getting mcdev logs"); + try { + const logsAttached = []; + for (const file of fs.readdirSync("logs")) { + Log2.debug("- " + file); + logsAttached.push(Copado2.attachLog("logs/" + file)); + } + const response = await Promise.all(logsAttached); + Log2.debug("Attached mcdev logs"); + return response; + } catch (ex) { + Log2.debug("attaching mcdev logs failed:" + ex.message); + } + } + }; + module2.exports = Copado2; + } }); // Init.fn.js @@ -374,7 +351,7 @@ CONFIG.client_secret = process.env.client_secret; CONFIG.auth_url = process.env.auth_url; CONFIG.account_id = process.env.account_id; CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; -CONFIG.gitEmail = process.env.gitEmail; +CONFIG.gitCredentials = process.env.gitCredentials; CONFIG.configFilePath = null; CONFIG.repoUrl = process.env.repoUrl; CONFIG.debug = process.env.debug === "true" ? true : false; @@ -384,6 +361,8 @@ CONFIG.mcdevVersion = process.env.mcdev_version; CONFIG.metadataFilePath = null; CONFIG.source_mid = null; CONFIG.tmpDirectory = "../tmp"; +CONFIG.userEmail = process.env.git_email; +CONFIG.userName = process.env.git_name; CONFIG.source_sfid = null; CONFIG.commitMessage = null; CONFIG.featureBranch = null; @@ -391,10 +370,10 @@ CONFIG.fileSelectionSalesforceId = null; CONFIG.fileSelectionFileName = null; CONFIG.recreateFeatureBranch = null; CONFIG.envVariables = { - source: null, - sourceChildren: null, - destination: null, - destinationChildren: null + source: null, + sourceChildren: null, + destination: null, + destinationChildren: null }; CONFIG.deltaPackageLog = null; CONFIG.destinationBranch = null; @@ -405,72 +384,75 @@ CONFIG.promotionBranch = null; CONFIG.promotionName = null; CONFIG.target_mid = null; async function run() { - Log.info("McdevInit.js started"); - Log.debug(""); - Log.debug("Parameters"); - Log.debug("==================="); - if ([CONFIG.client_id, CONFIG.client_secret, CONFIG.auth_url, CONFIG.account_id].includes()) { - Log.error( - `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` - ); - throw new Error( - `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` - ); - } - try { - CONFIG.credentials = JSON.parse(CONFIG.credentials); - } catch (ex) { - Log.error(`Could not parse credentials: ${CONFIG.credentials}`); - throw ex; - } - Log.debug(CONFIG); - if (!CONFIG.credentials[CONFIG.credentialNameSource]) { - Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); - throw new Error(`No credentials`); - } - Log.debug("Credentials found for source BU"); - Log.debug("Environment"); - Log.debug("==================="); - if (CONFIG.debug) { - Util.execCommand(null, "npm --version", null); - Util.execCommand(null, "node --version", null); - Util.execCommand(null, "git version", null); - } - Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); - try { - Util.execCommand(null, [ - "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) - ]); - } catch { - Log.error("Could not set tmp directoy as safe directory"); - } - process.chdir(CONFIG.tmpDirectory); - Log.debug(process.cwd()); - try { - Log.info(""); - Log.info("Adding git email"); - Log.info("==================="); - Util.execCommand(null, [`git config --global user.email "${CONFIG.gitEmail}"`]); - Log.info(""); - } catch (ex) { - Log.error("adding git email failed: " + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Preparing"); - Log.info("==================="); - Log.info(""); - Util.provideMCDevTools(); - Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, CONFIG.repoUrl); - } catch (ex) { - Log.error("initializing failed: " + ex.message); - throw ex; - } + Log.info("McdevInit.js started"); + Log.debug(""); + Log.debug("Parameters"); + Log.debug("==================="); + if ([CONFIG.client_id, CONFIG.client_secret, CONFIG.auth_url, CONFIG.account_id].includes()) { + Log.error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + throw new Error( + `Could not find credentials: ${CONFIG.client_id}, ${CONFIG.client_secret}, ${CONFIG.auth_url}, ${CONFIG.account_id}` + ); + } + try { + CONFIG.credentials = JSON.parse(CONFIG.credentials); + } catch (ex) { + Log.error(`Could not parse credentials: ${CONFIG.credentials}`); + throw ex; + } + Log.debug(CONFIG); + if (!CONFIG.credentials[CONFIG.credentialNameSource]) { + Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); + throw new Error(`No credentials`); + } + Log.debug("Credentials found for source BU"); + Log.debug("Environment"); + Log.debug("==================="); + if (CONFIG.debug) { + Util.execCommand(null, "npm --version", null); + Util.execCommand(null, "node --version", null); + Util.execCommand(null, "git version", null); + } + Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + try { + Util.execCommand(null, [ + "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) + ]); + } catch { + Log.error("Could not set tmp directoy as safe directory"); + } + process.chdir(CONFIG.tmpDirectory); + Log.debug(process.cwd()); + try { + Log.info(""); + Log.info("Adding git email and name"); + Log.info("==================="); + Log.info(""); + Util.execCommand(null, [ + `git config --global user.email "${CONFIG.userEmail}"`, + `git config --global user.name "${CONFIG.userName}"` + ]); + } catch (ex) { + Log.error("adding git email and name failed: " + ex.message); + throw ex; + } + try { Log.info(""); + Log.info("Preparing"); Log.info("==================="); Log.info(""); - Log.info("McdevInit.js done"); - Copado.uploadToolLogs(); + Util.provideMCDevTools(); + Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, CONFIG.repoUrl); + } catch (ex) { + Log.error("initializing failed: " + ex.message); + throw ex; + } + Log.info(""); + Log.info("==================="); + Log.info(""); + Log.info("McdevInit.js done"); + Copado.uploadToolLogs(); } run(); From 0de9ccd05221e3c0e11e4945a7ec5d51b174f702 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 21 Nov 2022 13:59:21 +0000 Subject: [PATCH 05/28] #296 dividing logic try catch in order to make each one do a different thing --- copado-function/app/Init.fn.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 303c67f..c6e03f6 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -127,9 +127,18 @@ async function run() { Log.info('==================='); Log.info(''); Util.provideMCDevTools(); + } catch (ex) { + Log.error('Preparing failed: ' + ex.message); + throw ex; + } + try { + Log.info(''); + Log.info('Initializing mcdev tools'); + Log.info('==================='); + Log.info(''); Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, CONFIG.repoUrl); } catch (ex) { - Log.error('initializing failed: ' + ex.message); + Log.error('Initializing failed: ' + ex.message); throw ex; } From 3e3bafd2b077a073b569212ed1dd462c95baaabd Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 21 Nov 2022 16:22:38 +0000 Subject: [PATCH 06/28] #296 adding chose value of gitPush and value of downloadBUs logic --- copado-function/app/Init.fn.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index c6e03f6..853ab86 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -18,6 +18,8 @@ CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.c // generic CONFIG.configFilePath = null; CONFIG.repoUrl = process.env.repoUrl; +CONFIG.downloadBUs = process.env.downloadBUs === 'true' ? true : false; +CONFIG.gitPush = process.env.gitPush === 'true' ? true : false; CONFIG.debug = process.env.debug === 'true' ? true : false; CONFIG.installMcdevLocally = process.env.installMcdevLocally === 'true' ? true : false; CONFIG.mainBranch = null; @@ -136,7 +138,11 @@ async function run() { Log.info('Initializing mcdev tools'); Log.info('==================='); Log.info(''); - Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, CONFIG.repoUrl); + Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { + url: CONFIG.repoUrl, + downloadBUs: CONFIG.downloadBUs, + gitPush: CONFIG.gitPush, + }); } catch (ex) { Log.error('Initializing failed: ' + ex.message); throw ex; From 72ad8cfa41407a42f4eb0a7d519e9d3dbee3abd4 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 21 Nov 2022 16:23:03 +0000 Subject: [PATCH 07/28] #296 adding chose value of gitPush and value of downloadBUs logic (dist file) --- copado-function/dist/Init.fn.js | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 3a0a2ab..5691bd2 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-18T15:41:44.283Z) + * mcdev-copado v1.1.2 (built 2022-11-21T16:06:40.873Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -250,11 +250,11 @@ var require_Copado = __commonJS({ var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { - static mcdevInit(credentials, credentialName, url) { + static mcdevInit(credentials, credentialName, options) { Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, + `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBus}" --y.gitPush "${options.gitPush}"` ], "Mcdev initialized!" ); @@ -351,9 +351,10 @@ CONFIG.client_secret = process.env.client_secret; CONFIG.auth_url = process.env.auth_url; CONFIG.account_id = process.env.account_id; CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; -CONFIG.gitCredentials = process.env.gitCredentials; CONFIG.configFilePath = null; CONFIG.repoUrl = process.env.repoUrl; +CONFIG.downloadBUs = process.env.downloadBUs === "true" ? true : false; +CONFIG.gitPush = process.env.gitPush === "true" ? true : false; CONFIG.debug = process.env.debug === "true" ? true : false; CONFIG.installMcdevLocally = process.env.installMcdevLocally === "true" ? true : false; CONFIG.mainBranch = null; @@ -444,9 +445,22 @@ async function run() { Log.info("==================="); Log.info(""); Util.provideMCDevTools(); - Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, CONFIG.repoUrl); } catch (ex) { - Log.error("initializing failed: " + ex.message); + Log.error("Preparing failed: " + ex.message); + throw ex; + } + try { + Log.info(""); + Log.info("Initializing mcdev tools"); + Log.info("==================="); + Log.info(""); + Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { + url: CONFIG.repoUrl, + downloadBUs: CONFIG.downloadBUs, + gitPush: CONFIG.gitPush + }); + } catch (ex) { + Log.error("Initializing failed: " + ex.message); throw ex; } Log.info(""); From ea80602f697fc42d99d2cd7f94146fb9a8270f59 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 21 Nov 2022 16:26:29 +0000 Subject: [PATCH 08/28] #296 adding chose value of gitPush and value of downloadBUs logic (copado file) --- copado-function/app/common/Copado.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/copado-function/app/common/Copado.js b/copado-function/app/common/Copado.js index 46fa6b5..1dfdee0 100644 --- a/copado-function/app/common/Copado.js +++ b/copado-function/app/common/Copado.js @@ -14,13 +14,13 @@ class Copado { * * @param {object} credentials the credentials for the salesforce marketing cloud * @param {string }credentialName the credential name - * @param {string} url the git remote URL + * @param {object} options contains the url, the downloadBUs and the gitPush values */ - static mcdevInit(credentials, credentialName, url) { + static mcdevInit(credentials, credentialName, options) { Util.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, + `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"`, + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"`, ], 'Mcdev initialized!' ); From 446c82529dc3f02e677ed6ae44c91cce91f50a10 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 21 Nov 2022 16:28:20 +0000 Subject: [PATCH 09/28] #296 bug fixed after the copado file change --- copado-function/dist/Init.fn.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 5691bd2..1ab207e 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -254,7 +254,7 @@ var require_Copado = __commonJS({ Util2.execCommand( `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBus}" --y.gitPush "${options.gitPush}"` + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"` ], "Mcdev initialized!" ); From 1c32ea3eeca60f749ed2d4a80e385eb741351965 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 22 Nov 2022 10:15:24 +0000 Subject: [PATCH 10/28] #296 changing account_id to enterprise_id --- copado-function/app/Init.fn.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 853ab86..1857369 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -12,7 +12,7 @@ CONFIG.credentialNameTarget = null; CONFIG.client_id = process.env.client_id; CONFIG.client_secret = process.env.client_secret; CONFIG.auth_url = process.env.auth_url; -CONFIG.account_id = process.env.account_id; +CONFIG.account_id = process.env.enterprise_id; CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; // generic From fb79af2c4fdd20776d987ae4893affa8eaac9466 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 22 Nov 2022 10:20:15 +0000 Subject: [PATCH 11/28] #296 moved mcdev init and removed npm install from init function --- copado-function/app/Init.fn.js | 43 +- copado-function/app/common/Copado.js | 16 - copado-function/dist/Commit.fn.js | 1065 +++++++-------- copado-function/dist/Deploy.fn.js | 1767 ++++++++++++------------- copado-function/dist/Init.fn.js | 44 +- copado-function/dist/Retrieve.fn.js | 1060 +++++++-------- copado-function/docs/documentation.md | 32 +- 7 files changed, 1932 insertions(+), 2095 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 1857369..1e87c75 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -17,11 +17,8 @@ CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.c // generic CONFIG.configFilePath = null; -CONFIG.repoUrl = process.env.repoUrl; -CONFIG.downloadBUs = process.env.downloadBUs === 'true' ? true : false; -CONFIG.gitPush = process.env.gitPush === 'true' ? true : false; CONFIG.debug = process.env.debug === 'true' ? true : false; -CONFIG.installMcdevLocally = process.env.installMcdevLocally === 'true' ? true : false; +CONFIG.installMcdevLocally = null; CONFIG.mainBranch = null; CONFIG.mcdevVersion = process.env.mcdev_version; // this will only be needed if installMcdevLocally=true CONFIG.metadataFilePath = null; // do not change - LWC depends on it! // not needed in this case, previous value: 'mcmetadata.json' @@ -53,6 +50,10 @@ CONFIG.merge_strategy = null; // set default merge strategy CONFIG.promotionBranch = null; // The promotion branch of a PR CONFIG.promotionName = null; // The promotion name of a PR CONFIG.target_mid = null; +// init +CONFIG.repoUrl = process.env.repoUrl; +CONFIG.downloadBUs = process.env.downloadBUs === 'true' ? true : false; +CONFIG.gitPush = process.env.gitPush === 'true' ? true : false; /** * main method that combines runs this function @@ -123,22 +124,13 @@ async function run() { Log.error('adding git email and name failed: ' + ex.message); throw ex; } - try { - Log.info(''); - Log.info('Preparing'); - Log.info('==================='); - Log.info(''); - Util.provideMCDevTools(); - } catch (ex) { - Log.error('Preparing failed: ' + ex.message); - throw ex; - } + try { Log.info(''); Log.info('Initializing mcdev tools'); Log.info('==================='); Log.info(''); - Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { + Init.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { url: CONFIG.repoUrl, downloadBUs: CONFIG.downloadBUs, gitPush: CONFIG.gitPush, @@ -156,4 +148,25 @@ async function run() { Copado.uploadToolLogs(); } +/** + * Class for Init function + */ +class Init { + /** + * + * @param {object} credentials the credentials for the salesforce marketing cloud + * @param {string }credentialName the credential name + * @param {object} options contains the url, the downloadBUs and the gitPush values + */ + static mcdevInit(credentials, credentialName, options) { + Util.execCommand( + `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, + [ + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"`, + ], + 'Mcdev initialized!' + ); + } +} + run(); // eslint-disable-line unicorn/prefer-top-level-await diff --git a/copado-function/app/common/Copado.js b/copado-function/app/common/Copado.js index 1dfdee0..14e77b2 100644 --- a/copado-function/app/common/Copado.js +++ b/copado-function/app/common/Copado.js @@ -10,22 +10,6 @@ const Util = require('./Util'); * methods to handle interaction with the copado platform */ class Copado { - /** - * - * @param {object} credentials the credentials for the salesforce marketing cloud - * @param {string }credentialName the credential name - * @param {object} options contains the url, the downloadBUs and the gitPush values - */ - static mcdevInit(credentials, credentialName, options) { - Util.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"`, - ], - 'Mcdev initialized!' - ); - } - /** * Finally, attach the resulting metadata JSON to the source environment * diff --git a/copado-function/dist/Commit.fn.js b/copado-function/dist/Commit.fn.js index 3c7699a..fc08a8f 100644 --- a/copado-function/dist/Commit.fn.js +++ b/copado-function/dist/Commit.fn.js @@ -1,461 +1,414 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-17T12:49:31.548Z) + * mcdev-copado v1.1.2 (built 2022-11-22T09:51:50.826Z) * Function: Commit.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme * Support: https://github.com/Accenture/sfmc-devtools-copado/issues * Git-Repository: https://github.com/Accenture/sfmc-devtools-copado.git * Copyright (c) 2022 Accenture. MIT licensed - */ +*/ + var __getOwnPropNames = Object.getOwnPropertyNames; -var __commonJS = (cb, mod) => - function __require() { - return ( - mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), - mod.exports - ); - }; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; // types/mcdev-copado.d.js var require_mcdev_copado_d = __commonJS({ - "types/mcdev-copado.d.js"(exports, module2) { - module2.exports = {}; - } + "types/mcdev-copado.d.js"(exports, module2) { + module2.exports = {}; + } }); // common/Config.js var require_Config = __commonJS({ - "common/Config.js"(exports, module2) { - module2.exports = {}; - } + "common/Config.js"(exports, module2) { + module2.exports = {}; + } }); // common/Log.js var require_Log = __commonJS({ - "common/Log.js"(exports, module2) { - "use strict"; - var execSync = require("child_process").execSync; - var CONFIG2 = require_Config(); - var Log2 = class { - static debug(msg) { - if (CONFIG2.debug) { - console.log("DEBUG:", msg); - } - } - static warn(msg) { - console.log("\u26A0", msg); - } - static info(msg) { - console.log(msg); - } - static error(error, msg = "Error") { - console.log("\u274C", error); - error = JSON.stringify(error); - msg = JSON.stringify(msg); - execSync(`copado --error-message ${error} --progress ${msg}`); - } - static result(json, msg = "Result attached") { - if (typeof json !== "string") { - json = JSON.stringify(json); - } - console.log("\u2705", json); - json = JSON.stringify(`${msg}: ${json}`); - msg = JSON.stringify(msg); - execSync(`copado --result-data ${json} --progress ${msg}`); - } - static progress(msg) { - msg = JSON.stringify(msg); - execSync(`copado --progress ${msg}`); - } - }; - module2.exports = Log2; - } + "common/Log.js"(exports, module2) { + "use strict"; + var execSync = require("child_process").execSync; + var CONFIG2 = require_Config(); + var Log2 = class { + static debug(msg) { + if (CONFIG2.debug) { + console.log("DEBUG:", msg); + } + } + static warn(msg) { + console.log("\u26A0", msg); + } + static info(msg) { + console.log(msg); + } + static error(error, msg = "Error") { + console.log("\u274C", error); + error = JSON.stringify(error); + msg = JSON.stringify(msg); + execSync(`copado --error-message ${error} --progress ${msg}`); + } + static result(json, msg = "Result attached") { + if (typeof json !== "string") { + json = JSON.stringify(json); + } + console.log("\u2705", json); + json = JSON.stringify(`${msg}: ${json}`); + msg = JSON.stringify(msg); + execSync(`copado --result-data ${json} --progress ${msg}`); + } + static progress(msg) { + msg = JSON.stringify(msg); + execSync(`copado --progress ${msg}`); + } + }; + module2.exports = Log2; + } }); // common/Util.js var require_Util = __commonJS({ - "common/Util.js"(exports, module2) { - "use strict"; - var fs = require("fs"); - var execSync = require("child_process").execSync; - var TYPE2 = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = class { - static saveJsonFile(localPath, jsObj, beautify) { - const jsonString = beautify - ? JSON.stringify(jsObj, null, 4) - : JSON.stringify(jsObj); - fs.writeFileSync(localPath, jsonString, "utf8"); - } - static push(destinationBranch) { - Util2.execCommand( - `Pushing updates to ${destinationBranch} branch`, - ['git push origin "' + destinationBranch + '"'], - "Completed pushing branch" - ); - } - static execCommand(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - if (null != postMsg) { - Log2.debug("\u2714\uFE0F " + postMsg); - } - } - static execCommandReturnStatus(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - let exitCode = null; - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - exitCode = 0; - } catch (ex) { - Log2.warn("\u274C " + ex.status + ": " + ex.message); - exitCode = ex.status; - return exitCode; - } - if (null != postMsg) { - Log2.progress("\u2714\uFE0F " + postMsg); - } - return exitCode; - } - static provideMCDevTools() { - if (fs.existsSync("package.json")) { - Log2.debug("package.json found, assuming npm was already initialized"); - } else { - Util2.execCommand( - "Initializing npm", - ["npm init -y"], - "Completed initializing NPM" - ); - } - let installer; - if (!CONFIG2.installMcdevLocally) { - Util2.execCommand( - `Initializing Accenture SFMC DevTools (packaged version)`, - [ - `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, - "mcdev --version" - ], - "Completed installing Accenture SFMC DevTools" - ); - return; - } else if (!CONFIG2.mcdevVersion) { - Log2.error("Please specify mcdev_version in pipeline & environment settings"); - throw new Error( - "Please specify mcdev_version in pipeline & environment settings" - ); - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; - } else { - installer = `mcdev@${CONFIG2.mcdevVersion}`; - } - Util2.execCommand( - `Initializing Accenture SFMC DevTools (${installer})`, - [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], - "Completed installing Accenture SFMC DevTools" - ); - } - static provideMCDevCredentials(credentials) { - Log2.info("Provide authentication"); - Util2.saveJsonFile(".mcdev-auth.json", credentials, true); - } - static convertSourceProperties(properties) { - const response = {}; - for (const item of properties) { - response[item.copado__API_Name__c] = item.copado__Value__c; - } - return response; - } - static convertEnvVariables(envVariables) { - Object.keys(envVariables).map((key) => { - if (key.endsWith("Children")) { - envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); - } else { - envVariables[key] = Util2._convertEnvVars(envVariables[key]); - } - }); - } - static _convertEnvVars(envVarArr) { - if (!envVarArr) { - return envVarArr; - } - if (typeof envVarArr === "string") { - envVarArr = JSON.parse(envVarArr); - } - const response = {}; - for (const item of envVarArr) { - response[item.name] = item.value; - } - return response; - } - static _convertEnvChildVars(envChildVarArr) { - if (!envChildVarArr) { - return envChildVarArr; - } - if (typeof envChildVarArr === "string") { - envChildVarArr = JSON.parse(envChildVarArr); - } - const response = {}; - for (const item of envChildVarArr) { - response[item.id] = Util2._convertEnvVars(item.environmentVariables); - } - return response; - } - static getBuName(credName, mid) { - let credBuName; - if (!credName) { - throw new Error('System Property "credentialName" not set'); - } - if (!mid) { - throw new Error('System Property "mid" not set'); - } - if (!fs.existsSync(CONFIG2.configFilePath)) { - throw new Error("Could not find config file " + CONFIG2.configFilePath); - } - const config = JSON.parse(fs.readFileSync(CONFIG2.configFilePath, "utf8")); - if (config.credentials[credName] && config.credentials[credName].businessUnits) { - const myBuNameArr = Object.keys( - config.credentials[credName].businessUnits - ).filter((buName) => config.credentials[credName].businessUnits[buName] == mid); - if (myBuNameArr.length === 1) { - Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); - credBuName = credName + "/" + myBuNameArr[0]; - } else { - throw new Error(`MID ${mid} not found for ${credName}`); - } - } - return credBuName; - } - }; - module2.exports = Util2; - } + "common/Util.js"(exports, module2) { + "use strict"; + var fs = require("fs"); + var execSync = require("child_process").execSync; + var TYPE2 = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = class { + static saveJsonFile(localPath, jsObj, beautify) { + const jsonString = beautify ? JSON.stringify(jsObj, null, 4) : JSON.stringify(jsObj); + fs.writeFileSync(localPath, jsonString, "utf8"); + } + static push(destinationBranch) { + Util2.execCommand( + `Pushing updates to ${destinationBranch} branch`, + ['git push origin "' + destinationBranch + '"'], + "Completed pushing branch" + ); + } + static execCommand(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + if (null != postMsg) { + Log2.debug("\u2714\uFE0F " + postMsg); + } + } + static execCommandReturnStatus(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + let exitCode = null; + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + exitCode = 0; + } catch (ex) { + Log2.warn("\u274C " + ex.status + ": " + ex.message); + exitCode = ex.status; + return exitCode; + } + if (null != postMsg) { + Log2.progress("\u2714\uFE0F " + postMsg); + } + return exitCode; + } + static provideMCDevTools() { + if (fs.existsSync("package.json")) { + Log2.debug("package.json found, assuming npm was already initialized"); + } else { + Util2.execCommand("Initializing npm", ["npm init -y"], "Completed initializing NPM"); + } + let installer; + if (!CONFIG2.installMcdevLocally) { + Util2.execCommand( + `Initializing Accenture SFMC DevTools (packaged version)`, + [ + `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, + "mcdev --version" + ], + "Completed installing Accenture SFMC DevTools" + ); + return; + } else if (!CONFIG2.mcdevVersion) { + Log2.error("Please specify mcdev_version in pipeline & environment settings"); + throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; + } else { + installer = `mcdev@${CONFIG2.mcdevVersion}`; + } + Util2.execCommand( + `Initializing Accenture SFMC DevTools (${installer})`, + [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], + "Completed installing Accenture SFMC DevTools" + ); + } + static provideMCDevCredentials(credentials) { + Log2.info("Provide authentication"); + Util2.saveJsonFile(".mcdev-auth.json", credentials, true); + } + static convertSourceProperties(properties) { + const response = {}; + for (const item of properties) { + response[item.copado__API_Name__c] = item.copado__Value__c; + } + return response; + } + static convertEnvVariables(envVariables) { + Object.keys(envVariables).map((key) => { + if (key.endsWith("Children")) { + envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); + } else { + envVariables[key] = Util2._convertEnvVars(envVariables[key]); + } + }); + } + static _convertEnvVars(envVarArr) { + if (!envVarArr) { + return envVarArr; + } + if (typeof envVarArr === "string") { + envVarArr = JSON.parse(envVarArr); + } + const response = {}; + for (const item of envVarArr) { + response[item.name] = item.value; + } + return response; + } + static _convertEnvChildVars(envChildVarArr) { + if (!envChildVarArr) { + return envChildVarArr; + } + if (typeof envChildVarArr === "string") { + envChildVarArr = JSON.parse(envChildVarArr); + } + const response = {}; + for (const item of envChildVarArr) { + response[item.id] = Util2._convertEnvVars(item.environmentVariables); + } + return response; + } + static getBuName(credName, mid) { + let credBuName; + if (!credName) { + throw new Error('System Property "credentialName" not set'); + } + if (!mid) { + throw new Error('System Property "mid" not set'); + } + if (!fs.existsSync(CONFIG2.configFilePath)) { + throw new Error("Could not find config file " + CONFIG2.configFilePath); + } + const config = JSON.parse(fs.readFileSync(CONFIG2.configFilePath, "utf8")); + if (config.credentials[credName] && config.credentials[credName].businessUnits) { + const myBuNameArr = Object.keys(config.credentials[credName].businessUnits).filter( + (buName) => config.credentials[credName].businessUnits[buName] == mid + ); + if (myBuNameArr.length === 1) { + Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); + credBuName = credName + "/" + myBuNameArr[0]; + } else { + throw new Error(`MID ${mid} not found for ${credName}`); + } + } + return credBuName; + } + }; + module2.exports = Util2; + } }); // common/Copado.js var require_Copado = __commonJS({ - "common/Copado.js"(exports, module2) { - "use strict"; - var fs = require("fs"); - var exec = require("child_process").exec; - var TYPE2 = require_mcdev_copado_d(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Copado2 = class { - static mcdevInit(credentials, credentialName, url) { - Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` - ], - "Mcdev initialized!" - ); - } - static attachJson(localPath, parentSfid, async = false, preMsg) { - Copado2._attachFile(localPath, async, parentSfid, preMsg); - } - static async attachLog(localPath) { - Copado2._attachFile(localPath, true); + "common/Copado.js"(exports, module2) { + "use strict"; + var fs = require("fs"); + var exec = require("child_process").exec; + var TYPE2 = require_mcdev_copado_d(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Copado2 = class { + static attachJson(localPath, parentSfid, async = false, preMsg) { + Copado2._attachFile(localPath, async, parentSfid, preMsg); + } + static async attachLog(localPath) { + Copado2._attachFile(localPath, true); + } + static _attachFile(localPath, async = false, parentSfid, preMsg, postMsg = "Completed uploading file") { + const command = `copado --uploadfile "${localPath}"` + (parentSfid ? ` --parentid "${parentSfid}"` : ""); + if (async) { + Log2.debug("\u26A1 " + command); + try { + exec(command); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + } else { + if (!preMsg) { + preMsg = "Uploading file " + localPath; + if (parentSfid) { + preMsg += ` to ${parentSfid}`; } - static _attachFile( - localPath, - async = false, - parentSfid, - preMsg, - postMsg = "Completed uploading file" - ) { - const command = - `copado --uploadfile "${localPath}"` + - (parentSfid ? ` --parentid "${parentSfid}"` : ""); - if (async) { - Log2.debug("\u26A1 " + command); - try { - exec(command); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - } else { - if (!preMsg) { - preMsg = "Uploading file " + localPath; - if (parentSfid) { - preMsg += ` to ${parentSfid}`; - } - } - Util2.execCommand(preMsg, [command], postMsg); - } - } - static _downloadFile(fileSFID, preMsg) { - if (fileSFID) { - if (!preMsg) { - preMsg = `Download ${fileSFID}.`; - } - Util2.execCommand( - preMsg, - `copado --downloadfiles "${fileSFID}"`, - "Completed download" - ); - } else { - throw new Error("fileSalesforceId is not set"); - } - } - static getJsonFile(fileSFID, fileName, preMsg) { - Copado2._downloadFile(fileSFID, preMsg); - return JSON.parse(fs.readFileSync(fileName, "utf8")); - } - static checkoutSrc(workingBranch, createBranch = false) { - Util2.execCommand( - `Switching to ${workingBranch} branch`, - [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], - "Completed creating/checking out branch" - ); - } - static deleteBranch(featureBranch) { - Util2.execCommand( - `Deleting branch ${featureBranch} on server`, - [`git push origin --delete ${featureBranch}`], - "Completed deleting server branch " + featureBranch - ); - Util2.execCommand( - `Deleting branch ${featureBranch} locally`, - [`git branch --delete --force ${featureBranch}`], - "Completed deleting local branch " + featureBranch - ); - } - static async uploadToolLogs() { - Log2.debug("Getting mcdev logs"); - try { - const logsAttached = []; - for (const file of fs.readdirSync("logs")) { - Log2.debug("- " + file); - logsAttached.push(Copado2.attachLog("logs/" + file)); - } - const response = await Promise.all(logsAttached); - Log2.debug("Attached mcdev logs"); - return response; - } catch (ex) { - Log2.debug("attaching mcdev logs failed:" + ex.message); - } - } - }; - module2.exports = Copado2; - } + } + Util2.execCommand(preMsg, [command], postMsg); + } + } + static _downloadFile(fileSFID, preMsg) { + if (fileSFID) { + if (!preMsg) { + preMsg = `Download ${fileSFID}.`; + } + Util2.execCommand(preMsg, `copado --downloadfiles "${fileSFID}"`, "Completed download"); + } else { + throw new Error("fileSalesforceId is not set"); + } + } + static getJsonFile(fileSFID, fileName, preMsg) { + Copado2._downloadFile(fileSFID, preMsg); + return JSON.parse(fs.readFileSync(fileName, "utf8")); + } + static checkoutSrc(workingBranch, createBranch = false) { + Util2.execCommand( + `Switching to ${workingBranch} branch`, + [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], + "Completed creating/checking out branch" + ); + } + static deleteBranch(featureBranch) { + Util2.execCommand( + `Deleting branch ${featureBranch} on server`, + [`git push origin --delete ${featureBranch}`], + "Completed deleting server branch " + featureBranch + ); + Util2.execCommand( + `Deleting branch ${featureBranch} locally`, + [`git branch --delete --force ${featureBranch}`], + "Completed deleting local branch " + featureBranch + ); + } + static async uploadToolLogs() { + Log2.debug("Getting mcdev logs"); + try { + const logsAttached = []; + for (const file of fs.readdirSync("logs")) { + Log2.debug("- " + file); + logsAttached.push(Copado2.attachLog("logs/" + file)); + } + const response = await Promise.all(logsAttached); + Log2.debug("Attached mcdev logs"); + return response; + } catch (ex) { + Log2.debug("attaching mcdev logs failed:" + ex.message); + } + } + }; + module2.exports = Copado2; + } }); // common/Commit.js var require_Commit = __commonJS({ - "common/Commit.js"(exports, module2) { - "use strict"; - var fs = require("fs"); - var execSync = require("child_process").execSync; - var TYPE2 = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Commit2 = class { - static async retrieveCommitSelection(sourceBU, commitSelectionArr) { - const mcdev = require("../tmp/node_modules/mcdev/lib/"); - mcdev.setSkipInteraction(true); - commitSelectionArr = commitSelectionArr.filter((item) => item.a === "add"); - const typeKeyMap = {}; - for (const item of commitSelectionArr) { - if (!typeKeyMap[item.t]) { - typeKeyMap[item.t] = []; - } - const jObj = JSON.parse(item.j); - typeKeyMap[item.t].push(jObj.newKey || jObj.key); - } - const typeArr = [...new Set(commitSelectionArr.map((item) => item.t))]; - await mcdev.retrieve(sourceBU, typeKeyMap, null, false); - const fileArr = ( - await Promise.all( - typeArr.map((type) => { - const keyArr = [ - ...new Set( - commitSelectionArr - .filter((item) => item.t === type) - .map((item) => { - const jObj = JSON.parse(item.j); - return jObj.newKey || jObj.key; - }) - ) - ]; - return mcdev.getFilesToCommit(sourceBU, type.split("-")[0], keyArr); - }) - ) - ).flat(); - return fileArr; - } - static addSelectedComponents(gitAddArr) { - for (const filePath of gitAddArr) { - if (fs.existsSync(filePath)) { - Util2.execCommand( - null, - ['git add "' + filePath + '"'], - "staged " + filePath - ); - } else { - Log2.warn("\u274C could not find " + filePath); - } - } - } - static commit(originalSelection) { - const gitDiffArr = execSync("git diff --staged --name-only") - .toString() - .split("\n") - .map((item) => item.trim()) - .filter((item) => !!item); - Log2.debug("Git diff ended with the result:"); - Log2.debug(gitDiffArr); - if (Array.isArray(gitDiffArr) && gitDiffArr.length) { - Util2.execCommand( - "Committing changes to branch", - ['git commit -n -m "' + CONFIG2.commitMessage + '"'], - "Completed committing" - ); - const result = { - committed: gitDiffArr, - noChangesFound: originalSelection - .map((item) => item.replace(new RegExp("\\\\", "g"), "/")) - .filter((item) => !gitDiffArr.includes(item)) - }; - Log2.result( - result, - `Committed ${ - result.committed.filter((item) => item.endsWith(".json")).length - } items with ${result.committed.length} files` - ); - } else { - Log2.error( - "Nothing to commit as all selected components have the same content as already exists in Git. " + - JSON.stringify(originalSelection), - "Nothing to commit" - ); - throw new Error("Nothing to commit"); - } - } - }; - module2.exports = Commit2; - } + "common/Commit.js"(exports, module2) { + "use strict"; + var fs = require("fs"); + var execSync = require("child_process").execSync; + var TYPE2 = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Commit2 = class { + static async retrieveCommitSelection(sourceBU, commitSelectionArr) { + const mcdev = require("../tmp/node_modules/mcdev/lib/"); + mcdev.setSkipInteraction(true); + commitSelectionArr = commitSelectionArr.filter((item) => item.a === "add"); + const typeKeyMap = {}; + for (const item of commitSelectionArr) { + if (!typeKeyMap[item.t]) { + typeKeyMap[item.t] = []; + } + const jObj = JSON.parse(item.j); + typeKeyMap[item.t].push(jObj.newKey || jObj.key); + } + const typeArr = [...new Set(commitSelectionArr.map((item) => item.t))]; + await mcdev.retrieve(sourceBU, typeKeyMap, null, false); + const fileArr = (await Promise.all( + typeArr.map((type) => { + const keyArr = [ + ...new Set( + commitSelectionArr.filter((item) => item.t === type).map((item) => { + const jObj = JSON.parse(item.j); + return jObj.newKey || jObj.key; + }) + ) + ]; + return mcdev.getFilesToCommit(sourceBU, type.split("-")[0], keyArr); + }) + )).flat(); + return fileArr; + } + static addSelectedComponents(gitAddArr) { + for (const filePath of gitAddArr) { + if (fs.existsSync(filePath)) { + Util2.execCommand(null, ['git add "' + filePath + '"'], "staged " + filePath); + } else { + Log2.warn("\u274C could not find " + filePath); + } + } + } + static commit(originalSelection) { + const gitDiffArr = execSync("git diff --staged --name-only").toString().split("\n").map((item) => item.trim()).filter((item) => !!item); + Log2.debug("Git diff ended with the result:"); + Log2.debug(gitDiffArr); + if (Array.isArray(gitDiffArr) && gitDiffArr.length) { + Util2.execCommand( + "Committing changes to branch", + ['git commit -n -m "' + CONFIG2.commitMessage + '"'], + "Completed committing" + ); + const result = { + committed: gitDiffArr, + noChangesFound: originalSelection.map((item) => item.replace(new RegExp("\\\\", "g"), "/")).filter( + (item) => !gitDiffArr.includes(item) + ) + }; + Log2.result( + result, + `Committed ${result.committed.filter((item) => item.endsWith(".json")).length} items with ${result.committed.length} files` + ); + } else { + Log2.error( + "Nothing to commit as all selected components have the same content as already exists in Git. " + JSON.stringify(originalSelection), + "Nothing to commit" + ); + throw new Error("Nothing to commit"); + } + } + }; + module2.exports = Commit2; + } }); // Commit.fn.js @@ -485,10 +438,10 @@ CONFIG.fileSelectionSalesforceId = process.env.metadata_file; CONFIG.fileSelectionFileName = "Copado Commit changes"; CONFIG.recreateFeatureBranch = process.env.recreateFeatureBranch === "true" ? true : false; CONFIG.envVariables = { - source: null, - sourceChildren: null, - destination: null, - destinationChildren: null + source: null, + sourceChildren: null, + destination: null, + destinationChildren: null }; CONFIG.deltaPackageLog = null; CONFIG.destinationBranch = null; @@ -499,146 +452,146 @@ CONFIG.promotionBranch = null; CONFIG.promotionName = null; CONFIG.target_mid = null; async function run() { - Log.info("Commit.js started"); - Log.debug(""); - Log.debug("Parameters"); - Log.debug("==================="); + Log.info("Commit.js started"); + Log.debug(""); + Log.debug("Parameters"); + Log.debug("==================="); + try { + CONFIG.credentials = JSON.parse(CONFIG.credentials); + } catch (ex) { + Log.error("Could not parse credentials"); + throw ex; + } + Util.convertEnvVariables(CONFIG.envVariables); + Log.debug(CONFIG); + if (!CONFIG.credentials[CONFIG.credentialNameSource]) { + Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); + throw new Error(`No source credentials`); + } + Log.debug("Environment"); + Log.debug("==================="); + if (CONFIG.debug) { + Util.execCommand(null, "npm --version", null); + Util.execCommand(null, "node --version", null); + Util.execCommand(null, "git version", null); + } + Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + try { + Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + } catch { try { - CONFIG.credentials = JSON.parse(CONFIG.credentials); - } catch (ex) { - Log.error("Could not parse credentials"); - throw ex; - } - Util.convertEnvVariables(CONFIG.envVariables); - Log.debug(CONFIG); - if (!CONFIG.credentials[CONFIG.credentialNameSource]) { - Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); - throw new Error(`No source credentials`); - } - Log.debug("Environment"); - Log.debug("==================="); - if (CONFIG.debug) { - Util.execCommand(null, "npm --version", null); - Util.execCommand(null, "node --version", null); - Util.execCommand(null, "git version", null); + Util.execCommand(null, [ + "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) + ]); + } catch { + Log.error("Could not set tmp directoy as safe directory"); } - Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + } + process.chdir(CONFIG.tmpDirectory); + Log.debug(process.cwd()); + Log.info(""); + Log.info("Clone repository"); + Log.info("==================="); + Log.info(""); + try { + Copado.checkoutSrc(CONFIG.mainBranch); try { - Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); - } catch { - try { - Util.execCommand(null, [ - "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) - ]); - } catch { - Log.error("Could not set tmp directoy as safe directory"); - } + if (CONFIG.recreateFeatureBranch) { + Copado.deleteBranch(CONFIG.featureBranch); + } + } catch (ex) { + Log.warn("Delete feature branch failed:" + ex.message); } - process.chdir(CONFIG.tmpDirectory); - Log.debug(process.cwd()); + Copado.checkoutSrc(CONFIG.featureBranch, true); + } catch (ex) { + Log.error("Checkout to feature and/or master branch failed:" + ex.message); + throw ex; + } + let commitSelectionArr; + try { Log.info(""); - Log.info("Clone repository"); + Log.info( + `Add selected components defined in ${CONFIG.fileSelectionSalesforceId} to metadata JSON` + ); Log.info("==================="); Log.info(""); - try { - Copado.checkoutSrc(CONFIG.mainBranch); - try { - if (CONFIG.recreateFeatureBranch) { - Copado.deleteBranch(CONFIG.featureBranch); - } - } catch (ex) { - Log.warn("Delete feature branch failed:" + ex.message); - } - Copado.checkoutSrc(CONFIG.featureBranch, true); - } catch (ex) { - Log.error("Checkout to feature and/or master branch failed:" + ex.message); - throw ex; - } - let commitSelectionArr; - try { - Log.info(""); - Log.info( - `Add selected components defined in ${CONFIG.fileSelectionSalesforceId} to metadata JSON` - ); - Log.info("==================="); - Log.info(""); - commitSelectionArr = Copado.getJsonFile( - CONFIG.fileSelectionSalesforceId, - CONFIG.fileSelectionFileName, - "Retrieving list of selected items" - ); - if (!Array.isArray(commitSelectionArr) || commitSelectionArr.length === 0) { - throw new Error( - "Copado has not registered any files selected for commit. Please go back and select at least one item in the Commit page." - ); - } - } catch (ex) { - Log.error("Getting Commit-selection file failed:" + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Preparing"); - Log.info("==================="); - Log.info(""); - Util.provideMCDevTools(); - Util.provideMCDevCredentials(CONFIG.credentials); - } catch (ex) { - Log.error("initializing failed: " + ex.message); - throw ex; - } - let sourceBU; - let gitAddArr; - try { - Log.info(""); - Log.info("Get source BU"); - Log.info("==================="); - Log.info(""); - sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); - } catch (ex) { - Log.error("Getting Source BU failed: " + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Retrieve components"); - Log.info("==================="); - Log.info(""); - gitAddArr = await Commit.retrieveCommitSelection(sourceBU, commitSelectionArr); - } catch (ex) { - Log.error("Retrieving failed: " + ex.message); - Copado.uploadToolLogs(); - throw ex; - } - try { - Log.info(""); - Log.info("Add components in metadata JSON to Git history"); - Log.info("==================="); - Log.info(""); - Commit.addSelectedComponents(gitAddArr); - } catch (ex) { - Log.error("git add failed:" + ex.message); - Copado.uploadToolLogs(); - throw ex; - } - try { - Log.info(""); - Log.info("Commit"); - Log.info("==================="); - Log.info(""); - Commit.commit(gitAddArr); - Log.info("Push"); - Log.info("==================="); - Util.push(CONFIG.featureBranch); - } catch (ex) { - Log.error("git commit / push failed:" + ex.message); - Copado.uploadToolLogs(); - throw ex; + commitSelectionArr = Copado.getJsonFile( + CONFIG.fileSelectionSalesforceId, + CONFIG.fileSelectionFileName, + "Retrieving list of selected items" + ); + if (!Array.isArray(commitSelectionArr) || commitSelectionArr.length === 0) { + throw new Error( + "Copado has not registered any files selected for commit. Please go back and select at least one item in the Commit page." + ); } + } catch (ex) { + Log.error("Getting Commit-selection file failed:" + ex.message); + throw ex; + } + try { + Log.info(""); + Log.info("Preparing"); + Log.info("==================="); + Log.info(""); + Util.provideMCDevTools(); + Util.provideMCDevCredentials(CONFIG.credentials); + } catch (ex) { + Log.error("initializing failed: " + ex.message); + throw ex; + } + let sourceBU; + let gitAddArr; + try { + Log.info(""); + Log.info("Get source BU"); + Log.info("==================="); + Log.info(""); + sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); + } catch (ex) { + Log.error("Getting Source BU failed: " + ex.message); + throw ex; + } + try { + Log.info(""); + Log.info("Retrieve components"); + Log.info("==================="); + Log.info(""); + gitAddArr = await Commit.retrieveCommitSelection(sourceBU, commitSelectionArr); + } catch (ex) { + Log.error("Retrieving failed: " + ex.message); + Copado.uploadToolLogs(); + throw ex; + } + try { + Log.info(""); + Log.info("Add components in metadata JSON to Git history"); + Log.info("==================="); + Log.info(""); + Commit.addSelectedComponents(gitAddArr); + } catch (ex) { + Log.error("git add failed:" + ex.message); + Copado.uploadToolLogs(); + throw ex; + } + try { Log.info(""); + Log.info("Commit"); Log.info("==================="); Log.info(""); - Log.info("Commit.js done"); + Commit.commit(gitAddArr); + Log.info("Push"); + Log.info("==================="); + Util.push(CONFIG.featureBranch); + } catch (ex) { + Log.error("git commit / push failed:" + ex.message); Copado.uploadToolLogs(); + throw ex; + } + Log.info(""); + Log.info("==================="); + Log.info(""); + Log.info("Commit.js done"); + Copado.uploadToolLogs(); } run(); diff --git a/copado-function/dist/Deploy.fn.js b/copado-function/dist/Deploy.fn.js index ab2d868..652ae48 100644 --- a/copado-function/dist/Deploy.fn.js +++ b/copado-function/dist/Deploy.fn.js @@ -1,461 +1,414 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-17T12:49:31.608Z) + * mcdev-copado v1.1.2 (built 2022-11-22T09:51:50.855Z) * Function: Deploy.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme * Support: https://github.com/Accenture/sfmc-devtools-copado/issues * Git-Repository: https://github.com/Accenture/sfmc-devtools-copado.git * Copyright (c) 2022 Accenture. MIT licensed - */ +*/ + var __getOwnPropNames = Object.getOwnPropertyNames; -var __commonJS = (cb, mod) => - function __require() { - return ( - mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), - mod.exports - ); - }; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; // types/mcdev-copado.d.js var require_mcdev_copado_d = __commonJS({ - "types/mcdev-copado.d.js"(exports, module2) { - module2.exports = {}; - } + "types/mcdev-copado.d.js"(exports, module2) { + module2.exports = {}; + } }); // common/Config.js var require_Config = __commonJS({ - "common/Config.js"(exports, module2) { - module2.exports = {}; - } + "common/Config.js"(exports, module2) { + module2.exports = {}; + } }); // common/Log.js var require_Log = __commonJS({ - "common/Log.js"(exports, module2) { - "use strict"; - var execSync2 = require("child_process").execSync; - var CONFIG2 = require_Config(); - var Log2 = class { - static debug(msg) { - if (CONFIG2.debug) { - console.log("DEBUG:", msg); - } - } - static warn(msg) { - console.log("\u26A0", msg); - } - static info(msg) { - console.log(msg); - } - static error(error, msg = "Error") { - console.log("\u274C", error); - error = JSON.stringify(error); - msg = JSON.stringify(msg); - execSync2(`copado --error-message ${error} --progress ${msg}`); - } - static result(json, msg = "Result attached") { - if (typeof json !== "string") { - json = JSON.stringify(json); - } - console.log("\u2705", json); - json = JSON.stringify(`${msg}: ${json}`); - msg = JSON.stringify(msg); - execSync2(`copado --result-data ${json} --progress ${msg}`); - } - static progress(msg) { - msg = JSON.stringify(msg); - execSync2(`copado --progress ${msg}`); - } - }; - module2.exports = Log2; - } + "common/Log.js"(exports, module2) { + "use strict"; + var execSync2 = require("child_process").execSync; + var CONFIG2 = require_Config(); + var Log2 = class { + static debug(msg) { + if (CONFIG2.debug) { + console.log("DEBUG:", msg); + } + } + static warn(msg) { + console.log("\u26A0", msg); + } + static info(msg) { + console.log(msg); + } + static error(error, msg = "Error") { + console.log("\u274C", error); + error = JSON.stringify(error); + msg = JSON.stringify(msg); + execSync2(`copado --error-message ${error} --progress ${msg}`); + } + static result(json, msg = "Result attached") { + if (typeof json !== "string") { + json = JSON.stringify(json); + } + console.log("\u2705", json); + json = JSON.stringify(`${msg}: ${json}`); + msg = JSON.stringify(msg); + execSync2(`copado --result-data ${json} --progress ${msg}`); + } + static progress(msg) { + msg = JSON.stringify(msg); + execSync2(`copado --progress ${msg}`); + } + }; + module2.exports = Log2; + } }); // common/Util.js var require_Util = __commonJS({ - "common/Util.js"(exports, module2) { - "use strict"; - var fs2 = require("fs"); - var execSync2 = require("child_process").execSync; - var TYPE2 = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = class { - static saveJsonFile(localPath, jsObj, beautify) { - const jsonString = beautify - ? JSON.stringify(jsObj, null, 4) - : JSON.stringify(jsObj); - fs2.writeFileSync(localPath, jsonString, "utf8"); - } - static push(destinationBranch) { - Util2.execCommand( - `Pushing updates to ${destinationBranch} branch`, - ['git push origin "' + destinationBranch + '"'], - "Completed pushing branch" - ); - } - static execCommand(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - try { - execSync2(command, { stdio: [0, 1, 2], stderr: "inherit" }); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - if (null != postMsg) { - Log2.debug("\u2714\uFE0F " + postMsg); - } - } - static execCommandReturnStatus(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - let exitCode = null; - try { - execSync2(command, { stdio: [0, 1, 2], stderr: "inherit" }); - exitCode = 0; - } catch (ex) { - Log2.warn("\u274C " + ex.status + ": " + ex.message); - exitCode = ex.status; - return exitCode; - } - if (null != postMsg) { - Log2.progress("\u2714\uFE0F " + postMsg); - } - return exitCode; - } - static provideMCDevTools() { - if (fs2.existsSync("package.json")) { - Log2.debug("package.json found, assuming npm was already initialized"); - } else { - Util2.execCommand( - "Initializing npm", - ["npm init -y"], - "Completed initializing NPM" - ); - } - let installer; - if (!CONFIG2.installMcdevLocally) { - Util2.execCommand( - `Initializing Accenture SFMC DevTools (packaged version)`, - [ - `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, - "mcdev --version" - ], - "Completed installing Accenture SFMC DevTools" - ); - return; - } else if (!CONFIG2.mcdevVersion) { - Log2.error("Please specify mcdev_version in pipeline & environment settings"); - throw new Error( - "Please specify mcdev_version in pipeline & environment settings" - ); - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; - } else { - installer = `mcdev@${CONFIG2.mcdevVersion}`; - } - Util2.execCommand( - `Initializing Accenture SFMC DevTools (${installer})`, - [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], - "Completed installing Accenture SFMC DevTools" - ); - } - static provideMCDevCredentials(credentials) { - Log2.info("Provide authentication"); - Util2.saveJsonFile(".mcdev-auth.json", credentials, true); - } - static convertSourceProperties(properties) { - const response = {}; - for (const item of properties) { - response[item.copado__API_Name__c] = item.copado__Value__c; - } - return response; - } - static convertEnvVariables(envVariables) { - Object.keys(envVariables).map((key) => { - if (key.endsWith("Children")) { - envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); - } else { - envVariables[key] = Util2._convertEnvVars(envVariables[key]); - } - }); - } - static _convertEnvVars(envVarArr) { - if (!envVarArr) { - return envVarArr; - } - if (typeof envVarArr === "string") { - envVarArr = JSON.parse(envVarArr); - } - const response = {}; - for (const item of envVarArr) { - response[item.name] = item.value; - } - return response; - } - static _convertEnvChildVars(envChildVarArr) { - if (!envChildVarArr) { - return envChildVarArr; - } - if (typeof envChildVarArr === "string") { - envChildVarArr = JSON.parse(envChildVarArr); - } - const response = {}; - for (const item of envChildVarArr) { - response[item.id] = Util2._convertEnvVars(item.environmentVariables); - } - return response; - } - static getBuName(credName, mid) { - let credBuName; - if (!credName) { - throw new Error('System Property "credentialName" not set'); - } - if (!mid) { - throw new Error('System Property "mid" not set'); - } - if (!fs2.existsSync(CONFIG2.configFilePath)) { - throw new Error("Could not find config file " + CONFIG2.configFilePath); - } - const config = JSON.parse(fs2.readFileSync(CONFIG2.configFilePath, "utf8")); - if (config.credentials[credName] && config.credentials[credName].businessUnits) { - const myBuNameArr = Object.keys( - config.credentials[credName].businessUnits - ).filter((buName) => config.credentials[credName].businessUnits[buName] == mid); - if (myBuNameArr.length === 1) { - Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); - credBuName = credName + "/" + myBuNameArr[0]; - } else { - throw new Error(`MID ${mid} not found for ${credName}`); - } - } - return credBuName; - } - }; - module2.exports = Util2; - } + "common/Util.js"(exports, module2) { + "use strict"; + var fs2 = require("fs"); + var execSync2 = require("child_process").execSync; + var TYPE2 = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = class { + static saveJsonFile(localPath, jsObj, beautify) { + const jsonString = beautify ? JSON.stringify(jsObj, null, 4) : JSON.stringify(jsObj); + fs2.writeFileSync(localPath, jsonString, "utf8"); + } + static push(destinationBranch) { + Util2.execCommand( + `Pushing updates to ${destinationBranch} branch`, + ['git push origin "' + destinationBranch + '"'], + "Completed pushing branch" + ); + } + static execCommand(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + try { + execSync2(command, { stdio: [0, 1, 2], stderr: "inherit" }); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + if (null != postMsg) { + Log2.debug("\u2714\uFE0F " + postMsg); + } + } + static execCommandReturnStatus(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + let exitCode = null; + try { + execSync2(command, { stdio: [0, 1, 2], stderr: "inherit" }); + exitCode = 0; + } catch (ex) { + Log2.warn("\u274C " + ex.status + ": " + ex.message); + exitCode = ex.status; + return exitCode; + } + if (null != postMsg) { + Log2.progress("\u2714\uFE0F " + postMsg); + } + return exitCode; + } + static provideMCDevTools() { + if (fs2.existsSync("package.json")) { + Log2.debug("package.json found, assuming npm was already initialized"); + } else { + Util2.execCommand("Initializing npm", ["npm init -y"], "Completed initializing NPM"); + } + let installer; + if (!CONFIG2.installMcdevLocally) { + Util2.execCommand( + `Initializing Accenture SFMC DevTools (packaged version)`, + [ + `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, + "mcdev --version" + ], + "Completed installing Accenture SFMC DevTools" + ); + return; + } else if (!CONFIG2.mcdevVersion) { + Log2.error("Please specify mcdev_version in pipeline & environment settings"); + throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; + } else { + installer = `mcdev@${CONFIG2.mcdevVersion}`; + } + Util2.execCommand( + `Initializing Accenture SFMC DevTools (${installer})`, + [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], + "Completed installing Accenture SFMC DevTools" + ); + } + static provideMCDevCredentials(credentials) { + Log2.info("Provide authentication"); + Util2.saveJsonFile(".mcdev-auth.json", credentials, true); + } + static convertSourceProperties(properties) { + const response = {}; + for (const item of properties) { + response[item.copado__API_Name__c] = item.copado__Value__c; + } + return response; + } + static convertEnvVariables(envVariables) { + Object.keys(envVariables).map((key) => { + if (key.endsWith("Children")) { + envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); + } else { + envVariables[key] = Util2._convertEnvVars(envVariables[key]); + } + }); + } + static _convertEnvVars(envVarArr) { + if (!envVarArr) { + return envVarArr; + } + if (typeof envVarArr === "string") { + envVarArr = JSON.parse(envVarArr); + } + const response = {}; + for (const item of envVarArr) { + response[item.name] = item.value; + } + return response; + } + static _convertEnvChildVars(envChildVarArr) { + if (!envChildVarArr) { + return envChildVarArr; + } + if (typeof envChildVarArr === "string") { + envChildVarArr = JSON.parse(envChildVarArr); + } + const response = {}; + for (const item of envChildVarArr) { + response[item.id] = Util2._convertEnvVars(item.environmentVariables); + } + return response; + } + static getBuName(credName, mid) { + let credBuName; + if (!credName) { + throw new Error('System Property "credentialName" not set'); + } + if (!mid) { + throw new Error('System Property "mid" not set'); + } + if (!fs2.existsSync(CONFIG2.configFilePath)) { + throw new Error("Could not find config file " + CONFIG2.configFilePath); + } + const config = JSON.parse(fs2.readFileSync(CONFIG2.configFilePath, "utf8")); + if (config.credentials[credName] && config.credentials[credName].businessUnits) { + const myBuNameArr = Object.keys(config.credentials[credName].businessUnits).filter( + (buName) => config.credentials[credName].businessUnits[buName] == mid + ); + if (myBuNameArr.length === 1) { + Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); + credBuName = credName + "/" + myBuNameArr[0]; + } else { + throw new Error(`MID ${mid} not found for ${credName}`); + } + } + return credBuName; + } + }; + module2.exports = Util2; + } }); // common/Copado.js var require_Copado = __commonJS({ - "common/Copado.js"(exports, module2) { - "use strict"; - var fs2 = require("fs"); - var exec = require("child_process").exec; - var TYPE2 = require_mcdev_copado_d(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Copado2 = class { - static mcdevInit(credentials, credentialName, url) { - Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` - ], - "Mcdev initialized!" - ); - } - static attachJson(localPath, parentSfid, async = false, preMsg) { - Copado2._attachFile(localPath, async, parentSfid, preMsg); - } - static async attachLog(localPath) { - Copado2._attachFile(localPath, true); - } - static _attachFile( - localPath, - async = false, - parentSfid, - preMsg, - postMsg = "Completed uploading file" - ) { - const command = - `copado --uploadfile "${localPath}"` + - (parentSfid ? ` --parentid "${parentSfid}"` : ""); - if (async) { - Log2.debug("\u26A1 " + command); - try { - exec(command); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - } else { - if (!preMsg) { - preMsg = "Uploading file " + localPath; - if (parentSfid) { - preMsg += ` to ${parentSfid}`; - } - } - Util2.execCommand(preMsg, [command], postMsg); - } - } - static _downloadFile(fileSFID, preMsg) { - if (fileSFID) { - if (!preMsg) { - preMsg = `Download ${fileSFID}.`; - } - Util2.execCommand( - preMsg, - `copado --downloadfiles "${fileSFID}"`, - "Completed download" - ); - } else { - throw new Error("fileSalesforceId is not set"); - } - } - static getJsonFile(fileSFID, fileName, preMsg) { - Copado2._downloadFile(fileSFID, preMsg); - return JSON.parse(fs2.readFileSync(fileName, "utf8")); - } - static checkoutSrc(workingBranch, createBranch = false) { - Util2.execCommand( - `Switching to ${workingBranch} branch`, - [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], - "Completed creating/checking out branch" - ); - } - static deleteBranch(featureBranch) { - Util2.execCommand( - `Deleting branch ${featureBranch} on server`, - [`git push origin --delete ${featureBranch}`], - "Completed deleting server branch " + featureBranch - ); - Util2.execCommand( - `Deleting branch ${featureBranch} locally`, - [`git branch --delete --force ${featureBranch}`], - "Completed deleting local branch " + featureBranch - ); - } - static async uploadToolLogs() { - Log2.debug("Getting mcdev logs"); - try { - const logsAttached = []; - for (const file of fs2.readdirSync("logs")) { - Log2.debug("- " + file); - logsAttached.push(Copado2.attachLog("logs/" + file)); - } - const response = await Promise.all(logsAttached); - Log2.debug("Attached mcdev logs"); - return response; - } catch (ex) { - Log2.debug("attaching mcdev logs failed:" + ex.message); - } + "common/Copado.js"(exports, module2) { + "use strict"; + var fs2 = require("fs"); + var exec = require("child_process").exec; + var TYPE2 = require_mcdev_copado_d(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Copado2 = class { + static attachJson(localPath, parentSfid, async = false, preMsg) { + Copado2._attachFile(localPath, async, parentSfid, preMsg); + } + static async attachLog(localPath) { + Copado2._attachFile(localPath, true); + } + static _attachFile(localPath, async = false, parentSfid, preMsg, postMsg = "Completed uploading file") { + const command = `copado --uploadfile "${localPath}"` + (parentSfid ? ` --parentid "${parentSfid}"` : ""); + if (async) { + Log2.debug("\u26A1 " + command); + try { + exec(command); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + } else { + if (!preMsg) { + preMsg = "Uploading file " + localPath; + if (parentSfid) { + preMsg += ` to ${parentSfid}`; } - }; - module2.exports = Copado2; - } + } + Util2.execCommand(preMsg, [command], postMsg); + } + } + static _downloadFile(fileSFID, preMsg) { + if (fileSFID) { + if (!preMsg) { + preMsg = `Download ${fileSFID}.`; + } + Util2.execCommand(preMsg, `copado --downloadfiles "${fileSFID}"`, "Completed download"); + } else { + throw new Error("fileSalesforceId is not set"); + } + } + static getJsonFile(fileSFID, fileName, preMsg) { + Copado2._downloadFile(fileSFID, preMsg); + return JSON.parse(fs2.readFileSync(fileName, "utf8")); + } + static checkoutSrc(workingBranch, createBranch = false) { + Util2.execCommand( + `Switching to ${workingBranch} branch`, + [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], + "Completed creating/checking out branch" + ); + } + static deleteBranch(featureBranch) { + Util2.execCommand( + `Deleting branch ${featureBranch} on server`, + [`git push origin --delete ${featureBranch}`], + "Completed deleting server branch " + featureBranch + ); + Util2.execCommand( + `Deleting branch ${featureBranch} locally`, + [`git branch --delete --force ${featureBranch}`], + "Completed deleting local branch " + featureBranch + ); + } + static async uploadToolLogs() { + Log2.debug("Getting mcdev logs"); + try { + const logsAttached = []; + for (const file of fs2.readdirSync("logs")) { + Log2.debug("- " + file); + logsAttached.push(Copado2.attachLog("logs/" + file)); + } + const response = await Promise.all(logsAttached); + Log2.debug("Attached mcdev logs"); + return response; + } catch (ex) { + Log2.debug("attaching mcdev logs failed:" + ex.message); + } + } + }; + module2.exports = Copado2; + } }); // common/Commit.js var require_Commit = __commonJS({ - "common/Commit.js"(exports, module2) { - "use strict"; - var fs2 = require("fs"); - var execSync2 = require("child_process").execSync; - var TYPE2 = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Commit2 = class { - static async retrieveCommitSelection(sourceBU, commitSelectionArr) { - const mcdev = require("../tmp/node_modules/mcdev/lib/"); - mcdev.setSkipInteraction(true); - commitSelectionArr = commitSelectionArr.filter((item) => item.a === "add"); - const typeKeyMap = {}; - for (const item of commitSelectionArr) { - if (!typeKeyMap[item.t]) { - typeKeyMap[item.t] = []; - } - const jObj = JSON.parse(item.j); - typeKeyMap[item.t].push(jObj.newKey || jObj.key); - } - const typeArr = [...new Set(commitSelectionArr.map((item) => item.t))]; - await mcdev.retrieve(sourceBU, typeKeyMap, null, false); - const fileArr = ( - await Promise.all( - typeArr.map((type) => { - const keyArr = [ - ...new Set( - commitSelectionArr - .filter((item) => item.t === type) - .map((item) => { - const jObj = JSON.parse(item.j); - return jObj.newKey || jObj.key; - }) - ) - ]; - return mcdev.getFilesToCommit(sourceBU, type.split("-")[0], keyArr); - }) - ) - ).flat(); - return fileArr; - } - static addSelectedComponents(gitAddArr) { - for (const filePath of gitAddArr) { - if (fs2.existsSync(filePath)) { - Util2.execCommand( - null, - ['git add "' + filePath + '"'], - "staged " + filePath - ); - } else { - Log2.warn("\u274C could not find " + filePath); - } - } - } - static commit(originalSelection) { - const gitDiffArr = execSync2("git diff --staged --name-only") - .toString() - .split("\n") - .map((item) => item.trim()) - .filter((item) => !!item); - Log2.debug("Git diff ended with the result:"); - Log2.debug(gitDiffArr); - if (Array.isArray(gitDiffArr) && gitDiffArr.length) { - Util2.execCommand( - "Committing changes to branch", - ['git commit -n -m "' + CONFIG2.commitMessage + '"'], - "Completed committing" - ); - const result = { - committed: gitDiffArr, - noChangesFound: originalSelection - .map((item) => item.replace(new RegExp("\\\\", "g"), "/")) - .filter((item) => !gitDiffArr.includes(item)) - }; - Log2.result( - result, - `Committed ${ - result.committed.filter((item) => item.endsWith(".json")).length - } items with ${result.committed.length} files` - ); - } else { - Log2.error( - "Nothing to commit as all selected components have the same content as already exists in Git. " + - JSON.stringify(originalSelection), - "Nothing to commit" - ); - throw new Error("Nothing to commit"); - } - } - }; - module2.exports = Commit2; - } + "common/Commit.js"(exports, module2) { + "use strict"; + var fs2 = require("fs"); + var execSync2 = require("child_process").execSync; + var TYPE2 = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Commit2 = class { + static async retrieveCommitSelection(sourceBU, commitSelectionArr) { + const mcdev = require("../tmp/node_modules/mcdev/lib/"); + mcdev.setSkipInteraction(true); + commitSelectionArr = commitSelectionArr.filter((item) => item.a === "add"); + const typeKeyMap = {}; + for (const item of commitSelectionArr) { + if (!typeKeyMap[item.t]) { + typeKeyMap[item.t] = []; + } + const jObj = JSON.parse(item.j); + typeKeyMap[item.t].push(jObj.newKey || jObj.key); + } + const typeArr = [...new Set(commitSelectionArr.map((item) => item.t))]; + await mcdev.retrieve(sourceBU, typeKeyMap, null, false); + const fileArr = (await Promise.all( + typeArr.map((type) => { + const keyArr = [ + ...new Set( + commitSelectionArr.filter((item) => item.t === type).map((item) => { + const jObj = JSON.parse(item.j); + return jObj.newKey || jObj.key; + }) + ) + ]; + return mcdev.getFilesToCommit(sourceBU, type.split("-")[0], keyArr); + }) + )).flat(); + return fileArr; + } + static addSelectedComponents(gitAddArr) { + for (const filePath of gitAddArr) { + if (fs2.existsSync(filePath)) { + Util2.execCommand(null, ['git add "' + filePath + '"'], "staged " + filePath); + } else { + Log2.warn("\u274C could not find " + filePath); + } + } + } + static commit(originalSelection) { + const gitDiffArr = execSync2("git diff --staged --name-only").toString().split("\n").map((item) => item.trim()).filter((item) => !!item); + Log2.debug("Git diff ended with the result:"); + Log2.debug(gitDiffArr); + if (Array.isArray(gitDiffArr) && gitDiffArr.length) { + Util2.execCommand( + "Committing changes to branch", + ['git commit -n -m "' + CONFIG2.commitMessage + '"'], + "Completed committing" + ); + const result = { + committed: gitDiffArr, + noChangesFound: originalSelection.map((item) => item.replace(new RegExp("\\\\", "g"), "/")).filter( + (item) => !gitDiffArr.includes(item) + ) + }; + Log2.result( + result, + `Committed ${result.committed.filter((item) => item.endsWith(".json")).length} items with ${result.committed.length} files` + ); + } else { + Log2.error( + "Nothing to commit as all selected components have the same content as already exists in Git. " + JSON.stringify(originalSelection), + "Nothing to commit" + ); + throw new Error("Nothing to commit"); + } + } + }; + module2.exports = Commit2; + } }); // Deploy.fn.js @@ -485,10 +438,10 @@ CONFIG.commitMessage = null; CONFIG.featureBranch = null; CONFIG.recreateFeatureBranch = null; CONFIG.envVariables = { - source: process.env.envVariablesSource, - sourceChildren: process.env.envVariablesSourceChildren, - destination: process.env.envVariablesDestination, - destinationChildren: process.env.envVariablesDestinationChildren + source: process.env.envVariablesSource, + sourceChildren: process.env.envVariablesSourceChildren, + destination: process.env.envVariablesDestination, + destinationChildren: process.env.envVariablesDestinationChildren }; CONFIG.deltaPackageLog = "docs/deltaPackage/delta_package.md"; CONFIG.destinationBranch = process.env.toBranch; @@ -503,525 +456,507 @@ CONFIG.target_mid = process.env.target_mid; CONFIG.sourceProperties = process.env.sourceProperties; CONFIG.deployNTimes = process.env.deployNTimes === "true" ? true : false; async function run() { - Log.info("Deploy.js started"); - Log.debug(""); - Log.debug("Parameters"); - Log.debug("==================="); - try { - CONFIG.credentials = JSON.parse(CONFIG.credentials); - } catch (ex) { - Log.error("Could not parse credentials"); - throw ex; - } + Log.info("Deploy.js started"); + Log.debug(""); + Log.debug("Parameters"); + Log.debug("==================="); + try { + CONFIG.credentials = JSON.parse(CONFIG.credentials); + } catch (ex) { + Log.error("Could not parse credentials"); + throw ex; + } + try { + CONFIG.sourceProperties = JSON.parse(CONFIG.sourceProperties); + } catch (ex) { + Log.error("Could not parse sourceProperties"); + throw ex; + } + Util.convertEnvVariables(CONFIG.envVariables); + CONFIG.sourceProperties = Util.convertSourceProperties(CONFIG.sourceProperties); + CONFIG.source_mid = CONFIG.sourceProperties.mid; + CONFIG.credentialNameSource = CONFIG.sourceProperties.credential_name; + Log.debug(CONFIG); + if (!CONFIG.credentials[CONFIG.credentialNameSource]) { + Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); + throw new Error(`No source credentials`); + } + if (!CONFIG.credentials[CONFIG.credentialNameTarget]) { + Log.error(`No credentials found for target (${CONFIG.credentialNameTarget})`); + throw new Error(`No target credentials`); + } + Log.debug("Environment"); + Log.debug("==================="); + if (CONFIG.debug) { + Util.execCommand(null, "npm --version", null); + Util.execCommand(null, "node --version", null); + Util.execCommand(null, "git version", null); + } + Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + try { + Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + } catch { try { - CONFIG.sourceProperties = JSON.parse(CONFIG.sourceProperties); - } catch (ex) { - Log.error("Could not parse sourceProperties"); - throw ex; - } - Util.convertEnvVariables(CONFIG.envVariables); - CONFIG.sourceProperties = Util.convertSourceProperties(CONFIG.sourceProperties); - CONFIG.source_mid = CONFIG.sourceProperties.mid; - CONFIG.credentialNameSource = CONFIG.sourceProperties.credential_name; - Log.debug(CONFIG); - if (!CONFIG.credentials[CONFIG.credentialNameSource]) { - Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); - throw new Error(`No source credentials`); - } - if (!CONFIG.credentials[CONFIG.credentialNameTarget]) { - Log.error(`No credentials found for target (${CONFIG.credentialNameTarget})`); - throw new Error(`No target credentials`); - } - Log.debug("Environment"); - Log.debug("==================="); - if (CONFIG.debug) { - Util.execCommand(null, "npm --version", null); - Util.execCommand(null, "node --version", null); - Util.execCommand(null, "git version", null); - } - Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); - try { - Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + Util.execCommand(null, [ + "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) + ]); } catch { - try { - Util.execCommand(null, [ - "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) - ]); - } catch { - Log.error("Could not set tmp directoy as safe directory"); - } - } - process.chdir(CONFIG.tmpDirectory); - Log.debug(process.cwd()); - try { - Log.info(""); - Log.info("Clone repository"); - Log.info("==================="); - Log.info(""); - Copado.checkoutSrc(CONFIG.promotionBranch); - Copado.checkoutSrc(CONFIG.mainBranch); - } catch (ex) { - Log.error("Cloning failed:" + ex.message); - throw ex; + Log.error("Could not set tmp directoy as safe directory"); } + } + process.chdir(CONFIG.tmpDirectory); + Log.debug(process.cwd()); + try { + Log.info(""); + Log.info("Clone repository"); + Log.info("==================="); + Log.info(""); + Copado.checkoutSrc(CONFIG.promotionBranch); + Copado.checkoutSrc(CONFIG.mainBranch); + } catch (ex) { + Log.error("Cloning failed:" + ex.message); + throw ex; + } + try { + Log.info(""); + Log.info("Merge branch"); + Log.info("==================="); + Log.info(""); + Deploy.merge(CONFIG.promotionBranch, CONFIG.mainBranch); + } catch (ex) { + Log.error("Merge failed: " + ex.message); + throw ex; + } + let commitSelectionArr; + try { + Log.info(""); + Log.info( + `Add selected components defined in ${CONFIG.fileSelectionSalesforceId} to metadata JSON` + ); + Log.info("==================="); + Log.info(""); + commitSelectionArr = Copado.getJsonFile( + CONFIG.fileSelectionSalesforceId, + CONFIG.fileSelectionFileName, + "Retrieving list of selected items" + ); + if (!Array.isArray(commitSelectionArr) || commitSelectionArr.length === 0) { + throw new Error( + "Copado has not registered any files ready for deployment. Please check if you committed all files." + ); + } + } catch (ex) { + Log.error("Getting Deploy-selection file failed:" + ex.message); + throw ex; + } + try { + Log.info(""); + Log.info("Preparing"); + Log.info("==================="); + Log.info(""); + Util.provideMCDevTools(); + Util.provideMCDevCredentials(CONFIG.credentials); + } catch (ex) { + Log.error("initializing failed: " + ex.message); + throw ex; + } + let deployFolder; + try { + Log.info(""); + Log.info("Determine deploy folder"); + Log.info("==================="); + Log.info(""); + deployFolder = Deploy.getDeployFolder(); + } catch (ex) { + Log.error("getDeployFolder failed: " + ex.message); + throw ex; + } + let sourceBU; + let targetBU; + try { + Log.info(""); + Log.info("Create delta package"); + Log.info("==================="); + Log.info(""); + sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); + targetBU = Util.getBuName(CONFIG.credentialNameTarget, CONFIG.target_mid); + } catch (ex) { + Log.error("Getting Source / Target BU failed: " + ex.message); + throw ex; + } + try { + Deploy.updateMarketLists(sourceBU, targetBU, CONFIG.envVariables); + } catch (ex) { + Log.error("Updateing Market List failed: " + ex.message); + throw ex; + } + try { + if (await Deploy.createDeltaPackage( + deployFolder, + commitSelectionArr, + sourceBU.split("/")[1] + )) { + Log.info("Deploy BUs"); + Log.info("==================="); + const deployResult = await Deploy.deployBU(targetBU); + commitSelectionArr = Deploy.replaceMarketValues(commitSelectionArr); + Deploy.replaceAssetKeys(targetBU, commitSelectionArr, deployResult); + } else { + throw new Error("No changes found. Nothing to deploy"); + } + } catch (ex) { + Log.error("Deploy failed: " + ex.message); + Copado.uploadToolLogs(); + throw ex; + } + let gitDiffArr; + let verificationText; + try { + gitDiffArr = await Deploy.retrieveAndCommit(targetBU, commitSelectionArr); + } catch (ex) { + verificationText = "Failed deploy verification, check BU on SFMC to verify manually. Git not updated with the changes on target BU"; + Log.warn(verificationText + ": " + ex.message); + gitDiffArr = []; + } + let success = false; + let i = 0; + do { + i++; try { - Log.info(""); - Log.info("Merge branch"); - Log.info("==================="); - Log.info(""); - Deploy.merge(CONFIG.promotionBranch, CONFIG.mainBranch); + Log.info("git-push changes"); + Log.info("==================="); + Util.push(CONFIG.mainBranch); + success = true; } catch (ex) { - Log.error("Merge failed: " + ex.message); - throw ex; - } - let commitSelectionArr; + if (ex.message === `Error: Command failed: git push origin "${CONFIG.mainBranch}"`) { + Log.progress("Merging changes from parallel deployments"); + Util.execCommand(null, ['git fetch origin "' + CONFIG.mainBranch + '"'], null); + Util.execCommand(null, ["git reset --hard origin/" + CONFIG.mainBranch], null); + Util.execCommand(null, ['git merge "' + CONFIG.promotionBranch + '"'], null); + } + } + } while (!success && i <= 50); + Log.info(""); + Log.info("==================="); + Log.info(""); + Log.info("Deploy.js done"); + Log.result( + gitDiffArr, + `Deployed ${gitDiffArr.filter((item) => item.endsWith(".json")).length} items with ${gitDiffArr.length} files` + (verificationText ? ` (${verificationText})` : "") + ); + Copado.uploadToolLogs(); +} +var Deploy = class { + static stashChanges() { + Util.execCommand(null, [`git stash`], null); + } + static async retrieveAndCommit(targetBU, commitSelectionArr) { + let gitAddArr; + let gitDiffArr = []; try { - Log.info(""); - Log.info( - `Add selected components defined in ${CONFIG.fileSelectionSalesforceId} to metadata JSON` - ); - Log.info("==================="); - Log.info(""); - commitSelectionArr = Copado.getJsonFile( - CONFIG.fileSelectionSalesforceId, - CONFIG.fileSelectionFileName, - "Retrieving list of selected items" - ); - if (!Array.isArray(commitSelectionArr) || commitSelectionArr.length === 0) { - throw new Error( - "Copado has not registered any files ready for deployment. Please check if you committed all files." - ); - } + Log.info( + `Stashing changes made by mcdev.deploy() to avoid issues during branch checkout` + ); + Deploy.stashChanges(); + Log.info("Switch to source branch to add updates for target"); + Copado.checkoutSrc(CONFIG.promotionBranch); } catch (ex) { - Log.error("Getting Deploy-selection file failed:" + ex.message); - throw ex; + Log.error("Switching failed:" + ex.message); + throw ex; } try { - Log.info(""); - Log.info("Preparing"); - Log.info("==================="); - Log.info(""); - Util.provideMCDevTools(); - Util.provideMCDevCredentials(CONFIG.credentials); + Log.info(""); + Log.info("Retrieve components"); + Log.info("==================="); + Log.info(""); + gitAddArr = await Commit.retrieveCommitSelection(targetBU, commitSelectionArr); } catch (ex) { - Log.error("initializing failed: " + ex.message); - throw ex; + Log.error("Retrieving failed: " + ex.message); + Copado.uploadToolLogs(); + throw ex; } - let deployFolder; try { - Log.info(""); - Log.info("Determine deploy folder"); - Log.info("==================="); - Log.info(""); - deployFolder = Deploy.getDeployFolder(); + Log.info(""); + Log.info("Add components in metadata JSON to Git history"); + Log.info("==================="); + Log.info(""); + Commit.addSelectedComponents(gitAddArr); } catch (ex) { - Log.error("getDeployFolder failed: " + ex.message); - throw ex; + Log.error("git add failed:" + ex.message); + throw ex; } - let sourceBU; - let targetBU; try { - Log.info(""); - Log.info("Create delta package"); - Log.info("==================="); - Log.info(""); - sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); - targetBU = Util.getBuName(CONFIG.credentialNameTarget, CONFIG.target_mid); + Log.info(""); + Log.info("Commit"); + Log.info("==================="); + Log.info(""); + const commitMsgLines = Deploy.getCommitMessage(targetBU, commitSelectionArr); + gitDiffArr = Deploy.commit(commitMsgLines); } catch (ex) { - Log.error("Getting Source / Target BU failed: " + ex.message); - throw ex; + Log.error("git commit failed:" + ex.message); + throw ex; } try { - Deploy.updateMarketLists(sourceBU, targetBU, CONFIG.envVariables); + Log.info("Switch back to main branch to allow merging promotion branch into it"); + Copado.checkoutSrc(CONFIG.mainBranch); } catch (ex) { - Log.error("Updateing Market List failed: " + ex.message); - throw ex; + Log.error("Switching failed:" + ex.message); + throw ex; } try { - if ( - await Deploy.createDeltaPackage( - deployFolder, - commitSelectionArr, - sourceBU.split("/")[1] - ) - ) { - Log.info("Deploy BUs"); - Log.info("==================="); - const deployResult = await Deploy.deployBU(targetBU); - commitSelectionArr = Deploy.replaceMarketValues(commitSelectionArr); - Deploy.replaceAssetKeys(targetBU, commitSelectionArr, deployResult); - } else { - throw new Error("No changes found. Nothing to deploy"); - } + Log.info("Merge promotion into main branch"); + Deploy.merge(CONFIG.promotionBranch, CONFIG.mainBranch); } catch (ex) { - Log.error("Deploy failed: " + ex.message); - Copado.uploadToolLogs(); - throw ex; - } - let gitDiffArr; - let verificationText; + Log.error("Merge failed: " + ex.message); + throw ex; + } + return gitDiffArr; + } + static commit(commitMsgLines) { + const gitDiffArr = execSync("git diff --staged --name-only").toString().split("\n").map((item) => item.trim()).filter((item) => !!item); + Log.debug("Git diff ended with the result:"); + Log.debug(gitDiffArr); + if (Array.isArray(gitDiffArr) && gitDiffArr.length) { + if (!Array.isArray(commitMsgLines)) { + commitMsgLines = [CONFIG.commitMessage]; + } + const commitMsgParam = commitMsgLines.map((line) => '-m "' + line + '"').join(" "); + Util.execCommand( + "Committing changes", + ["git commit -n " + commitMsgParam], + "Completed committing" + ); + Log.progress("Commit of target BU files completed"); + } else { + Log.error( + "Nothing to commit as all selected components have the same content as already exists in Git.", + "Nothing to commit" + ); + throw new Error("Nothing to commit"); + } + return gitDiffArr; + } + static getCommitMessage(targetBU, commitSelectionArr) { + const userStoryNames = [ + ...new Set(commitSelectionArr.map((item) => item.u).filter(Boolean)) + ].sort(); + const commitMsgLines = [ + CONFIG.promotionName + ": " + userStoryNames.join(", "), + `Updated BU "${targetBU}" (${CONFIG.target_mid})` + ]; + return commitMsgLines; + } + static _convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU) { + return commitSelectionArr.map( + (item) => ({ + type: item.t.split("-")[0], + name: item.n, + externalKey: JSON.parse(item.j).newKey || JSON.parse(item.j).key, + gitAction: "add/update", + _credential: CONFIG.credentialNameSource, + _businessUnit: sourceBU + }) + ); + } + static getDeployFolder() { + var _a; + if (!fs.existsSync(CONFIG.configFilePath)) { + throw new Error("Could not find config file " + CONFIG.configFilePath); + } + const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); + const folder = (_a = config == null ? void 0 : config.directories) == null ? void 0 : _a.deploy; + if (!folder) { + throw new Error("Could not find config.directories.deploy in " + CONFIG.configFilePath); + } + Log.debug("Deploy folder is: " + folder); + return folder; + } + static updateMarketLists(sourceBU, targetBU, marketVariables) { + const deploySourceList = "deployment-source"; + const deployTargetList = "deployment-target"; + const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); + config.options.deployment.sourceTargetMapping = {}; + config.options.deployment.sourceTargetMapping[deploySourceList] = deployTargetList; + config.markets = {}; + if (CONFIG.deployNTimes) { + if (Object.keys(CONFIG.envVariables.sourceChildren).length !== 1) { + throw new Error( + 'Expected exactly one source child BU when "deployNTimes" is active in pipeline but found ' + Object.keys(CONFIG.envVariables.sourceChildren).length + ); + } + for (const childSfid in CONFIG.envVariables.sourceChildren) { + config.markets[childSfid] = CONFIG.envVariables.sourceChildren[childSfid]; + } + for (const childSfid in CONFIG.envVariables.destinationChildren) { + config.markets[childSfid] = CONFIG.envVariables.destinationChildren[childSfid]; + } + } else { + config.markets["source"] = marketVariables.source; + config.markets["target"] = marketVariables.destination; + } + config.marketList = {}; + for (const listName of [deploySourceList, deployTargetList]) { + config.marketList[listName] = {}; + } + if (CONFIG.deployNTimes) { + config.marketList[deploySourceList][sourceBU] = Object.keys( + CONFIG.envVariables.sourceChildren + )[0]; + config.marketList[deployTargetList][targetBU] = Object.keys( + CONFIG.envVariables.destinationChildren + ); + } else { + config.marketList[deploySourceList][sourceBU] = "source"; + config.marketList[deployTargetList][targetBU] = "target"; + } + Log.debug("config.options.deployment.sourceTargetMapping"); + Log.debug(config.options.deployment.sourceTargetMapping); + Log.debug("config.markets"); + Log.debug(config.markets); + Log.debug("config.marketList"); + Log.debug(JSON.stringify(config.marketList)); try { - gitDiffArr = await Deploy.retrieveAndCommit(targetBU, commitSelectionArr); + fs.renameSync(CONFIG.configFilePath, CONFIG.configFilePath + ".BAK"); + Util.saveJsonFile(CONFIG.configFilePath, config, "utf8"); } catch (ex) { - verificationText = - "Failed deploy verification, check BU on SFMC to verify manually. Git not updated with the changes on target BU"; - Log.warn(verificationText + ": " + ex.message); - gitDiffArr = []; - } - let success = false; - let i = 0; - do { - i++; - try { - Log.info("git-push changes"); - Log.info("==================="); - Util.push(CONFIG.mainBranch); - success = true; - } catch (ex) { - if (ex.message === `Error: Command failed: git push origin "${CONFIG.mainBranch}"`) { - Log.progress("Merging changes from parallel deployments"); - Util.execCommand(null, ['git fetch origin "' + CONFIG.mainBranch + '"'], null); - Util.execCommand(null, ["git reset --hard origin/" + CONFIG.mainBranch], null); - Util.execCommand(null, ['git merge "' + CONFIG.promotionBranch + '"'], null); - } + Log.error("Updating updateMarketLists failed: " + ex.message); + throw ex; + } + } + static async createDeltaPackage(deployFolder, commitSelectionArr, sourceBU) { + const mcdev = require("../tmp/node_modules/mcdev/lib"); + mcdev.setSkipInteraction(true); + const versionRange = null; + let deltaPkgItems = null; + if (Array.isArray(commitSelectionArr) && commitSelectionArr.length) { + deltaPkgItems = this._convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU); + Log.info(`Found ${deltaPkgItems.length} changed components in commits`); + Log.debug("DeltaPkgItems: "); + Log.debug(deltaPkgItems); + } else { + Log.info("No changed components found in commits"); + } + const deltaPackageLog = await mcdev.createDeltaPkg({ + range: versionRange, + diffArr: deltaPkgItems + }); + Log.debug("deltaPackageLog: " + JSON.stringify(deltaPackageLog)); + if (!(deltaPackageLog == null ? void 0 : deltaPackageLog.length)) { + Log.error("No changes found for deployment"); + return false; + } else { + Log.debug("deltaPackageLog:"); + Log.debug(deltaPackageLog); + } + Log.debug("Completed creating delta package"); + if (fs.existsSync(CONFIG.deltaPackageLog)) { + Copado.attachLog(CONFIG.deltaPackageLog); + } + if (fs.existsSync(deployFolder)) { + const deltaPackageFiles = fs.readdirSync(deployFolder); + if (null != deltaPackageFiles) { + Log.debug("Found " + deltaPackageFiles.length + " files to deploy"); + if (0 < deltaPackageFiles.length) { + return true; } - } while (!success && i <= 50); - Log.info(""); - Log.info("==================="); - Log.info(""); - Log.info("Deploy.js done"); - Log.result( - gitDiffArr, - `Deployed ${gitDiffArr.filter((item) => item.endsWith(".json")).length} items with ${ - gitDiffArr.length - } files` + (verificationText ? ` (${verificationText})` : "") - ); - Copado.uploadToolLogs(); -} -var Deploy = class { - static stashChanges() { - Util.execCommand(null, [`git stash`], null); - } - static async retrieveAndCommit(targetBU, commitSelectionArr) { - let gitAddArr; - let gitDiffArr = []; - try { - Log.info( - `Stashing changes made by mcdev.deploy() to avoid issues during branch checkout` - ); - Deploy.stashChanges(); - Log.info("Switch to source branch to add updates for target"); - Copado.checkoutSrc(CONFIG.promotionBranch); - } catch (ex) { - Log.error("Switching failed:" + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Retrieve components"); - Log.info("==================="); - Log.info(""); - gitAddArr = await Commit.retrieveCommitSelection(targetBU, commitSelectionArr); - } catch (ex) { - Log.error("Retrieving failed: " + ex.message); - Copado.uploadToolLogs(); - throw ex; - } - try { - Log.info(""); - Log.info("Add components in metadata JSON to Git history"); - Log.info("==================="); - Log.info(""); - Commit.addSelectedComponents(gitAddArr); - } catch (ex) { - Log.error("git add failed:" + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Commit"); - Log.info("==================="); - Log.info(""); - const commitMsgLines = Deploy.getCommitMessage(targetBU, commitSelectionArr); - gitDiffArr = Deploy.commit(commitMsgLines); - } catch (ex) { - Log.error("git commit failed:" + ex.message); - throw ex; - } - try { - Log.info("Switch back to main branch to allow merging promotion branch into it"); - Copado.checkoutSrc(CONFIG.mainBranch); - } catch (ex) { - Log.error("Switching failed:" + ex.message); - throw ex; - } - try { - Log.info("Merge promotion into main branch"); - Deploy.merge(CONFIG.promotionBranch, CONFIG.mainBranch); - } catch (ex) { - Log.error("Merge failed: " + ex.message); - throw ex; - } - return gitDiffArr; - } - static commit(commitMsgLines) { - const gitDiffArr = execSync("git diff --staged --name-only") - .toString() - .split("\n") - .map((item) => item.trim()) - .filter((item) => !!item); - Log.debug("Git diff ended with the result:"); - Log.debug(gitDiffArr); - if (Array.isArray(gitDiffArr) && gitDiffArr.length) { - if (!Array.isArray(commitMsgLines)) { - commitMsgLines = [CONFIG.commitMessage]; - } - const commitMsgParam = commitMsgLines.map((line) => '-m "' + line + '"').join(" "); - Util.execCommand( - "Committing changes", - ["git commit -n " + commitMsgParam], - "Completed committing" - ); - Log.progress("Commit of target BU files completed"); + } else { + Log.debug("Could not find any files to deploy in folder " + deployFolder); + } + } else { + Log.debug("Could not find deploy folder " + deployFolder); + } + return false; + } + static _getConfigForToBranch(branch) { + let configBranch = branch; + if (branch.startsWith("release/")) { + configBranch = "release/*"; + } else if (branch.startsWith("hotfix/")) { + configBranch = "hotfix/*"; + } + Log.debug("Config branch for branch " + branch + " is " + configBranch); + return configBranch; + } + static async deployBU(bu) { + const mcdev = require("../tmp/node_modules/mcdev/lib"); + mcdev.setSkipInteraction(true); + const deployResult = await mcdev.deploy(bu); + if (process.exitCode === 1) { + throw new Error( + "Deployment of BU " + bu + " failed. Please check the SFMC DevTools logs for more details." + ); + } + return deployResult; + } + static replaceAssetKeys(bu, commitSelectionArr, deployResult) { + const commitSelectionArrMap = []; + for (const i in commitSelectionArr) { + if (commitSelectionArr[i].t.split("-")[0] === "asset") { + const suffix = "-" + CONFIG.target_mid; + const jObj = JSON.parse(commitSelectionArr[i].j); + const oldKey = jObj.newKey || jObj.key; + const newKey = CONFIG.source_mid === CONFIG.target_mid || oldKey.endsWith(suffix) ? oldKey : oldKey.slice(0, Math.max(0, 36 - suffix.length)) + suffix; + if (deployResult[bu].asset[newKey]) { + jObj.newKey = newKey; + commitSelectionArr[i].j = JSON.stringify(jObj); + commitSelectionArrMap.push(jObj); } else { - Log.error( - "Nothing to commit as all selected components have the same content as already exists in Git.", - "Nothing to commit" - ); - throw new Error("Nothing to commit"); - } - return gitDiffArr; - } - static getCommitMessage(targetBU, commitSelectionArr) { - const userStoryNames = [ - ...new Set(commitSelectionArr.map((item) => item.u).filter(Boolean)) - ].sort(); - const commitMsgLines = [ - CONFIG.promotionName + ": " + userStoryNames.join(", "), - `Updated BU "${targetBU}" (${CONFIG.target_mid})` - ]; - return commitMsgLines; - } - static _convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU) { - return commitSelectionArr.map((item) => ({ - type: item.t.split("-")[0], - name: item.n, - externalKey: JSON.parse(item.j).newKey || JSON.parse(item.j).key, - gitAction: "add/update", - _credential: CONFIG.credentialNameSource, - _businessUnit: sourceBU - })); - } - static getDeployFolder() { - var _a; - if (!fs.existsSync(CONFIG.configFilePath)) { - throw new Error("Could not find config file " + CONFIG.configFilePath); - } - const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); - const folder = - (_a = config == null ? void 0 : config.directories) == null ? void 0 : _a.deploy; - if (!folder) { - throw new Error("Could not find config.directories.deploy in " + CONFIG.configFilePath); - } - Log.debug("Deploy folder is: " + folder); - return folder; - } - static updateMarketLists(sourceBU, targetBU, marketVariables) { - const deploySourceList = "deployment-source"; - const deployTargetList = "deployment-target"; - const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); - config.options.deployment.sourceTargetMapping = {}; - config.options.deployment.sourceTargetMapping[deploySourceList] = deployTargetList; - config.markets = {}; - if (CONFIG.deployNTimes) { - if (Object.keys(CONFIG.envVariables.sourceChildren).length !== 1) { - throw new Error( - 'Expected exactly one source child BU when "deployNTimes" is active in pipeline but found ' + - Object.keys(CONFIG.envVariables.sourceChildren).length - ); - } - for (const childSfid in CONFIG.envVariables.sourceChildren) { - config.markets[childSfid] = CONFIG.envVariables.sourceChildren[childSfid]; - } - for (const childSfid in CONFIG.envVariables.destinationChildren) { - config.markets[childSfid] = CONFIG.envVariables.destinationChildren[childSfid]; - } - } else { - config.markets["source"] = marketVariables.source; - config.markets["target"] = marketVariables.destination; - } - config.marketList = {}; - for (const listName of [deploySourceList, deployTargetList]) { - config.marketList[listName] = {}; - } - if (CONFIG.deployNTimes) { - config.marketList[deploySourceList][sourceBU] = Object.keys( - CONFIG.envVariables.sourceChildren - )[0]; - config.marketList[deployTargetList][targetBU] = Object.keys( - CONFIG.envVariables.destinationChildren - ); - } else { - config.marketList[deploySourceList][sourceBU] = "source"; - config.marketList[deployTargetList][targetBU] = "target"; - } - Log.debug("config.options.deployment.sourceTargetMapping"); - Log.debug(config.options.deployment.sourceTargetMapping); - Log.debug("config.markets"); - Log.debug(config.markets); - Log.debug("config.marketList"); - Log.debug(JSON.stringify(config.marketList)); - try { - fs.renameSync(CONFIG.configFilePath, CONFIG.configFilePath + ".BAK"); - Util.saveJsonFile(CONFIG.configFilePath, config, "utf8"); - } catch (ex) { - Log.error("Updating updateMarketLists failed: " + ex.message); - throw ex; + throw new Error( + `New key for ${commitSelectionArr[i].n} does not match any valid keys.` + ); } - } - static async createDeltaPackage(deployFolder, commitSelectionArr, sourceBU) { - const mcdev = require("../tmp/node_modules/mcdev/lib"); - mcdev.setSkipInteraction(true); - const versionRange = null; - let deltaPkgItems = null; - if (Array.isArray(commitSelectionArr) && commitSelectionArr.length) { - deltaPkgItems = this._convertCommitToDeltaPkgItems(commitSelectionArr, sourceBU); - Log.info(`Found ${deltaPkgItems.length} changed components in commits`); - Log.debug("DeltaPkgItems: "); - Log.debug(deltaPkgItems); - } else { - Log.info("No changed components found in commits"); - } - const deltaPackageLog = await mcdev.createDeltaPkg({ - range: versionRange, - diffArr: deltaPkgItems - }); - Log.debug("deltaPackageLog: " + JSON.stringify(deltaPackageLog)); - if (!(deltaPackageLog == null ? void 0 : deltaPackageLog.length)) { - Log.error("No changes found for deployment"); - return false; - } else { - Log.debug("deltaPackageLog:"); - Log.debug(deltaPackageLog); - } - Log.debug("Completed creating delta package"); - if (fs.existsSync(CONFIG.deltaPackageLog)) { - Copado.attachLog(CONFIG.deltaPackageLog); - } - if (fs.existsSync(deployFolder)) { - const deltaPackageFiles = fs.readdirSync(deployFolder); - if (null != deltaPackageFiles) { - Log.debug("Found " + deltaPackageFiles.length + " files to deploy"); - if (0 < deltaPackageFiles.length) { - return true; - } - } else { - Log.debug("Could not find any files to deploy in folder " + deployFolder); - } - } else { - Log.debug("Could not find deploy folder " + deployFolder); - } - return false; - } - static _getConfigForToBranch(branch) { - let configBranch = branch; - if (branch.startsWith("release/")) { - configBranch = "release/*"; - } else if (branch.startsWith("hotfix/")) { - configBranch = "hotfix/*"; - } - Log.debug("Config branch for branch " + branch + " is " + configBranch); - return configBranch; - } - static async deployBU(bu) { - const mcdev = require("../tmp/node_modules/mcdev/lib"); - mcdev.setSkipInteraction(true); - const deployResult = await mcdev.deploy(bu); - if (process.exitCode === 1) { - throw new Error( - "Deployment of BU " + - bu + - " failed. Please check the SFMC DevTools logs for more details." - ); + } + } + Util.saveJsonFile(`Copado Deploy changes-${CONFIG.target_mid}.json`, commitSelectionArr); + Copado.attachJson(`Copado Deploy changes-${CONFIG.target_mid}.json`, null, true); + } + static merge(promotionBranch, currentBranch) { + Util.execCommand( + `Merge ${promotionBranch} into ${currentBranch}`, + ['git merge "' + promotionBranch + '"'], + "Completed merging commit" + ); + } + static replaceMarketValues(commitSelectionArr) { + Log.debug("replacing market values"); + const commitSelectionArrNew = []; + const replaceMapList = []; + if (CONFIG.deployNTimes) { + for (const sfid in CONFIG.envVariables.destinationChildren) { + const replaceMap = {}; + const sourceSfid = Object.keys(CONFIG.envVariables.sourceChildren)[0]; + for (const item in CONFIG.envVariables.sourceChildren[sourceSfid]) { + if (typeof CONFIG.envVariables.destinationChildren[sfid][item] !== "undefined") { + replaceMap[CONFIG.envVariables.sourceChildren[sourceSfid][item]] = CONFIG.envVariables.destinationChildren[sfid][item]; + } } - return deployResult; - } - static replaceAssetKeys(bu, commitSelectionArr, deployResult) { - const commitSelectionArrMap = []; - for (const i in commitSelectionArr) { - if (commitSelectionArr[i].t.split("-")[0] === "asset") { - const suffix = "-" + CONFIG.target_mid; - const jObj = JSON.parse(commitSelectionArr[i].j); - const oldKey = jObj.newKey || jObj.key; - const newKey = - CONFIG.source_mid === CONFIG.target_mid || oldKey.endsWith(suffix) - ? oldKey - : oldKey.slice(0, Math.max(0, 36 - suffix.length)) + suffix; - if (deployResult[bu].asset[newKey]) { - jObj.newKey = newKey; - commitSelectionArr[i].j = JSON.stringify(jObj); - commitSelectionArrMap.push(jObj); - } else { - throw new Error( - `New key for ${commitSelectionArr[i].n} does not match any valid keys.` - ); - } - } + replaceMapList.push(replaceMap); + } + } else { + const replaceMap = {}; + for (const item in CONFIG.envVariables.source) { + if (typeof CONFIG.envVariables.destination[item] !== "undefined") { + replaceMap[CONFIG.envVariables.source[item]] = CONFIG.envVariables.destination[item]; } - Util.saveJsonFile(`Copado Deploy changes-${CONFIG.target_mid}.json`, commitSelectionArr); - Copado.attachJson(`Copado Deploy changes-${CONFIG.target_mid}.json`, null, true); - } - static merge(promotionBranch, currentBranch) { - Util.execCommand( - `Merge ${promotionBranch} into ${currentBranch}`, - ['git merge "' + promotionBranch + '"'], - "Completed merging commit" - ); - } - static replaceMarketValues(commitSelectionArr) { - Log.debug("replacing market values"); - const commitSelectionArrNew = []; - const replaceMapList = []; - if (CONFIG.deployNTimes) { - for (const sfid in CONFIG.envVariables.destinationChildren) { - const replaceMap = {}; - const sourceSfid = Object.keys(CONFIG.envVariables.sourceChildren)[0]; - for (const item in CONFIG.envVariables.sourceChildren[sourceSfid]) { - if ( - typeof CONFIG.envVariables.destinationChildren[sfid][item] !== "undefined" - ) { - replaceMap[CONFIG.envVariables.sourceChildren[sourceSfid][item]] = - CONFIG.envVariables.destinationChildren[sfid][item]; - } - } - replaceMapList.push(replaceMap); - } - } else { - const replaceMap = {}; - for (const item in CONFIG.envVariables.source) { - if (typeof CONFIG.envVariables.destination[item] !== "undefined") { - replaceMap[CONFIG.envVariables.source[item]] = - CONFIG.envVariables.destination[item]; - } - } - replaceMapList.push(replaceMap); - } - for (const replaceMap of replaceMapList) { - const commitSelectionArrClone = JSON.parse(JSON.stringify(commitSelectionArr)); - for (const item of commitSelectionArrClone) { - for (const oldValue in replaceMap) { - item.n = item.n.replace(new RegExp(oldValue, "g"), replaceMap[oldValue]); - const jObj = JSON.parse(item.j); - jObj.newKey = (jObj.newKey || jObj.key).replace( - new RegExp(oldValue, "g"), - replaceMap[oldValue] - ); - item.j = JSON.stringify(jObj); - } - } - commitSelectionArrNew.push(...commitSelectionArrClone); + } + replaceMapList.push(replaceMap); + } + for (const replaceMap of replaceMapList) { + const commitSelectionArrClone = JSON.parse(JSON.stringify(commitSelectionArr)); + for (const item of commitSelectionArrClone) { + for (const oldValue in replaceMap) { + item.n = item.n.replace(new RegExp(oldValue, "g"), replaceMap[oldValue]); + const jObj = JSON.parse(item.j); + jObj.newKey = (jObj.newKey || jObj.key).replace( + new RegExp(oldValue, "g"), + replaceMap[oldValue] + ); + item.j = JSON.stringify(jObj); } - return commitSelectionArrNew; + } + commitSelectionArrNew.push(...commitSelectionArrClone); } + return commitSelectionArrNew; + } }; run(); diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 1ab207e..b7f72df 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-21T16:06:40.873Z) + * mcdev-copado v1.1.2 (built 2022-11-22T09:51:50.911Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -250,15 +250,6 @@ var require_Copado = __commonJS({ var Log2 = require_Log(); var Util2 = require_Util(); var Copado2 = class { - static mcdevInit(credentials, credentialName, options) { - Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"` - ], - "Mcdev initialized!" - ); - } static attachJson(localPath, parentSfid, async = false, preMsg) { Copado2._attachFile(localPath, async, parentSfid, preMsg); } @@ -349,14 +340,11 @@ CONFIG.credentialNameTarget = null; CONFIG.client_id = process.env.client_id; CONFIG.client_secret = process.env.client_secret; CONFIG.auth_url = process.env.auth_url; -CONFIG.account_id = process.env.account_id; +CONFIG.account_id = process.env.enterprise_id; CONFIG.credentials = `{"${CONFIG.credentialNameSource}":{"client_id":"${CONFIG.client_id}","client_secret":"${CONFIG.client_secret}","auth_url":"${CONFIG.auth_url}","account_id":"${CONFIG.account_id}"}}`; CONFIG.configFilePath = null; -CONFIG.repoUrl = process.env.repoUrl; -CONFIG.downloadBUs = process.env.downloadBUs === "true" ? true : false; -CONFIG.gitPush = process.env.gitPush === "true" ? true : false; CONFIG.debug = process.env.debug === "true" ? true : false; -CONFIG.installMcdevLocally = process.env.installMcdevLocally === "true" ? true : false; +CONFIG.installMcdevLocally = null; CONFIG.mainBranch = null; CONFIG.mcdevVersion = process.env.mcdev_version; CONFIG.metadataFilePath = null; @@ -384,6 +372,9 @@ CONFIG.merge_strategy = null; CONFIG.promotionBranch = null; CONFIG.promotionName = null; CONFIG.target_mid = null; +CONFIG.repoUrl = process.env.repoUrl; +CONFIG.downloadBUs = process.env.downloadBUs === "true" ? true : false; +CONFIG.gitPush = process.env.gitPush === "true" ? true : false; async function run() { Log.info("McdevInit.js started"); Log.debug(""); @@ -439,22 +430,12 @@ async function run() { Log.error("adding git email and name failed: " + ex.message); throw ex; } - try { - Log.info(""); - Log.info("Preparing"); - Log.info("==================="); - Log.info(""); - Util.provideMCDevTools(); - } catch (ex) { - Log.error("Preparing failed: " + ex.message); - throw ex; - } try { Log.info(""); Log.info("Initializing mcdev tools"); Log.info("==================="); Log.info(""); - Copado.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { + Init.mcdevInit(CONFIG.credentials, CONFIG.credentialNameSource, { url: CONFIG.repoUrl, downloadBUs: CONFIG.downloadBUs, gitPush: CONFIG.gitPush @@ -469,4 +450,15 @@ async function run() { Log.info("McdevInit.js done"); Copado.uploadToolLogs(); } +var Init = class { + static mcdevInit(credentials, credentialName, options) { + Util.execCommand( + `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, + [ + `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"` + ], + "Mcdev initialized!" + ); + } +}; run(); diff --git a/copado-function/dist/Retrieve.fn.js b/copado-function/dist/Retrieve.fn.js index 6478d1d..a5dcdb5 100644 --- a/copado-function/dist/Retrieve.fn.js +++ b/copado-function/dist/Retrieve.fn.js @@ -1,365 +1,333 @@ #!/usr/bin/env node /* - * mcdev-copado v1.1.2 (built 2022-11-17T12:49:28.085Z) + * mcdev-copado v1.1.2 (built 2022-11-22T09:51:48.953Z) * Function: Retrieve.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme * Support: https://github.com/Accenture/sfmc-devtools-copado/issues * Git-Repository: https://github.com/Accenture/sfmc-devtools-copado.git * Copyright (c) 2022 Accenture. MIT licensed - */ +*/ + "use strict"; var __getOwnPropNames = Object.getOwnPropertyNames; -var __commonJS = (cb, mod) => - function __require() { - return ( - mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), - mod.exports - ); - }; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; // types/mcdev-copado.d.js var require_mcdev_copado_d = __commonJS({ - "types/mcdev-copado.d.js"(exports, module2) { - module2.exports = {}; - } + "types/mcdev-copado.d.js"(exports, module2) { + module2.exports = {}; + } }); // common/Config.js var require_Config = __commonJS({ - "common/Config.js"(exports, module2) { - module2.exports = {}; - } + "common/Config.js"(exports, module2) { + module2.exports = {}; + } }); // common/Log.js var require_Log = __commonJS({ - "common/Log.js"(exports, module2) { - "use strict"; - var execSync = require("child_process").execSync; - var CONFIG2 = require_Config(); - var Log2 = class { - static debug(msg) { - if (CONFIG2.debug) { - console.log("DEBUG:", msg); - } - } - static warn(msg) { - console.log("\u26A0", msg); - } - static info(msg) { - console.log(msg); - } - static error(error, msg = "Error") { - console.log("\u274C", error); - error = JSON.stringify(error); - msg = JSON.stringify(msg); - execSync(`copado --error-message ${error} --progress ${msg}`); - } - static result(json, msg = "Result attached") { - if (typeof json !== "string") { - json = JSON.stringify(json); - } - console.log("\u2705", json); - json = JSON.stringify(`${msg}: ${json}`); - msg = JSON.stringify(msg); - execSync(`copado --result-data ${json} --progress ${msg}`); - } - static progress(msg) { - msg = JSON.stringify(msg); - execSync(`copado --progress ${msg}`); - } - }; - module2.exports = Log2; - } + "common/Log.js"(exports, module2) { + "use strict"; + var execSync = require("child_process").execSync; + var CONFIG2 = require_Config(); + var Log2 = class { + static debug(msg) { + if (CONFIG2.debug) { + console.log("DEBUG:", msg); + } + } + static warn(msg) { + console.log("\u26A0", msg); + } + static info(msg) { + console.log(msg); + } + static error(error, msg = "Error") { + console.log("\u274C", error); + error = JSON.stringify(error); + msg = JSON.stringify(msg); + execSync(`copado --error-message ${error} --progress ${msg}`); + } + static result(json, msg = "Result attached") { + if (typeof json !== "string") { + json = JSON.stringify(json); + } + console.log("\u2705", json); + json = JSON.stringify(`${msg}: ${json}`); + msg = JSON.stringify(msg); + execSync(`copado --result-data ${json} --progress ${msg}`); + } + static progress(msg) { + msg = JSON.stringify(msg); + execSync(`copado --progress ${msg}`); + } + }; + module2.exports = Log2; + } }); // common/Util.js var require_Util = __commonJS({ - "common/Util.js"(exports, module2) { - "use strict"; - var fs2 = require("fs"); - var execSync = require("child_process").execSync; - var TYPE2 = require_mcdev_copado_d(); - var CONFIG2 = require_Config(); - var Log2 = require_Log(); - var Util2 = class { - static saveJsonFile(localPath, jsObj, beautify) { - const jsonString = beautify - ? JSON.stringify(jsObj, null, 4) - : JSON.stringify(jsObj); - fs2.writeFileSync(localPath, jsonString, "utf8"); - } - static push(destinationBranch) { - Util2.execCommand( - `Pushing updates to ${destinationBranch} branch`, - ['git push origin "' + destinationBranch + '"'], - "Completed pushing branch" - ); - } - static execCommand(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - if (null != postMsg) { - Log2.debug("\u2714\uFE0F " + postMsg); - } - } - static execCommandReturnStatus(preMsg, command, postMsg) { - if (null != preMsg) { - Log2.progress(preMsg); - } - if (command && Array.isArray(command)) { - command = command.join(" && "); - } - Log2.debug("\u26A1 " + command); - let exitCode = null; - try { - execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); - exitCode = 0; - } catch (ex) { - Log2.warn("\u274C " + ex.status + ": " + ex.message); - exitCode = ex.status; - return exitCode; - } - if (null != postMsg) { - Log2.progress("\u2714\uFE0F " + postMsg); - } - return exitCode; - } - static provideMCDevTools() { - if (fs2.existsSync("package.json")) { - Log2.debug("package.json found, assuming npm was already initialized"); - } else { - Util2.execCommand( - "Initializing npm", - ["npm init -y"], - "Completed initializing NPM" - ); - } - let installer; - if (!CONFIG2.installMcdevLocally) { - Util2.execCommand( - `Initializing Accenture SFMC DevTools (packaged version)`, - [ - `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, - "mcdev --version" - ], - "Completed installing Accenture SFMC DevTools" - ); - return; - } else if (!CONFIG2.mcdevVersion) { - Log2.error("Please specify mcdev_version in pipeline & environment settings"); - throw new Error( - "Please specify mcdev_version in pipeline & environment settings" - ); - } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { - installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; - } else { - installer = `mcdev@${CONFIG2.mcdevVersion}`; - } - Util2.execCommand( - `Initializing Accenture SFMC DevTools (${installer})`, - [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], - "Completed installing Accenture SFMC DevTools" - ); - } - static provideMCDevCredentials(credentials) { - Log2.info("Provide authentication"); - Util2.saveJsonFile(".mcdev-auth.json", credentials, true); - } - static convertSourceProperties(properties) { - const response = {}; - for (const item of properties) { - response[item.copado__API_Name__c] = item.copado__Value__c; - } - return response; - } - static convertEnvVariables(envVariables) { - Object.keys(envVariables).map((key) => { - if (key.endsWith("Children")) { - envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); - } else { - envVariables[key] = Util2._convertEnvVars(envVariables[key]); - } - }); - } - static _convertEnvVars(envVarArr) { - if (!envVarArr) { - return envVarArr; - } - if (typeof envVarArr === "string") { - envVarArr = JSON.parse(envVarArr); - } - const response = {}; - for (const item of envVarArr) { - response[item.name] = item.value; - } - return response; - } - static _convertEnvChildVars(envChildVarArr) { - if (!envChildVarArr) { - return envChildVarArr; - } - if (typeof envChildVarArr === "string") { - envChildVarArr = JSON.parse(envChildVarArr); - } - const response = {}; - for (const item of envChildVarArr) { - response[item.id] = Util2._convertEnvVars(item.environmentVariables); - } - return response; - } - static getBuName(credName, mid) { - let credBuName; - if (!credName) { - throw new Error('System Property "credentialName" not set'); - } - if (!mid) { - throw new Error('System Property "mid" not set'); - } - if (!fs2.existsSync(CONFIG2.configFilePath)) { - throw new Error("Could not find config file " + CONFIG2.configFilePath); - } - const config = JSON.parse(fs2.readFileSync(CONFIG2.configFilePath, "utf8")); - if (config.credentials[credName] && config.credentials[credName].businessUnits) { - const myBuNameArr = Object.keys( - config.credentials[credName].businessUnits - ).filter((buName) => config.credentials[credName].businessUnits[buName] == mid); - if (myBuNameArr.length === 1) { - Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); - credBuName = credName + "/" + myBuNameArr[0]; - } else { - throw new Error(`MID ${mid} not found for ${credName}`); - } - } - return credBuName; - } - }; - module2.exports = Util2; - } + "common/Util.js"(exports, module2) { + "use strict"; + var fs2 = require("fs"); + var execSync = require("child_process").execSync; + var TYPE2 = require_mcdev_copado_d(); + var CONFIG2 = require_Config(); + var Log2 = require_Log(); + var Util2 = class { + static saveJsonFile(localPath, jsObj, beautify) { + const jsonString = beautify ? JSON.stringify(jsObj, null, 4) : JSON.stringify(jsObj); + fs2.writeFileSync(localPath, jsonString, "utf8"); + } + static push(destinationBranch) { + Util2.execCommand( + `Pushing updates to ${destinationBranch} branch`, + ['git push origin "' + destinationBranch + '"'], + "Completed pushing branch" + ); + } + static execCommand(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + if (null != postMsg) { + Log2.debug("\u2714\uFE0F " + postMsg); + } + } + static execCommandReturnStatus(preMsg, command, postMsg) { + if (null != preMsg) { + Log2.progress(preMsg); + } + if (command && Array.isArray(command)) { + command = command.join(" && "); + } + Log2.debug("\u26A1 " + command); + let exitCode = null; + try { + execSync(command, { stdio: [0, 1, 2], stderr: "inherit" }); + exitCode = 0; + } catch (ex) { + Log2.warn("\u274C " + ex.status + ": " + ex.message); + exitCode = ex.status; + return exitCode; + } + if (null != postMsg) { + Log2.progress("\u2714\uFE0F " + postMsg); + } + return exitCode; + } + static provideMCDevTools() { + if (fs2.existsSync("package.json")) { + Log2.debug("package.json found, assuming npm was already initialized"); + } else { + Util2.execCommand("Initializing npm", ["npm init -y"], "Completed initializing NPM"); + } + let installer; + if (!CONFIG2.installMcdevLocally) { + Util2.execCommand( + `Initializing Accenture SFMC DevTools (packaged version)`, + [ + `npm link mcdev --no-audit --no-fund --ignore-scripts --omit=dev --omit=peer --omit=optional`, + "mcdev --version" + ], + "Completed installing Accenture SFMC DevTools" + ); + return; + } else if (!CONFIG2.mcdevVersion) { + Log2.error("Please specify mcdev_version in pipeline & environment settings"); + throw new Error("Please specify mcdev_version in pipeline & environment settings"); + } else if (CONFIG2.mcdevVersion.charAt(0) === "#") { + installer = `accenture/sfmc-devtools${CONFIG2.mcdevVersion}`; + } else { + installer = `mcdev@${CONFIG2.mcdevVersion}`; + } + Util2.execCommand( + `Initializing Accenture SFMC DevTools (${installer})`, + [`npm install ${installer}`, "node ./node_modules/mcdev/lib/cli.js --version"], + "Completed installing Accenture SFMC DevTools" + ); + } + static provideMCDevCredentials(credentials) { + Log2.info("Provide authentication"); + Util2.saveJsonFile(".mcdev-auth.json", credentials, true); + } + static convertSourceProperties(properties) { + const response = {}; + for (const item of properties) { + response[item.copado__API_Name__c] = item.copado__Value__c; + } + return response; + } + static convertEnvVariables(envVariables) { + Object.keys(envVariables).map((key) => { + if (key.endsWith("Children")) { + envVariables[key] = Util2._convertEnvChildVars(envVariables[key]); + } else { + envVariables[key] = Util2._convertEnvVars(envVariables[key]); + } + }); + } + static _convertEnvVars(envVarArr) { + if (!envVarArr) { + return envVarArr; + } + if (typeof envVarArr === "string") { + envVarArr = JSON.parse(envVarArr); + } + const response = {}; + for (const item of envVarArr) { + response[item.name] = item.value; + } + return response; + } + static _convertEnvChildVars(envChildVarArr) { + if (!envChildVarArr) { + return envChildVarArr; + } + if (typeof envChildVarArr === "string") { + envChildVarArr = JSON.parse(envChildVarArr); + } + const response = {}; + for (const item of envChildVarArr) { + response[item.id] = Util2._convertEnvVars(item.environmentVariables); + } + return response; + } + static getBuName(credName, mid) { + let credBuName; + if (!credName) { + throw new Error('System Property "credentialName" not set'); + } + if (!mid) { + throw new Error('System Property "mid" not set'); + } + if (!fs2.existsSync(CONFIG2.configFilePath)) { + throw new Error("Could not find config file " + CONFIG2.configFilePath); + } + const config = JSON.parse(fs2.readFileSync(CONFIG2.configFilePath, "utf8")); + if (config.credentials[credName] && config.credentials[credName].businessUnits) { + const myBuNameArr = Object.keys(config.credentials[credName].businessUnits).filter( + (buName) => config.credentials[credName].businessUnits[buName] == mid + ); + if (myBuNameArr.length === 1) { + Log2.debug("BU Name is: " + credName + "/" + myBuNameArr[0]); + credBuName = credName + "/" + myBuNameArr[0]; + } else { + throw new Error(`MID ${mid} not found for ${credName}`); + } + } + return credBuName; + } + }; + module2.exports = Util2; + } }); // common/Copado.js var require_Copado = __commonJS({ - "common/Copado.js"(exports, module2) { - "use strict"; - var fs2 = require("fs"); - var exec = require("child_process").exec; - var TYPE2 = require_mcdev_copado_d(); - var Log2 = require_Log(); - var Util2 = require_Util(); - var Copado2 = class { - static mcdevInit(credentials, credentialName, url) { - Util2.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${url}", ${credentials[credentialName].account_id}`, - [ - `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "false" --y.gitPush "true"` - ], - "Mcdev initialized!" - ); - } - static attachJson(localPath, parentSfid, async = false, preMsg) { - Copado2._attachFile(localPath, async, parentSfid, preMsg); - } - static async attachLog(localPath) { - Copado2._attachFile(localPath, true); - } - static _attachFile( - localPath, - async = false, - parentSfid, - preMsg, - postMsg = "Completed uploading file" - ) { - const command = - `copado --uploadfile "${localPath}"` + - (parentSfid ? ` --parentid "${parentSfid}"` : ""); - if (async) { - Log2.debug("\u26A1 " + command); - try { - exec(command); - } catch (ex) { - Log2.info(ex.status + ": " + ex.message); - throw new Error(ex); - } - } else { - if (!preMsg) { - preMsg = "Uploading file " + localPath; - if (parentSfid) { - preMsg += ` to ${parentSfid}`; - } - } - Util2.execCommand(preMsg, [command], postMsg); - } - } - static _downloadFile(fileSFID, preMsg) { - if (fileSFID) { - if (!preMsg) { - preMsg = `Download ${fileSFID}.`; - } - Util2.execCommand( - preMsg, - `copado --downloadfiles "${fileSFID}"`, - "Completed download" - ); - } else { - throw new Error("fileSalesforceId is not set"); - } - } - static getJsonFile(fileSFID, fileName, preMsg) { - Copado2._downloadFile(fileSFID, preMsg); - return JSON.parse(fs2.readFileSync(fileName, "utf8")); - } - static checkoutSrc(workingBranch, createBranch = false) { - Util2.execCommand( - `Switching to ${workingBranch} branch`, - [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], - "Completed creating/checking out branch" - ); - } - static deleteBranch(featureBranch) { - Util2.execCommand( - `Deleting branch ${featureBranch} on server`, - [`git push origin --delete ${featureBranch}`], - "Completed deleting server branch " + featureBranch - ); - Util2.execCommand( - `Deleting branch ${featureBranch} locally`, - [`git branch --delete --force ${featureBranch}`], - "Completed deleting local branch " + featureBranch - ); - } - static async uploadToolLogs() { - Log2.debug("Getting mcdev logs"); - try { - const logsAttached = []; - for (const file of fs2.readdirSync("logs")) { - Log2.debug("- " + file); - logsAttached.push(Copado2.attachLog("logs/" + file)); - } - const response = await Promise.all(logsAttached); - Log2.debug("Attached mcdev logs"); - return response; - } catch (ex) { - Log2.debug("attaching mcdev logs failed:" + ex.message); - } + "common/Copado.js"(exports, module2) { + "use strict"; + var fs2 = require("fs"); + var exec = require("child_process").exec; + var TYPE2 = require_mcdev_copado_d(); + var Log2 = require_Log(); + var Util2 = require_Util(); + var Copado2 = class { + static attachJson(localPath, parentSfid, async = false, preMsg) { + Copado2._attachFile(localPath, async, parentSfid, preMsg); + } + static async attachLog(localPath) { + Copado2._attachFile(localPath, true); + } + static _attachFile(localPath, async = false, parentSfid, preMsg, postMsg = "Completed uploading file") { + const command = `copado --uploadfile "${localPath}"` + (parentSfid ? ` --parentid "${parentSfid}"` : ""); + if (async) { + Log2.debug("\u26A1 " + command); + try { + exec(command); + } catch (ex) { + Log2.info(ex.status + ": " + ex.message); + throw new Error(ex); + } + } else { + if (!preMsg) { + preMsg = "Uploading file " + localPath; + if (parentSfid) { + preMsg += ` to ${parentSfid}`; } - }; - module2.exports = Copado2; - } + } + Util2.execCommand(preMsg, [command], postMsg); + } + } + static _downloadFile(fileSFID, preMsg) { + if (fileSFID) { + if (!preMsg) { + preMsg = `Download ${fileSFID}.`; + } + Util2.execCommand(preMsg, `copado --downloadfiles "${fileSFID}"`, "Completed download"); + } else { + throw new Error("fileSalesforceId is not set"); + } + } + static getJsonFile(fileSFID, fileName, preMsg) { + Copado2._downloadFile(fileSFID, preMsg); + return JSON.parse(fs2.readFileSync(fileName, "utf8")); + } + static checkoutSrc(workingBranch, createBranch = false) { + Util2.execCommand( + `Switching to ${workingBranch} branch`, + [`copado-git-get ${createBranch ? "--create " : ""}"${workingBranch}"`], + "Completed creating/checking out branch" + ); + } + static deleteBranch(featureBranch) { + Util2.execCommand( + `Deleting branch ${featureBranch} on server`, + [`git push origin --delete ${featureBranch}`], + "Completed deleting server branch " + featureBranch + ); + Util2.execCommand( + `Deleting branch ${featureBranch} locally`, + [`git branch --delete --force ${featureBranch}`], + "Completed deleting local branch " + featureBranch + ); + } + static async uploadToolLogs() { + Log2.debug("Getting mcdev logs"); + try { + const logsAttached = []; + for (const file of fs2.readdirSync("logs")) { + Log2.debug("- " + file); + logsAttached.push(Copado2.attachLog("logs/" + file)); + } + const response = await Promise.all(logsAttached); + Log2.debug("Attached mcdev logs"); + return response; + } catch (ex) { + Log2.debug("attaching mcdev logs failed:" + ex.message); + } + } + }; + module2.exports = Copado2; + } }); // Retrieve.fn.js @@ -389,10 +357,10 @@ CONFIG.fileSelectionSalesforceId = null; CONFIG.fileSelectionFileName = null; CONFIG.recreateFeatureBranch = null; CONFIG.envVariables = { - source: null, - sourceChildren: null, - destination: null, - destinationChildren: null + source: null, + sourceChildren: null, + destination: null, + destinationChildren: null }; CONFIG.deltaPackageLog = null; CONFIG.destinationBranch = null; @@ -403,241 +371,225 @@ CONFIG.promotionBranch = null; CONFIG.promotionName = null; CONFIG.target_mid = null; async function run() { - Log.info("Retrieve.js started"); - Log.debug(""); - Log.debug("Parameters"); - Log.debug("==================="); - try { - CONFIG.credentials = JSON.parse(CONFIG.credentials); - } catch (ex) { - Log.error("Could not parse credentials"); - throw ex; - } - Util.convertEnvVariables(CONFIG.envVariables); - Log.debug(CONFIG); - if (!CONFIG.credentials[CONFIG.credentialNameSource]) { - Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); - throw new Error(`No credentials`); - } - Log.debug("Credentials found for source BU"); - Log.debug("Environment"); - Log.debug("==================="); - if (CONFIG.debug) { - Util.execCommand(null, "npm --version", null); - Util.execCommand(null, "node --version", null); - Util.execCommand(null, "git version", null); - } - Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + Log.info("Retrieve.js started"); + Log.debug(""); + Log.debug("Parameters"); + Log.debug("==================="); + try { + CONFIG.credentials = JSON.parse(CONFIG.credentials); + } catch (ex) { + Log.error("Could not parse credentials"); + throw ex; + } + Util.convertEnvVariables(CONFIG.envVariables); + Log.debug(CONFIG); + if (!CONFIG.credentials[CONFIG.credentialNameSource]) { + Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); + throw new Error(`No credentials`); + } + Log.debug("Credentials found for source BU"); + Log.debug("Environment"); + Log.debug("==================="); + if (CONFIG.debug) { + Util.execCommand(null, "npm --version", null); + Util.execCommand(null, "node --version", null); + Util.execCommand(null, "git version", null); + } + Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); + try { + Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + } catch { try { - Util.execCommand(null, ["git config --global --add safe.directory /tmp"]); + Util.execCommand(null, [ + "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) + ]); } catch { - try { - Util.execCommand(null, [ - "git config --global --add safe.directory " + resolve(CONFIG.tmpDirectory) - ]); - } catch { - Log.error("Could not set tmp directoy as safe directory"); - } - } - process.chdir(CONFIG.tmpDirectory); - Log.debug(process.cwd()); - try { - Log.info(""); - Log.info("Clone repository"); - Log.info("==================="); - Log.info(""); - Copado.checkoutSrc(CONFIG.mainBranch); - } catch (ex) { - Log.error("Cloning failed:" + ex.message); - throw ex; - } - try { - Log.info(""); - Log.info("Preparing"); - Log.info("==================="); - Log.info(""); - Util.provideMCDevTools(); - Util.provideMCDevCredentials(CONFIG.credentials); - } catch (ex) { - Log.error("initializing failed: " + ex.message); - throw ex; - } - let sourceBU; - let metadataJson; - try { - Log.info(""); - Log.info("Get source BU"); - Log.info("==================="); - Log.info(""); - sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); - } catch (ex) { - Log.error("Getting Source BU failed: " + ex.message); - throw ex; - } - try { - Log.info(""); - Log.progress("Retrieving components"); - Log.info("==================="); - Log.info(""); - metadataJson = await Retrieve.retrieveChangelog(sourceBU); - } catch (ex) { - Log.error("Retrieving failed: " + ex.message); - Copado.uploadToolLogs(); - throw ex; - } - try { - Log.info(""); - Log.info("Saving metadata JSON to disk"); - Log.info("==================="); - Log.info(""); - Util.saveJsonFile(CONFIG.metadataFilePath, metadataJson); - } catch (ex) { - Log.error("Saving metadata JSON failed:" + ex.message); - throw ex; - } - Log.result(`Found ${metadataJson.length} items on server`, "Refresh done"); - try { - Log.info(""); - Log.info("Attach JSON"); - Log.info("==================="); - Log.info(""); - Copado.attachJson( - CONFIG.metadataFilePath, - CONFIG.source_sfid, - false, - "Loading items into Copado" - ); - } catch (ex) { - Log.error("Attaching JSON file failed:" + ex.message); - throw ex; + Log.error("Could not set tmp directoy as safe directory"); } + } + process.chdir(CONFIG.tmpDirectory); + Log.debug(process.cwd()); + try { + Log.info(""); + Log.info("Clone repository"); + Log.info("==================="); + Log.info(""); + Copado.checkoutSrc(CONFIG.mainBranch); + } catch (ex) { + Log.error("Cloning failed:" + ex.message); + throw ex; + } + try { Log.info(""); + Log.info("Preparing"); Log.info("==================="); Log.info(""); - Log.info("Retrieve.js done"); + Util.provideMCDevTools(); + Util.provideMCDevCredentials(CONFIG.credentials); + } catch (ex) { + Log.error("initializing failed: " + ex.message); + throw ex; + } + let sourceBU; + let metadataJson; + try { + Log.info(""); + Log.info("Get source BU"); + Log.info("==================="); + Log.info(""); + sourceBU = Util.getBuName(CONFIG.credentialNameSource, CONFIG.source_mid); + } catch (ex) { + Log.error("Getting Source BU failed: " + ex.message); + throw ex; + } + try { + Log.info(""); + Log.progress("Retrieving components"); + Log.info("==================="); + Log.info(""); + metadataJson = await Retrieve.retrieveChangelog(sourceBU); + } catch (ex) { + Log.error("Retrieving failed: " + ex.message); Copado.uploadToolLogs(); + throw ex; + } + try { + Log.info(""); + Log.info("Saving metadata JSON to disk"); + Log.info("==================="); + Log.info(""); + Util.saveJsonFile(CONFIG.metadataFilePath, metadataJson); + } catch (ex) { + Log.error("Saving metadata JSON failed:" + ex.message); + throw ex; + } + Log.result(`Found ${metadataJson.length} items on server`, "Refresh done"); + try { + Log.info(""); + Log.info("Attach JSON"); + Log.info("==================="); + Log.info(""); + Copado.attachJson( + CONFIG.metadataFilePath, + CONFIG.source_sfid, + false, + "Loading items into Copado" + ); + } catch (ex) { + Log.error("Attaching JSON file failed:" + ex.message); + throw ex; + } + Log.info(""); + Log.info("==================="); + Log.info(""); + Log.info("Retrieve.js done"); + Copado.uploadToolLogs(); } var Retrieve = class { - static getRetrieveFolder() { - if (!fs.existsSync(CONFIG.configFilePath)) { - throw new Error("Could not find config file " + CONFIG.configFilePath); - } - const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); - const directories = config["directories"]; - if (null == directories) { - throw new Error("Could not find directories in " + CONFIG.configFilePath); - } - const folder = directories["retrieve"]; - if (null == folder) { - throw new Error("Could not find directories/retrieve in " + CONFIG.configFilePath); - } - Log.debug("Retrieve folder is: " + folder); - return folder; + static getRetrieveFolder() { + if (!fs.existsSync(CONFIG.configFilePath)) { + throw new Error("Could not find config file " + CONFIG.configFilePath); } - static async retrieveChangelog(sourceBU) { - const mcdev = require("../tmp/node_modules/mcdev/lib"); - const Definition = require("../tmp/node_modules/mcdev/lib/MetadataTypeDefinitions"); - const MetadataType = require("../tmp/node_modules/mcdev/lib/MetadataTypeInfo"); - if (!CONFIG.debug) { - mcdev.setLoggingLevel({ silent: true }); - } - mcdev.setSkipInteraction(true); - const customDefinition = { - automation: { - keyField: "CustomerKey", - nameField: "Name", - createdDateField: "CreatedDate", - createdNameField: "CreatedBy", - lastmodDateField: "LastSaveDate", - lastmodNameField: "LastSavedBy" + const config = JSON.parse(fs.readFileSync(CONFIG.configFilePath, "utf8")); + const directories = config["directories"]; + if (null == directories) { + throw new Error("Could not find directories in " + CONFIG.configFilePath); + } + const folder = directories["retrieve"]; + if (null == folder) { + throw new Error("Could not find directories/retrieve in " + CONFIG.configFilePath); + } + Log.debug("Retrieve folder is: " + folder); + return folder; + } + static async retrieveChangelog(sourceBU) { + const mcdev = require("../tmp/node_modules/mcdev/lib"); + const Definition = require("../tmp/node_modules/mcdev/lib/MetadataTypeDefinitions"); + const MetadataType = require("../tmp/node_modules/mcdev/lib/MetadataTypeInfo"); + if (!CONFIG.debug) { + mcdev.setLoggingLevel({ silent: true }); + } + mcdev.setSkipInteraction(true); + const customDefinition = { + automation: { + keyField: "CustomerKey", + nameField: "Name", + createdDateField: "CreatedDate", + createdNameField: "CreatedBy", + lastmodDateField: "LastSaveDate", + lastmodNameField: "LastSavedBy" + } + }; + const retrieve = await mcdev.retrieve(sourceBU, ["accountUser"], null, true); + if (!retrieve) { + throw new Error("Could not retrieve User List"); + } + const userList = retrieve.accountUser; + for (const key of Object.keys(userList)) { + userList[userList[key].ID] = userList[key].Name; + delete userList[key]; + } + const changelogList = await mcdev.retrieve(sourceBU, null, null, true); + const allMetadata = []; + Object.keys(changelogList).map((type) => { + if (changelogList[type]) { + const def = customDefinition[type] || Definition[type]; + allMetadata.push( + ...Object.keys(changelogList[type]).map((key) => { + const item = changelogList[type][key]; + const salesforceRegex = new RegExp(/(_Salesforce)(_[0-9])?$/gm); + if (MetadataType[type].isFiltered(item, true) || MetadataType[type].isFiltered(item, false)) { + return; } - }; - const retrieve = await mcdev.retrieve(sourceBU, ["accountUser"], null, true); - if (!retrieve) { - throw new Error("Could not retrieve User List"); - } - const userList = retrieve.accountUser; - for (const key of Object.keys(userList)) { - userList[userList[key].ID] = userList[key].Name; - delete userList[key]; - } - const changelogList = await mcdev.retrieve(sourceBU, null, null, true); - const allMetadata = []; - Object.keys(changelogList).map((type) => { - if (changelogList[type]) { - const def = customDefinition[type] || Definition[type]; - allMetadata.push( - ...Object.keys(changelogList[type]).map((key) => { - const item = changelogList[type][key]; - const salesforceRegex = new RegExp(/(_Salesforce)(_[0-9])?$/gm); - if ( - MetadataType[type].isFiltered(item, true) || - MetadataType[type].isFiltered(item, false) - ) { - return; - } - if ( - type === "dataExtension" && - (this._getAttrValue(item, def.nameField).startsWith( - "QueryStudioResults at " - ) || - salesforceRegex.test(this._getAttrValue(item, def.nameField))) - ) { - return; - } - const listEntry = { - n: this._getAttrValue(item, def.nameField), - k: this._getAttrValue(item, def.keyField), - p: this._getAttrValue(item, "r__folder_Path"), - t: this._getAttrValue(item, "_subType") - ? type + "-" + this._getAttrValue(item, "_subType") - : type, - cd: this._convertTimestamp( - this._getAttrValue(item, def.createdDateField) - ), - cb: this._getUserName(userList, item, def.createdNameField), - ld: this._convertTimestamp( - this._getAttrValue(item, def.lastmodDateField) !== - "0001-01-01T00:00:00" - ? this._getAttrValue(item, def.lastmodDateField) - : this._getAttrValue(item, def.createdDateField) - ), - lb: this._getUserName(userList, item, def.lastmodNameField) - }; - return listEntry; - }) - ); + if (type === "dataExtension" && (this._getAttrValue(item, def.nameField).startsWith( + "QueryStudioResults at " + ) || salesforceRegex.test(this._getAttrValue(item, def.nameField)))) { + return; } - }); - return allMetadata.filter((item) => void 0 !== item); + const listEntry = { + n: this._getAttrValue(item, def.nameField), + k: this._getAttrValue(item, def.keyField), + p: this._getAttrValue(item, "r__folder_Path"), + t: this._getAttrValue(item, "_subType") ? type + "-" + this._getAttrValue(item, "_subType") : type, + cd: this._convertTimestamp( + this._getAttrValue(item, def.createdDateField) + ), + cb: this._getUserName(userList, item, def.createdNameField), + ld: this._convertTimestamp( + this._getAttrValue(item, def.lastmodDateField) !== "0001-01-01T00:00:00" ? this._getAttrValue(item, def.lastmodDateField) : this._getAttrValue(item, def.createdDateField) + ), + lb: this._getUserName(userList, item, def.lastmodNameField) + }; + return listEntry; + }) + ); + } + }); + return allMetadata.filter((item) => void 0 !== item); + } + static _convertTimestamp(iso8601dateTime) { + if (!iso8601dateTime || iso8601dateTime === "0001-01-01T00:00:00") { + return "-"; } - static _convertTimestamp(iso8601dateTime) { - if (!iso8601dateTime || iso8601dateTime === "0001-01-01T00:00:00") { - return "-"; - } - if (iso8601dateTime.split("-").length === 3) { - iso8601dateTime += "-06:00"; - } - return iso8601dateTime; + if (iso8601dateTime.split("-").length === 3) { + iso8601dateTime += "-06:00"; } - static _getUserName(userList, item, fieldname) { - return ( - userList[this._getAttrValue(item, fieldname)] || - this._getAttrValue(item, fieldname) || - "n/a" - ); + return iso8601dateTime; + } + static _getUserName(userList, item, fieldname) { + return userList[this._getAttrValue(item, fieldname)] || this._getAttrValue(item, fieldname) || "n/a"; + } + static _getAttrValue(obj, key) { + if (!key || !obj) { + return null; } - static _getAttrValue(obj, key) { - if (!key || !obj) { - return null; - } - if (key.includes(".")) { - const keys = key.split("."); - const first = keys.shift(); - return this._getAttrValue(obj[first], keys.join(".")); - } else { - return obj[key]; - } + if (key.includes(".")) { + const keys = key.split("."); + const first = keys.shift(); + return this._getAttrValue(obj[first], keys.join(".")); + } else { + return obj[key]; } + } }; run(); diff --git a/copado-function/docs/documentation.md b/copado-function/docs/documentation.md index 24783f6..9604d17 100644 --- a/copado-function/docs/documentation.md +++ b/copado-function/docs/documentation.md @@ -4,6 +4,9 @@
Deploy

handles downloading metadata

+
Init
+

Class for Init function

+
Retrieve

handles downloading metadata

@@ -224,6 +227,23 @@ applies market values of target onto name and key of commitSelectionArr | --- | --- | --- | | commitSelectionArr | Array.<TYPE.CommitSelection> | list of items to be added | + + +## Init +Class for Init function + +**Kind**: global class + + +### Init.mcdevInit(credentials, credentialName, options) +**Kind**: static method of [Init](#Init) + +| Param | Type | Description | +| --- | --- | --- | +| credentials | object | the credentials for the salesforce marketing cloud | +| credentialName | string | the credential name | +| options | object | contains the url, the downloadBUs and the gitPush values | + ## Retrieve @@ -315,7 +335,6 @@ methods to handle interaction with the copado platform **Kind**: global class * [Copado](#Copado) - * [.mcdevInit(credentials, credentialName, url)](#Copado.mcdevInit) * [.attachJson(localPath, [parentSfid], [async], [preMsg])](#Copado.attachJson) ⇒ void * [.attachLog(localPath)](#Copado.attachLog) ⇒ Promise.<void> * [._downloadFile(fileSFID, [preMsg])](#Copado._downloadFile) ⇒ void @@ -324,17 +343,6 @@ methods to handle interaction with the copado platform * [.deleteBranch(featureBranch)](#Copado.deleteBranch) ⇒ void * [.uploadToolLogs()](#Copado.uploadToolLogs) ⇒ Promise.<void> - - -### Copado.mcdevInit(credentials, credentialName, url) -**Kind**: static method of [Copado](#Copado) - -| Param | Type | Description | -| --- | --- | --- | -| credentials | object | the credentials for the salesforce marketing cloud | -| credentialName | string | the credential name | -| url | string | the git remote URL | - ### Copado.attachJson(localPath, [parentSfid], [async], [preMsg]) ⇒ void From f24797d4afdcdbecb127b22fb880d1ed65c62d64 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 22 Nov 2022 10:35:37 +0000 Subject: [PATCH 12/28] #296 changing default values of downloadBUs and gitPush --- copado-function/app/Init.fn.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index c2c1e9d..042b93b 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -53,8 +53,8 @@ CONFIG.promotionName = null; // The promotion name of a PR CONFIG.target_mid = null; // init CONFIG.repoUrl = process.env.repoUrl; -CONFIG.downloadBUs = process.env.downloadBUs === 'true' ? true : false; -CONFIG.gitPush = process.env.gitPush === 'true' ? true : false; +CONFIG.downloadBUs = process.env.downloadBUs === 'false' ? false : true; +CONFIG.gitPush = process.env.gitPush === 'false' ? false : true; /** * main method that combines runs this function From 9b09f8d7d707af639e93cc03f49b275d2b9c089d Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 22 Nov 2022 12:04:48 +0100 Subject: [PATCH 13/28] #296: small updates --- .vscode/launch.json | 17 ++++------------- copado-function/app/Init.fn.js | 7 ++++++- copado-function/app/esbuild.js | 2 +- copado-function/dist/Commit.fn.js | 2 +- copado-function/dist/Deploy.fn.js | 2 +- copado-function/dist/Init.fn.js | 26 +++++++++++++++----------- copado-function/dist/Retrieve.fn.js | 2 +- 7 files changed, 29 insertions(+), 29 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 2af8f0e..40052d0 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -9,7 +9,7 @@ }, { "type": "node-terminal", - "name": "debug: dist/init", + "name": "init (dist/)", "request": "launch", "command": "node Init.fn.js --preserve-symlinks", "cwd": "${workspaceFolder}/copado-function/dist", @@ -18,7 +18,7 @@ }, { "type": "node-terminal", - "name": "debug: dist/retrieve", + "name": "retrieve (dist/)", "request": "launch", "command": "node Retrieve.fn.js --preserve-symlinks", "cwd": "${workspaceFolder}/copado-function/dist", @@ -27,7 +27,7 @@ }, { "type": "node-terminal", - "name": "debug: dist/commit", + "name": "commit (dist/)", "request": "launch", "command": "node Commit.fn.js --preserve-symlinks", "cwd": "${workspaceFolder}/copado-function/dist", @@ -36,21 +36,12 @@ }, { "type": "node-terminal", - "name": "debug: dist/deploy", + "name": "deploy (dist/)", "request": "launch", "command": "node Deploy.fn.js --preserve-symlinks", "cwd": "${workspaceFolder}/copado-function/dist", "envFile": "${workspaceFolder}/copado-function/app/environments/Deploy.env", "preLaunchTask": "esbuild" - }, - { - "type": "node-terminal", - "name": "debug: dist/upgrade", - "request": "launch", - "command": "node Upgrade.fn.js --preserve-symlinks", - "cwd": "${workspaceFolder}/copado-function/dist", - "envFile": "${workspaceFolder}/copado-function/app/environments/Upgrade.env", - "preLaunchTask": "esbuild" } ] } \ No newline at end of file diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 042b93b..564039e 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -2,6 +2,7 @@ 'use strict'; const resolve = require('node:path').resolve; +const fs = require('node:fs'); const CONFIG = require('./common/Config'); const Log = require('./common/Log'); const Util = require('./common/Util'); @@ -96,6 +97,7 @@ async function run() { Util.execCommand(null, 'npm --version', null); Util.execCommand(null, 'node --version', null); Util.execCommand(null, 'git version', null); + Util.execCommand(null, 'mcdev --version', null); } Log.debug(`Change Working directory to: ${CONFIG.tmpDirectory}`); @@ -109,6 +111,9 @@ async function run() { } // actually change working directory + if (!fs.existsSync(CONFIG.tmpDirectory)) { + fs.mkdirSync(CONFIG.tmpDirectory); + } process.chdir(CONFIG.tmpDirectory); Log.debug(process.cwd()); @@ -156,7 +161,7 @@ class Init { /** * * @param {object} credentials the credentials for the salesforce marketing cloud - * @param {string }credentialName the credential name + * @param {string} credentialName the credential name * @param {object} options contains the url, the downloadBUs and the gitPush values */ static mcdevInit(credentials, credentialName, options) { diff --git a/copado-function/app/esbuild.js b/copado-function/app/esbuild.js index fd834f3..433bd11 100644 --- a/copado-function/app/esbuild.js +++ b/copado-function/app/esbuild.js @@ -42,7 +42,7 @@ const isWatch = args.includes('--watch'); '*/\n\n', }, platform: 'node', - external: ['../tmp/*'], + external: ['../tmp/*', '../../node_modules/*'], preserveSymlinks: true, outdir: '../dist', absWorkingDir: absWorkingDir, diff --git a/copado-function/dist/Commit.fn.js b/copado-function/dist/Commit.fn.js index 605c2ca..3e3ed0f 100644 --- a/copado-function/dist/Commit.fn.js +++ b/copado-function/dist/Commit.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.2.0 (built 2022-11-22T10:27:33.256Z) + * mcdev-copado v1.2.0 (built 2022-11-22T11:00:11.013Z) * Function: Commit.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme diff --git a/copado-function/dist/Deploy.fn.js b/copado-function/dist/Deploy.fn.js index 60fe68c..a1ad7e7 100644 --- a/copado-function/dist/Deploy.fn.js +++ b/copado-function/dist/Deploy.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.2.0 (built 2022-11-22T10:27:33.275Z) + * mcdev-copado v1.2.0 (built 2022-11-22T11:00:11.151Z) * Function: Deploy.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index 28f4e12..8c526fd 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.2.0 (built 2022-11-22T10:27:33.326Z) + * mcdev-copado v1.2.0 (built 2022-11-22T11:00:11.237Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -77,7 +77,7 @@ var require_mcdev_copado_d = __commonJS({ var require_Util = __commonJS({ "common/Util.js"(exports, module2) { "use strict"; - var fs = require("fs"); + var fs2 = require("fs"); var execSync = require("child_process").execSync; var TYPE = require_mcdev_copado_d(); var CONFIG2 = require_Config(); @@ -85,7 +85,7 @@ var require_Util = __commonJS({ var Util2 = class { static saveJsonFile(localPath, jsObj, beautify) { const jsonString = beautify ? JSON.stringify(jsObj, null, 4) : JSON.stringify(jsObj); - fs.writeFileSync(localPath, jsonString, "utf8"); + fs2.writeFileSync(localPath, jsonString, "utf8"); } static push(destinationBranch) { Util2.execCommand( @@ -135,7 +135,7 @@ var require_Util = __commonJS({ return exitCode; } static provideMCDevTools() { - if (fs.existsSync("package.json")) { + if (fs2.existsSync("package.json")) { Log2.debug("package.json found, assuming npm was already initialized"); } else { Util2.execCommand("Initializing npm", ["npm init -y"], "Completed initializing NPM"); @@ -219,10 +219,10 @@ var require_Util = __commonJS({ if (!mid) { throw new Error('System Property "mid" not set'); } - if (!fs.existsSync(CONFIG2.configFilePath)) { + if (!fs2.existsSync(CONFIG2.configFilePath)) { throw new Error("Could not find config file " + CONFIG2.configFilePath); } - const config = JSON.parse(fs.readFileSync(CONFIG2.configFilePath, "utf8")); + const config = JSON.parse(fs2.readFileSync(CONFIG2.configFilePath, "utf8")); if (config.credentials[credName] && config.credentials[credName].businessUnits) { const myBuNameArr = Object.keys(config.credentials[credName].businessUnits).filter( (buName) => config.credentials[credName].businessUnits[buName] == mid @@ -245,7 +245,7 @@ var require_Util = __commonJS({ var require_Copado = __commonJS({ "common/Copado.js"(exports, module2) { "use strict"; - var fs = require("fs"); + var fs2 = require("fs"); var exec = require("child_process").exec; var TYPE = require_mcdev_copado_d(); var Log2 = require_Log(); @@ -289,7 +289,7 @@ var require_Copado = __commonJS({ } static getJsonFile(fileSFID, fileName, preMsg) { Copado2._downloadFile(fileSFID, preMsg); - return JSON.parse(fs.readFileSync(fileName, "utf8")); + return JSON.parse(fs2.readFileSync(fileName, "utf8")); } static checkoutSrc(workingBranch, createBranch = false) { Util2.execCommand( @@ -314,7 +314,7 @@ var require_Copado = __commonJS({ Log2.debug("Getting mcdev logs"); try { const logsAttached = []; - for (const file of fs.readdirSync("logs")) { + for (const file of fs2.readdirSync("logs")) { Log2.debug("- " + file); logsAttached.push(Copado2.attachLog("logs/" + file)); } @@ -332,6 +332,7 @@ var require_Copado = __commonJS({ // Init.fn.js var resolve = require("path").resolve; +var fs = require("fs"); var CONFIG = require_Config(); var Log = require_Log(); var Util = require_Util(); @@ -374,8 +375,8 @@ CONFIG.promotionBranch = null; CONFIG.promotionName = null; CONFIG.target_mid = null; CONFIG.repoUrl = process.env.repoUrl; -CONFIG.downloadBUs = process.env.downloadBUs === "true" ? true : false; -CONFIG.gitPush = process.env.gitPush === "true" ? true : false; +CONFIG.downloadBUs = process.env.downloadBUs === "false" ? false : true; +CONFIG.gitPush = process.env.gitPush === "false" ? false : true; async function run() { Log.info("McdevInit.js started"); Log.debug(""); @@ -416,6 +417,9 @@ async function run() { } catch { Log.error("Could not set tmp directoy as safe directory"); } + if (!fs.existsSync(CONFIG.tmpDirectory)) { + fs.mkdirSync(CONFIG.tmpDirectory); + } process.chdir(CONFIG.tmpDirectory); Log.debug(process.cwd()); try { diff --git a/copado-function/dist/Retrieve.fn.js b/copado-function/dist/Retrieve.fn.js index dce292e..3ca7fca 100644 --- a/copado-function/dist/Retrieve.fn.js +++ b/copado-function/dist/Retrieve.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.2.0 (built 2022-11-22T10:27:32.381Z) + * mcdev-copado v1.2.0 (built 2022-11-22T11:00:08.542Z) * Function: Retrieve.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme From bdf7a5f1e456391fce42b6b048860fdae7497604 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 28 Nov 2022 18:49:16 +0000 Subject: [PATCH 14/28] #296 - updating init.env-sample --- .../app/environments/Init.env-sample | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/copado-function/app/environments/Init.env-sample b/copado-function/app/environments/Init.env-sample index ded4e4e..cac77e0 100644 --- a/copado-function/app/environments/Init.env-sample +++ b/copado-function/app/environments/Init.env-sample @@ -1,7 +1,14 @@ -installMcdevLocally=true -debug=true -repoUrl="UPDATE ME" +repoUrl="UPDATE ME" # url +debug="UPDATE ME" # true or false +downloadBUs="UPDATE ME" # true or false +gitPush="UPDATE ME" # true or false ## generic -credentials="UPDATE ME" -credentialNameSource="UPDATE ME" +credentialName="UPDATE ME" +client_id="UPDATE ME" +client_secret="UPDATE ME" +auth_url="UPDATE ME" # url +enterprise_id="UPDATE ME" +mcdev_version="UPDATE ME" +git_email="UPDATE ME" # email +git_name="UPDATE ME" \ No newline at end of file From 6ef7909afe0c36e11dc5bc70205a2622d60a3403 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 6 Dec 2022 13:21:09 +0000 Subject: [PATCH 15/28] #296 setting mcdevVersion = null as we don't use it, and changed the initializing mcdev message --- copado-function/app/Init.fn.js | 4 ++-- copado-function/app/environments/Init.env-sample | 1 - copado-function/dist/Init.fn.js | 6 +++--- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 558d006..7692b64 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -24,7 +24,7 @@ CONFIG.configFilePath = null; CONFIG.debug = process.env.debug === 'true' ? true : false; CONFIG.installMcdevLocally = null; CONFIG.mainBranch = null; -CONFIG.mcdevVersion = process.env.mcdev_version; // this will only be needed if installMcdevLocally=true +CONFIG.mcdevVersion = null; CONFIG.metadataFilePath = null; // do not change - LWC depends on it! // not needed in this case, previous value: 'mcmetadata.json' CONFIG.source_mid = null; CONFIG.tmpDirectory = '../tmp'; @@ -168,7 +168,7 @@ class Init { */ static mcdevInit(credentials, credentialName, options) { Util.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, + `Initializing mcdev`, [ `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"`, ], diff --git a/copado-function/app/environments/Init.env-sample b/copado-function/app/environments/Init.env-sample index cac77e0..d1363be 100644 --- a/copado-function/app/environments/Init.env-sample +++ b/copado-function/app/environments/Init.env-sample @@ -9,6 +9,5 @@ client_id="UPDATE ME" client_secret="UPDATE ME" auth_url="UPDATE ME" # url enterprise_id="UPDATE ME" -mcdev_version="UPDATE ME" git_email="UPDATE ME" # email git_name="UPDATE ME" \ No newline at end of file diff --git a/copado-function/dist/Init.fn.js b/copado-function/dist/Init.fn.js index f270ca7..d921074 100644 --- a/copado-function/dist/Init.fn.js +++ b/copado-function/dist/Init.fn.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * mcdev-copado v1.3.0 (built 2022-12-05T16:05:54.809Z) + * mcdev-copado v1.3.0 (built 2022-12-06T13:20:00.630Z) * Function: Init.fn.js * Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1 * Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme @@ -349,7 +349,7 @@ CONFIG.configFilePath = null; CONFIG.debug = process.env.debug === "true" ? true : false; CONFIG.installMcdevLocally = null; CONFIG.mainBranch = null; -CONFIG.mcdevVersion = process.env.mcdev_version; +CONFIG.mcdevVersion = null; CONFIG.metadataFilePath = null; CONFIG.source_mid = null; CONFIG.tmpDirectory = "../tmp"; @@ -460,7 +460,7 @@ async function run() { var Init = class { static mcdevInit(credentials, credentialName, options) { Util.execCommand( - `Initializing mcdev: ${credentialName}, ${credentials[credentialName].client_id}", "${credentials[credentialName].client_secret}", "${credentials[credentialName].auth_url}", "${options.url}", "${options.downloadBUs}", "${options.gitPush}", ${credentials[credentialName].account_id}`, + `Initializing mcdev`, [ `mcdev init --y.credentialName "${credentialName}" --y.client_id "${credentials[credentialName].client_id}" --y.client_secret "${credentials[credentialName].client_secret}" --y.auth_url "${credentials[credentialName].auth_url}" --y.gitRemoteUrl "${options.url}" --y.account_id ${credentials[credentialName].account_id} --y.downloadBUs "${options.downloadBUs}" --y.gitPush "${options.gitPush}"` ], From 1e3c768447cb433cc96484055088cfcff66b35b2 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Thu, 15 Dec 2022 12:22:57 +0000 Subject: [PATCH 16/28] #296 - adding a new env variable to get the env variables that we want to set per BU --- copado-function/app/Init.fn.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 7692b64..c15f665 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -58,6 +58,10 @@ CONFIG.target_mid = null; CONFIG.repoUrl = process.env.repoUrl; CONFIG.downloadBUs = process.env.downloadBUs === 'false' ? false : true; CONFIG.gitPush = process.env.gitPush === 'false' ? false : true; +CONFIG.copadoEnvironmentVariables = + process.env.copadoEnvironmentVariables === undefined + ? '{}' + : process.env.copadoEnvironmentVariables; /** * main method that combines runs this function @@ -84,6 +88,9 @@ async function run() { Log.error(`Could not parse credentials: ${CONFIG.credentials}`); throw ex; } + + CONFIG.copadoEnvironmentVariables = JSON.parse(CONFIG.copadoEnvironmentVariables); + Log.debug(CONFIG); // ensure we got SFMC credentials for our source BU From f399f8ad0f040505417f961ad0423e85e572acf4 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Thu, 15 Dec 2022 12:26:07 +0000 Subject: [PATCH 17/28] #296 - updating init.env-sample to have the copadoEnvionmentVariables option --- copado-function/app/environments/Init.env-sample | 1 + 1 file changed, 1 insertion(+) diff --git a/copado-function/app/environments/Init.env-sample b/copado-function/app/environments/Init.env-sample index d1363be..aa7d4ba 100644 --- a/copado-function/app/environments/Init.env-sample +++ b/copado-function/app/environments/Init.env-sample @@ -2,6 +2,7 @@ repoUrl="UPDATE ME" # url debug="UPDATE ME" # true or false downloadBUs="UPDATE ME" # true or false gitPush="UPDATE ME" # true or false +copadoEnvironmentVariables="UPDATE ME" # json, example: {"BU_NAME":[{"ENV_VARIABLE_NAME":"ENV_VARIABLE_CONTENT"}]} ## generic credentialName="UPDATE ME" From 8e76cd5b5bc178af537fd810063e1ec6427551ad Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Thu, 15 Dec 2022 16:29:14 +0000 Subject: [PATCH 18/28] #296 - updating logic to use json array instead of json attributes --- copado-function/app/Init.fn.js | 2 +- copado-function/app/environments/Init.env-sample | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index c15f665..7754210 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -60,7 +60,7 @@ CONFIG.downloadBUs = process.env.downloadBUs === 'false' ? false : true; CONFIG.gitPush = process.env.gitPush === 'false' ? false : true; CONFIG.copadoEnvironmentVariables = process.env.copadoEnvironmentVariables === undefined - ? '{}' + ? '[]' : process.env.copadoEnvironmentVariables; /** diff --git a/copado-function/app/environments/Init.env-sample b/copado-function/app/environments/Init.env-sample index aa7d4ba..0d8adeb 100644 --- a/copado-function/app/environments/Init.env-sample +++ b/copado-function/app/environments/Init.env-sample @@ -2,7 +2,7 @@ repoUrl="UPDATE ME" # url debug="UPDATE ME" # true or false downloadBUs="UPDATE ME" # true or false gitPush="UPDATE ME" # true or false -copadoEnvironmentVariables="UPDATE ME" # json, example: {"BU_NAME":[{"ENV_VARIABLE_NAME":"ENV_VARIABLE_CONTENT"}]} +copadoEnvironmentVariables="UPDATE ME" # json array, example: [{"BU_NAME":[{"ENV_VARIABLE_NAME":"ENV_VARIABLE_CONTENT"}]}] ## generic credentialName="UPDATE ME" From e63464d1e251c30110f28049903b29fc930e71e3 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Fri, 16 Dec 2022 08:53:51 +0000 Subject: [PATCH 19/28] #296 - creating apex function to be used as call back on the mc init function to create the environments --- .../default/classes/mcdo_CreateEnvironments.cls | 16 ++++++++++++++++ .../classes/mcdo_CreateEnvironments.cls-meta.xml | 10 ++++++++++ 2 files changed, 26 insertions(+) create mode 100644 force-app/main/default/classes/mcdo_CreateEnvironments.cls create mode 100644 force-app/main/default/classes/mcdo_CreateEnvironments.cls-meta.xml diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls b/force-app/main/default/classes/mcdo_CreateEnvironments.cls new file mode 100644 index 0000000..268a277 --- /dev/null +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls @@ -0,0 +1,16 @@ +/** + * This class is used by the MC Init function, + * responsible for creating all environments + */ +Global class mcdo_CreateEnvironments implements copado.MCCallback { + Global void execute(copado__Function__c function, copado__Result__c result, String status) { + if(status == 'Failed') { + // handle Error + } else if(status == 'Success') { + // handle Success + System.debug('Entered the createEnvironments callback function with the status equals to "Success"'); + } else { + // handle In progress if necessary + } + } +} \ No newline at end of file diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls-meta.xml b/force-app/main/default/classes/mcdo_CreateEnvironments.cls-meta.xml new file mode 100644 index 0000000..d2c8c8c --- /dev/null +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls-meta.xml @@ -0,0 +1,10 @@ + + + 56.0 + + 20 + 2 + copado + + Active + From 5c90bfd6c9a71165bec6379ed7ff34916d002a0f Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 19 Dec 2022 11:39:22 +0000 Subject: [PATCH 20/28] #296 adding examples for createEnvVariables json and createEnvironment Apex Code --- .../app/environments/createEnvVariablesJsonExample.txt | 1 + .../app/environments/createEnvironmentApexCodeExample.txt | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 copado-function/app/environments/createEnvVariablesJsonExample.txt create mode 100644 copado-function/app/environments/createEnvironmentApexCodeExample.txt diff --git a/copado-function/app/environments/createEnvVariablesJsonExample.txt b/copado-function/app/environments/createEnvVariablesJsonExample.txt new file mode 100644 index 0000000..d2e236d --- /dev/null +++ b/copado-function/app/environments/createEnvVariablesJsonExample.txt @@ -0,0 +1 @@ +[{"_ParentBU_":[{"environmentVariables":[{"name":"suffix","value":"_Parent"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"1111111","hideValue":false}]}]},{"MCDEV_Training_DEV":[{"environmentVariables":[{"name":"suffix","value":"_DEV"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"2222222","hideValue":false}]}]},{"MCDEV_Training_Prod_1":[{"environmentVariables":[{"name":"suffix","value":"_PROD1"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"33333333","hideValue":false}]}]},{"MCDEV_Training_Prod_2":[{"environmentVariables":[{"name":"suffix","value":"_PROD2"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"4444444","hideValue":false}]}]},{"MCDEV_Training_QA":[{"environmentVariables":[{"name":"suffix","value":"_QA"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"55555555","hideValue":false}]}]}] \ No newline at end of file diff --git a/copado-function/app/environments/createEnvironmentApexCodeExample.txt b/copado-function/app/environments/createEnvironmentApexCodeExample.txt new file mode 100644 index 0000000..0843135 --- /dev/null +++ b/copado-function/app/environments/createEnvironmentApexCodeExample.txt @@ -0,0 +1,7 @@ +copado.CreateExecution.Request request = new copado.CreateExecution.Request(); +request.parentId = 'functionId'; +request.templateName = 'jobTemplateApiName'; +request.callback = 'mcdo_CreateEnvironments'; +request.preSteps = new List(); +request.postSteps = new List(); +request.runAfterInstantiation = true; copado.CreateExecution.execute(new List{ request }); \ No newline at end of file From f259f2e0b88b90b60c57343364fab034c3459bbd Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 19 Dec 2022 11:56:50 +0000 Subject: [PATCH 21/28] #296 updating create environment apex code example values --- .../app/environments/createEnvironmentApexCodeExample.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/copado-function/app/environments/createEnvironmentApexCodeExample.txt b/copado-function/app/environments/createEnvironmentApexCodeExample.txt index 0843135..3efd2ff 100644 --- a/copado-function/app/environments/createEnvironmentApexCodeExample.txt +++ b/copado-function/app/environments/createEnvironmentApexCodeExample.txt @@ -1,7 +1,7 @@ copado.CreateExecution.Request request = new copado.CreateExecution.Request(); -request.parentId = 'functionId'; -request.templateName = 'jobTemplateApiName'; -request.callback = 'mcdo_CreateEnvironments'; +request.parentId = '[functionId]'; +request.templateName = '[jobTemplateApiName]'; +request.callback = '[callBackClassName]'; request.preSteps = new List(); request.postSteps = new List(); request.runAfterInstantiation = true; copado.CreateExecution.execute(new List{ request }); \ No newline at end of file From 575d9ea1d8d6ced2775f7dfee0712b4587f16773 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 19 Dec 2022 16:47:39 +0000 Subject: [PATCH 22/28] #296 giving logic in order to show error message if function fails and show job execution if function is succeeded --- .../default/classes/mcdo_CreateEnvironments.cls | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls b/force-app/main/default/classes/mcdo_CreateEnvironments.cls index 268a277..8ae2f3f 100644 --- a/force-app/main/default/classes/mcdo_CreateEnvironments.cls +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls @@ -1,16 +1,20 @@ /** - * This class is used by the MC Init function, + * This class is used by the MC Init function, g * responsible for creating all environments */ -Global class mcdo_CreateEnvironments implements copado.MCCallback { - Global void execute(copado__Function__c function, copado__Result__c result, String status) { - if(status == 'Failed') { +global class mcdo_CreateEnvironments implements copado.JobExecutionCallback { + global void execute(copado__JobExecution__c job, String status) { + if(status == 'Error') { // handle Error - } else if(status == 'Success') { + System.debug('Error: ' + job.copado__ErrorMessage__c); + } else if(status == 'Successful') { // handle Success - System.debug('Entered the createEnvironments callback function with the status equals to "Success"'); + System.debug('Job: ' + job); + // TODO: create all the needed environments + } else { // handle In progress if necessary + System.debug('still in progress...'); } } } \ No newline at end of file From 33612e1ea272cde0733c20a83f02926bc98ce0f3 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 19 Dec 2022 17:58:57 +0000 Subject: [PATCH 23/28] #296 added logic to read json array in apex --- .../main/default/classes/mcdo_CreateEnvironments.cls | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls b/force-app/main/default/classes/mcdo_CreateEnvironments.cls index 8ae2f3f..9491fcc 100644 --- a/force-app/main/default/classes/mcdo_CreateEnvironments.cls +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls @@ -10,7 +10,15 @@ global class mcdo_CreateEnvironments implements copado.JobExecutionCallback { } else if(status == 'Successful') { // handle Success System.debug('Job: ' + job); + System.debug('Job.copado__DataJson__c: ' + job.copado__DataJson__c); // TODO: create all the needed environments + List dataJson = (List)JSON.deserializeUntyped(job.copado__DataJson__c); + System.debug(dataJson); + for(Object dt : dataJson){ + System.debug('Entered the for loop'); + Map data = (Map)dt; + System.debug(data.get('Name')); + } } else { // handle In progress if necessary From 47b54d32136b43ef95c447f880e28370a80c28fb Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Mon, 19 Dec 2022 17:59:50 +0000 Subject: [PATCH 24/28] #296 updated json array so it can be iterated --- .../app/environments/createEnvVariablesJsonExample.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/copado-function/app/environments/createEnvVariablesJsonExample.txt b/copado-function/app/environments/createEnvVariablesJsonExample.txt index d2e236d..ee6c75c 100644 --- a/copado-function/app/environments/createEnvVariablesJsonExample.txt +++ b/copado-function/app/environments/createEnvVariablesJsonExample.txt @@ -1 +1 @@ -[{"_ParentBU_":[{"environmentVariables":[{"name":"suffix","value":"_Parent"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"1111111","hideValue":false}]}]},{"MCDEV_Training_DEV":[{"environmentVariables":[{"name":"suffix","value":"_DEV"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"2222222","hideValue":false}]}]},{"MCDEV_Training_Prod_1":[{"environmentVariables":[{"name":"suffix","value":"_PROD1"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"33333333","hideValue":false}]}]},{"MCDEV_Training_Prod_2":[{"environmentVariables":[{"name":"suffix","value":"_PROD2"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"4444444","hideValue":false}]}]},{"MCDEV_Training_QA":[{"environmentVariables":[{"name":"suffix","value":"_QA"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"55555555","hideValue":false}]}]}] \ No newline at end of file +[{"Name":"_ParentBU_","environmentVariables":[{"name":"suffix","value":"_Parent"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"1111111","hideValue":false}]},{"Name":"MCDEV_Training_DEV","environmentVariables":[{"name":"suffix","value":"_DEV"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"2222222","hideValue":false}]},{"Name":"MCDEV_Training_Prod_1","environmentVariables":[{"name":"suffix","value":"_PROD1"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"33333333","hideValue":false}]},{"Name":"MCDEV_Training_Prod_2","environmentVariables":[{"name":"suffix","value":"_PROD2"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"4444444","hideValue":false}]},{"Name":"MCDEV_Training_QA","environmentVariables":[{"name":"suffix","value":"_QA"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"55555555","hideValue":false}]}] \ No newline at end of file From 522ade82d43302c0a3f7d3817f44d30fea3953fb Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 20 Dec 2022 10:05:27 +0000 Subject: [PATCH 25/28] #296 updating json example and apex code to create environment example in order to make it more detailed --- .../app/environments/createEnvVariablesJsonExample.txt | 2 +- .../app/environments/createEnvironmentApexCodeExample.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/copado-function/app/environments/createEnvVariablesJsonExample.txt b/copado-function/app/environments/createEnvVariablesJsonExample.txt index ee6c75c..eb1d113 100644 --- a/copado-function/app/environments/createEnvVariablesJsonExample.txt +++ b/copado-function/app/environments/createEnvVariablesJsonExample.txt @@ -1 +1 @@ -[{"Name":"_ParentBU_","environmentVariables":[{"name":"suffix","value":"_Parent"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"1111111","hideValue":false}]},{"Name":"MCDEV_Training_DEV","environmentVariables":[{"name":"suffix","value":"_DEV"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"2222222","hideValue":false}]},{"Name":"MCDEV_Training_Prod_1","environmentVariables":[{"name":"suffix","value":"_PROD1"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"33333333","hideValue":false}]},{"Name":"MCDEV_Training_Prod_2","environmentVariables":[{"name":"suffix","value":"_PROD2"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"4444444","hideValue":false}]},{"Name":"MCDEV_Training_QA","environmentVariables":[{"name":"suffix","value":"_QA"}],"properties":[{"propertyName":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"propertyName":"MID","apiName":"mid","value":"55555555","hideValue":false}]}] \ No newline at end of file +[{"Name":"_ParentBU_","environmentVariables":[{"name":"suffix","value":"_Parent"}],"properties":[{"name":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"name":"MID","apiName":"mid","value":"1111111","hideValue":false}]},{"Name":"MCDEV_Training_DEV","environmentVariables":[{"name":"suffix","value":"_DEV"}],"properties":[{"name":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"name":"MID","apiName":"mid","value":"2222222","hideValue":false}]},{"Name":"MCDEV_Training_Prod_1","environmentVariables":[{"name":"suffix","value":"_PROD1"}],"properties":[{"name":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"name":"MID","apiName":"mid","value":"33333333","hideValue":false}]},{"Name":"MCDEV_Training_Prod_2","environmentVariables":[{"name":"suffix","value":"_PROD2"}],"properties":[{"name":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"name":"MID","apiName":"mid","value":"4444444","hideValue":false}]},{"Name":"MCDEV_Training_QA","environmentVariables":[{"name":"suffix","value":"_QA"}],"properties":[{"name":"CredentialName","apiName":"credential_name","value":"CREDENTIAL_NAME","hideValue":false},{"name":"MID","apiName":"mid","value":"55555555","hideValue":false}]}] \ No newline at end of file diff --git a/copado-function/app/environments/createEnvironmentApexCodeExample.txt b/copado-function/app/environments/createEnvironmentApexCodeExample.txt index 3efd2ff..142e6e6 100644 --- a/copado-function/app/environments/createEnvironmentApexCodeExample.txt +++ b/copado-function/app/environments/createEnvironmentApexCodeExample.txt @@ -2,6 +2,6 @@ copado.CreateExecution.Request request = new copado.CreateExecution.Request(); request.parentId = '[functionId]'; request.templateName = '[jobTemplateApiName]'; request.callback = '[callBackClassName]'; -request.preSteps = new List(); -request.postSteps = new List(); -request.runAfterInstantiation = true; copado.CreateExecution.execute(new List{ request }); \ No newline at end of file +request.dataJson = '[{"Name":"ENVIRONMENT_NAME","environmentVariables":[{"name":"ENVIRONMENT_VARIABLE_NAME","value":"ENVIRONMENT_VARIABLE_VALUE"}],"properties":[{"name":"PROPERTY_NAME","apiName":"PROPERTY_API_NAME","value":"PROPERTY_VALUE","hideValue":TRUE_OR_FALSE}]}]'; +request.runAfterInstantiation = true; +copado.CreateExecution.execute(new List{ request }); \ No newline at end of file From 9a6edd6e37ac8a2388adb31fb199109054a7b759 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 20 Dec 2022 10:14:11 +0000 Subject: [PATCH 26/28] #296 removing the copadoEnvironmentVariables from the environment variables, once we will not use them in here anymore --- copado-function/app/Init.fn.js | 7 ------- copado-function/app/environments/Init.env-sample | 1 - 2 files changed, 8 deletions(-) diff --git a/copado-function/app/Init.fn.js b/copado-function/app/Init.fn.js index 7754210..7f63401 100644 --- a/copado-function/app/Init.fn.js +++ b/copado-function/app/Init.fn.js @@ -58,10 +58,6 @@ CONFIG.target_mid = null; CONFIG.repoUrl = process.env.repoUrl; CONFIG.downloadBUs = process.env.downloadBUs === 'false' ? false : true; CONFIG.gitPush = process.env.gitPush === 'false' ? false : true; -CONFIG.copadoEnvironmentVariables = - process.env.copadoEnvironmentVariables === undefined - ? '[]' - : process.env.copadoEnvironmentVariables; /** * main method that combines runs this function @@ -89,10 +85,7 @@ async function run() { throw ex; } - CONFIG.copadoEnvironmentVariables = JSON.parse(CONFIG.copadoEnvironmentVariables); - Log.debug(CONFIG); - // ensure we got SFMC credentials for our source BU if (!CONFIG.credentials[CONFIG.credentialNameSource]) { Log.error(`No credentials found for source (${CONFIG.credentialNameSource})`); diff --git a/copado-function/app/environments/Init.env-sample b/copado-function/app/environments/Init.env-sample index 0d8adeb..d1363be 100644 --- a/copado-function/app/environments/Init.env-sample +++ b/copado-function/app/environments/Init.env-sample @@ -2,7 +2,6 @@ repoUrl="UPDATE ME" # url debug="UPDATE ME" # true or false downloadBUs="UPDATE ME" # true or false gitPush="UPDATE ME" # true or false -copadoEnvironmentVariables="UPDATE ME" # json array, example: [{"BU_NAME":[{"ENV_VARIABLE_NAME":"ENV_VARIABLE_CONTENT"}]}] ## generic credentialName="UPDATE ME" From 9e4797ca7cbca6f7f3888e784ad5ac4dbf67ddbc Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 20 Dec 2022 10:20:18 +0000 Subject: [PATCH 27/28] #296 updating mcdo_CreateEnvironment to create the environments, the environment variables and the system properties --- .../classes/mcdo_CreateEnvironments.cls | 93 ++++++++++++++++--- 1 file changed, 78 insertions(+), 15 deletions(-) diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls b/force-app/main/default/classes/mcdo_CreateEnvironments.cls index 9491fcc..e47728d 100644 --- a/force-app/main/default/classes/mcdo_CreateEnvironments.cls +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls @@ -1,28 +1,91 @@ /** - * This class is used by the MC Init function, g + * This class is used by the MC Init function, * responsible for creating all environments */ -global class mcdo_CreateEnvironments implements copado.JobExecutionCallback { - global void execute(copado__JobExecution__c job, String status) { +global class mcdo_CreateEnvironments implements copado.JobExecutionCallback { + global void execute(copado__JobExecution__c job, String status) { + // in case of error: if(status == 'Error') { - // handle Error + + // handle Error System.debug('Error: ' + job.copado__ErrorMessage__c); + } else if(status == 'Successful') { - // handle Success - System.debug('Job: ' + job); - System.debug('Job.copado__DataJson__c: ' + job.copado__DataJson__c); - // TODO: create all the needed environments - List dataJson = (List)JSON.deserializeUntyped(job.copado__DataJson__c); - System.debug(dataJson); - for(Object dt : dataJson){ - System.debug('Entered the for loop'); - Map data = (Map)dt; - System.debug(data.get('Name')); - } + // handle Success + // Go through the environment json array + List dataJson = (List)JSON.deserializeUntyped(job.copado__DataJson__c); + for(Object env : dataJson){ + + Map environment = (Map)env; + String envName = environment.get('Name').toString(); + + // TODO: CREATE ENVIRONMENT IN HERE + copado__Environment__c environmentCopado = new copado__Environment__c( + copado__Platform__c='Marketing Cloud', + Name=envName + ); + insert environmentCopado; + + // Create a list of environment variables so we can add all of them in here and then insert them + // this way we will avoid to get into governor limits + List envVarList = new List(); + + // Go through the environmentVariables json array + List environmentVariables = (List) environment.get('environmentVariables'); + for(Object var: environmentVariables){ + Map variables = (Map)var; + String envVarName = variables.get('name').toString(); + String envVarValue = variables.get('value').toString(); + + // create the environment variable + copado__Environmental_Variable__c environmentVariableCopado = new copado__Environmental_Variable__c( + copado__Environment__c=environmentCopado.id, + Name=envVarName, + copado__Value__c=envVarValue + ); + + //add it to the list + envVarList.add(environmentVariableCopado); + } + + //insert the list + insert envVarList; + + // Create a list of system properties as well + // this way we will avoid to get into governor limits + List sysPropList = new List(); + + // Go through the systemProperties json array + List systemProperties = (List) environment.get('properties'); + for(Object prop: systemProperties){ + Map properties = (Map)prop; + String sysPropName = properties.get('name').toString(); + String sysPropApiName = properties.get('apiName').toString(); + String sysPropValue = properties.get('value').toString(); + Boolean sysPropHideValue = Boolean.valueOf(properties.get('hideValue')); + + // create the system property + copado__System_Property__c systemPropertyCopado = new copado__System_Property__c( + copado__Environment__c=environmentCopado.id, + Name=sysPropName, + copado__API_Name__c=sysPropApiName, + copado__Value__c=sysPropValue, + copado__Is_Sensitive__c=sysPropHideValue + ); + + //add it to the list + sysPropList.add(systemPropertyCopado); + } + + //insert the list + insert sysPropList; + } } else { + // handle In progress if necessary System.debug('still in progress...'); + } } } \ No newline at end of file From d714f60590aa9b01c108d81a1db54d1c98e84123 Mon Sep 17 00:00:00 2001 From: Daniel Ventura Date: Tue, 20 Dec 2022 10:22:05 +0000 Subject: [PATCH 28/28] #296 deleting TODO comment and writing a new one saying what it does --- force-app/main/default/classes/mcdo_CreateEnvironments.cls | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/force-app/main/default/classes/mcdo_CreateEnvironments.cls b/force-app/main/default/classes/mcdo_CreateEnvironments.cls index e47728d..c745f53 100644 --- a/force-app/main/default/classes/mcdo_CreateEnvironments.cls +++ b/force-app/main/default/classes/mcdo_CreateEnvironments.cls @@ -20,7 +20,7 @@ global class mcdo_CreateEnvironments implements copado.JobExecutionCallback { Map environment = (Map)env; String envName = environment.get('Name').toString(); - // TODO: CREATE ENVIRONMENT IN HERE + // create the environment copado__Environment__c environmentCopado = new copado__Environment__c( copado__Platform__c='Marketing Cloud', Name=envName