contensis-cli 1.0.9-beta.3 → 1.0.9-beta.4

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.
@@ -52,7 +52,9 @@ class ContensisDev extends import_ContensisRoleService.default {
52
52
  }
53
53
  DevelopmentInit = async (projectHome, opts) => {
54
54
  const git = this.git = new import_git.GitHelper(projectHome);
55
- git.checkIsRepo();
55
+ const isRepo = git.checkIsRepo();
56
+ if (!isRepo)
57
+ return;
56
58
  const { dryRun = false } = opts || {};
57
59
  const { currentEnv, currentProject, log, messages } = this;
58
60
  const contensis = await this.ConnectContensis();
@@ -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 // Retrieve git info\n const git = (this.git = new GitHelper(projectHome));\n // Check if we are in a git repo\n git.checkIsRepo();\n\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 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;AAE1D,UAAM,MAAO,KAAK,MAAM,IAAI,qBAAU,WAAW;AAEjD,QAAI,YAAY;AAEhB,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,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AK,MAAM,IAAI;AAAG,WAAK,KAAK,MAAM,cAAc;AAI/D,UAAM,YAAQ,4BAAM,SAAS,MAAM,EAAE,OAAO,UAAU,CAAC;AAGvD,QAAI,KAAK,8BAA8B;AACvC,QAAI,6CAAc;AAChB,WAAK,IAAI;AAAA,QACP,wCAAwC,KAAK;AAAA,UAC3C,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEF,QAAI,YAAY;AAGhB,yCAAO,WAAP,mBAAe,GAAG,QAAQ,UAAQ;AAChC,kBAAY;AACZ,UAAI,IAAI,IAAI;AAAA,IACd;AAEA,yCAAO,WAAP,mBAAe,GAAG,QAAQ,UAAQ;AAChC,UAAI,MAAM,IAAI;AAAA,IAChB;AAEA,UAAM,GAAG,SAAS,MAAM;AACtB,kBAAY;AACZ,UAAI;AAAA,QACF;AAAA,MACF;AAAA,IAEF,CAAC;AAED,UAAM,GAAG,QAAQ,UAAQ;AACvB,kBAAY;AAEZ,UAAI,SAAS,IAAI,YAAY;AAAA,QAC3B,oCAAoC;AAAA;AAAA,MACtC;AAAA,IACF,CAAC;AAED,UAAM,GAAG,SAAS,WAAS;AACzB,kBAAY;AACZ,UAAI,MAAM;AAAA,EAAmD,OAAO;AAAA,IACtE,CAAC;AAED,UAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAGtD,WAAO,MAAe;AACpB,UAAI,CAAC,WAAW;AAEd;AAAA,MACF;AACA,YAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAAA,IACxD;AAAA,EACF;AACF;AACO,MAAM,aAAa,CACxB,aACA,YACA,gBAAyC,CAAC,MACvC;AACH,SAAO,IAAI,aAAa,CAAC,IAAI,IAAI,GAAG,WAAW,GAAG,YAAY,aAAa;AAC7E;AAEA,IAAO,8BAAQ;",
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 // 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 // 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 = `${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;AA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,UAAI;AAAA,QACF;AAAA,MACF;AAAA,IAEF,CAAC;AAED,UAAM,GAAG,QAAQ,UAAQ;AACvB,kBAAY;AAEZ,UAAI,SAAS,IAAI,YAAY;AAAA,QAC3B,oCAAoC;AAAA;AAAA,MACtC;AAAA,IACF,CAAC;AAED,UAAM,GAAG,SAAS,WAAS;AACzB,kBAAY;AACZ,UAAI,MAAM;AAAA,EAAmD,OAAO;AAAA,IACtE,CAAC;AAED,UAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAGtD,WAAO,MAAe;AACpB,UAAI,CAAC,WAAW;AAEd;AAAA,MACF;AACA,YAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,GAAI,CAAC;AAAA,IACxD;AAAA,EACF;AACF;AACO,MAAM,aAAa,CACxB,aACA,YACA,gBAAyC,CAAC,MACvC;AACH,SAAO,IAAI,aAAa,CAAC,IAAI,IAAI,GAAG,WAAW,GAAG,YAAY,aAAa;AAC7E;AAEA,IAAO,8BAAQ;",
6
6
  "names": ["ContensisRole", "inquirer", "to", "path"]
7
7
  }
