contensis-cli 1.0.9-beta.1 → 1.0.9-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mappers/DevInit-to-CIWorkflow.js +8 -4
- package/dist/mappers/DevInit-to-CIWorkflow.js.map +2 -2
- package/dist/services/ContensisDevService.js +22 -6
- package/dist/services/ContensisDevService.js.map +2 -2
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/src/mappers/DevInit-to-CIWorkflow.ts +14 -8
- package/src/services/ContensisDevService.ts +31 -6
- package/src/version.ts +1 -1
|
@@ -75,12 +75,12 @@ const findExistingJobSteps = (path, json, resultType) => {
|
|
|
75
75
|
});
|
|
76
76
|
return existingJobStep;
|
|
77
77
|
};
|
|
78
|
+
const findPath = (path) => typeof path === "string" && path.includes(".") ? path.split(".").map((p) => Number(p) || Number(p) !== 0 ? p : Number(p)) : path;
|
|
78
79
|
const setWorkflowElement = (workflowDoc, path, value) => {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
workflowDoc.setIn(findPath, value);
|
|
80
|
+
if (workflowDoc.hasIn(findPath(path))) {
|
|
81
|
+
workflowDoc.setIn(findPath(path), value);
|
|
82
82
|
} else {
|
|
83
|
-
workflowDoc.addIn(findPath, value);
|
|
83
|
+
workflowDoc.addIn(findPath(path), value);
|
|
84
84
|
}
|
|
85
85
|
};
|
|
86
86
|
const mapGitLabCIWorkflowContent = async (cli, blockId, workflowDoc, workflowJS) => {
|
|
@@ -206,6 +206,10 @@ const mapGitHubActionCIWorkflowContent = async (cli, blockId, workflowDoc, workf
|
|
|
206
206
|
cli.clientSecret
|
|
207
207
|
);
|
|
208
208
|
}
|
|
209
|
+
if (cli.clientDetailsLocation === "git") {
|
|
210
|
+
workflowDoc.deleteIn(findPath(`env.CONTENSIS_CLIENT_ID`));
|
|
211
|
+
workflowDoc.deleteIn(findPath(`env.CONTENSIS_SHARED_SECRET`));
|
|
212
|
+
}
|
|
209
213
|
if (existingJobStep.length) {
|
|
210
214
|
const step = existingJobStep[0];
|
|
211
215
|
const stepPath = step.path.replace("$[", "").replaceAll("][", ".").replace("]", "").replaceAll("'", "");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/mappers/DevInit-to-CIWorkflow.ts"],
|
|
4
|
-
"sourcesContent": ["import inquirer from 'inquirer';\nimport { JSONPath, JSONPathOptions } from 'jsonpath-plus';\nimport { Document } from 'yaml';\nimport {\n GitHubActionPushBlockJob,\n GitHubActionPushBlockJobStep,\n GitLabPushBlockJobStage,\n} from '~/models/DevService';\nimport { readFile } from '~/providers/file-provider';\nimport ContensisDev from '~/services/ContensisDevService';\nimport { diffFileContent } from '~/util/diff';\nimport { logError } from '~/util/logger';\nimport { normaliseLineEndings } from '~/util/os';\nimport { parseYamlDocument, validateWorkflowYaml } from '~/util/yaml';\n\ntype MappedWorkflowOutput = {\n existingWorkflow: string;\n newWorkflow: string;\n diff: string;\n};\n\nexport const mapCIWorkflowContent = async (\n cli: ContensisDev\n): Promise<MappedWorkflowOutput | undefined> => {\n // get existing workflow file\n const workflowFile = readFile(cli.git.ciFilePath);\n if (!workflowFile) return undefined;\n\n const blockId = cli.git.name;\n\n // parse yaml to js\n const workflowDoc = parseYamlDocument(workflowFile);\n const workflowJS = workflowDoc.toJS();\n\n if (cli.git.type === 'github') {\n const newWorkflow = await mapGitHubActionCIWorkflowContent(\n cli,\n blockId,\n workflowDoc,\n workflowJS\n );\n return {\n existingWorkflow: workflowFile,\n newWorkflow,\n diff: diffFileContent(workflowFile, newWorkflow),\n };\n } else if (cli.git.type === 'gitlab') {\n const newWorkflow = await mapGitLabCIWorkflowContent(\n cli,\n blockId,\n workflowDoc,\n workflowJS\n );\n return {\n existingWorkflow: workflowFile,\n newWorkflow,\n diff: diffFileContent(workflowFile, newWorkflow),\n };\n }\n};\n\nconst findExistingJobSteps = (\n path: string,\n json: any,\n resultType: JSONPathOptions['resultType']\n) => {\n const existingJobStep = JSONPath({\n path,\n json,\n resultType: resultType,\n });\n\n return existingJobStep;\n};\n\nconst setWorkflowElement = (\n workflowDoc: Document,\n path: string | any[],\n value: any\n) => {\n const findPath =\n typeof path === 'string' && path.includes('.')\n ? path.split('.').map(p => (Number(p) || Number(p) !== 0 ? p : Number(p)))\n : path;\n\n if (workflowDoc.hasIn(findPath)) {\n workflowDoc.setIn(findPath, value);\n } else {\n workflowDoc.addIn(findPath, value);\n }\n};\n\nconst mapGitLabCIWorkflowContent = async (\n cli: ContensisDev,\n blockId: string,\n workflowDoc: Document,\n workflowJS: any\n) => {\n const addGitLabJobStage: GitLabPushBlockJobStage = {\n stage: 'push-block',\n variables: {\n block_id: blockId,\n alias: cli.currentEnv,\n project_id: cli.currentProject,\n client_id:\n cli.clientDetailsLocation === 'env'\n ? cli.clientId\n : '$CONTENSIS_CLIENT_ID',\n shared_secret:\n cli.clientDetailsLocation === 'env'\n ? cli.clientSecret\n : '$CONTENSIS_SHARED_SECRET',\n },\n };\n\n const addAppImageUri = async () => {\n // Look in document level \"variables\"\n const appImageUri = await determineAppImageUri(\n cli,\n Object.entries(workflowJS.variables || {}),\n '$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME/app:build-$CI_PIPELINE_IID'\n );\n\n if (appImageUri.addVar)\n setWorkflowElement(\n workflowDoc,\n `variables.${appImageUri.var}`,\n appImageUri.uri\n );\n\n if (appImageUri.var)\n addGitLabJobStage.variables['image_uri'] = `\\$${appImageUri.var}`;\n };\n\n // look for line in job\n // jobname[stage: push-block]\n const existingJobStep = findExistingJobSteps(\n '$..[?(@property === \"stage\" && @.match(/^push-block/i))]^',\n workflowJS,\n 'all'\n );\n\n // update job step\n if (existingJobStep.length) {\n // cli.log.json(existingJobStep);\n\n // The [0] index means we're only looking at updating the first instance in the file\n const step = existingJobStep[0];\n\n // Path looks like this \"$['job_name']\"\n // We want it to look like this \"job_name\"\n const stepPath = step.path\n .replace('$[', '')\n .replaceAll('][', '.')\n .replace(']', '')\n .replaceAll(\"'\", '');\n\n cli.log.info(\n `Found existing Job step:\n ${stepPath}\n stage: ${step.value.stage}\\n`\n );\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.alias`,\n cli.currentEnv\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.project_id`,\n cli.currentProject\n );\n setWorkflowElement(workflowDoc, `${stepPath}.variables.block_id`, blockId);\n\n // This is likely not needed when updating an existing push-block job step\n // we are assuming this is a forked/copied workflow with an already working image-uri reference\n // await addAppImageUri();\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.client_id`,\n cli.clientDetailsLocation === 'env'\n ? cli.clientId\n : '$CONTENSIS_CLIENT_ID'\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.shared_secret`,\n cli.clientDetailsLocation === 'env'\n ? cli.clientSecret\n : '$CONTENSIS_SHARED_SECRET'\n );\n } else {\n // create job with push step\n\n // Does a series of checks and prompts to determine the correct image-uri\n // for the app container build\n await addAppImageUri();\n\n // Add the new \"job\" to the Yaml Document\n workflowDoc.addIn(['stages'], 'push-block');\n workflowDoc.addIn([], {\n key: 'push-to-contensis',\n value: addGitLabJobStage,\n });\n setWorkflowElement(\n workflowDoc,\n `include`,\n 'https://gitlab.zengenti.com/ops/contensis-ci/-/raw/main/push-block.yml'\n );\n }\n\n cli.log.debug(`New file content to write\\n\\n${workflowDoc}`);\n\n const newWorkflow = normaliseLineEndings(\n workflowDoc.toString({ lineWidth: 0 })\n );\n\n return newWorkflow;\n};\n\nconst mapGitHubActionCIWorkflowContent = async (\n cli: ContensisDev,\n blockId: string,\n workflowDoc: Document,\n workflowJS: any\n) => {\n const addGitHubActionJobStep: GitHubActionPushBlockJobStep = {\n name: 'Push block to Contensis',\n id: 'push-block',\n uses: 'contensis/block-push@v1',\n with: {\n 'block-id': blockId,\n // 'image-uri': '${{ steps.build.outputs.image-uri }}',\n alias: cli.currentEnv,\n 'project-id': cli.currentProject,\n 'client-id':\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_CLIENT_ID }}'\n : '${{ secrets.CONTENSIS_CLIENT_ID }}',\n 'shared-secret':\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_SHARED_SECRET }}'\n : '${{ secrets.CONTENSIS_SHARED_SECRET }}',\n },\n };\n\n const addAppImageUri = async () => {\n // Look in document level \"env\" vars\n const appImageUri = await determineAppImageUri(\n cli,\n Object.entries(workflowJS.env || {}),\n 'ghcr.io/${{ github.repository }}/${{ github.ref_name }}/app'\n );\n\n if (appImageUri.addVar)\n setWorkflowElement(\n workflowDoc,\n `env.${appImageUri.var}`,\n appImageUri.uri\n );\n // workflowDoc.addIn(['env'], { [appImageUri.var]: appImageUri.uri });\n\n if (appImageUri.var)\n addGitHubActionJobStep.with[\n 'image-uri'\n ] = `\\${{ env.${appImageUri.var} }}:build-\\${{ github.run_number }}`;\n };\n\n // look for line in job\n // jobs.x.steps[uses: contensis/block-push]\n const existingJobStep = findExistingJobSteps(\n '$.jobs..steps.*[?(@property === \"uses\" && @.match(/^contensis\\\\/block-push/i))]^',\n workflowJS,\n 'all'\n );\n\n // Update 'env' and store client id and secret\n if (cli.clientDetailsLocation === 'env') {\n setWorkflowElement(workflowDoc, `env.CONTENSIS_CLIENT_ID`, cli.clientId);\n setWorkflowElement(\n workflowDoc,\n `env.CONTENSIS_SHARED_SECRET`,\n cli.clientSecret\n );\n }\n\n // update job step\n if (existingJobStep.length) {\n //cli.log.json(existingJobStep);\n\n // The [0] index means we're only looking at updating the first instance in the file\n const step = existingJobStep[0];\n\n // Path looks like this \"$['jobs']['build']['steps'][3]\"\n // We want it to look like this \"jobs.build.steps.3\"\n const stepPath = step.path\n .replace('$[', '')\n .replaceAll('][', '.')\n .replace(']', '')\n .replaceAll(\"'\", '');\n\n cli.log.info(\n `Found existing Job step: ${stepPath}\n - name: ${step.value.name}\n id: ${step.value.id}\\n`\n );\n\n setWorkflowElement(workflowDoc, `${stepPath}.with.alias`, cli.currentEnv);\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.project-id`,\n cli.currentProject\n );\n setWorkflowElement(workflowDoc, `${stepPath}.with.block-id`, blockId);\n\n // This is likely not needed when updating an existing push-block job step\n // we are assuming this is a forked/copied workflow with an already working image-uri reference\n // await addAppImageUri();\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.client-id`,\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_CLIENT_ID }}'\n : '${{ secrets.CONTENSIS_CLIENT_ID }}'\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.shared-secret`,\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_SHARED_SECRET }}'\n : '${{ secrets.CONTENSIS_SHARED_SECRET }}'\n );\n } else {\n // create job with push step\n\n // is there already a job with a property name containing \"build\"?\n const existingBuildJobStep = findExistingJobSteps(\n '$.jobs[?(@property.match(/build/i))]',\n workflowJS,\n 'all'\n ) as JSONPathOptions[]; // This isn't the correct type for this object\n\n let needs: string | undefined;\n // There are multiple jobs called *build*\n if (existingBuildJobStep.length > 1) {\n // prompt which build job we should depend on before pushing the block\n const choices = existingBuildJobStep.map(s => s.parentProperty);\n choices.push(new inquirer.Separator() as any);\n choices.push('none');\n if (choices.includes('build-app')) needs = 'build-app';\n else {\n ({ needs } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u231B',\n message: cli.messages.devinit.ciMultipleBuildJobChoices(),\n name: 'needs',\n choices,\n default: choices.find(\n s => typeof s === 'string' && s.includes('docker')\n ),\n },\n ]));\n }\n\n cli.log.raw('');\n } else if (existingBuildJobStep.length === 1)\n // Exactly one job step found containing a property name of *build*\n // we'll assume that is the one the push-block job depends on\n needs = existingBuildJobStep[0].parentProperty;\n\n if (existingBuildJobStep.length === 0 || needs === 'none') {\n // No existing build step found or chosen, offer all job steps in prompt\n const choices = Object.keys(workflowJS.jobs);\n choices.push(new inquirer.Separator() as any);\n choices.push('none');\n\n ({ needs } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u231B',\n message: cli.messages.devinit.ciMultipleJobChoices(),\n name: 'needs',\n choices,\n default: choices.find(\n j => typeof j === 'string' && j.includes('docker')\n ),\n },\n ]));\n if (needs === 'none') needs = undefined;\n cli.log.raw('');\n }\n\n // Does a series of checks and prompts to determine the correct image-uri\n // for the app container build\n await addAppImageUri();\n\n const newJob: GitHubActionPushBlockJob = {\n name: 'Deploy container image to Contensis',\n 'runs-on': 'ubuntu-latest',\n needs,\n steps: [addGitHubActionJobStep],\n };\n\n // Add the new \"job\" to the Yaml Document\n workflowDoc.addIn(['jobs'], {\n key: 'deploy',\n value: newJob,\n });\n }\n\n // Workflow validation provided by @action-validator/core package\n const workflowIsValid = validateWorkflowYaml(workflowDoc.toString());\n\n // We could expand validation to check for having a build step to wait for\n // or if a valid image-uri attribute is set\n if (workflowIsValid === true) {\n cli.log.success(`GitHub workflow YAML is valid`);\n cli.log.debug(`New file content to write\\n\\n${workflowDoc}`);\n } else if (Array.isArray(workflowIsValid)) {\n // Errors\n logError(\n [\n ...workflowIsValid.map(\n res => new Error(`${res.code}: ${res.detail || res.title}`)\n ),\n workflowDoc.toString(),\n ],\n `GitHub workflow YAML did not pass validation check`\n );\n }\n\n // const newWorkflow = normaliseLineEndings(\n // workflowDoc.toString({ lineWidth: 0 })\n // );\n\n const newWorkflow = workflowDoc.toString();\n\n return newWorkflow;\n};\n\nconst determineAppImageUri = async (\n cli: ContensisDev,\n vars: [string, string][],\n defaultUri: string\n) => {\n // Determine container image-uri via variables and/or prompts\n\n // Find vars including the word \"image\"\n const imageVars = vars.filter(([varname]) =>\n varname.toLowerCase().includes('image')\n );\n // Find vars named \"image\" that include the word \"app\"\n const appImageVars = imageVars.filter(\n ([varname, value]) =>\n !varname.toLowerCase().includes('builder_') &&\n (varname.toLowerCase().includes('app_') ||\n varname.toLowerCase().includes('build_') ||\n value?.toLowerCase().includes('/app'))\n );\n\n const appImageUriGuess = appImageVars?.[0];\n\n let appImageUri: string | undefined;\n let appImageVar: string | undefined;\n\n if (appImageUriGuess) {\n cli.log.success(\n `Found variable ${cli.log.standardText(\n appImageUriGuess[0]\n )} we'll use for pulling the block image from: ${cli.log.infoText(\n appImageUriGuess[1]\n )}`\n );\n appImageVar = appImageUriGuess[0];\n } else {\n // Could not find a suitable var to use for block image-uri\n // prompt for an app image uri\n const choices = vars.map(v => v[0]);\n const enterOwnMsg = 'enter my own / use default';\n\n choices.push(new inquirer.Separator() as any);\n choices.push(enterOwnMsg);\n choices.push(defaultUri);\n\n ({ appImageVar, appImageUri } = await inquirer.prompt([\n // First question determines if an existing env variable\n // already containes the tagged app image uri\n {\n type: 'list',\n prefix: '\uD83D\uDC33',\n message: cli.messages.devinit.ciMultipleAppImageVarChoices(),\n name: 'appImageVar',\n choices,\n default: choices.find(\n v => typeof v === 'string' && v.toLowerCase().includes('image')\n ),\n },\n // Subsequent prompt allows input of an image-uri if needed\n {\n type: 'input',\n when(answers) {\n return [enterOwnMsg, defaultUri].includes(answers.appImageVar);\n },\n prefix: `\\n \\n\uD83D\uDD17`,\n message: cli.messages.devinit.ciEnterOwnAppImagePrompt(cli.git),\n name: 'appImageUri',\n default: defaultUri,\n },\n ]));\n cli.log.raw('');\n\n // this indicates a uri has been added and we will add a new var\n // to the workflow to encourage users to update the docker tag part\n // of their build workflow to use the same var as the push-block job/step\n if ([enterOwnMsg, defaultUri].includes(appImageVar || ''))\n appImageVar = undefined;\n }\n\n if (appImageVar)\n appImageUri =\n cli.git.type === 'github'\n ? `\\${{ env.${appImageVar} }}`\n : `\\$${appImageVar}`;\n\n // TODO: prompt further for image tag\n\n return {\n addVar: !appImageVar,\n uri: appImageUri,\n var: appImageVar || 'BUILD_IMAGE',\n };\n};\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAqB;AACrB,2BAA0C;AAO1C,2BAAyB;AAEzB,kBAAgC;AAChC,oBAAyB;AACzB,gBAAqC;AACrC,IAAAA,eAAwD;AAQjD,MAAM,uBAAuB,OAClC,QAC8C;AAE9C,QAAM,mBAAe,+BAAS,IAAI,IAAI,UAAU;AAChD,MAAI,CAAC;AAAc,WAAO;AAE1B,QAAM,UAAU,IAAI,IAAI;AAGxB,QAAM,kBAAc,gCAAkB,YAAY;AAClD,QAAM,aAAa,YAAY,KAAK;AAEpC,MAAI,IAAI,IAAI,SAAS,UAAU;AAC7B,UAAM,cAAc,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,MACL,kBAAkB;AAAA,MAClB;AAAA,MACA,UAAM,6BAAgB,cAAc,WAAW;AAAA,IACjD;AAAA,EACF,WAAW,IAAI,IAAI,SAAS,UAAU;AACpC,UAAM,cAAc,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,MACL,kBAAkB;AAAA,MAClB;AAAA,MACA,UAAM,6BAAgB,cAAc,WAAW;AAAA,IACjD;AAAA,EACF;AACF;AAEA,MAAM,uBAAuB,CAC3B,MACA,MACA,eACG;AACH,QAAM,sBAAkB,+BAAS;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAEA,MAAM,
|
|
4
|
+
"sourcesContent": ["import inquirer from 'inquirer';\nimport { JSONPath, JSONPathOptions } from 'jsonpath-plus';\nimport { Document } from 'yaml';\nimport {\n GitHubActionPushBlockJob,\n GitHubActionPushBlockJobStep,\n GitLabPushBlockJobStage,\n} from '~/models/DevService';\nimport { readFile } from '~/providers/file-provider';\nimport ContensisDev from '~/services/ContensisDevService';\nimport { diffFileContent } from '~/util/diff';\nimport { logError } from '~/util/logger';\nimport { normaliseLineEndings } from '~/util/os';\nimport { parseYamlDocument, validateWorkflowYaml } from '~/util/yaml';\n\ntype MappedWorkflowOutput = {\n existingWorkflow: string;\n newWorkflow: string;\n diff: string;\n};\n\nexport const mapCIWorkflowContent = async (\n cli: ContensisDev\n): Promise<MappedWorkflowOutput | undefined> => {\n // get existing workflow file\n const workflowFile = readFile(cli.git.ciFilePath);\n if (!workflowFile) return undefined;\n\n const blockId = cli.git.name;\n\n // parse yaml to js\n const workflowDoc = parseYamlDocument(workflowFile);\n const workflowJS = workflowDoc.toJS();\n\n if (cli.git.type === 'github') {\n const newWorkflow = await mapGitHubActionCIWorkflowContent(\n cli,\n blockId,\n workflowDoc,\n workflowJS\n );\n return {\n existingWorkflow: workflowFile,\n newWorkflow,\n diff: diffFileContent(workflowFile, newWorkflow),\n };\n } else if (cli.git.type === 'gitlab') {\n const newWorkflow = await mapGitLabCIWorkflowContent(\n cli,\n blockId,\n workflowDoc,\n workflowJS\n );\n return {\n existingWorkflow: workflowFile,\n newWorkflow,\n diff: diffFileContent(workflowFile, newWorkflow),\n };\n }\n};\n\nconst findExistingJobSteps = (\n path: string,\n json: any,\n resultType: JSONPathOptions['resultType']\n) => {\n const existingJobStep = JSONPath({\n path,\n json,\n resultType: resultType,\n });\n\n return existingJobStep;\n};\n\nconst findPath = (path: string | any[]) =>\n typeof path === 'string' && path.includes('.')\n ? path.split('.').map(p => (Number(p) || Number(p) !== 0 ? p : Number(p)))\n : path;\n\nconst setWorkflowElement = (\n workflowDoc: Document,\n path: string | any[],\n value: any\n) => {\n if (workflowDoc.hasIn(findPath(path))) {\n workflowDoc.setIn(findPath(path), value);\n } else {\n workflowDoc.addIn(findPath(path), value);\n }\n};\n\nconst mapGitLabCIWorkflowContent = async (\n cli: ContensisDev,\n blockId: string,\n workflowDoc: Document,\n workflowJS: any\n) => {\n const addGitLabJobStage: GitLabPushBlockJobStage = {\n stage: 'push-block',\n variables: {\n block_id: blockId,\n alias: cli.currentEnv,\n project_id: cli.currentProject,\n client_id:\n cli.clientDetailsLocation === 'env'\n ? cli.clientId\n : '$CONTENSIS_CLIENT_ID',\n shared_secret:\n cli.clientDetailsLocation === 'env'\n ? cli.clientSecret\n : '$CONTENSIS_SHARED_SECRET',\n },\n };\n\n const addAppImageUri = async () => {\n // Look in document level \"variables\"\n const appImageUri = await determineAppImageUri(\n cli,\n Object.entries(workflowJS.variables || {}),\n '$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME/app:build-$CI_PIPELINE_IID'\n );\n\n if (appImageUri.addVar)\n setWorkflowElement(\n workflowDoc,\n `variables.${appImageUri.var}`,\n appImageUri.uri\n );\n\n if (appImageUri.var)\n addGitLabJobStage.variables['image_uri'] = `\\$${appImageUri.var}`;\n };\n\n // look for line in job\n // jobname[stage: push-block]\n const existingJobStep = findExistingJobSteps(\n '$..[?(@property === \"stage\" && @.match(/^push-block/i))]^',\n workflowJS,\n 'all'\n );\n\n // update job step\n if (existingJobStep.length) {\n // cli.log.json(existingJobStep);\n\n // The [0] index means we're only looking at updating the first instance in the file\n const step = existingJobStep[0];\n\n // Path looks like this \"$['job_name']\"\n // We want it to look like this \"job_name\"\n const stepPath = step.path\n .replace('$[', '')\n .replaceAll('][', '.')\n .replace(']', '')\n .replaceAll(\"'\", '');\n\n cli.log.info(\n `Found existing Job step:\n ${stepPath}\n stage: ${step.value.stage}\\n`\n );\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.alias`,\n cli.currentEnv\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.project_id`,\n cli.currentProject\n );\n setWorkflowElement(workflowDoc, `${stepPath}.variables.block_id`, blockId);\n\n // This is likely not needed when updating an existing push-block job step\n // we are assuming this is a forked/copied workflow with an already working image-uri reference\n // await addAppImageUri();\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.client_id`,\n cli.clientDetailsLocation === 'env'\n ? cli.clientId\n : '$CONTENSIS_CLIENT_ID'\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.variables.shared_secret`,\n cli.clientDetailsLocation === 'env'\n ? cli.clientSecret\n : '$CONTENSIS_SHARED_SECRET'\n );\n } else {\n // create job with push step\n\n // Does a series of checks and prompts to determine the correct image-uri\n // for the app container build\n await addAppImageUri();\n\n // Add the new \"job\" to the Yaml Document\n workflowDoc.addIn(['stages'], 'push-block');\n workflowDoc.addIn([], {\n key: 'push-to-contensis',\n value: addGitLabJobStage,\n });\n setWorkflowElement(\n workflowDoc,\n `include`,\n 'https://gitlab.zengenti.com/ops/contensis-ci/-/raw/main/push-block.yml'\n );\n }\n\n cli.log.debug(`New file content to write\\n\\n${workflowDoc}`);\n\n const newWorkflow = normaliseLineEndings(\n workflowDoc.toString({ lineWidth: 0 })\n );\n\n return newWorkflow;\n};\n\nconst mapGitHubActionCIWorkflowContent = async (\n cli: ContensisDev,\n blockId: string,\n workflowDoc: Document,\n workflowJS: any\n) => {\n const addGitHubActionJobStep: GitHubActionPushBlockJobStep = {\n name: 'Push block to Contensis',\n id: 'push-block',\n uses: 'contensis/block-push@v1',\n with: {\n 'block-id': blockId,\n // 'image-uri': '${{ steps.build.outputs.image-uri }}',\n alias: cli.currentEnv,\n 'project-id': cli.currentProject,\n 'client-id':\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_CLIENT_ID }}'\n : '${{ secrets.CONTENSIS_CLIENT_ID }}',\n 'shared-secret':\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_SHARED_SECRET }}'\n : '${{ secrets.CONTENSIS_SHARED_SECRET }}',\n },\n };\n\n const addAppImageUri = async () => {\n // Look in document level \"env\" vars\n const appImageUri = await determineAppImageUri(\n cli,\n Object.entries(workflowJS.env || {}),\n 'ghcr.io/${{ github.repository }}/${{ github.ref_name }}/app'\n );\n\n if (appImageUri.addVar)\n setWorkflowElement(\n workflowDoc,\n `env.${appImageUri.var}`,\n appImageUri.uri\n );\n // workflowDoc.addIn(['env'], { [appImageUri.var]: appImageUri.uri });\n\n if (appImageUri.var)\n addGitHubActionJobStep.with[\n 'image-uri'\n ] = `\\${{ env.${appImageUri.var} }}:build-\\${{ github.run_number }}`;\n };\n\n // look for line in job\n // jobs.x.steps[uses: contensis/block-push]\n const existingJobStep = findExistingJobSteps(\n '$.jobs..steps.*[?(@property === \"uses\" && @.match(/^contensis\\\\/block-push/i))]^',\n workflowJS,\n 'all'\n );\n\n // Update 'env' and store client id and secret\n if (cli.clientDetailsLocation === 'env') {\n setWorkflowElement(workflowDoc, `env.CONTENSIS_CLIENT_ID`, cli.clientId);\n setWorkflowElement(\n workflowDoc,\n `env.CONTENSIS_SHARED_SECRET`,\n cli.clientSecret\n );\n }\n\n if (cli.clientDetailsLocation === 'git') {\n // remove env vars from yml if we choose git\n workflowDoc.deleteIn(findPath(`env.CONTENSIS_CLIENT_ID`));\n workflowDoc.deleteIn(findPath(`env.CONTENSIS_SHARED_SECRET`));\n }\n\n // update job step\n if (existingJobStep.length) {\n //cli.log.json(existingJobStep);\n\n // The [0] index means we're only looking at updating the first instance in the file\n const step = existingJobStep[0];\n\n // Path looks like this \"$['jobs']['build']['steps'][3]\"\n // We want it to look like this \"jobs.build.steps.3\"\n const stepPath = step.path\n .replace('$[', '')\n .replaceAll('][', '.')\n .replace(']', '')\n .replaceAll(\"'\", '');\n\n cli.log.info(\n `Found existing Job step: ${stepPath}\n - name: ${step.value.name}\n id: ${step.value.id}\\n`\n );\n\n setWorkflowElement(workflowDoc, `${stepPath}.with.alias`, cli.currentEnv);\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.project-id`,\n cli.currentProject\n );\n setWorkflowElement(workflowDoc, `${stepPath}.with.block-id`, blockId);\n\n // This is likely not needed when updating an existing push-block job step\n // we are assuming this is a forked/copied workflow with an already working image-uri reference\n // await addAppImageUri();\n\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.client-id`,\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_CLIENT_ID }}'\n : '${{ secrets.CONTENSIS_CLIENT_ID }}'\n );\n setWorkflowElement(\n workflowDoc,\n `${stepPath}.with.shared-secret`,\n cli.clientDetailsLocation === 'env'\n ? '${{ env.CONTENSIS_SHARED_SECRET }}'\n : '${{ secrets.CONTENSIS_SHARED_SECRET }}'\n );\n } else {\n // create job with push step\n\n // is there already a job with a property name containing \"build\"?\n const existingBuildJobStep = findExistingJobSteps(\n '$.jobs[?(@property.match(/build/i))]',\n workflowJS,\n 'all'\n ) as JSONPathOptions[]; // This isn't the correct type for this object\n\n let needs: string | undefined;\n // There are multiple jobs called *build*\n if (existingBuildJobStep.length > 1) {\n // prompt which build job we should depend on before pushing the block\n const choices = existingBuildJobStep.map(s => s.parentProperty);\n choices.push(new inquirer.Separator() as any);\n choices.push('none');\n if (choices.includes('build-app')) needs = 'build-app';\n else {\n ({ needs } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u231B',\n message: cli.messages.devinit.ciMultipleBuildJobChoices(),\n name: 'needs',\n choices,\n default: choices.find(\n s => typeof s === 'string' && s.includes('docker')\n ),\n },\n ]));\n }\n\n cli.log.raw('');\n } else if (existingBuildJobStep.length === 1)\n // Exactly one job step found containing a property name of *build*\n // we'll assume that is the one the push-block job depends on\n needs = existingBuildJobStep[0].parentProperty;\n\n if (existingBuildJobStep.length === 0 || needs === 'none') {\n // No existing build step found or chosen, offer all job steps in prompt\n const choices = Object.keys(workflowJS.jobs);\n choices.push(new inquirer.Separator() as any);\n choices.push('none');\n\n ({ needs } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u231B',\n message: cli.messages.devinit.ciMultipleJobChoices(),\n name: 'needs',\n choices,\n default: choices.find(\n j => typeof j === 'string' && j.includes('docker')\n ),\n },\n ]));\n if (needs === 'none') needs = undefined;\n cli.log.raw('');\n }\n\n // Does a series of checks and prompts to determine the correct image-uri\n // for the app container build\n await addAppImageUri();\n\n const newJob: GitHubActionPushBlockJob = {\n name: 'Deploy container image to Contensis',\n 'runs-on': 'ubuntu-latest',\n needs,\n steps: [addGitHubActionJobStep],\n };\n\n // Add the new \"job\" to the Yaml Document\n workflowDoc.addIn(['jobs'], {\n key: 'deploy',\n value: newJob,\n });\n }\n\n // Workflow validation provided by @action-validator/core package\n const workflowIsValid = validateWorkflowYaml(workflowDoc.toString());\n\n // We could expand validation to check for having a build step to wait for\n // or if a valid image-uri attribute is set\n if (workflowIsValid === true) {\n cli.log.success(`GitHub workflow YAML is valid`);\n cli.log.debug(`New file content to write\\n\\n${workflowDoc}`);\n } else if (Array.isArray(workflowIsValid)) {\n // Errors\n logError(\n [\n ...workflowIsValid.map(\n res => new Error(`${res.code}: ${res.detail || res.title}`)\n ),\n workflowDoc.toString(),\n ],\n `GitHub workflow YAML did not pass validation check`\n );\n }\n\n // const newWorkflow = normaliseLineEndings(\n // workflowDoc.toString({ lineWidth: 0 })\n // );\n\n const newWorkflow = workflowDoc.toString();\n\n return newWorkflow;\n};\n\nconst determineAppImageUri = async (\n cli: ContensisDev,\n vars: [string, string][],\n defaultUri: string\n) => {\n // Determine container image-uri via variables and/or prompts\n\n // Find vars including the word \"image\"\n const imageVars = vars.filter(([varname]) =>\n varname.toLowerCase().includes('image')\n );\n // Find vars named \"image\" that include the word \"app\"\n const appImageVars = imageVars.filter(\n ([varname, value]) =>\n !varname.toLowerCase().includes('builder_') &&\n (varname.toLowerCase().includes('app_') ||\n varname.toLowerCase().includes('build_') ||\n value?.toLowerCase().includes('/app'))\n );\n\n const appImageUriGuess = appImageVars?.[0];\n\n let appImageUri: string | undefined;\n let appImageVar: string | undefined;\n\n if (appImageUriGuess) {\n cli.log.success(\n `Found variable ${cli.log.standardText(\n appImageUriGuess[0]\n )} we'll use for pulling the block image from: ${cli.log.infoText(\n appImageUriGuess[1]\n )}`\n );\n appImageVar = appImageUriGuess[0];\n } else {\n // Could not find a suitable var to use for block image-uri\n // prompt for an app image uri\n const choices = vars.map(v => v[0]);\n const enterOwnMsg = 'enter my own / use default';\n\n choices.push(new inquirer.Separator() as any);\n choices.push(enterOwnMsg);\n choices.push(defaultUri);\n\n ({ appImageVar, appImageUri } = await inquirer.prompt([\n // First question determines if an existing env variable\n // already containes the tagged app image uri\n {\n type: 'list',\n prefix: '\uD83D\uDC33',\n message: cli.messages.devinit.ciMultipleAppImageVarChoices(),\n name: 'appImageVar',\n choices,\n default: choices.find(\n v => typeof v === 'string' && v.toLowerCase().includes('image')\n ),\n },\n // Subsequent prompt allows input of an image-uri if needed\n {\n type: 'input',\n when(answers) {\n return [enterOwnMsg, defaultUri].includes(answers.appImageVar);\n },\n prefix: `\\n \\n\uD83D\uDD17`,\n message: cli.messages.devinit.ciEnterOwnAppImagePrompt(cli.git),\n name: 'appImageUri',\n default: defaultUri,\n },\n ]));\n cli.log.raw('');\n\n // this indicates a uri has been added and we will add a new var\n // to the workflow to encourage users to update the docker tag part\n // of their build workflow to use the same var as the push-block job/step\n if ([enterOwnMsg, defaultUri].includes(appImageVar || ''))\n appImageVar = undefined;\n }\n\n if (appImageVar)\n appImageUri =\n cli.git.type === 'github'\n ? `\\${{ env.${appImageVar} }}`\n : `\\$${appImageVar}`;\n\n // TODO: prompt further for image tag\n\n return {\n addVar: !appImageVar,\n uri: appImageUri,\n var: appImageVar || 'BUILD_IMAGE',\n };\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAqB;AACrB,2BAA0C;AAO1C,2BAAyB;AAEzB,kBAAgC;AAChC,oBAAyB;AACzB,gBAAqC;AACrC,IAAAA,eAAwD;AAQjD,MAAM,uBAAuB,OAClC,QAC8C;AAE9C,QAAM,mBAAe,+BAAS,IAAI,IAAI,UAAU;AAChD,MAAI,CAAC;AAAc,WAAO;AAE1B,QAAM,UAAU,IAAI,IAAI;AAGxB,QAAM,kBAAc,gCAAkB,YAAY;AAClD,QAAM,aAAa,YAAY,KAAK;AAEpC,MAAI,IAAI,IAAI,SAAS,UAAU;AAC7B,UAAM,cAAc,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,MACL,kBAAk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WACb,YAAY,mBACZ,IAAK;AAIb,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,KAAK;AAAA,IACL,KAAK,eAAe;AAAA,EACtB;AACF;",
|
|
6
6
|
"names": ["import_yaml", "inquirer"]
|
|
7
7
|
}
|
|
@@ -196,6 +196,9 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
196
196
|
log.success(messages.devinit.createDeployKey(deployKeyName, true));
|
|
197
197
|
checkpoint("api keys done");
|
|
198
198
|
}
|
|
199
|
+
const envFilePath = `${projectHome}/.env`;
|
|
200
|
+
const existingEnvFile = (0, import_file_provider.readFile)(envFilePath);
|
|
201
|
+
let existingEnvFileArray = (existingEnvFile || "").split("\n").filter((l) => !!l);
|
|
199
202
|
const envContentsToAdd = {
|
|
200
203
|
ALIAS: currentEnv,
|
|
201
204
|
PROJECT: currentProject
|
|
@@ -203,15 +206,28 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
203
206
|
if (accessToken)
|
|
204
207
|
envContentsToAdd["ACCESS_TOKEN"] = accessToken;
|
|
205
208
|
if (this.clientDetailsLocation === "env") {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
+
envContentsToAdd["CONTENSIS_CLIENT_ID"] = this.clientId;
|
|
210
|
+
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] = this.clientSecret;
|
|
211
|
+
}
|
|
212
|
+
const removeEnvItems = (items) => {
|
|
213
|
+
const indexesToRemove = [];
|
|
214
|
+
for (let i = 0; i < existingEnvFileArray.length; i++) {
|
|
215
|
+
for (const item of items) {
|
|
216
|
+
if (existingEnvFileArray[i].includes(item)) {
|
|
217
|
+
indexesToRemove.push(i);
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (let i = indexesToRemove.length - 1; i >= 0; i--) {
|
|
223
|
+
existingEnvFileArray.splice(indexesToRemove[i], 1);
|
|
209
224
|
}
|
|
225
|
+
};
|
|
226
|
+
if (this.clientDetailsLocation === "git") {
|
|
227
|
+
removeEnvItems(["CONTENSIS_CLIENT_ID", "CONTENSIS_CLIENT_SECRET"]);
|
|
210
228
|
}
|
|
211
|
-
const envFilePath = `${projectHome}/.env`;
|
|
212
|
-
const existingEnvFile = (0, import_file_provider.readFile)(envFilePath);
|
|
213
229
|
const envFileLines = (0, import_dotenv.mergeDotEnvFileContents)(
|
|
214
|
-
|
|
230
|
+
existingEnvFileArray,
|
|
215
231
|
envContentsToAdd
|
|
216
232
|
);
|
|
217
233
|
const newEnvFileContent = envFileLines.join("\n");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/ContensisDevService.ts"],
|
|
4
|
-
"sourcesContent": ["import to from 'await-to-js';\nimport { spawn } from 'child_process';\nimport inquirer from 'inquirer';\nimport path from 'path';\n\nimport { Role } from 'contensis-management-api/lib/models';\nimport { MigrateRequest } from 'migratortron';\n\nimport ContensisRole from './ContensisRoleService';\nimport { OutputOptionsConstructorArg } from '~/models/CliService';\nimport { EnvContentsToAdd } from '~/models/DevService';\nimport { mapSiteConfigYaml } from '~/mappers/DevRequests-to-RequestHanderSiteConfigYaml';\nimport { mapCIWorkflowContent } from '~/mappers/DevInit-to-CIWorkflow';\nimport {\n deployKeyRole,\n devKeyRole,\n} from '~/mappers/DevInit-to-RolePermissions';\nimport { appRootDir, readFile, writeFile } from '~/providers/file-provider';\nimport { diffFileContent } from '~/util/diff';\nimport { mergeDotEnvFileContents } from '~/util/dotenv';\nimport { findByIdOrName } from '~/util/find';\nimport { GitHelper } from '~/util/git';\nimport { jsonFormatter } from '~/util/json.formatter';\nimport { winSlash } from '~/util/os';\nimport { stringifyYaml } from '~/util/yaml';\nimport { createSpinner } from 'nanospinner';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n\n constructor(\n args: string[],\n outputOpts?: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n ) {\n super(args, outputOpts, contensisOpts);\n }\n\n DevelopmentInit = async (projectHome: string, opts: any) => {\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n // Retrieve keys list for env\n const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();\n if (keysErr) {\n log.error(messages.keys.noList(currentEnv));\n log.error(jsonFormatter(keysErr));\n return;\n }\n const apiKeyExists = (findKey: string) =>\n apiKeys?.find(\n k => k.name.trim().toLowerCase() === findKey?.trim().toLowerCase()\n );\n\n // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n\n // Retrieve ci workflow info\n const workflowFiles = git.workflows;\n\n // Set variables for performing operations and logging etc.\n let ciFileName = git.ciFileName;\n\n // const devKeyName = `${git.name} development`;\n // const devKeyDescription = `${git.name} [contensis-cli]`;\n // let existingDevKey = apiKeyExists(devKeyName);\n\n const deployKeyName = `${git.name} deployment`;\n const deployKeyDescription = `${git.name} deploy [contensis-cli]`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\n\n // if api key doesn't exisit go and create it (we need this for yml file).\n if (!existingDeployKey) {\n log.info('Please wait, creating deploy key');\n existingDeployKey = await this.CreateOrUpdateApiKey(\n existingDeployKey,\n deployKeyName,\n deployKeyDescription\n );\n log.success('Successfully created deploy key');\n }\n\n // check we have the deply key so we can assign them to this values\n if (existingDeployKey) {\n // Add client id and secret to global 'this'\n this.clientId = existingDeployKey?.id;\n this.clientSecret = existingDeployKey?.sharedSecret;\n }\n\n const blockId = git.name;\n const errors = [] as AppError[];\n\n // Start render console output\n log.raw('');\n log.success(messages.devinit.intro());\n log.raw('');\n log.raw(\n log.infoText(\n messages.devinit.projectDetails(\n git.name,\n currentEnv,\n currentProject,\n git\n )\n )\n );\n // log.raw(\n // log.infoText(\n // messages.devinit.developmentKey(devKeyName, !!existingDevKey)\n // )\n // );\n log.raw(\n log.infoText(\n messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)\n )\n );\n log.raw('');\n\n if (Array.isArray(workflowFiles) && workflowFiles.length > 1) {\n // Choose GitHub workflow file (if multiple)\n ({ ciFileName } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u29F0',\n message: messages.devinit.ciMultipleChoices(),\n name: 'ciFileName',\n choices: workflowFiles,\n default: workflowFiles.find(f => f.includes('docker')),\n },\n ]));\n log.raw('');\n git.ciFileName = ciFileName;\n }\n\n log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));\n\n let mappedWorkflow;\n // Location for Client ID / Secret.\n const { clientDetailsOption } = await inquirer.prompt({\n name: 'clientDetailsOption',\n type: 'list',\n prefix: '\uD83D\uDD11',\n // Where would you like to store your Client ID/Secret?\n message: messages.devinit.clientDetailsLocation(),\n choices: [\n messages.devinit.clientDetailsInGit(git),\n messages.devinit.clientDetailsInEnv(),\n ],\n });\n\n // global 'clientDetailsLocation' variable stores users input on where client id / secert are stored\n if (clientDetailsOption === messages.devinit.clientDetailsInEnv()) {\n this.clientDetailsLocation = 'env';\n } else {\n this.clientDetailsLocation = 'git';\n }\n\n if (this.clientDetailsLocation === 'env') {\n // Update CI Workflow to pull from ENV variables\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, this.clientDetailsLocation));\n } else {\n // Look at the workflow file content and make updates\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, this.clientDetailsLocation));\n }\n\n if (!dryRun) {\n // Confirm prompt\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n message: messages.devinit.confirm(),\n name: 'confirm',\n default: false,\n },\n ]);\n log.raw('');\n if (!confirm) return;\n }\n\n // Fetching access token\n let accessToken: string | undefined = undefined;\n log.raw('');\n\n const spinner = createSpinner(messages.devinit.accessTokenFetch());\n spinner.start();\n\n const token = await this.GetDeliveryApiKey();\n\n if (token) {\n spinner.success();\n this.log.success(messages.devinit.accessTokenSuccess(token));\n accessToken = token;\n } else {\n spinner.error();\n this.log.error(messages.devinit.accessTokenFailed());\n return;\n }\n\n // Magic happens...\n const checkpoint = (op: string) => {\n if (errors.length) throw errors[0];\n else log.debug(`${op} completed ok`);\n return true;\n };\n\n // Arrange API keys for development and deployment\n const [getRolesErr, roles] = await to(contensis.roles.GetRoles());\n if (!roles && getRolesErr) errors.push(getRolesErr);\n checkpoint(`fetched ${roles?.length} roles`);\n if (dryRun) {\n checkpoint(`skip api key creation (dry-run)`);\n } else {\n // existingDevKey = await this.CreateOrUpdateApiKey(\n // existingDevKey,\n // devKeyName,\n // devKeyDescription\n // );\n // checkpoint('dev key created');\n\n // Ensure dev API key is assigned to a role\n // let existingDevRole = findByIdOrName(roles || [], devKeyName, true) as\n // | Role\n // | undefined;\n // existingDevRole = await this.CreateOrUpdateRole(\n // existingDevRole,\n // devKeyRole(devKeyName, devKeyDescription)\n // );\n // checkpoint('dev key role assigned');\n // log.success(messages.devinit.createDevKey(devKeyName, true));\n\n // Ensure deploy API key is assigned to a role with the right permissions\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployKeyName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployKeyName, deployKeyDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(messages.devinit.createDeployKey(deployKeyName, true));\n checkpoint('api keys done');\n }\n\n // Update or create a file called .env in project home\n const envContentsToAdd: EnvContentsToAdd = {\n ALIAS: currentEnv,\n PROJECT: currentProject,\n };\n if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;\n if (this.clientDetailsLocation === 'env') {\n if (git.type === 'github') {\n envContentsToAdd['CONTENSIS_CLIENT_ID'] = this.clientId;\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] = this.clientSecret;\n }\n }\n\n const envFilePath = `${projectHome}/.env`;\n const existingEnvFile = readFile(envFilePath);\n const envFileLines = mergeDotEnvFileContents(\n (existingEnvFile || '').split('\\n').filter(l => !!l),\n envContentsToAdd\n );\n const newEnvFileContent = envFileLines.join('\\n');\n const envDiff = diffFileContent(existingEnvFile || '', newEnvFileContent);\n\n if (dryRun) {\n if (envDiff) {\n log.info(`Updating .env file ${winSlash(envFilePath)}:\\n${envDiff}`);\n log.raw('');\n }\n checkpoint('skip .env file update (dry-run)');\n } else {\n if (envDiff) log.info(`updating .env file ${winSlash(envFilePath)}`);\n writeFile(envFilePath, envFileLines.join('\\n'));\n checkpoint('.env file updated');\n log.success(messages.devinit.writeEnvFile());\n // log.help(messages.devinit.useEnvFileTip());\n }\n\n // Update CI file -- different for GH/GL\n if (mappedWorkflow?.diff) {\n log.info(\n `Updating ${winSlash(ciFileName)} file:\\n${mappedWorkflow.diff}`\n );\n log.raw('');\n }\n if (dryRun) {\n checkpoint('skip CI file update (dry-run)');\n //log.object(ciFileLines);\n } else {\n if (mappedWorkflow?.newWorkflow) {\n if (mappedWorkflow?.diff) {\n writeFile(git.ciFilePath, mappedWorkflow.newWorkflow);\n log.success(messages.devinit.writeCiFile(`./${ciFileName}`));\n log.info(\n messages.devinit.ciBlockTip(blockId, currentEnv, currentProject)\n );\n } else {\n log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));\n }\n checkpoint('CI file updated');\n }\n }\n\n if (this.clientDetailsLocation === 'git') {\n // Echo Deployment API key to console, ask user to add secrets to repo\n log.warning(messages.devinit.addGitSecretsIntro());\n log.help(\n messages.devinit.addGitSecretsHelp(\n git,\n existingDeployKey?.id,\n existingDeployKey?.sharedSecret\n )\n );\n }\n\n if (dryRun) {\n log.success(messages.devinit.dryRun());\n log.help(messages.devinit.noChanges());\n } else {\n log.success(messages.devinit.success());\n log.help(messages.devinit.startProjectTip());\n }\n }\n };\n\n ExecRequestHandler = async (blockIds: string[], overrideArgs?: string[]) => {\n // if no request handler exe\n // download it.\n\n // if update arg, redownload it\n\n const { log } = this;\n // const getPrefixOld = log.getPrefix;\n const exeHome = path.join(appRootDir, 'reqhan');\n const exe = 'Zengenti.Contensis.RequestHandler.LocalDevelopment';\n const exePath = path.join(exeHome, exe);\n const siteConfigPath = path.join(appRootDir, 'site_config.yaml');\n\n const siteConfig = await mapSiteConfigYaml(this);\n writeFile('site_config.yaml', stringifyYaml(siteConfig));\n\n const args = overrideArgs\n ? typeof overrideArgs?.[0] === 'string' &&\n overrideArgs[0].includes(' ', 2)\n ? overrideArgs[0].split(' ')\n : overrideArgs\n : []; // args could be [ '-c .\\\\site_config.yaml' ] or [ '-c', '.\\\\site_config.yaml' ]\n\n // Add required args\n if (!args.find(a => a === '-c')) args.push('-c', siteConfigPath);\n\n // const child = execFile(exePath, args);\n\n const child = spawn(exePath, args, { stdio: 'inherit' });\n\n // log.raw('');\n log.info(`Launching request handler...`);\n if (overrideArgs?.length)\n this.log.warning(\n `Spawning process with supplied args: ${JSON.stringify(\n child.spawnargs,\n null,\n 2\n )}`\n );\n\n let isRunning = false;\n\n // Log child output through event listeners\n child?.stdout?.on('data', data => {\n isRunning = true;\n log.raw(data);\n });\n\n child?.stderr?.on('data', data => {\n log.error(data);\n });\n\n child.on('spawn', () => {\n isRunning = true;\n log.help(\n `You may see a firewall popup requesting network access, it is safe to approve`\n );\n // log.getPrefix = () => Logger.infoText(`[rqh]`);\n });\n\n child.on('exit', code => {\n isRunning = false;\n\n log[code === 0 ? 'success' : 'warning'](\n `Request handler exited with code ${code}\\n`\n );\n });\n\n child.on('error', error => {\n isRunning = false;\n log.error(`Could not launch request handler due to error \\n${error}`);\n });\n\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n // keep the method running until we can return\n while (true === true) {\n if (!isRunning) {\n // log.getPrefix = getPrefixOld; // restore logger state\n return;\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n };\n}\nexport const devCommand = (\n commandArgs: string[],\n outputOpts: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n) => {\n return new ContensisDev(['', '', ...commandArgs], outputOpts, contensisOpts);\n};\n\nexport default ContensisDev;\n"],
|
|
5
|
-
"mappings": ";;;;;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AC,aAAa,KAAK,IAAI,UAAM,mBAAAC,SAAG,UAAU,MAAM,SAAS,CAAC;AAChE,UAAI,CAAC,SAAS;AAAa,eAAO,KAAK,WAAW;AAClD,iBAAW,WAAW,+BAAO,cAAc;AAC3C,UAAI,QAAQ;AACV,mBAAW,iCAAiC;AAAA,MAC9C,OAAO;AAoBL,YAAI,yBAAqB;AAAA,UACvB,SAAS,CAAC;AAAA,UACV;AAAA,UACA;AAAA,QACF;AACA,6BAAqB,MAAM,KAAK;AAAA,UAC9B;AAAA,cACA,iDAAc,eAAe,oBAAoB;AAAA,QACnD;AAEA,mBAAW,0BAA0B;AACrC,YAAI,QAAQ,SAAS,QAAQ,gBAAgB,eAAe,IAAI,CAAC;AACjE,mBAAW,eAAe;AAAA,MAC5B;
|
|
4
|
+
"sourcesContent": ["import to from 'await-to-js';\nimport { spawn } from 'child_process';\nimport inquirer from 'inquirer';\nimport path from 'path';\n\nimport { Role } from 'contensis-management-api/lib/models';\nimport { MigrateRequest } from 'migratortron';\n\nimport ContensisRole from './ContensisRoleService';\nimport { OutputOptionsConstructorArg } from '~/models/CliService';\nimport { EnvContentsToAdd } from '~/models/DevService';\nimport { mapSiteConfigYaml } from '~/mappers/DevRequests-to-RequestHanderSiteConfigYaml';\nimport { mapCIWorkflowContent } from '~/mappers/DevInit-to-CIWorkflow';\nimport {\n deployKeyRole,\n devKeyRole,\n} from '~/mappers/DevInit-to-RolePermissions';\nimport { appRootDir, readFile, writeFile } from '~/providers/file-provider';\nimport { diffFileContent } from '~/util/diff';\nimport { mergeDotEnvFileContents } from '~/util/dotenv';\nimport { findByIdOrName } from '~/util/find';\nimport { GitHelper } from '~/util/git';\nimport { jsonFormatter } from '~/util/json.formatter';\nimport { winSlash } from '~/util/os';\nimport { stringifyYaml } from '~/util/yaml';\nimport { createSpinner } from 'nanospinner';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n\n constructor(\n args: string[],\n outputOpts?: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n ) {\n super(args, outputOpts, contensisOpts);\n }\n\n DevelopmentInit = async (projectHome: string, opts: any) => {\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n // Retrieve keys list for env\n const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();\n if (keysErr) {\n log.error(messages.keys.noList(currentEnv));\n log.error(jsonFormatter(keysErr));\n return;\n }\n const apiKeyExists = (findKey: string) =>\n apiKeys?.find(\n k => k.name.trim().toLowerCase() === findKey?.trim().toLowerCase()\n );\n\n // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n\n // Retrieve ci workflow info\n const workflowFiles = git.workflows;\n\n // Set variables for performing operations and logging etc.\n let ciFileName = git.ciFileName;\n\n // const devKeyName = `${git.name} development`;\n // const devKeyDescription = `${git.name} [contensis-cli]`;\n // let existingDevKey = apiKeyExists(devKeyName);\n\n const deployKeyName = `${git.name} deployment`;\n const deployKeyDescription = `${git.name} deploy [contensis-cli]`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\n\n // if api key doesn't exisit go and create it (we need this for yml file).\n if (!existingDeployKey) {\n log.info('Please wait, creating deploy key');\n existingDeployKey = await this.CreateOrUpdateApiKey(\n existingDeployKey,\n deployKeyName,\n deployKeyDescription\n );\n log.success('Successfully created deploy key');\n }\n\n // check we have the deply key so we can assign them to this values\n if (existingDeployKey) {\n // Add client id and secret to global 'this'\n this.clientId = existingDeployKey?.id;\n this.clientSecret = existingDeployKey?.sharedSecret;\n }\n\n const blockId = git.name;\n const errors = [] as AppError[];\n\n // Start render console output\n log.raw('');\n log.success(messages.devinit.intro());\n log.raw('');\n log.raw(\n log.infoText(\n messages.devinit.projectDetails(\n git.name,\n currentEnv,\n currentProject,\n git\n )\n )\n );\n // log.raw(\n // log.infoText(\n // messages.devinit.developmentKey(devKeyName, !!existingDevKey)\n // )\n // );\n log.raw(\n log.infoText(\n messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)\n )\n );\n log.raw('');\n\n if (Array.isArray(workflowFiles) && workflowFiles.length > 1) {\n // Choose GitHub workflow file (if multiple)\n ({ ciFileName } = await inquirer.prompt([\n {\n type: 'list',\n prefix: '\u29F0',\n message: messages.devinit.ciMultipleChoices(),\n name: 'ciFileName',\n choices: workflowFiles,\n default: workflowFiles.find(f => f.includes('docker')),\n },\n ]));\n log.raw('');\n git.ciFileName = ciFileName;\n }\n\n log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));\n\n let mappedWorkflow;\n // Location for Client ID / Secret.\n const { clientDetailsOption } = await inquirer.prompt({\n name: 'clientDetailsOption',\n type: 'list',\n prefix: '\uD83D\uDD11',\n // Where would you like to store your Client ID/Secret?\n message: messages.devinit.clientDetailsLocation(),\n choices: [\n messages.devinit.clientDetailsInGit(git),\n messages.devinit.clientDetailsInEnv(),\n ],\n });\n\n // global 'clientDetailsLocation' variable stores users input on where client id / secert are stored\n if (clientDetailsOption === messages.devinit.clientDetailsInEnv()) {\n this.clientDetailsLocation = 'env';\n } else {\n this.clientDetailsLocation = 'git';\n }\n\n if (this.clientDetailsLocation === 'env') {\n // Update CI Workflow to pull from ENV variables\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, this.clientDetailsLocation));\n } else {\n // Look at the workflow file content and make updates\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, this.clientDetailsLocation));\n }\n\n if (!dryRun) {\n // Confirm prompt\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n message: messages.devinit.confirm(),\n name: 'confirm',\n default: false,\n },\n ]);\n log.raw('');\n if (!confirm) return;\n }\n\n // Fetching access token\n let accessToken: string | undefined = undefined;\n log.raw('');\n\n const spinner = createSpinner(messages.devinit.accessTokenFetch());\n spinner.start();\n\n const token = await this.GetDeliveryApiKey();\n\n if (token) {\n spinner.success();\n this.log.success(messages.devinit.accessTokenSuccess(token));\n accessToken = token;\n } else {\n spinner.error();\n this.log.error(messages.devinit.accessTokenFailed());\n return;\n }\n\n // Magic happens...\n const checkpoint = (op: string) => {\n if (errors.length) throw errors[0];\n else log.debug(`${op} completed ok`);\n return true;\n };\n\n // Arrange API keys for development and deployment\n const [getRolesErr, roles] = await to(contensis.roles.GetRoles());\n if (!roles && getRolesErr) errors.push(getRolesErr);\n checkpoint(`fetched ${roles?.length} roles`);\n if (dryRun) {\n checkpoint(`skip api key creation (dry-run)`);\n } else {\n // existingDevKey = await this.CreateOrUpdateApiKey(\n // existingDevKey,\n // devKeyName,\n // devKeyDescription\n // );\n // checkpoint('dev key created');\n\n // Ensure dev API key is assigned to a role\n // let existingDevRole = findByIdOrName(roles || [], devKeyName, true) as\n // | Role\n // | undefined;\n // existingDevRole = await this.CreateOrUpdateRole(\n // existingDevRole,\n // devKeyRole(devKeyName, devKeyDescription)\n // );\n // checkpoint('dev key role assigned');\n // log.success(messages.devinit.createDevKey(devKeyName, true));\n\n // Ensure deploy API key is assigned to a role with the right permissions\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployKeyName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployKeyName, deployKeyDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(messages.devinit.createDeployKey(deployKeyName, true));\n checkpoint('api keys done');\n }\n\n const envFilePath = `${projectHome}/.env`;\n const existingEnvFile = readFile(envFilePath);\n let existingEnvFileArray = (existingEnvFile || '')\n .split('\\n')\n .filter(l => !!l);\n\n // Update or create a file called .env in project home\n const envContentsToAdd: EnvContentsToAdd = {\n ALIAS: currentEnv,\n PROJECT: currentProject,\n };\n if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;\n // add client id and secret to the env file\n if (this.clientDetailsLocation === 'env') {\n envContentsToAdd['CONTENSIS_CLIENT_ID'] = this.clientId;\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] = this.clientSecret;\n }\n\n // if we have client id / secret in our env remove it\n const removeEnvItems = (items: string[]) => {\n const indexesToRemove = [];\n\n for (let i = 0; i < existingEnvFileArray.length; i++) {\n for (const item of items) {\n if (existingEnvFileArray[i].includes(item)) {\n indexesToRemove.push(i);\n break;\n }\n }\n }\n\n for (let i = indexesToRemove.length - 1; i >= 0; i--) {\n existingEnvFileArray.splice(indexesToRemove[i], 1);\n }\n };\n\n if (this.clientDetailsLocation === 'git') {\n removeEnvItems(['CONTENSIS_CLIENT_ID', 'CONTENSIS_CLIENT_SECRET']);\n }\n\n const envFileLines = mergeDotEnvFileContents(\n existingEnvFileArray,\n envContentsToAdd\n );\n const newEnvFileContent = envFileLines.join('\\n');\n const envDiff = diffFileContent(existingEnvFile || '', newEnvFileContent);\n\n if (dryRun) {\n if (envDiff) {\n log.info(`Updating .env file ${winSlash(envFilePath)}:\\n${envDiff}`);\n log.raw('');\n }\n checkpoint('skip .env file update (dry-run)');\n } else {\n if (envDiff) log.info(`updating .env file ${winSlash(envFilePath)}`);\n writeFile(envFilePath, envFileLines.join('\\n'));\n checkpoint('.env file updated');\n log.success(messages.devinit.writeEnvFile());\n // log.help(messages.devinit.useEnvFileTip());\n }\n\n // Update CI file -- different for GH/GL\n if (mappedWorkflow?.diff) {\n log.info(\n `Updating ${winSlash(ciFileName)} file:\\n${mappedWorkflow.diff}`\n );\n log.raw('');\n }\n if (dryRun) {\n checkpoint('skip CI file update (dry-run)');\n //log.object(ciFileLines);\n } else {\n if (mappedWorkflow?.newWorkflow) {\n if (mappedWorkflow?.diff) {\n writeFile(git.ciFilePath, mappedWorkflow.newWorkflow);\n log.success(messages.devinit.writeCiFile(`./${ciFileName}`));\n log.info(\n messages.devinit.ciBlockTip(blockId, currentEnv, currentProject)\n );\n } else {\n log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));\n }\n checkpoint('CI file updated');\n }\n }\n\n if (this.clientDetailsLocation === 'git') {\n // Echo Deployment API key to console, ask user to add secrets to repo\n log.warning(messages.devinit.addGitSecretsIntro());\n log.help(\n messages.devinit.addGitSecretsHelp(\n git,\n existingDeployKey?.id,\n existingDeployKey?.sharedSecret\n )\n );\n }\n\n if (dryRun) {\n log.success(messages.devinit.dryRun());\n log.help(messages.devinit.noChanges());\n } else {\n log.success(messages.devinit.success());\n log.help(messages.devinit.startProjectTip());\n }\n }\n };\n\n ExecRequestHandler = async (blockIds: string[], overrideArgs?: string[]) => {\n // if no request handler exe\n // download it.\n\n // if update arg, redownload it\n\n const { log } = this;\n // const getPrefixOld = log.getPrefix;\n const exeHome = path.join(appRootDir, 'reqhan');\n const exe = 'Zengenti.Contensis.RequestHandler.LocalDevelopment';\n const exePath = path.join(exeHome, exe);\n const siteConfigPath = path.join(appRootDir, 'site_config.yaml');\n\n const siteConfig = await mapSiteConfigYaml(this);\n writeFile('site_config.yaml', stringifyYaml(siteConfig));\n\n const args = overrideArgs\n ? typeof overrideArgs?.[0] === 'string' &&\n overrideArgs[0].includes(' ', 2)\n ? overrideArgs[0].split(' ')\n : overrideArgs\n : []; // args could be [ '-c .\\\\site_config.yaml' ] or [ '-c', '.\\\\site_config.yaml' ]\n\n // Add required args\n if (!args.find(a => a === '-c')) args.push('-c', siteConfigPath);\n\n // const child = execFile(exePath, args);\n\n const child = spawn(exePath, args, { stdio: 'inherit' });\n\n // log.raw('');\n log.info(`Launching request handler...`);\n if (overrideArgs?.length)\n this.log.warning(\n `Spawning process with supplied args: ${JSON.stringify(\n child.spawnargs,\n null,\n 2\n )}`\n );\n\n let isRunning = false;\n\n // Log child output through event listeners\n child?.stdout?.on('data', data => {\n isRunning = true;\n log.raw(data);\n });\n\n child?.stderr?.on('data', data => {\n log.error(data);\n });\n\n child.on('spawn', () => {\n isRunning = true;\n log.help(\n `You may see a firewall popup requesting network access, it is safe to approve`\n );\n // log.getPrefix = () => Logger.infoText(`[rqh]`);\n });\n\n child.on('exit', code => {\n isRunning = false;\n\n log[code === 0 ? 'success' : 'warning'](\n `Request handler exited with code ${code}\\n`\n );\n });\n\n child.on('error', error => {\n isRunning = false;\n log.error(`Could not launch request handler due to error \\n${error}`);\n });\n\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n // keep the method running until we can return\n while (true === true) {\n if (!isRunning) {\n // log.getPrefix = getPrefixOld; // restore logger state\n return;\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n };\n}\nexport const devCommand = (\n commandArgs: string[],\n outputOpts: OutputOptionsConstructorArg,\n contensisOpts: Partial<MigrateRequest> = {}\n) => {\n return new ContensisDev(['', '', ...commandArgs], outputOpts, contensisOpts);\n};\n\nexport default ContensisDev;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAe;AACf,2BAAsB;AACtB,sBAAqB;AACrB,kBAAiB;AAKjB,kCAA0B;AAG1B,wDAAkC;AAClC,mCAAqC;AACrC,wCAGO;AACP,2BAAgD;AAChD,kBAAgC;AAChC,oBAAwC;AACxC,kBAA+B;AAC/B,iBAA0B;AAC1B,kBAA8B;AAC9B,gBAAyB;AACzB,kBAA8B;AAC9B,yBAA8B;AAE9B,MAAM,qBAAqB,4BAAAA,QAAc;AAAA,EACvC;AAAA,EAEA,YACE,MACA,YACA,gBAAyC,CAAC,GAC1C;AACA,UAAM,MAAM,YAAY,aAAa;AAAA,EACvC;AAAA,EAEA,kBAAkB,OAAO,aAAqB,SAAc;AAC1D,UAAM,EAAE,SAAS,MAAM,IAAI,QAAQ,CAAC;AACpC,UAAM,EAAE,YAAY,gBAAgB,KAAK,SAAS,IAAI;AACtD,UAAM,YAAY,MAAM,KAAK,iBAAiB;AAE9C,QAAI,WAAW;AAEb,YAAM,CAAC,SAAS,OAAO,IAAI,MAAM,UAAU,QAAQ,QAAQ;AAC3D,UAAI,SAAS;AACX,YAAI,MAAM,SAAS,KAAK,OAAO,UAAU,CAAC;AAC1C,YAAI,UAAM,2BAAc,OAAO,CAAC;AAChC;AAAA,MACF;AACA,YAAM,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21
21
|
LIB_VERSION: () => LIB_VERSION
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(version_exports);
|
|
24
|
-
const LIB_VERSION = "1.0.9-beta.
|
|
24
|
+
const LIB_VERSION = "1.0.9-beta.2";
|
|
25
25
|
// Annotate the CommonJS export names for ESM import in node:
|
|
26
26
|
0 && (module.exports = {
|
|
27
27
|
LIB_VERSION
|
package/dist/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/version.ts"],
|
|
4
|
-
"sourcesContent": ["export const LIB_VERSION = \"1.0.9-beta.
|
|
4
|
+
"sourcesContent": ["export const LIB_VERSION = \"1.0.9-beta.2\";\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,cAAc;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "contensis-cli",
|
|
3
|
-
"version": "1.0.9-beta.
|
|
3
|
+
"version": "1.0.9-beta.2",
|
|
4
4
|
"description": "A fully featured Contensis command line interface with a shell UI provides simple and intuitive ways to manage or profile your content in any NodeJS terminal.",
|
|
5
5
|
"repository": "https://github.com/contensis/node-cli",
|
|
6
6
|
"homepage": "https://github.com/contensis/node-cli/tree/main/packages/contensis-cli#readme",
|
|
@@ -73,20 +73,20 @@ const findExistingJobSteps = (
|
|
|
73
73
|
return existingJobStep;
|
|
74
74
|
};
|
|
75
75
|
|
|
76
|
+
const findPath = (path: string | any[]) =>
|
|
77
|
+
typeof path === 'string' && path.includes('.')
|
|
78
|
+
? path.split('.').map(p => (Number(p) || Number(p) !== 0 ? p : Number(p)))
|
|
79
|
+
: path;
|
|
80
|
+
|
|
76
81
|
const setWorkflowElement = (
|
|
77
82
|
workflowDoc: Document,
|
|
78
83
|
path: string | any[],
|
|
79
84
|
value: any
|
|
80
85
|
) => {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
? path.split('.').map(p => (Number(p) || Number(p) !== 0 ? p : Number(p)))
|
|
84
|
-
: path;
|
|
85
|
-
|
|
86
|
-
if (workflowDoc.hasIn(findPath)) {
|
|
87
|
-
workflowDoc.setIn(findPath, value);
|
|
86
|
+
if (workflowDoc.hasIn(findPath(path))) {
|
|
87
|
+
workflowDoc.setIn(findPath(path), value);
|
|
88
88
|
} else {
|
|
89
|
-
workflowDoc.addIn(findPath, value);
|
|
89
|
+
workflowDoc.addIn(findPath(path), value);
|
|
90
90
|
}
|
|
91
91
|
};
|
|
92
92
|
|
|
@@ -286,6 +286,12 @@ const mapGitHubActionCIWorkflowContent = async (
|
|
|
286
286
|
);
|
|
287
287
|
}
|
|
288
288
|
|
|
289
|
+
if (cli.clientDetailsLocation === 'git') {
|
|
290
|
+
// remove env vars from yml if we choose git
|
|
291
|
+
workflowDoc.deleteIn(findPath(`env.CONTENSIS_CLIENT_ID`));
|
|
292
|
+
workflowDoc.deleteIn(findPath(`env.CONTENSIS_SHARED_SECRET`));
|
|
293
|
+
}
|
|
294
|
+
|
|
289
295
|
// update job step
|
|
290
296
|
if (existingJobStep.length) {
|
|
291
297
|
//cli.log.json(existingJobStep);
|
|
@@ -249,23 +249,48 @@ class ContensisDev extends ContensisRole {
|
|
|
249
249
|
checkpoint('api keys done');
|
|
250
250
|
}
|
|
251
251
|
|
|
252
|
+
const envFilePath = `${projectHome}/.env`;
|
|
253
|
+
const existingEnvFile = readFile(envFilePath);
|
|
254
|
+
let existingEnvFileArray = (existingEnvFile || '')
|
|
255
|
+
.split('\n')
|
|
256
|
+
.filter(l => !!l);
|
|
257
|
+
|
|
252
258
|
// Update or create a file called .env in project home
|
|
253
259
|
const envContentsToAdd: EnvContentsToAdd = {
|
|
254
260
|
ALIAS: currentEnv,
|
|
255
261
|
PROJECT: currentProject,
|
|
256
262
|
};
|
|
257
263
|
if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;
|
|
264
|
+
// add client id and secret to the env file
|
|
258
265
|
if (this.clientDetailsLocation === 'env') {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
266
|
+
envContentsToAdd['CONTENSIS_CLIENT_ID'] = this.clientId;
|
|
267
|
+
envContentsToAdd['CONTENSIS_CLIENT_SECRET'] = this.clientSecret;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// if we have client id / secret in our env remove it
|
|
271
|
+
const removeEnvItems = (items: string[]) => {
|
|
272
|
+
const indexesToRemove = [];
|
|
273
|
+
|
|
274
|
+
for (let i = 0; i < existingEnvFileArray.length; i++) {
|
|
275
|
+
for (const item of items) {
|
|
276
|
+
if (existingEnvFileArray[i].includes(item)) {
|
|
277
|
+
indexesToRemove.push(i);
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
262
281
|
}
|
|
282
|
+
|
|
283
|
+
for (let i = indexesToRemove.length - 1; i >= 0; i--) {
|
|
284
|
+
existingEnvFileArray.splice(indexesToRemove[i], 1);
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
if (this.clientDetailsLocation === 'git') {
|
|
289
|
+
removeEnvItems(['CONTENSIS_CLIENT_ID', 'CONTENSIS_CLIENT_SECRET']);
|
|
263
290
|
}
|
|
264
291
|
|
|
265
|
-
const envFilePath = `${projectHome}/.env`;
|
|
266
|
-
const existingEnvFile = readFile(envFilePath);
|
|
267
292
|
const envFileLines = mergeDotEnvFileContents(
|
|
268
|
-
|
|
293
|
+
existingEnvFileArray,
|
|
269
294
|
envContentsToAdd
|
|
270
295
|
);
|
|
271
296
|
const newEnvFileContent = envFileLines.join('\n');
|
package/src/version.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const LIB_VERSION = "1.0.9-beta.
|
|
1
|
+
export const LIB_VERSION = "1.0.9-beta.2";
|