contensis-cli 1.0.9-beta.6 → 1.0.9-beta.8
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/models/DevService.d.js.map +1 -1
- package/dist/services/ContensisDevService.js +23 -4
- package/dist/services/ContensisDevService.js.map +2 -2
- package/dist/util/gitignore.js +50 -0
- package/dist/util/gitignore.js.map +7 -0
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/src/models/DevService.d.ts +1 -1
- package/src/services/ContensisDevService.ts +29 -31
- package/src/util/gitignore.ts +35 -0
- package/src/version.ts +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/models/DevService.d.ts"],
|
|
4
|
-
"sourcesContent": ["export type EnvContentsToAdd = {\n ALIAS: string;\n
|
|
4
|
+
"sourcesContent": ["export type EnvContentsToAdd = {\n ALIAS: string;\n PROJECT_API_ID: string;\n ACCESS_TOKEN?: string;\n CONTENSIS_CLIENT_ID?: string;\n CONTENSIS_CLIENT_SECRET?: string;\n BLOCK_ID: string;\n};\n\nexport type GitHubActionPushBlockJobStep = {\n name: string;\n id: 'push-block';\n uses: string;\n with: {\n 'block-id': string;\n alias: string;\n 'project-id': string;\n 'client-id': string;\n 'shared-secret': string;\n 'image-uri'?: string;\n };\n};\n\nexport type GitHubActionPushBlockJob = {\n name: string;\n 'runs-on': string;\n needs?: string;\n steps: GitHubActionPushBlockJobStep[];\n};\n\nexport type GitLabPushBlockJobStage = {\n stage: string;\n variables: {\n alias: string;\n project_id: string;\n block_id: string;\n image_uri?: string;\n client_id: string;\n shared_secret: string;\n };\n};\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -45,6 +45,7 @@ var import_json = require("../util/json.formatter");
|
|
|
45
45
|
var import_os = require("../util/os");
|
|
46
46
|
var import_yaml = require("../util/yaml");
|
|
47
47
|
var import_nanospinner = require("nanospinner");
|
|
48
|
+
var import_gitignore = require("../util/gitignore");
|
|
48
49
|
class ContensisDev extends import_ContensisRoleService.default {
|
|
49
50
|
git;
|
|
50
51
|
blockId;
|
|
@@ -87,11 +88,21 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
87
88
|
);
|
|
88
89
|
const workflowFiles = git.workflows;
|
|
89
90
|
let ciFileName = git.ciFileName;
|
|
91
|
+
const devKeyName = `${blockId} development`;
|
|
92
|
+
const devKeyDescription = `${blockId} [contensis-cli]`;
|
|
93
|
+
let existingDevKey = apiKeyExists(devKeyName);
|
|
94
|
+
if (!existingDevKey) {
|
|
95
|
+
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
96
|
+
existingDevKey,
|
|
97
|
+
devKeyName,
|
|
98
|
+
devKeyDescription
|
|
99
|
+
);
|
|
100
|
+
log.success("Successfully created development key");
|
|
101
|
+
}
|
|
90
102
|
const deployKeyName = `${blockId} deployment`;
|
|
91
103
|
const deployKeyDescription = `${blockId} deploy [contensis-cli]`;
|
|
92
104
|
let existingDeployKey = apiKeyExists(deployKeyName);
|
|
93
105
|
if (!existingDeployKey) {
|
|
94
|
-
log.info("Please wait, creating deploy key");
|
|
95
106
|
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
96
107
|
existingDeployKey,
|
|
97
108
|
deployKeyName,
|
|
@@ -118,6 +129,11 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
118
129
|
)
|
|
119
130
|
)
|
|
120
131
|
);
|
|
132
|
+
log.raw(
|
|
133
|
+
log.infoText(
|
|
134
|
+
messages.devinit.developmentKey(devKeyName, !!existingDevKey)
|
|
135
|
+
)
|
|
136
|
+
);
|
|
121
137
|
log.raw(
|
|
122
138
|
log.infoText(
|
|
123
139
|
messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)
|
|
@@ -221,14 +237,14 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
221
237
|
let existingEnvFileArray = (existingEnvFile || "").split("\n").filter((l) => !!l);
|
|
222
238
|
const envContentsToAdd = {
|
|
223
239
|
ALIAS: currentEnv,
|
|
224
|
-
|
|
240
|
+
PROJECT_API_ID: currentProject,
|
|
225
241
|
BLOCK_ID: blockId
|
|
226
242
|
};
|
|
227
243
|
if (accessToken)
|
|
228
244
|
envContentsToAdd["ACCESS_TOKEN"] = accessToken;
|
|
229
245
|
if (this.clientDetailsLocation === "env") {
|
|
230
|
-
envContentsToAdd["CONTENSIS_CLIENT_ID"] =
|
|
231
|
-
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] =
|
|
246
|
+
envContentsToAdd["CONTENSIS_CLIENT_ID"] = existingDevKey == null ? void 0 : existingDevKey.id;
|
|
247
|
+
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] = existingDevKey == null ? void 0 : existingDevKey.sharedSecret;
|
|
232
248
|
}
|
|
233
249
|
const removeEnvItems = (items) => {
|
|
234
250
|
const indexesToRemove = [];
|
|
@@ -267,6 +283,9 @@ ${envDiff}`);
|
|
|
267
283
|
checkpoint(".env file updated");
|
|
268
284
|
log.success(messages.devinit.writeEnvFile());
|
|
269
285
|
}
|
|
286
|
+
const gitIgnorePath = `${projectHome}/.gitignore`;
|
|
287
|
+
const gitIgnoreContentsToAdd = [".env"];
|
|
288
|
+
(0, import_gitignore.mergeContentsToAddWithGitignore)(gitIgnorePath, gitIgnoreContentsToAdd);
|
|
270
289
|
if (mappedWorkflow == null ? void 0 : mappedWorkflow.diff) {
|
|
271
290
|
log.info(
|
|
272
291
|
`Updating ${(0, import_os.winSlash)(ciFileName)} file:
|
|
@@ -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 blockId: string;\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 // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n // Check if we are in a git repo\n const isRepo = git.checkIsRepo();\n if (!isRepo) return;\n\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n // First we need to get the block id from the user\n const validateBlockId = (blockId: string) => {\n const pattern = /^[a-z-]*$/;\n if (typeof blockId === 'string' && blockId.length >= 3) {\n return pattern.test(blockId);\n } else return false;\n };\n let { blockId } = await inquirer.prompt({\n name: 'blockId',\n type: 'input',\n prefix: '\uD83E\uDDF1',\n message: messages.devinit.blockIdQuestion,\n validate: validateBlockId,\n });\n // make sure block id is lowercase\n this.blockId = blockId.toLowerCase();\n log.success(`Valid block id: ${blockId.toLowerCase()}`);\n\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 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 = `${blockId} deployment`;\n const deployKeyDescription = `${blockId} 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 blockId,\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, 'env'));\n } else {\n // Look at the workflow file content and make updates\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, 'git'));\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 BLOCK_ID: blockId,\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;
|
|
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';\nimport { mergeContentsToAddWithGitignore } from '~/util/gitignore';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n blockId: string;\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 // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n // Check if we are in a git repo\n const isRepo = git.checkIsRepo();\n if (!isRepo) return;\n\n const { dryRun = false } = opts || {};\n const { currentEnv, currentProject, log, messages } = this;\n const contensis = await this.ConnectContensis();\n\n if (contensis) {\n // First we need to get the block id from the user\n const validateBlockId = (blockId: string) => {\n const pattern = /^[a-z-]*$/;\n if (typeof blockId === 'string' && blockId.length >= 3) {\n return pattern.test(blockId);\n } else return false;\n };\n let { blockId } = await inquirer.prompt({\n name: 'blockId',\n type: 'input',\n prefix: '\uD83E\uDDF1',\n message: messages.devinit.blockIdQuestion,\n validate: validateBlockId,\n });\n // make sure block id is lowercase\n this.blockId = blockId.toLowerCase();\n log.success(`Valid block id: ${blockId.toLowerCase()}`);\n\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 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 = `${blockId} development`;\n const devKeyDescription = `${blockId} [contensis-cli]`;\n let existingDevKey = apiKeyExists(devKeyName);\n\n // if dev api key doesn't exisit go and create it (we need this for local development, we will store these details in the .env file).\n if (!existingDevKey) {\n existingDevKey = await this.CreateOrUpdateApiKey(\n existingDevKey,\n devKeyName,\n devKeyDescription\n );\n log.success('Successfully created development key');\n }\n\n const deployKeyName = `${blockId} deployment`;\n const deployKeyDescription = `${blockId} deploy [contensis-cli]`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\n\n // if deploy api key doesn't exisit go and create it (we need this for yml file).\n if (!existingDeployKey) {\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 blockId,\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, 'env'));\n } else {\n // Look at the workflow file content and make updates\n mappedWorkflow = await mapCIWorkflowContent(this);\n log.help(messages.devinit.ciIntro(git, 'git'));\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 // 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_API_ID: currentProject,\n BLOCK_ID: blockId,\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'] = existingDevKey?.id;\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =\n existingDevKey?.sharedSecret;\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 git ignore\n const gitIgnorePath = `${projectHome}/.gitignore`;\n const gitIgnoreContentsToAdd = ['.env'];\n mergeContentsToAddWithGitignore(gitIgnorePath, gitIgnoreContentsToAdd);\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;AAC9B,uBAAgD;AAEhD,MAAM,qBAAqB,4BAAAA,QAAc;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YACE,MACA,YACA,gBAAyC,CAAC,GAC1C;AACA,UAA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
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
|
+
mod
|
|
23
|
+
));
|
|
24
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
25
|
+
var gitignore_exports = {};
|
|
26
|
+
__export(gitignore_exports, {
|
|
27
|
+
mergeContentsToAddWithGitignore: () => mergeContentsToAddWithGitignore
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(gitignore_exports);
|
|
30
|
+
var import_fs = __toESM(require("fs"));
|
|
31
|
+
var import_logger = require("./logger");
|
|
32
|
+
const mergeContentsToAddWithGitignore = (filename, contentsToAdd) => {
|
|
33
|
+
if (import_fs.default.existsSync(filename)) {
|
|
34
|
+
const existingContent = import_fs.default.readFileSync(filename, "utf-8");
|
|
35
|
+
const existingLines = existingContent.split("\n").filter((line) => line.trim() !== "");
|
|
36
|
+
const mergedLines = [...existingLines, ...contentsToAdd];
|
|
37
|
+
const updatedContent = Array.from(new Set(mergedLines)).sort().join("\n");
|
|
38
|
+
import_fs.default.writeFileSync(filename, updatedContent);
|
|
39
|
+
import_logger.Logger.success(".gitignore file updated");
|
|
40
|
+
} else {
|
|
41
|
+
const gitignoreContent = contentsToAdd.join("\n");
|
|
42
|
+
import_fs.default.writeFileSync(filename, gitignoreContent);
|
|
43
|
+
import_logger.Logger.success(".gitignore file created and updated");
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
47
|
+
0 && (module.exports = {
|
|
48
|
+
mergeContentsToAddWithGitignore
|
|
49
|
+
});
|
|
50
|
+
//# sourceMappingURL=gitignore.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/util/gitignore.ts"],
|
|
4
|
+
"sourcesContent": ["import fs from 'fs';\nimport { Logger } from './logger';\n\nexport const mergeContentsToAddWithGitignore = (\n filename: string,\n contentsToAdd: string[]\n) => {\n // Check if .gitignore file already exists\n if (fs.existsSync(filename)) {\n // Read the existing .gitignore file\n const existingContent = fs.readFileSync(filename, 'utf-8');\n\n // Split the existing content by newline and remove empty lines\n const existingLines = existingContent\n .split('\\n')\n .filter(line => line.trim() !== '');\n\n // Merge the existing content with the new contents to add\n const mergedLines = [...existingLines, ...contentsToAdd];\n\n // Deduplicate and sort the lines\n const updatedContent = Array.from(new Set(mergedLines)).sort().join('\\n');\n\n // Write the updated content back to .gitignore\n fs.writeFileSync(filename, updatedContent);\n\n Logger.success('.gitignore file updated');\n } else {\n // If .gitignore doesn't exist, create one and add the contents to add\n const gitignoreContent = contentsToAdd.join('\\n');\n fs.writeFileSync(filename, gitignoreContent);\n\n Logger.success('.gitignore file created and updated');\n }\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAe;AACf,oBAAuB;AAEhB,MAAM,kCAAkC,CAC7C,UACA,kBACG;AAEH,MAAI,UAAAA,QAAG,WAAW,QAAQ,GAAG;AAE3B,UAAM,kBAAkB,UAAAA,QAAG,aAAa,UAAU,OAAO;AAGzD,UAAM,gBAAgB,gBACnB,MAAM,IAAI,EACV,OAAO,UAAQ,KAAK,KAAK,MAAM,EAAE;AAGpC,UAAM,cAAc,CAAC,GAAG,eAAe,GAAG,aAAa;AAGvD,UAAM,iBAAiB,MAAM,KAAK,IAAI,IAAI,WAAW,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI;AAGxE,cAAAA,QAAG,cAAc,UAAU,cAAc;AAEzC,yBAAO,QAAQ,yBAAyB;AAAA,EAC1C,OAAO;AAEL,UAAM,mBAAmB,cAAc,KAAK,IAAI;AAChD,cAAAA,QAAG,cAAc,UAAU,gBAAgB;AAE3C,yBAAO,QAAQ,qCAAqC;AAAA,EACtD;AACF;",
|
|
6
|
+
"names": ["fs"]
|
|
7
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -21,7 +21,7 @@ __export(version_exports, {
|
|
|
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.8";
|
|
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.8\";\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.8",
|
|
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",
|
|
@@ -24,6 +24,7 @@ import { jsonFormatter } from '~/util/json.formatter';
|
|
|
24
24
|
import { winSlash } from '~/util/os';
|
|
25
25
|
import { stringifyYaml } from '~/util/yaml';
|
|
26
26
|
import { createSpinner } from 'nanospinner';
|
|
27
|
+
import { mergeContentsToAddWithGitignore } from '~/util/gitignore';
|
|
27
28
|
|
|
28
29
|
class ContensisDev extends ContensisRole {
|
|
29
30
|
git!: GitHelper;
|
|
@@ -85,18 +86,27 @@ class ContensisDev extends ContensisRole {
|
|
|
85
86
|
// Set variables for performing operations and logging etc.
|
|
86
87
|
let ciFileName = git.ciFileName;
|
|
87
88
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
const devKeyName = `${blockId} development`;
|
|
90
|
+
const devKeyDescription = `${blockId} [contensis-cli]`;
|
|
91
|
+
let existingDevKey = apiKeyExists(devKeyName);
|
|
92
|
+
|
|
93
|
+
// if dev api key doesn't exisit go and create it (we need this for local development, we will store these details in the .env file).
|
|
94
|
+
if (!existingDevKey) {
|
|
95
|
+
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
96
|
+
existingDevKey,
|
|
97
|
+
devKeyName,
|
|
98
|
+
devKeyDescription
|
|
99
|
+
);
|
|
100
|
+
log.success('Successfully created development key');
|
|
101
|
+
}
|
|
91
102
|
|
|
92
103
|
const deployKeyName = `${blockId} deployment`;
|
|
93
104
|
const deployKeyDescription = `${blockId} deploy [contensis-cli]`;
|
|
94
105
|
|
|
95
106
|
let existingDeployKey = apiKeyExists(deployKeyName);
|
|
96
107
|
|
|
97
|
-
// if api key doesn't exisit go and create it (we need this for yml file).
|
|
108
|
+
// if deploy api key doesn't exisit go and create it (we need this for yml file).
|
|
98
109
|
if (!existingDeployKey) {
|
|
99
|
-
log.info('Please wait, creating deploy key');
|
|
100
110
|
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
101
111
|
existingDeployKey,
|
|
102
112
|
deployKeyName,
|
|
@@ -130,11 +140,11 @@ class ContensisDev extends ContensisRole {
|
|
|
130
140
|
)
|
|
131
141
|
)
|
|
132
142
|
);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
143
|
+
log.raw(
|
|
144
|
+
log.infoText(
|
|
145
|
+
messages.devinit.developmentKey(devKeyName, !!existingDevKey)
|
|
146
|
+
)
|
|
147
|
+
);
|
|
138
148
|
log.raw(
|
|
139
149
|
log.infoText(
|
|
140
150
|
messages.devinit.deploymentKey(deployKeyName, !!existingDeployKey)
|
|
@@ -238,24 +248,6 @@ class ContensisDev extends ContensisRole {
|
|
|
238
248
|
if (dryRun) {
|
|
239
249
|
checkpoint(`skip api key creation (dry-run)`);
|
|
240
250
|
} else {
|
|
241
|
-
// existingDevKey = await this.CreateOrUpdateApiKey(
|
|
242
|
-
// existingDevKey,
|
|
243
|
-
// devKeyName,
|
|
244
|
-
// devKeyDescription
|
|
245
|
-
// );
|
|
246
|
-
// checkpoint('dev key created');
|
|
247
|
-
|
|
248
|
-
// Ensure dev API key is assigned to a role
|
|
249
|
-
// let existingDevRole = findByIdOrName(roles || [], devKeyName, true) as
|
|
250
|
-
// | Role
|
|
251
|
-
// | undefined;
|
|
252
|
-
// existingDevRole = await this.CreateOrUpdateRole(
|
|
253
|
-
// existingDevRole,
|
|
254
|
-
// devKeyRole(devKeyName, devKeyDescription)
|
|
255
|
-
// );
|
|
256
|
-
// checkpoint('dev key role assigned');
|
|
257
|
-
// log.success(messages.devinit.createDevKey(devKeyName, true));
|
|
258
|
-
|
|
259
251
|
// Ensure deploy API key is assigned to a role with the right permissions
|
|
260
252
|
let existingDeployRole = findByIdOrName(
|
|
261
253
|
roles || [],
|
|
@@ -281,14 +273,15 @@ class ContensisDev extends ContensisRole {
|
|
|
281
273
|
// Update or create a file called .env in project home
|
|
282
274
|
const envContentsToAdd: EnvContentsToAdd = {
|
|
283
275
|
ALIAS: currentEnv,
|
|
284
|
-
|
|
276
|
+
PROJECT_API_ID: currentProject,
|
|
285
277
|
BLOCK_ID: blockId,
|
|
286
278
|
};
|
|
287
279
|
if (accessToken) envContentsToAdd['ACCESS_TOKEN'] = accessToken;
|
|
288
280
|
// add client id and secret to the env file
|
|
289
281
|
if (this.clientDetailsLocation === 'env') {
|
|
290
|
-
envContentsToAdd['CONTENSIS_CLIENT_ID'] =
|
|
291
|
-
envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =
|
|
282
|
+
envContentsToAdd['CONTENSIS_CLIENT_ID'] = existingDevKey?.id;
|
|
283
|
+
envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =
|
|
284
|
+
existingDevKey?.sharedSecret;
|
|
292
285
|
}
|
|
293
286
|
|
|
294
287
|
// if we have client id / secret in our env remove it
|
|
@@ -334,6 +327,11 @@ class ContensisDev extends ContensisRole {
|
|
|
334
327
|
// log.help(messages.devinit.useEnvFileTip());
|
|
335
328
|
}
|
|
336
329
|
|
|
330
|
+
// Update git ignore
|
|
331
|
+
const gitIgnorePath = `${projectHome}/.gitignore`;
|
|
332
|
+
const gitIgnoreContentsToAdd = ['.env'];
|
|
333
|
+
mergeContentsToAddWithGitignore(gitIgnorePath, gitIgnoreContentsToAdd);
|
|
334
|
+
|
|
337
335
|
// Update CI file -- different for GH/GL
|
|
338
336
|
if (mappedWorkflow?.diff) {
|
|
339
337
|
log.info(
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import { Logger } from './logger';
|
|
3
|
+
|
|
4
|
+
export const mergeContentsToAddWithGitignore = (
|
|
5
|
+
filename: string,
|
|
6
|
+
contentsToAdd: string[]
|
|
7
|
+
) => {
|
|
8
|
+
// Check if .gitignore file already exists
|
|
9
|
+
if (fs.existsSync(filename)) {
|
|
10
|
+
// Read the existing .gitignore file
|
|
11
|
+
const existingContent = fs.readFileSync(filename, 'utf-8');
|
|
12
|
+
|
|
13
|
+
// Split the existing content by newline and remove empty lines
|
|
14
|
+
const existingLines = existingContent
|
|
15
|
+
.split('\n')
|
|
16
|
+
.filter(line => line.trim() !== '');
|
|
17
|
+
|
|
18
|
+
// Merge the existing content with the new contents to add
|
|
19
|
+
const mergedLines = [...existingLines, ...contentsToAdd];
|
|
20
|
+
|
|
21
|
+
// Deduplicate and sort the lines
|
|
22
|
+
const updatedContent = Array.from(new Set(mergedLines)).sort().join('\n');
|
|
23
|
+
|
|
24
|
+
// Write the updated content back to .gitignore
|
|
25
|
+
fs.writeFileSync(filename, updatedContent);
|
|
26
|
+
|
|
27
|
+
Logger.success('.gitignore file updated');
|
|
28
|
+
} else {
|
|
29
|
+
// If .gitignore doesn't exist, create one and add the contents to add
|
|
30
|
+
const gitignoreContent = contentsToAdd.join('\n');
|
|
31
|
+
fs.writeFileSync(filename, gitignoreContent);
|
|
32
|
+
|
|
33
|
+
Logger.success('.gitignore file created and updated');
|
|
34
|
+
}
|
|
35
|
+
};
|
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.8";
|