package/dist/util/git.js CHANGED
@@ -38,7 +38,6 @@ const GITLAB_CI_FILENAME = ".gitlab-ci.yml";
38
38
  class GitHelper {
39
39
  gitRepoPath;
40
40
  ciFile;
41
- isRepo;
42
41
  config = {};
43
42
  info;
44
43
  home;
@@ -57,7 +56,10 @@ class GitHelper {
57
56
  return ((_a = this.info) == null ? void 0 : _a.project) || ((_b = this.home) == null ? void 0 : _b.split("/").pop()) || "[set arg --name]";
58
57
  }
59
58
  get originUrl() {
60
- return this.config.remote.origin.url;
59
+ var _a, _b, _c;
60
+ const originUrl = (_c = (_b = (_a = this == null ? void 0 : this.config) == null ? void 0 : _a.remote) == null ? void 0 : _b.origin) == null ? void 0 : _c.url;
61
+ if (originUrl)
62
+ return originUrl;
61
63
  }
62
64
  get secretsUri() {
63
65
  return `${this.type === "github" ? `${this.home}/settings/secrets/actions` : `${this.home}/-/settings/ci_cd`}`;
@@ -78,9 +80,12 @@ class GitHelper {
78
80
  gitcwd = () => import_path.default.join(this.gitRepoPath);
79
81
  gitInfo = (url = this.originUrl) => import_hosted_git_info.default.fromUrl(url);
80
82
  hostType = (url = this.originUrl) => {
81
- if (url.includes("github.com"))
82
- return "github";
83
- return "gitlab";
83
+ if (url) {
84
+ if (url.includes("github.com"))
85
+ return "github";
86
+ else
87
+ return "gitlab";
88
+ }
84
89
  };
85
90
  gitConfig = (cwd = this.gitRepoPath) => {
86
91
  const config = import_parse_git_config.default.sync({
@@ -125,9 +130,10 @@ class GitHelper {
125
130
  checkIsRepo = () => {
126
131
  if (this.config && this.config.core && this.config.core.repositoryformatversion) {
127
132
  import_logger.Logger.success("You are inside a Git repository.");
133
+ return true;
128
134
  } else {
129
135
  import_logger.Logger.error("You are not inside a Git repository.");
130
- return;
136
+ return false;
131
137
  }
132
138
  };
133
139
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/util/git.ts"],
4
- "sourcesContent": ["import giturl from 'giturl';\nimport hostedGitInfo from 'hosted-git-info';\nimport parseGitConfig from 'parse-git-config';\nimport path from 'path';\n\nimport { linuxSlash } from './os';\nimport { readFile, readFiles } from '~/providers/file-provider';\nimport { Logger } from './logger';\n\nconst GITLAB_CI_FILENAME = '.gitlab-ci.yml';\n\ntype GitConfig = parseGitConfig.Config;\n\nexport type GitTypes = hostedGitInfo.Hosts;\n\nexport class GitHelper {\n private gitRepoPath: string;\n private ciFile?: string;\n\n isRepo: boolean | undefined;\n config = {} as GitConfig;\n info: hostedGitInfo | undefined;\n home: string | undefined;\n\n set ciFileName(fileName: string) {\n this.ciFile = fileName;\n }\n\n get ciFileName() {\n return (\n this.ciFile ||\n (this.workflows\n ? this.type === 'github'\n ? this.workflows.length > 1\n ? '[multiple workflows]'\n : this.workflows?.[0]\n : GITLAB_CI_FILENAME\n : '[unknown]')\n );\n }\n get ciFilePath() {\n return `${this.gitRepoPath}/${this.ciFileName}`;\n }\n get name() {\n return (\n this.info?.project || this.home?.split('/').pop() || '[set arg --name]'\n );\n }\n get originUrl() {\n return this.config.remote.origin.url;\n }\n get secretsUri() {\n return `${\n this.type === 'github'\n ? `${this.home}/settings/secrets/actions`\n : `${this.home}/-/settings/ci_cd`\n }`;\n }\n get type() {\n return this.info?.type || this.hostType();\n }\n get workflows() {\n return this.type === 'github'\n ? this.githubWorkflows()\n : this.gitlabWorkflow();\n }\n constructor(gitRepoPath: string = process.cwd()) {\n this.gitRepoPath = gitRepoPath;\n this.config = this.gitConfig();\n this.home = giturl.parse(this.originUrl);\n this.info = this.gitInfo();\n // console.log(this.config);\n // console.log(this.home);\n // console.log(this.info);\n }\n gitcwd = () => path.join(this.gitRepoPath);\n gitInfo = (url: string = this.originUrl) => hostedGitInfo.fromUrl(url);\n hostType = (url: string = this.originUrl): GitTypes => {\n if (url.includes('github.com')) return 'github';\n return 'gitlab';\n // if (url.includes('gitlab.com')) return 'gl';\n // if (url.includes('gitlab.zengenti.com')) return 'gl';\n };\n gitConfig = (cwd = this.gitRepoPath) => {\n // Find .git/config in project cwd\n const config = parseGitConfig.sync({\n path: '.git/config',\n expandKeys: true,\n });\n // console.log(cwd, config);\n if (Object.keys(config || {}).length) return config;\n\n // Recursively check the directory heirarchy for existance of a .git/config\n const pathParts = linuxSlash(cwd).split('/');\n for (let i = 1; i <= pathParts.length; i++) {\n const relPath = `${Array(i).fill('..').join('/')}/.git/config`;\n // Does not appear to work when using a shortened cwd, using relative path instead\n const config = parseGitConfig.sync({\n path: relPath,\n expandKeys: true,\n });\n // console.log(relPath, config);\n if (Object.keys(config || {}).length) {\n this.gitRepoPath = path.join(\n this.gitRepoPath,\n Array(i).fill('..').join('/')\n );\n return config;\n }\n }\n return config;\n };\n githubWorkflows = () => {\n const workflowPath = path.join(this.gitcwd(), '.github/workflows');\n const workflowFiles = readFiles(workflowPath, false);\n const addFolderSuffix = (files: string[]) =>\n files.map(f => `.github/workflows/${f}`);\n\n if (workflowFiles.some(f => f.includes('build'))) {\n return addFolderSuffix(workflowFiles.filter(f => f.includes('build')));\n } else {\n return addFolderSuffix(workflowFiles);\n }\n };\n gitlabWorkflow = (ciFileName = GITLAB_CI_FILENAME) => {\n const workflowPath = this.gitcwd();\n const workflowFilePath = path.join(workflowPath, ciFileName);\n const workflowFile = readFile(workflowFilePath);\n // console.log(ciFileName, workflowFile);\n\n return workflowFile;\n };\n checkIsRepo = () => {\n if (\n this.config &&\n this.config.core &&\n this.config.core.repositoryformatversion\n ) {\n Logger.success('You are inside a Git repository.');\n } else {\n Logger.error('You are not inside a Git repository.');\n return;\n }\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,6BAA0B;AAC1B,8BAA2B;AAC3B,kBAAiB;AAEjB,gBAA2B;AAC3B,2BAAoC;AACpC,oBAAuB;AAEvB,MAAM,qBAAqB;AAMpB,MAAM,UAAU;AAAA,EACb;AAAA,EACA;AAAA,EAER;AAAA,EACA,SAAS,CAAC;AAAA,EACV;AAAA,EACA;AAAA,EAEA,IAAI,WAAW,UAAkB;AAC/B,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,IAAI,aAAa;AA5BnB;AA6BI,WACE,KAAK,WACJ,KAAK,YACF,KAAK,SAAS,WACZ,KAAK,UAAU,SAAS,IACtB,0BACA,UAAK,cAAL,mBAAiB,KACnB,qBACF;AAAA,EAER;AAAA,EACA,IAAI,aAAa;AACf,WAAO,GAAG,KAAK,eAAe,KAAK;AAAA,EACrC;AAAA,EACA,IAAI,OAAO;AA3Cb;AA4CI,aACE,UAAK,SAAL,mBAAW,cAAW,UAAK,SAAL,mBAAW,MAAM,KAAK,UAAS;AAAA,EAEzD;AAAA,EACA,IAAI,YAAY;AACd,WAAO,KAAK,OAAO,OAAO,OAAO;AAAA,EACnC;AAAA,EACA,IAAI,aAAa;AACf,WAAO,GACL,KAAK,SAAS,WACV,GAAG,KAAK,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AC,EAAE,KAAK,IAAI,EAAE,KAAK,GAAG;AAAA,QAC9B;AACA,eAAOG;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EACA,kBAAkB,MAAM;AACtB,UAAM,eAAe,YAAAH,QAAK,KAAK,KAAK,OAAO,GAAG,mBAAmB;AACjE,UAAM,oBAAgB,gCAAU,cAAc,KAAK;AACnD,UAAM,kBAAkB,CAAC,UACvB,MAAM,IAAI,OAAK,qBAAqB,GAAG;AAEzC,QAAI,cAAc,KAAK,OAAK,EAAE,SAAS,OAAO,CAAC,GAAG;AAChD,aAAO,gBAAgB,cAAc,OAAO,OAAK,EAAE,SAAS,OAAO,CAAC,CAAC;AAAA,IACvE,OAAO;AACL,aAAO,gBAAgB,aAAa;AAAA,IACtC;AAAA,EACF;AAAA,EACA,iBAAiB,CAAC,aAAa,uBAAuB;AACpD,UAAM,eAAe,KAAK,OAAO;AACjC,UAAM,mBAAmB,YAAAA,QAAK,KAAK,cAAc,UAAU;AAC3D,UAAM,mBAAe,+BAAS,gBAAgB;AAG9C,WAAO;AAAA,EACT;AAAA,EACA,cAAc,MAAM;AAClB,QACE,KAAK,UACL,KAAK,OAAO,QACZ,KAAK,OAAO,KAAK,yBACjB;AACA,2BAAO,QAAQ,kCAAkC;AAAA,IACnD,OAAO;AACL,2BAAO,MAAM,sCAAsC;AACnD;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import giturl from 'giturl';\nimport hostedGitInfo from 'hosted-git-info';\nimport parseGitConfig from 'parse-git-config';\nimport path from 'path';\n\nimport { linuxSlash } from './os';\nimport { readFile, readFiles } from '~/providers/file-provider';\nimport { Logger } from './logger';\n\nconst GITLAB_CI_FILENAME = '.gitlab-ci.yml';\n\ntype GitConfig = parseGitConfig.Config;\n\nexport type GitTypes = hostedGitInfo.Hosts;\n\nexport class GitHelper {\n private gitRepoPath: string;\n private ciFile?: string;\n\n config = {} as GitConfig;\n info: hostedGitInfo | undefined;\n home: string | undefined;\n\n set ciFileName(fileName: string) {\n this.ciFile = fileName;\n }\n\n get ciFileName() {\n return (\n this.ciFile ||\n (this.workflows\n ? this.type === 'github'\n ? this.workflows.length > 1\n ? '[multiple workflows]'\n : this.workflows?.[0]\n : GITLAB_CI_FILENAME\n : '[unknown]')\n );\n }\n get ciFilePath() {\n return `${this.gitRepoPath}/${this.ciFileName}`;\n }\n get name() {\n return (\n this.info?.project || this.home?.split('/').pop() || '[set arg --name]'\n );\n }\n get originUrl() {\n const originUrl = this?.config?.remote?.origin?.url;\n if (originUrl) return originUrl;\n }\n get secretsUri() {\n return `${\n this.type === 'github'\n ? `${this.home}/settings/secrets/actions`\n : `${this.home}/-/settings/ci_cd`\n }`;\n }\n get type() {\n return this.info?.type || this.hostType();\n }\n get workflows() {\n return this.type === 'github'\n ? this.githubWorkflows()\n : this.gitlabWorkflow();\n }\n constructor(gitRepoPath: string = process.cwd()) {\n this.gitRepoPath = gitRepoPath;\n this.config = this.gitConfig();\n this.home = giturl.parse(this.originUrl);\n this.info = this.gitInfo();\n // console.log(this.config);\n // console.log(this.home);\n // console.log(this.info);\n }\n gitcwd = () => path.join(this.gitRepoPath);\n gitInfo = (url: string = this.originUrl) => hostedGitInfo.fromUrl(url);\n hostType = (url: string = this.originUrl): GitTypes => {\n if (url) {\n if (url.includes('github.com')) return 'github';\n else return 'gitlab';\n }\n\n // if (url.includes('gitlab.com')) return 'gl';\n // if (url.includes('gitlab.zengenti.com')) return 'gl';\n };\n gitConfig = (cwd = this.gitRepoPath) => {\n // Find .git/config in project cwd\n const config = parseGitConfig.sync({\n path: '.git/config',\n expandKeys: true,\n });\n // console.log(cwd, config);\n if (Object.keys(config || {}).length) return config;\n\n // Recursively check the directory heirarchy for existance of a .git/config\n const pathParts = linuxSlash(cwd).split('/');\n for (let i = 1; i <= pathParts.length; i++) {\n const relPath = `${Array(i).fill('..').join('/')}/.git/config`;\n // Does not appear to work when using a shortened cwd, using relative path instead\n const config = parseGitConfig.sync({\n path: relPath,\n expandKeys: true,\n });\n // console.log(relPath, config);\n if (Object.keys(config || {}).length) {\n this.gitRepoPath = path.join(\n this.gitRepoPath,\n Array(i).fill('..').join('/')\n );\n return config;\n }\n }\n return config;\n };\n githubWorkflows = () => {\n const workflowPath = path.join(this.gitcwd(), '.github/workflows');\n const workflowFiles = readFiles(workflowPath, false);\n const addFolderSuffix = (files: string[]) =>\n files.map(f => `.github/workflows/${f}`);\n\n if (workflowFiles.some(f => f.includes('build'))) {\n return addFolderSuffix(workflowFiles.filter(f => f.includes('build')));\n } else {\n return addFolderSuffix(workflowFiles);\n }\n };\n gitlabWorkflow = (ciFileName = GITLAB_CI_FILENAME) => {\n const workflowPath = this.gitcwd();\n const workflowFilePath = path.join(workflowPath, ciFileName);\n const workflowFile = readFile(workflowFilePath);\n // console.log(ciFileName, workflowFile);\n\n return workflowFile;\n };\n checkIsRepo = () => {\n if (\n this.config &&\n this.config.core &&\n this.config.core.repositoryformatversion\n ) {\n Logger.success('You are inside a Git repository.');\n return true;\n } else {\n Logger.error('You are not inside a Git repository.');\n return false;\n }\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,6BAA0B;AAC1B,8BAA2B;AAC3B,kBAAiB;AAEjB,gBAA2B;AAC3B,2BAAoC;AACpC,oBAAuB;AAEvB,MAAM,qBAAqB;AAMpB,MAAM,UAAU;AAAA,EACb;AAAA,EACA;AAAA,EAER,SAAS,CAAC;AAAA,EACV;AAAA,EACA;AAAA,EAEA,IAAI,WAAW,UAAkB;AAC/B,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,IAAI,aAAa;AA3BnB;AA4BI,WACE,KAAK,WACJ,KAAK,YACF,KAAK,SAAS,WACZ,KAAK,UAAU,SAAS,IACtB,0BACA,UAAK,cAAL,mBAAiB,KACnB,qBACF;AAAA,EAER;AAAA,EACA,IAAI,aAAa;AACf,WAAO,GAAG,KAAK,e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ACnD,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
6
6
  "names": ["giturl", "path", "hostedGitInfo", "parseGitConfig", "config"]
7
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.3";
24
+ const LIB_VERSION = "1.0.9-beta.4";
25
25
  // Annotate the CommonJS export names for ESM import in node:
26
26
  0 && (module.exports = {
27
27
  LIB_VERSION
@@ -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.3\";\n"],
4
+ "sourcesContent": ["export const LIB_VERSION = \"1.0.9-beta.4\";\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",
3
+ "version": "1.0.9-beta.4",
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",
@@ -40,7 +40,8 @@ class ContensisDev extends ContensisRole {
40
40
  // Retrieve git info
41
41
  const git = (this.git = new GitHelper(projectHome));
42
42
  // Check if we are in a git repo
43
- git.checkIsRepo();
43
+ const isRepo = git.checkIsRepo();
44
+ if (!isRepo) return;
44
45
 
45
46
  const { dryRun = false } = opts || {};
46
47
  const { currentEnv, currentProject, log, messages } = this;
package/src/util/git.ts CHANGED
@@ -17,7 +17,6 @@ export class GitHelper {
17
17
  private gitRepoPath: string;
18
18
  private ciFile?: string;
19
19
 
20
- isRepo: boolean | undefined;
21
20
  config = {} as GitConfig;
22
21
  info: hostedGitInfo | undefined;
23
22
  home: string | undefined;
@@ -47,7 +46,8 @@ export class GitHelper {
47
46
  );
48
47
  }
49
48
  get originUrl() {
50
- return this.config.remote.origin.url;
49
+ const originUrl = this?.config?.remote?.origin?.url;
50
+ if (originUrl) return originUrl;
51
51
  }
52
52
  get secretsUri() {
53
53
  return `${
@@ -76,8 +76,11 @@ export class GitHelper {
76
76
  gitcwd = () => path.join(this.gitRepoPath);
77
77
  gitInfo = (url: string = this.originUrl) => hostedGitInfo.fromUrl(url);
78
78
  hostType = (url: string = this.originUrl): GitTypes => {
79
- if (url.includes('github.com')) return 'github';
80
- return 'gitlab';
79
+ if (url) {
80
+ if (url.includes('github.com')) return 'github';
81
+ else return 'gitlab';
82
+ }
83
+
81
84
  // if (url.includes('gitlab.com')) return 'gl';
82
85
  // if (url.includes('gitlab.zengenti.com')) return 'gl';
83
86
  };
@@ -137,9 +140,10 @@ export class GitHelper {
137
140
  this.config.core.repositoryformatversion
138
141
  ) {
139
142
  Logger.success('You are inside a Git repository.');
143
+ return true;
140
144
  } else {
141
145
  Logger.error('You are not inside a Git repository.');
142
- return;
146
+ return false;
143
147
  }
144
148
  };
145
149
  }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const LIB_VERSION = "1.0.9-beta.3";
1
+ export const LIB_VERSION = "1.0.9-beta.4";