contensis-cli 1.0.12-beta.9 → 1.1.1-beta.0
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/CHANGELOG.md +38 -0
- package/dist/localisation/en-GB.js +5 -3
- package/dist/localisation/en-GB.js.map +2 -2
- package/dist/mappers/DevInit-to-CIWorkflow.js +6 -8
- package/dist/mappers/DevInit-to-CIWorkflow.js.map +2 -2
- package/dist/mappers/DevInit-to-RolePermissions.js +4 -4
- package/dist/mappers/DevInit-to-RolePermissions.js.map +2 -2
- package/dist/services/ContensisAuthService.js.map +2 -2
- package/dist/services/ContensisCliService.js +14 -16
- package/dist/services/ContensisCliService.js.map +2 -2
- package/dist/services/ContensisDevService.js +51 -56
- package/dist/services/ContensisDevService.js.map +3 -3
- package/dist/shell.js +2 -0
- package/dist/shell.js.map +2 -2
- package/dist/util/csv.formatter.js +3 -11
- package/dist/util/csv.formatter.js.map +3 -3
- package/dist/util/diff.js +1 -1
- package/dist/util/diff.js.map +2 -2
- package/dist/util/git.js +1 -0
- package/dist/util/git.js.map +2 -2
- package/dist/util/json.formatter.js +35 -3
- package/dist/util/json.formatter.js.map +3 -3
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
- package/src/localisation/en-GB.ts +6 -3
- package/src/mappers/DevInit-to-CIWorkflow.ts +8 -8
- package/src/mappers/DevInit-to-RolePermissions.ts +5 -2
- package/src/models/Cache.d.ts +2 -1
- package/src/services/ContensisAuthService.ts +1 -1
- package/src/services/ContensisCliService.ts +16 -25
- package/src/services/ContensisDevService.ts +76 -70
- package/src/shell.ts +4 -0
- package/src/util/csv.formatter.ts +1 -4
- package/src/util/diff.ts +1 -1
- package/src/util/git.ts +2 -1
- package/src/util/json.formatter.ts +32 -1
- package/src/version.ts +1 -1
|
@@ -28,9 +28,11 @@ __export(ContensisDevService_exports, {
|
|
|
28
28
|
devCommand: () => devCommand
|
|
29
29
|
});
|
|
30
30
|
module.exports = __toCommonJS(ContensisDevService_exports);
|
|
31
|
+
var import_ansi_escapes = __toESM(require("ansi-escapes"));
|
|
31
32
|
var import_await_to_js = __toESM(require("await-to-js"));
|
|
32
33
|
var import_child_process = require("child_process");
|
|
33
34
|
var import_inquirer = __toESM(require("inquirer"));
|
|
35
|
+
var import_nanospinner = require("nanospinner");
|
|
34
36
|
var import_path = __toESM(require("path"));
|
|
35
37
|
var import_ContensisRoleService = __toESM(require("./ContensisRoleService"));
|
|
36
38
|
var import_DevRequests_to_RequestHanderSiteConfigYaml = require("../mappers/DevRequests-to-RequestHanderSiteConfigYaml");
|
|
@@ -44,13 +46,14 @@ var import_git = require("../util/git");
|
|
|
44
46
|
var import_json = require("../util/json.formatter");
|
|
45
47
|
var import_os = require("../util/os");
|
|
46
48
|
var import_yaml = require("../util/yaml");
|
|
47
|
-
var import_nanospinner = require("nanospinner");
|
|
48
49
|
var import_gitignore = require("../util/gitignore");
|
|
49
|
-
var import_ContensisAuthService = __toESM(require("./ContensisAuthService"));
|
|
50
|
-
var import_ansi_escapes = __toESM(require("ansi-escapes"));
|
|
51
50
|
class ContensisDev extends import_ContensisRoleService.default {
|
|
52
51
|
git;
|
|
53
52
|
blockId;
|
|
53
|
+
deployCredentials = {
|
|
54
|
+
clientId: "",
|
|
55
|
+
clientSecret: ""
|
|
56
|
+
};
|
|
54
57
|
constructor(args, outputOpts, contensisOpts = {}) {
|
|
55
58
|
super(args, outputOpts, contensisOpts);
|
|
56
59
|
}
|
|
@@ -64,7 +67,6 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
64
67
|
const { currentEnv, currentProject, log, messages } = this;
|
|
65
68
|
const contensis = await this.ConnectContensis();
|
|
66
69
|
if (contensis) {
|
|
67
|
-
this.devinit = { ...this.devinit, invokedBy: this.invokedBy };
|
|
68
70
|
const validateBlockId = (blockId2) => {
|
|
69
71
|
const pattern = /^[0-9a-z](-?[0-9a-z])*$/;
|
|
70
72
|
if (blockId2.length >= 1 && blockId2.length <= 225) {
|
|
@@ -77,7 +79,8 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
77
79
|
type: "input",
|
|
78
80
|
prefix: "\u{1F9F1}",
|
|
79
81
|
message: messages.devinit.blockIdQuestion,
|
|
80
|
-
validate: validateBlockId
|
|
82
|
+
validate: validateBlockId,
|
|
83
|
+
default: git.name
|
|
81
84
|
});
|
|
82
85
|
this.blockId = blockId.toLowerCase();
|
|
83
86
|
log.success(`Valid block id: ${blockId.toLowerCase()}`);
|
|
@@ -96,47 +99,12 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
96
99
|
const devKeyName = `${apiKeyName}`;
|
|
97
100
|
const devKeyDescription = `Created by Contensis to allow API access from the running block`;
|
|
98
101
|
let existingDevKey = apiKeyExists(devKeyName);
|
|
99
|
-
if (!existingDevKey) {
|
|
100
|
-
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
101
|
-
existingDevKey,
|
|
102
|
-
devKeyName,
|
|
103
|
-
devKeyDescription
|
|
104
|
-
);
|
|
105
|
-
log.success("Successfully created development key");
|
|
106
|
-
}
|
|
107
102
|
const deployKeyName = `${apiKeyName}-ci`;
|
|
108
103
|
const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;
|
|
109
104
|
let existingDeployKey = apiKeyExists(deployKeyName);
|
|
110
|
-
if (!existingDeployKey) {
|
|
111
|
-
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
112
|
-
existingDeployKey,
|
|
113
|
-
deployKeyName,
|
|
114
|
-
deployKeyDescription
|
|
115
|
-
);
|
|
116
|
-
log.success("Successfully created deploy key");
|
|
117
|
-
}
|
|
118
|
-
if (existingDeployKey) {
|
|
119
|
-
this.devinit = {
|
|
120
|
-
...this.devinit,
|
|
121
|
-
credentials: {
|
|
122
|
-
clientId: existingDeployKey == null ? void 0 : existingDeployKey.id,
|
|
123
|
-
clientSecret: existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
const credentials = await this.GetCredentials(this.devinit.invokedBy);
|
|
128
|
-
let classicToken;
|
|
129
|
-
const auth = new import_ContensisAuthService.default({
|
|
130
|
-
username: (_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.account,
|
|
131
|
-
password: (_b = credentials == null ? void 0 : credentials.current) == null ? void 0 : _b.password,
|
|
132
|
-
projectId: currentProject,
|
|
133
|
-
rootUrl: `https://cms-${currentEnv}.cloud.contensis.com`
|
|
134
|
-
});
|
|
135
|
-
classicToken = await auth.ClassicToken();
|
|
136
105
|
const errors = [];
|
|
137
106
|
log.raw("");
|
|
138
107
|
log.success(messages.devinit.intro());
|
|
139
|
-
log.raw("");
|
|
140
108
|
log.raw(
|
|
141
109
|
log.infoText(
|
|
142
110
|
messages.devinit.projectDetails(
|
|
@@ -174,7 +142,6 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
174
142
|
git.ciFileName = ciFileName;
|
|
175
143
|
}
|
|
176
144
|
log.raw(log.infoText(messages.devinit.ciDetails(ciFileName)));
|
|
177
|
-
let mappedWorkflow;
|
|
178
145
|
const { loc } = await import_inquirer.default.prompt({
|
|
179
146
|
name: "loc",
|
|
180
147
|
type: "list",
|
|
@@ -191,8 +158,8 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
191
158
|
}
|
|
192
159
|
]
|
|
193
160
|
});
|
|
161
|
+
log.raw("");
|
|
194
162
|
log.help(messages.devinit.ciIntro(git, loc));
|
|
195
|
-
mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this, loc);
|
|
196
163
|
if (!dryRun) {
|
|
197
164
|
const { confirm } = await import_inquirer.default.prompt([
|
|
198
165
|
{
|
|
@@ -207,14 +174,13 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
207
174
|
return;
|
|
208
175
|
}
|
|
209
176
|
let accessToken = void 0;
|
|
210
|
-
log.raw("");
|
|
211
177
|
const spinner = (0, import_nanospinner.createSpinner)(messages.devinit.accessTokenFetch());
|
|
212
178
|
spinner.start();
|
|
213
179
|
const token = await this.GetDeliveryApiKey();
|
|
214
180
|
if (token) {
|
|
215
|
-
spinner.success();
|
|
216
|
-
this.log.success(messages.devinit.accessTokenSuccess(token));
|
|
217
181
|
accessToken = token;
|
|
182
|
+
spinner.success({ text: messages.devinit.accessTokenSuccess(token) });
|
|
183
|
+
log.raw("");
|
|
218
184
|
} else {
|
|
219
185
|
spinner.error();
|
|
220
186
|
this.log.error(messages.devinit.accessTokenFailed());
|
|
@@ -234,6 +200,27 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
234
200
|
if (dryRun) {
|
|
235
201
|
checkpoint(`skip api key creation (dry-run)`);
|
|
236
202
|
} else {
|
|
203
|
+
const devKeyExisted = !!existingDevKey;
|
|
204
|
+
if (!existingDevKey) {
|
|
205
|
+
existingDevKey = await this.CreateOrUpdateApiKey(
|
|
206
|
+
existingDevKey,
|
|
207
|
+
devKeyName,
|
|
208
|
+
devKeyDescription
|
|
209
|
+
);
|
|
210
|
+
log.success(messages.devinit.createDevKey(devKeyName, devKeyExisted));
|
|
211
|
+
}
|
|
212
|
+
const deployKeyExisted = !!existingDeployKey;
|
|
213
|
+
if (!existingDeployKey) {
|
|
214
|
+
existingDeployKey = await this.CreateOrUpdateApiKey(
|
|
215
|
+
existingDeployKey,
|
|
216
|
+
deployKeyName,
|
|
217
|
+
deployKeyDescription
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (existingDeployKey) {
|
|
221
|
+
this.deployCredentials.clientId = existingDeployKey == null ? void 0 : existingDeployKey.id;
|
|
222
|
+
this.deployCredentials.clientSecret = existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret;
|
|
223
|
+
}
|
|
237
224
|
const deployRoleName = `Role for CI push of block '${blockId}'`;
|
|
238
225
|
const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;
|
|
239
226
|
let existingDeployRole = (0, import_find.findByIdOrName)(
|
|
@@ -243,10 +230,12 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
243
230
|
);
|
|
244
231
|
existingDeployRole = await this.CreateOrUpdateRole(
|
|
245
232
|
existingDeployRole,
|
|
246
|
-
(0, import_DevInit_to_RolePermissions.deployKeyRole)(deployKeyName, deplyRoleDescription)
|
|
233
|
+
(0, import_DevInit_to_RolePermissions.deployKeyRole)(deployKeyName, deployRoleName, deplyRoleDescription)
|
|
247
234
|
);
|
|
248
235
|
checkpoint("deploy key role assigned");
|
|
249
|
-
log.success(
|
|
236
|
+
log.success(
|
|
237
|
+
messages.devinit.createDeployKey(deployRoleName, deployKeyExisted)
|
|
238
|
+
);
|
|
250
239
|
checkpoint("api keys done");
|
|
251
240
|
}
|
|
252
241
|
const envFilePath = `${projectHome}/.env`;
|
|
@@ -260,8 +249,8 @@ class ContensisDev extends import_ContensisRoleService.default {
|
|
|
260
249
|
if (accessToken)
|
|
261
250
|
envContentsToAdd["ACCESS_TOKEN"] = accessToken;
|
|
262
251
|
if (loc === "env") {
|
|
263
|
-
envContentsToAdd["CONTENSIS_CLIENT_ID"] = existingDevKey == null ? void 0 : existingDevKey.id;
|
|
264
|
-
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] = existingDevKey == null ? void 0 : existingDevKey.sharedSecret;
|
|
252
|
+
envContentsToAdd["CONTENSIS_CLIENT_ID"] = (existingDevKey == null ? void 0 : existingDevKey.id) || messages.devinit.dryRunKeyMessage(dryRun);
|
|
253
|
+
envContentsToAdd["CONTENSIS_CLIENT_SECRET"] = (existingDevKey == null ? void 0 : existingDevKey.sharedSecret) || messages.devinit.dryRunKeyMessage(dryRun);
|
|
265
254
|
}
|
|
266
255
|
const removeEnvItems = (items) => {
|
|
267
256
|
const indexesToRemove = [];
|
|
@@ -295,14 +284,18 @@ ${envDiff}`);
|
|
|
295
284
|
checkpoint("skip .env file update (dry-run)");
|
|
296
285
|
} else {
|
|
297
286
|
if (envDiff)
|
|
298
|
-
log.info(`
|
|
287
|
+
log.info(`Updating .env file ${(0, import_os.winSlash)(envFilePath)}`);
|
|
299
288
|
(0, import_file_provider.writeFile)(envFilePath, envFileLines.join("\n"));
|
|
300
289
|
checkpoint(".env file updated");
|
|
301
290
|
log.success(messages.devinit.writeEnvFile());
|
|
302
291
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
292
|
+
if (dryRun) {
|
|
293
|
+
checkpoint("skip .gitignore file update (dry-run)");
|
|
294
|
+
} else {
|
|
295
|
+
(0, import_gitignore.mergeContentsToAddWithGitignore)(`${projectHome}/.gitignore`, [".env"]);
|
|
296
|
+
log.raw("");
|
|
297
|
+
}
|
|
298
|
+
const mappedWorkflow = await (0, import_DevInit_to_CIWorkflow.mapCIWorkflowContent)(this, loc);
|
|
306
299
|
if (mappedWorkflow == null ? void 0 : mappedWorkflow.diff) {
|
|
307
300
|
log.info(
|
|
308
301
|
`Updating ${(0, import_os.winSlash)(ciFileName)} file:
|
|
@@ -323,6 +316,7 @@ ${mappedWorkflow.diff}`
|
|
|
323
316
|
} else {
|
|
324
317
|
log.info(messages.devinit.ciFileNoChanges(`./${ciFileName}`));
|
|
325
318
|
}
|
|
319
|
+
log.raw("");
|
|
326
320
|
checkpoint("CI file updated");
|
|
327
321
|
}
|
|
328
322
|
}
|
|
@@ -331,8 +325,8 @@ ${mappedWorkflow.diff}`
|
|
|
331
325
|
log.help(
|
|
332
326
|
messages.devinit.addGitSecretsHelp(
|
|
333
327
|
git,
|
|
334
|
-
existingDeployKey == null ? void 0 : existingDeployKey.id,
|
|
335
|
-
existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret
|
|
328
|
+
(existingDeployKey == null ? void 0 : existingDeployKey.id) || messages.devinit.dryRunKeyMessage(dryRun),
|
|
329
|
+
(existingDeployKey == null ? void 0 : existingDeployKey.sharedSecret) || messages.devinit.dryRunKeyMessage(dryRun)
|
|
336
330
|
)
|
|
337
331
|
);
|
|
338
332
|
}
|
|
@@ -342,10 +336,11 @@ ${mappedWorkflow.diff}`
|
|
|
342
336
|
} else {
|
|
343
337
|
log.success(messages.devinit.success());
|
|
344
338
|
log.help(messages.devinit.startProjectTip());
|
|
339
|
+
const classicToken = await ((_a = this.auth) == null ? void 0 : _a.ClassicToken());
|
|
345
340
|
log.help(
|
|
346
341
|
import_ansi_escapes.default.link(
|
|
347
342
|
`Open Contensis`,
|
|
348
|
-
|
|
343
|
+
`${(_b = this.urls) == null ? void 0 : _b.cms}${classicToken ? `?SecurityToken=${classicToken}` : ""}`
|
|
349
344
|
)
|
|
350
345
|
);
|
|
351
346
|
}
|
|
@@ -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 { deployKeyRole } 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';\nimport ContensisAuthService from './ContensisAuthService';\nimport ansiEscapes from 'ansi-escapes';\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 this.devinit = { ...this.devinit, invokedBy: this.invokedBy };\n\n // First we need to get the block id from the user\n const validateBlockId = (blockId: string) => {\n const pattern = /^[0-9a-z](-?[0-9a-z])*$/;\n if (blockId.length >= 1 && blockId.length <= 225) {\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 apiKeyName = `block-${currentProject}-${blockId}`.toLowerCase();\n\n const devKeyName = `${apiKeyName}`;\n const devKeyDescription = `Created by Contensis to allow API access from the running block`;\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 = `${apiKeyName}-ci`;\n const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;\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.devinit = {\n ...this.devinit,\n credentials: {\n clientId: existingDeployKey?.id,\n clientSecret: existingDeployKey?.sharedSecret,\n },\n };\n }\n\n // we need to credentials of the user so that we can create a auth service\n const credentials = await this.GetCredentials(this.devinit.invokedBy);\n\n // create new auth service using creds\n let classicToken: string | undefined | null;\n const auth = new ContensisAuthService({\n username: credentials?.current?.account,\n password: credentials?.current?.password,\n projectId: currentProject,\n rootUrl: `https://cms-${currentEnv}.cloud.contensis.com`,\n });\n\n // once we have auth service, we can go and fetch out classic token\n classicToken = await auth.ClassicToken();\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 { loc } = await inquirer.prompt({\n name: 'loc',\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 {\n name: messages.devinit.clientDetailsInGit(git),\n value: 'git',\n },\n {\n name: messages.devinit.clientDetailsInEnv(),\n value: 'env',\n },\n ],\n });\n\n log.help(messages.devinit.ciIntro(git, loc));\n // Update CI Workflow\n mappedWorkflow = await mapCIWorkflowContent(this, loc);\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 const deployRoleName = `Role for CI push of block '${blockId}'`;\n const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployRoleName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployKeyName, deplyRoleDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(messages.devinit.createDeployKey(deployRoleName, 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 (loc === '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 // remove client id and secret from env file\n if (loc === '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 (loc === '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 // open the cms link -- if no classic token just return the cms url\n log.help(\n ansiEscapes.link(\n `Open Contensis`,\n `https://cms-${currentEnv}.cloud.contensis.com${\n classicToken ? `?SecurityToken=${classicToken}` : ''\n }`\n )\n );\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,wCAA8B;AAC9B,2BAAgD;AAChD,kBAAgC;AAChC,oBAAwC;AACxC,kBAA+B;AAC/B,iBAA0B;AAC1B,kBAA8B;AAC9B,gBAAyB;AACzB,kBAA8B;AAC9B,
|
|
6
|
-
"names": ["ContensisRole", "blockId", "inquirer", "
|
|
4
|
+
"sourcesContent": ["import ansiEscapes from 'ansi-escapes';\nimport to from 'await-to-js';\nimport { spawn } from 'child_process';\nimport inquirer from 'inquirer';\nimport { createSpinner } from 'nanospinner';\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 { deployKeyRole } 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 { mergeContentsToAddWithGitignore } from '~/util/gitignore';\n\nclass ContensisDev extends ContensisRole {\n git!: GitHelper;\n blockId!: string;\n\n deployCredentials = {\n clientId: '',\n clientSecret: '',\n };\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 = /^[0-9a-z](-?[0-9a-z])*$/;\n if (blockId.length >= 1 && blockId.length <= 225) {\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 default: git.name,\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 apiKeyName = `block-${currentProject}-${blockId}`.toLowerCase();\n\n const devKeyName = `${apiKeyName}`;\n const devKeyDescription = `Created by Contensis to allow API access from the running block`;\n let existingDevKey = apiKeyExists(devKeyName);\n\n const deployKeyName = `${apiKeyName}-ci`;\n const deployKeyDescription = `Created by the Contensis CLI for use in continuous integration`;\n\n let existingDeployKey = apiKeyExists(deployKeyName);\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.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 // Location for Client ID / Secret.\n const { loc } = await inquirer.prompt({\n name: 'loc',\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 {\n name: messages.devinit.clientDetailsInGit(git),\n value: 'git',\n },\n {\n name: messages.devinit.clientDetailsInEnv(),\n value: 'env',\n },\n ],\n });\n\n log.raw('');\n log.help(messages.devinit.ciIntro(git, loc));\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\n const spinner = createSpinner(messages.devinit.accessTokenFetch());\n spinner.start();\n\n const token = await this.GetDeliveryApiKey();\n\n if (token) {\n accessToken = token;\n spinner.success({ text: messages.devinit.accessTokenSuccess(token) });\n log.raw('');\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\n if (dryRun) {\n checkpoint(`skip api key creation (dry-run)`);\n } else {\n // if dev api key doesn't exist go and create it (we need this for local development, we will store these details in the .env file).\n const devKeyExisted = !!existingDevKey;\n if (!existingDevKey) {\n existingDevKey = await this.CreateOrUpdateApiKey(\n existingDevKey,\n devKeyName,\n devKeyDescription\n );\n log.success(messages.devinit.createDevKey(devKeyName, devKeyExisted));\n }\n // NF 24/11/23 Added this commented code back in as we are not assigning the dev key to any role here\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\n // if deploy api key doesn't exist go and create it (we need this for yml file).\n const deployKeyExisted = !!existingDeployKey;\n if (!existingDeployKey) {\n existingDeployKey = await this.CreateOrUpdateApiKey(\n existingDeployKey,\n deployKeyName,\n deployKeyDescription\n );\n }\n\n // check we have the deploy key so we can assign them to this values\n if (existingDeployKey) {\n // Add client id and secret to credentials\n this.deployCredentials.clientId = existingDeployKey?.id;\n this.deployCredentials.clientSecret = existingDeployKey?.sharedSecret;\n }\n\n // Ensure deploy API key is assigned to a role with the right permissions\n const deployRoleName = `Role for CI push of block '${blockId}'`;\n const deplyRoleDescription = `Created by the Contensis CLI for use in continuous integration`;\n let existingDeployRole = findByIdOrName(\n roles || [],\n deployRoleName,\n true\n ) as Role | undefined;\n existingDeployRole = await this.CreateOrUpdateRole(\n existingDeployRole,\n deployKeyRole(deployKeyName, deployRoleName, deplyRoleDescription)\n );\n\n checkpoint('deploy key role assigned');\n log.success(\n messages.devinit.createDeployKey(deployRoleName, deployKeyExisted)\n );\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 (loc === 'env') {\n envContentsToAdd['CONTENSIS_CLIENT_ID'] =\n existingDevKey?.id || messages.devinit.dryRunKeyMessage(dryRun);\n envContentsToAdd['CONTENSIS_CLIENT_SECRET'] =\n existingDevKey?.sharedSecret ||\n messages.devinit.dryRunKeyMessage(dryRun);\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 // remove client id and secret from env file\n if (loc === '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 if (dryRun) {\n checkpoint('skip .gitignore file update (dry-run)');\n } else {\n mergeContentsToAddWithGitignore(`${projectHome}/.gitignore`, ['.env']);\n log.raw('');\n }\n\n // Update CI Workflow\n const mappedWorkflow = await mapCIWorkflowContent(this, loc);\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 log.raw('');\n checkpoint('CI file updated');\n }\n }\n\n if (loc === '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 || messages.devinit.dryRunKeyMessage(dryRun),\n existingDeployKey?.sharedSecret ||\n messages.devinit.dryRunKeyMessage(dryRun)\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 // open the cms link -- if no classic token just return the cms url\n\n // go and fetch the classic token from auth service\n const classicToken = await this.auth?.ClassicToken();\n log.help(\n ansiEscapes.link(\n `Open Contensis`,\n `${this.urls?.cms}${\n classicToken ? `?SecurityToken=${classicToken}` : ''\n }`\n )\n );\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,0BAAwB;AACxB,yBAAe;AACf,2BAAsB;AACtB,sBAAqB;AACrB,yBAA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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;",
|
|
6
|
+
"names": ["ContensisRole", "blockId", "inquirer", "to", "ansiEscapes", "path"]
|
|
7
7
|
}
|
package/dist/shell.js
CHANGED
package/dist/shell.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/shell.ts"],
|
|
4
|
-
"sourcesContent": ["import figlet from 'figlet';\nimport inquirer from 'inquirer';\nimport inquirerPrompt from 'inquirer-command-prompt';\nimport commands from './commands';\nimport { LogMessages } from './localisation/en-GB';\nimport CredentialProvider from './providers/CredentialProvider';\nimport { appRootDir } from './providers/file-provider';\nimport ContensisCli, { cliCommand } from './services/ContensisCliService';\nimport { Logging } from './util';\nimport { logError, Logger } from './util/logger';\nimport { LIB_VERSION } from './version';\n\nclass ContensisShell {\n private currentEnvironment!: string;\n private emptyInputCounter: number = 0;\n private env!: EnvironmentCache;\n private firstStart = true;\n private userId: string = '';\n private log = Logger;\n private messages = LogMessages;\n\n private refreshEnvironment = () => {\n // Reload any persisted changes from the disk cache\n const {\n cache: { currentEnvironment = '', environments = {} },\n } = new ContensisCli([]);\n // console.log(`refreshing env w/${currentEnvironment}`);\n this.currentEnvironment = currentEnvironment;\n this.env = environments[currentEnvironment];\n\n // Reload logging here to support changing language\n Logging('en-GB').then(({ messages, Log }) => {\n this.log = Log;\n this.messages = messages;\n });\n };\n\n constructor() {\n this.refreshEnvironment();\n inquirerPrompt.setConfig({\n history: {\n save: true,\n folder: appRootDir,\n limit: 100,\n blacklist: ['quit'],\n },\n });\n\n const { log, messages } = this;\n\n figlet.text(\n messages.app.contensis(),\n {\n font: 'Block',\n horizontalLayout: 'default',\n verticalLayout: 'default',\n width: process.stdout.columns,\n whitespaceBreak: true,\n },\n (err, data) => {\n if (err) {\n log.error(messages.app.unknownError());\n console.dir(err);\n return;\n }\n console.log(log.successText(data));\n console.log(log.infoText(messages.app.startup(LIB_VERSION)));\n console.log(log.helpText(messages.app.help()));\n\n this.start().catch(ex => log.error(ex));\n }\n );\n }\n\n restart = async () => {\n this.firstStart = false;\n this.log.line(); // add a line so we can see where the shell has been restarted\n await this.start();\n };\n\n start = async () => {\n this.refreshEnvironment();\n this.userId = '';\n const { currentEnvironment, env, log, messages } = this;\n\n if (env?.lastUserId) {\n const [credsErr, credentials] = await new CredentialProvider(\n {\n userId: env.lastUserId,\n alias: currentEnvironment,\n },\n env.passwordFallback\n ).Init();\n if (credsErr && !credentials.current) {\n log.error(credsErr.message);\n }\n if (credentials.current) {\n if (this.firstStart) {\n const token = await cliCommand(['login', env.lastUserId]).Login(\n env.lastUserId,\n {\n promptPassword: false,\n silent: true,\n }\n );\n if (token) {\n this.userId = env.lastUserId;\n if (!env.currentProject) log.warning(messages.projects.tip());\n }\n this.firstStart = false;\n this.refreshEnvironment();\n } else {\n this.userId = env.lastUserId;\n }\n }\n }\n await this.contensisPrompt();\n };\n\n contensisPrompt = async (): Promise<any> => {\n const { currentEnvironment, env, log, messages, userId } = this;\n\n const availableCommands = [\n {\n filter: (str: string) => {\n return str.replace(/ \\[.*$/, '');\n },\n },\n 'connect',\n 'list envs',\n 'quit',\n ];\n\n if (currentEnvironment)\n availableCommands.push('login', 'list projects', 'set project');\n if (userId)\n availableCommands.push(\n 'create key',\n 'create project',\n 'create role',\n 'diff models',\n 'execute block action release',\n 'execute block action makelive',\n 'execute block action rollback',\n 'execute block action markasbroken',\n 'get assets',\n 'get block',\n 'get block logs',\n 'get contenttype',\n 'get component',\n 'get entries',\n 'get nodes',\n 'get model',\n 'get project',\n 'get role',\n 'get token',\n 'get version',\n 'get webhook',\n 'get workflow',\n 'import contenttypes',\n 'import components',\n 'import entries',\n 'import models',\n 'import nodes',\n 'list blocks',\n 'list contenttypes',\n 'list components',\n 'list keys',\n 'list models',\n 'list proxies',\n 'list renderers',\n 'list roles',\n 'list webhooks',\n 'list workflows',\n 'push block',\n 'remove components',\n 'remove contenttypes',\n 'remove key',\n 'remove entries',\n 'remove nodes',\n 'remove role',\n 'set project name',\n 'set project description',\n 'set role name',\n 'set role description',\n 'set role assignments',\n 'set role enabled',\n 'set role permissions'\n );\n\n const prompt = inquirer.createPromptModule();\n prompt.registerPrompt('command', inquirerPrompt);\n return prompt([\n {\n type: 'command',\n name: 'cmd',\n autoCompletion: availableCommands.sort(),\n autocompletePrompt: log.infoText(messages.app.autocomplete()),\n message: `${userId ? `${userId}@` : ''}${currentEnvironment || ''}>`,\n context: 0,\n validate: (val: string) => {\n if (!val) this.emptyInputCounter++;\n if (this.emptyInputCounter > 1)\n console.log(this.log.infoText(this.messages.app.suggestions()));\n if (val) {\n this.emptyInputCounter = 0;\n return true;\n }\n },\n prefix: `${env?.currentProject || log.infoText('contensis')}`,\n short: true,\n },\n ])\n .then(async (answers: { cmd: string }) => {\n if (answers.cmd === 'quit') {\n this.quit();\n } else {\n try {\n if (answers.cmd) {\n const program = commands();\n await program.parseAsync(\n answers.cmd\n .match(/\"[^\"]+\"|[^\\s]+/g)\n ?.map(e => e.replace(/\"(.+)\"/, '$1')),\n {\n from: 'user',\n }\n );\n }\n } catch (ex: any) {\n const str = ex.toString();\n if (!str.includes('CommanderError'))\n logError(\n ex,\n `Shell ${\n ex instanceof Error\n ? ex.toString()\n : JSON.stringify(ex, null, 2)\n }`\n );\n } finally {\n return this.contensisPrompt();\n }\n }\n })\n .catch((err: Error) => {\n log.error(err.message);\n this.quit();\n });\n };\n\n quit = (error?: Error) => {\n const { log, messages } = this;\n process.removeAllListeners('exit');\n\n if (error) {\n log.error(error.message);\n process.exit(1);\n } else {\n log.success(messages.app.quit());\n process.exitCode = 0;\n process.exit(0);\n }\n };\n}\n\nlet globalShell: ContensisShell;\n\nexport const shell = () => {\n // Return a benign function for shell().restart() when used in cli context\n // as some commands need to restart the shell to show an updated prompt\n // after successful connect / login / set project\n if (typeof process.argv?.[2] !== 'undefined')\n return {\n quit: ContensisCli.quit,\n restart() {},\n } as any;\n if (!globalShell) globalShell = new ContensisShell();\n return globalShell;\n};\n\nprocess.on('uncaughtException', function (err) {\n // Handle the error safely\n console.log(err);\n});\n\nprocess.on('SIGINT', () => {\n Logger.warning('received SIGINT');\n shell().quit();\n // setTimeout(() => {\n // }, 2000);\n});\n\nprocess.on('SIGTERM', () => {\n Logger.warning('received SIGTERM');\n shell().quit();\n});\n\nprocess.stdin.on('data', key => {\n if ((key as any) == '\\u0003') {\n console.log('');\n Logger.info(`[CTRL]+[C] detected, exiting shell...`);\n shell().quit();\n }\n});\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,sBAAqB;AACrB,qCAA2B;AAC3B,sBAAqB;AACrB,mBAA4B;AAC5B,gCAA+B;AAC/B,2BAA2B;AAC3B,iCAAyC;AACzC,kBAAwB;AACxB,oBAA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AA,QACA,QAAQ,IAAG,2BAAK,mBAAkB,IAAI,SAAS,WAAW;AAAA,QAC1D,OAAO;AAAA,MACT;AAAA,IACF,CAAC,EACE,KAAK,OAAO,YAA6B;
|
|
4
|
+
"sourcesContent": ["import figlet from 'figlet';\nimport inquirer from 'inquirer';\nimport inquirerPrompt from 'inquirer-command-prompt';\nimport commands from './commands';\nimport { LogMessages } from './localisation/en-GB';\nimport CredentialProvider from './providers/CredentialProvider';\nimport { appRootDir } from './providers/file-provider';\nimport ContensisCli, { cliCommand } from './services/ContensisCliService';\nimport { Logging } from './util';\nimport { logError, Logger } from './util/logger';\nimport { LIB_VERSION } from './version';\n\nclass ContensisShell {\n private currentEnvironment!: string;\n private emptyInputCounter: number = 0;\n private env!: EnvironmentCache;\n private firstStart = true;\n private userId: string = '';\n private log = Logger;\n private messages = LogMessages;\n\n private refreshEnvironment = () => {\n // Reload any persisted changes from the disk cache\n const {\n cache: { currentEnvironment = '', environments = {} },\n } = new ContensisCli([]);\n // console.log(`refreshing env w/${currentEnvironment}`);\n this.currentEnvironment = currentEnvironment;\n this.env = environments[currentEnvironment];\n\n // Reload logging here to support changing language\n Logging('en-GB').then(({ messages, Log }) => {\n this.log = Log;\n this.messages = messages;\n });\n };\n\n constructor() {\n this.refreshEnvironment();\n inquirerPrompt.setConfig({\n history: {\n save: true,\n folder: appRootDir,\n limit: 100,\n blacklist: ['quit'],\n },\n });\n\n const { log, messages } = this;\n\n figlet.text(\n messages.app.contensis(),\n {\n font: 'Block',\n horizontalLayout: 'default',\n verticalLayout: 'default',\n width: process.stdout.columns,\n whitespaceBreak: true,\n },\n (err, data) => {\n if (err) {\n log.error(messages.app.unknownError());\n console.dir(err);\n return;\n }\n console.log(log.successText(data));\n console.log(log.infoText(messages.app.startup(LIB_VERSION)));\n console.log(log.helpText(messages.app.help()));\n\n this.start().catch(ex => log.error(ex));\n }\n );\n }\n\n restart = async () => {\n this.firstStart = false;\n this.log.line(); // add a line so we can see where the shell has been restarted\n await this.start();\n };\n\n start = async () => {\n this.refreshEnvironment();\n this.userId = '';\n const { currentEnvironment, env, log, messages } = this;\n\n if (env?.lastUserId) {\n const [credsErr, credentials] = await new CredentialProvider(\n {\n userId: env.lastUserId,\n alias: currentEnvironment,\n },\n env.passwordFallback\n ).Init();\n if (credsErr && !credentials.current) {\n log.error(credsErr.message);\n }\n if (credentials.current) {\n if (this.firstStart) {\n const token = await cliCommand(['login', env.lastUserId]).Login(\n env.lastUserId,\n {\n promptPassword: false,\n silent: true,\n }\n );\n if (token) {\n this.userId = env.lastUserId;\n if (!env.currentProject) log.warning(messages.projects.tip());\n }\n this.firstStart = false;\n this.refreshEnvironment();\n } else {\n this.userId = env.lastUserId;\n }\n }\n }\n await this.contensisPrompt();\n };\n\n contensisPrompt = async (): Promise<any> => {\n const { currentEnvironment, env, log, messages, userId } = this;\n\n const availableCommands = [\n {\n filter: (str: string) => {\n return str.replace(/ \\[.*$/, '');\n },\n },\n 'connect',\n 'list envs',\n 'quit',\n ];\n\n if (currentEnvironment)\n availableCommands.push('login', 'list projects', 'set project');\n if (userId)\n availableCommands.push(\n 'create key',\n 'create project',\n 'create role',\n 'diff models',\n 'execute block action release',\n 'execute block action makelive',\n 'execute block action rollback',\n 'execute block action markasbroken',\n 'get assets',\n 'get block',\n 'get block logs',\n 'get contenttype',\n 'get component',\n 'get entries',\n 'get nodes',\n 'get model',\n 'get project',\n 'get proxy',\n 'get renderer',\n 'get role',\n 'get token',\n 'get version',\n 'get webhook',\n 'get workflow',\n 'import contenttypes',\n 'import components',\n 'import entries',\n 'import models',\n 'import nodes',\n 'list blocks',\n 'list contenttypes',\n 'list components',\n 'list keys',\n 'list models',\n 'list proxies',\n 'list renderers',\n 'list roles',\n 'list webhooks',\n 'list workflows',\n 'push block',\n 'remove components',\n 'remove contenttypes',\n 'remove key',\n 'remove entries',\n 'remove nodes',\n 'remove role',\n 'set project name',\n 'set project description',\n 'set role name',\n 'set role description',\n 'set role assignments',\n 'set role enabled',\n 'set role permissions'\n );\n\n const prompt = inquirer.createPromptModule();\n prompt.registerPrompt('command', inquirerPrompt);\n return prompt([\n {\n type: 'command',\n name: 'cmd',\n autoCompletion: availableCommands.sort(),\n autocompletePrompt: log.infoText(messages.app.autocomplete()),\n message: `${userId ? `${userId}@` : ''}${currentEnvironment || ''}>`,\n context: 0,\n validate: (val: string) => {\n if (!val) this.emptyInputCounter++;\n if (this.emptyInputCounter > 1)\n console.log(this.log.infoText(this.messages.app.suggestions()));\n if (val) {\n this.emptyInputCounter = 0;\n return true;\n }\n },\n prefix: `${env?.currentProject || log.infoText('contensis')}`,\n short: true,\n },\n ])\n .then(async (answers: { cmd: string }) => {\n if (answers.cmd === 'quit') {\n this.quit();\n } else {\n try {\n if (answers.cmd) {\n const program = commands();\n await program.parseAsync(\n answers.cmd\n .match(/\"[^\"]+\"|[^\\s]+/g)\n ?.map(e => e.replace(/\"(.+)\"/, '$1')),\n {\n from: 'user',\n }\n );\n }\n } catch (ex: any) {\n const str = ex.toString();\n if (!str.includes('CommanderError'))\n logError(\n ex,\n `Shell ${\n ex instanceof Error\n ? ex.toString()\n : JSON.stringify(ex, null, 2)\n }`\n );\n } finally {\n return this.contensisPrompt();\n }\n }\n })\n .catch((err: Error) => {\n log.error(err.message);\n this.quit();\n });\n };\n\n quit = (error?: Error) => {\n const { log, messages } = this;\n process.removeAllListeners('exit');\n\n if (error) {\n log.error(error.message);\n process.exit(1);\n } else {\n log.success(messages.app.quit());\n process.exitCode = 0;\n process.exit(0);\n }\n };\n}\n\nlet globalShell: ContensisShell;\n\nexport const shell = () => {\n // Return a benign function for shell().restart() when used in cli context\n // as some commands need to restart the shell to show an updated prompt\n // after successful connect / login / set project\n if (typeof process.argv?.[2] !== 'undefined')\n return {\n quit: ContensisCli.quit,\n restart() {},\n } as any;\n if (!globalShell) globalShell = new ContensisShell();\n return globalShell;\n};\n\nprocess.on('uncaughtException', function (err) {\n // Handle the error safely\n console.log(err);\n});\n\nprocess.on('SIGINT', () => {\n Logger.warning('received SIGINT');\n shell().quit();\n // setTimeout(() => {\n // }, 2000);\n});\n\nprocess.on('SIGTERM', () => {\n Logger.warning('received SIGTERM');\n shell().quit();\n});\n\nprocess.stdin.on('data', key => {\n if ((key as any) == '\\u0003') {\n console.log('');\n Logger.info(`[CTRL]+[C] detected, exiting shell...`);\n shell().quit();\n }\n});\n\n// process.env.http_proxy = 'http://127.0.0.1:8888';\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,sBAAqB;AACrB,qCAA2B;AAC3B,sBAAqB;AACrB,mBAA4B;AAC5B,gCAA+B;AAC/B,2BAA2B;AAC3B,iCAAyC;AACzC,kBAAwB;AACxB,oBAAiC;AACjC,qBAA4B;AAE5B,MAAM,eAAe;AAAA,EACX;AAAA,EACA,oBAA4B;AAAA,EAC5B;AAAA,EACA,aAAa;AAAA,EACb,SAAiB;AAAA,EACjB,MAAM;AAAA,EACN,WAAW;AAAA,EAEX,qBAAqB,MAAM;AAEjC,UAAM;AAAA,MACJ,OAAO,EAAE,qBAAqB,IAAI,eAAe,CAAC,EAAE;AAAA,IACtD,IAAI,IAAI,2BAAAA,QAAa,CAAC,CAAC;AAEvB,SAAK,qBAAqB;AAC1B,SAAK,MAAM,aAAa;AAGxB,6BAAQ,OAAO,EAAE,KAAK,CAAC,EAAE,UAAU,IAAI,MAAM;AAC3C,WAAK,MAAM;AACX,WAAK,WAAW;AAAA,IAClB,CAAC;AAAA,EACH;AAAA,EAEA,cAAc;AACZ,SAAK,mBAAmB;AACxB,mCAAAC,QAAe,UAAU;AAAA,MACvB,SAAS;AAAA,QACP,MAAM;AAAA,QACN,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,WAAW,CAAC,MAAM;AAAA,MACpB;AAAA,IACF,CAAC;AAED,UAAM,EAAE,KAAK,SAAS,IAAI;AAE1B,kBAAAC,QAAO;AAAA,MACL,SAAS,IAAI,UAAU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3
2
|
var __defProp = Object.defineProperty;
|
|
4
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
6
|
var __export = (target, all) => {
|
|
9
7
|
for (var name in all)
|
|
@@ -17,28 +15,22 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
15
|
}
|
|
18
16
|
return to;
|
|
19
17
|
};
|
|
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
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
25
19
|
var csv_formatter_exports = {};
|
|
26
20
|
__export(csv_formatter_exports, {
|
|
27
21
|
csvFormatter: () => csvFormatter
|
|
28
22
|
});
|
|
29
23
|
module.exports = __toCommonJS(csv_formatter_exports);
|
|
30
|
-
var import_flat = require("flat");
|
|
31
24
|
var import_json2csv = require("json2csv");
|
|
32
|
-
var
|
|
33
|
-
const flattenObject = (obj) => (0, import_flat.flatten)((0, import_deep_cleaner.default)(obj, ["workflow"]));
|
|
25
|
+
var import_json = require("./json.formatter");
|
|
34
26
|
const csvFormatter = (entries) => {
|
|
35
27
|
const flatEntries = [];
|
|
36
28
|
if (Array.isArray(entries))
|
|
37
29
|
for (const entry of entries) {
|
|
38
|
-
flatEntries.push(flattenObject(entry));
|
|
30
|
+
flatEntries.push((0, import_json.flattenObject)(entry));
|
|
39
31
|
}
|
|
40
32
|
else
|
|
41
|
-
flatEntries.push(flattenObject(entries));
|
|
33
|
+
flatEntries.push((0, import_json.flattenObject)(entries));
|
|
42
34
|
const json2csvParser = new import_json2csv.Parser();
|
|
43
35
|
const csv = json2csvParser.parse(flatEntries);
|
|
44
36
|
return csv;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/util/csv.formatter.ts"],
|
|
4
|
-
"sourcesContent": ["import {
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
4
|
+
"sourcesContent": ["import { Parser } from 'json2csv';\nimport { flattenObject } from './json.formatter';\n\nexport const csvFormatter = <T>(entries: T | T[]) => {\n // Flatten the passed in object\n const flatEntries = [];\n if (Array.isArray(entries))\n for (const entry of entries) {\n flatEntries.push(flattenObject(entry));\n }\n else flatEntries.push(flattenObject(entries));\n\n // Parse the flattened object to csv\n const json2csvParser = new Parser();\n const csv = json2csvParser.parse(flatEntries);\n\n return csv;\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAuB;AACvB,kBAA8B;AAEvB,MAAM,eAAe,CAAI,YAAqB;AAEnD,QAAM,cAAc,CAAC;AACrB,MAAI,MAAM,QAAQ,OAAO;AACvB,eAAW,SAAS,SAAS;AAC3B,kBAAY,SAAK,2BAAc,KAAK,CAAC;AAAA,IACvC;AAAA;AACG,gBAAY,SAAK,2BAAc,OAAO,CAAC;AAG5C,QAAM,iBAAiB,IAAI,uBAAO;AAClC,QAAM,MAAM,eAAe,MAAM,WAAW;AAE5C,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/util/diff.js
CHANGED
package/dist/util/diff.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/util/diff.ts"],
|
|
4
|
-
"sourcesContent": ["import chalk from 'chalk';\nimport { Change, diffLines } from 'diff';\nimport { normaliseLineEndings } from './os';\n\nexport const diffLogStrings = (updates: string, previous: string) => {\n const lastFewLines = previous.split('\\n').slice(-10);\n const incomingLines = updates.split('\\n');\n\n // Find the line indices in the incoming lines\n // of the last few lines previously rendered\n const incomingLineIndices = [];\n for (const lastRenderedLine of lastFewLines) {\n if (lastRenderedLine.length > 10)\n incomingLineIndices.push(incomingLines.lastIndexOf(lastRenderedLine));\n }\n\n // Get the new lines from the next position on from the last of the already shown lines\n const differentFromPos = Math.max(...incomingLineIndices, 0) + 1;\n // Return just the incoming lines from the position we matched\n return incomingLines.slice(differentFromPos).join('\\n');\n};\n\nexport const diffFileContent = (\n existingContent: string,\n newContent: string\n) => {\n const existingContentNormalised = normaliseLineEndings(existingContent, '\\n');\n const newContentNormalised = normaliseLineEndings(newContent, '\\n');\n\n const diff = diffLines(existingContentNormalised, newContentNormalised, {\n newlineIsToken: true,\n });\n const diffRanges = addDiffPositionInfo(diff);\n\n // Create formatted output for console\n const output: string[] = [];\n const lnSpaceLength = Math.max(\n ...diffRanges.map(d => d.startLineNumber.toString().length),\n 0\n );\n\n const lnSpaces = Array(lnSpaceLength).join(' ');\n\n let needsNewLine = false;\n for (let i = 0; i < diffRanges.length; i++) {\n const part = diffRanges[i];\n if (part.added || part.removed) {\n const colour = part.added ? 'green' : part.removed ? 'red' : 'grey';\n\n if (part.value !== '\\n') {\n if (needsNewLine) {\n output.push('\\n### --');\n needsNewLine = false;\n }\n output.push(\n `\\n${part.value\n .split('\\n')\n .map((ln, idx) =>\n ln.trim() !== ''\n ? `${\n part.startLineNumber ? part.startLineNumber + idx : lnSpaces\n }${part.added ? '+' : part.removed ? '-' : ' '} ${chalk[\n colour\n ](`${ln}`)}`\n : ln\n )\n .join('\\n')}`\n );\n } else needsNewLine = true;\n } else needsNewLine = true;\n }\n\n return output.join('');\n};\n\nconst addDiffPositionInfo = (diff: Change[]) => {\n const diffRanges: (Change & {\n startLineNumber: number;\n startColumn: number;\n endLineNumber: number;\n endColumn: number;\n })[] = [];\n\n let lineNumber = 0;\n let column = 0;\n for (let partIndex = 0; partIndex < diff.length; partIndex++) {\n const part = diff[partIndex];\n\n // // Skip any parts that aren't in `after`\n // if (part.removed === true) {\n // continue;\n // }\n\n const startLineNumber = lineNumber;\n const startColumn = column;\n\n // Split the part into lines. Loop throug these lines to find\n // the line no. and column at the end of this part.\n const substring = part.value;\n const lines = substring.split('\\n');\n lines.forEach((line, lineIndex) => {\n // The first `line` is actually just a continuation of the last line\n if (lineIndex === 0) {\n column += line.length;\n // All other lines come after a line break.\n } else if (lineIndex > 0) {\n lineNumber += 1;\n column = line.length;\n }\n });\n\n // Save a range for all of the parts with position info added\n if (part.added === true || part.removed === true) {\n diffRanges.push({\n startLineNumber: startLineNumber + 1,\n startColumn: startColumn,\n endLineNumber: lineNumber,\n endColumn: column,\n ...part,\n });\n }\n }\n return diffRanges;\n};\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,kBAAkC;AAClC,gBAAqC;AAE9B,MAAM,iBAAiB,CAAC,SAAiB,aAAqB;AACnE,QAAM,eAAe,SAAS,MAAM,IAAI,EAAE,MAAM,GAAG;AACnD,QAAM,gBAAgB,QAAQ,MAAM,IAAI;AAIxC,QAAM,sBAAsB,CAAC;AAC7B,aAAW,oBAAoB,cAAc;AAC3C,QAAI,iBAAiB,SAAS;AAC5B,0BAAoB,KAAK,cAAc,YAAY,gBAAgB,CAAC;AAAA,EACxE;AAGA,QAAM,mBAAmB,KAAK,IAAI,GAAG,qBAAqB,CAAC,IAAI;AAE/D,SAAO,cAAc,MAAM,gBAAgB,EAAE,KAAK,IAAI;AACxD;AAEO,MAAM,kBAAkB,CAC7B,iBACA,eACG;AACH,QAAM,gCAA4B,gCAAqB,iBAAiB,IAAI;AAC5E,QAAM,2BAAuB,gCAAqB,YAAY,IAAI;AAElE,QAAM,WAAO,uBAAU,2BAA2B,sBAAsB;AAAA,IACtE,gBAAgB;AAAA,EAClB,CAAC;AACD,QAAM,aAAa,oBAAoB,IAAI;AAG3C,QAAM,SAAmB,CAAC;AAC1B,QAAM,gBAAgB,KAAK;AAAA,IACzB,GAAG,WAAW,IAAI,OAAK,EAAE,gBAAgB,SAAS,EAAE,MAAM;AAAA,IAC1D;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,aAAa,EAAE,KAAK,GAAG;AAE9C,MAAI,eAAe;AACnB,WAAS,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;AAC1C,UAAM,OAAO,WAAW;AACxB,QAAI,KAAK,SAAS,KAAK,SAAS;AAC9B,YAAM,SAAS,KAAK,QAAQ,UAAU,KAAK,UAAU,QAAQ;AAE7D,UAAI,KAAK,UAAU,MAAM;AACvB,YAAI,cAAc;AAChB,iBAAO,KAAK,UAAU;AACtB,yBAAe;AAAA,QACjB;AACA,eAAO;AAAA,UACL;AAAA,EAAK,KAAK,MACP,MAAM,IAAI,EACV;AAAA,YAAI,CAAC,IAAI,QACR,GAAG,KAAK,MAAM,KACV,GACE,KAAK,kBAAkB,KAAK,kBAAkB,MAAM,WACnD,KAAK,QAAQ,MAAM,KAAK,UAAU,MAAM,OAAO,aAAAA,QAChD,QACA,GAAG,IAAI,MACT;AAAA,UACN,EACC,KAAK,IAAI;AAAA,QACd;AAAA,MACF;AAAO,uBAAe;AAAA,IACxB;AAAO,qBAAe;AAAA,EACxB;AAEA,SAAO,OAAO,KAAK,EAAE;
|
|
4
|
+
"sourcesContent": ["import chalk from 'chalk';\nimport { Change, diffLines } from 'diff';\nimport { normaliseLineEndings } from './os';\n\nexport const diffLogStrings = (updates: string, previous: string) => {\n const lastFewLines = previous.split('\\n').slice(-10);\n const incomingLines = updates.split('\\n');\n\n // Find the line indices in the incoming lines\n // of the last few lines previously rendered\n const incomingLineIndices = [];\n for (const lastRenderedLine of lastFewLines) {\n if (lastRenderedLine.length > 10)\n incomingLineIndices.push(incomingLines.lastIndexOf(lastRenderedLine));\n }\n\n // Get the new lines from the next position on from the last of the already shown lines\n const differentFromPos = Math.max(...incomingLineIndices, 0) + 1;\n // Return just the incoming lines from the position we matched\n return incomingLines.slice(differentFromPos).join('\\n');\n};\n\nexport const diffFileContent = (\n existingContent: string,\n newContent: string\n) => {\n const existingContentNormalised = normaliseLineEndings(existingContent, '\\n');\n const newContentNormalised = normaliseLineEndings(newContent, '\\n');\n\n const diff = diffLines(existingContentNormalised, newContentNormalised, {\n newlineIsToken: true,\n });\n const diffRanges = addDiffPositionInfo(diff);\n\n // Create formatted output for console\n const output: string[] = [];\n const lnSpaceLength = Math.max(\n ...diffRanges.map(d => d.startLineNumber.toString().length),\n 0\n );\n\n const lnSpaces = Array(lnSpaceLength).join(' ');\n\n let needsNewLine = false;\n for (let i = 0; i < diffRanges.length; i++) {\n const part = diffRanges[i];\n if (part.added || part.removed) {\n const colour = part.added ? 'green' : part.removed ? 'red' : 'grey';\n\n if (part.value !== '\\n') {\n if (needsNewLine) {\n output.push('\\n### --');\n needsNewLine = false;\n }\n output.push(\n `\\n${part.value\n .split('\\n')\n .map((ln, idx) =>\n ln.trim() !== ''\n ? `${\n part.startLineNumber ? part.startLineNumber + idx : lnSpaces\n }${part.added ? '+' : part.removed ? '-' : ' '} ${chalk[\n colour\n ](`${ln}`)}`\n : ln\n )\n .join('\\n')}`\n );\n } else needsNewLine = true;\n } else needsNewLine = true;\n }\n\n return output.join('').replaceAll('\\n\\n\\n', '\\n\\n');\n};\n\nconst addDiffPositionInfo = (diff: Change[]) => {\n const diffRanges: (Change & {\n startLineNumber: number;\n startColumn: number;\n endLineNumber: number;\n endColumn: number;\n })[] = [];\n\n let lineNumber = 0;\n let column = 0;\n for (let partIndex = 0; partIndex < diff.length; partIndex++) {\n const part = diff[partIndex];\n\n // // Skip any parts that aren't in `after`\n // if (part.removed === true) {\n // continue;\n // }\n\n const startLineNumber = lineNumber;\n const startColumn = column;\n\n // Split the part into lines. Loop throug these lines to find\n // the line no. and column at the end of this part.\n const substring = part.value;\n const lines = substring.split('\\n');\n lines.forEach((line, lineIndex) => {\n // The first `line` is actually just a continuation of the last line\n if (lineIndex === 0) {\n column += line.length;\n // All other lines come after a line break.\n } else if (lineIndex > 0) {\n lineNumber += 1;\n column = line.length;\n }\n });\n\n // Save a range for all of the parts with position info added\n if (part.added === true || part.removed === true) {\n diffRanges.push({\n startLineNumber: startLineNumber + 1,\n startColumn: startColumn,\n endLineNumber: lineNumber,\n endColumn: column,\n ...part,\n });\n }\n }\n return diffRanges;\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,kBAAkC;AAClC,gBAAqC;AAE9B,MAAM,iBAAiB,CAAC,SAAiB,aAAqB;AACnE,QAAM,eAAe,SAAS,MAAM,IAAI,EAAE,MAAM,GAAG;AACnD,QAAM,gBAAgB,QAAQ,MAAM,IAAI;AAIxC,QAAM,sBAAsB,CAAC;AAC7B,aAAW,oBAAoB,cAAc;AAC3C,QAAI,iBAAiB,SAAS;AAC5B,0BAAoB,KAAK,cAAc,YAAY,gBAAgB,CAAC;AAAA,EACxE;AAGA,QAAM,mBAAmB,KAAK,IAAI,GAAG,qBAAqB,CAAC,IAAI;AAE/D,SAAO,cAAc,MAAM,gBAAgB,EAAE,KAAK,IAAI;AACxD;AAEO,MAAM,kBAAkB,CAC7B,iBACA,eACG;AACH,QAAM,gCAA4B,gCAAqB,iBAAiB,IAAI;AAC5E,QAAM,2BAAuB,gCAAqB,YAAY,IAAI;AAElE,QAAM,WAAO,uBAAU,2BAA2B,sBAAsB;AAAA,IACtE,gBAAgB;AAAA,EAClB,CAAC;AACD,QAAM,aAAa,oBAAoB,IAAI;AAG3C,QAAM,SAAmB,CAAC;AAC1B,QAAM,gBAAgB,KAAK;AAAA,IACzB,GAAG,WAAW,IAAI,OAAK,EAAE,gBAAgB,SAAS,EAAE,MAAM;AAAA,IAC1D;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,aAAa,EAAE,KAAK,GAAG;AAE9C,MAAI,eAAe;AAC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AAA,QACf,WAAW;AAAA,QACX,GAAG;AAAA,MACL,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": ["chalk"]
|
|
7
7
|
}
|
package/dist/util/git.js
CHANGED
package/dist/util/git.js.map
CHANGED
|
@@ -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 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,eAAe,KAAK;AAAA,EACrC;AAAA,EACA,IAAI,OAAO;AA1Cb;AA2CI,aACE,UAAK,SAAL,mBAAW,cAAW,UAAK,SAAL,mBAAW,MAAM,KAAK,UAAS;AAAA,EAEzD;AAAA,EACA,IAAI,YAAY;AA/ClB;AAgDI,UAAM,aAAY,8CAAM,WAAN,mBAAc,WAAd,mBAAsB,WAAtB,mBAA8B;AAChD,QAAI;AAAW,aAAO;AAAA,EACxB;AAAA,EACA,IAAI,aAAa;AACf,WAAO,GACL,KAAK,SAAS,WACV,GAAG,KAAK,kCACR,GAAG,KAAK;AAAA,EAEhB;AAAA,EACA,IAAI,OAAO;AA1Db;AA2DI,aAAO,UAAK,SAAL,mBAAW,SAAQ,KAAK,SAAS;AAAA,EAC1C;AAAA,EACA,IAAI,YAAY;AACd,WAAO,KAAK,SAAS,WACjB,KAAK,gBAAgB,IACrB,KAAK,eAAe;AAAA,EAC1B;AAAA,EACA,YAAY,cAAsB,QAAQ,IAAI,GAAG;AAC/C,SAAK,cAAc;AACnB,SAAK,SAAS,KAAK,UAAU;AAC7B,SAAK,OAAO,cAAAA,QAAO,MAAM,KAAK,SAAS;AACvC,SAAK,OAAO,KAAK,QAAQ;AAAA,EAI3B;AAAA,EACA,SAAS,MAAM,YAAAC,QAAK,KAAK,KAAK,WAAW;AAAA,EACzC,UAAU,CAAC,MAAc,KAAK,cAAc,uBAAAC,QAAc,QAAQ,GAAG;AAAA,EACrE,WAAW,CAAC,MAAc,KAAK,
|
|
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 | undefined => {\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 cwd,\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,eAAe,KAAK;AAAA,EACrC;AAAA,EACA,IAAI,OAAO;AA1Cb;AA2CI,aACE,UAAK,SAAL,mBAAW,cAAW,UAAK,SAAL,mBAAW,MAAM,KAAK,UAAS;AAAA,EAEzD;AAAA,EACA,IAAI,YAAY;AA/ClB;AAgDI,UAAM,aAAY,8CAAM,WAAN,mBAAc,WAAd,mBAAsB,WAAtB,mBAA8B;AAChD,QAAI;AAAW,aAAO;AAAA,EACxB;AAAA,EACA,IAAI,aAAa;AACf,WAAO,GACL,KAAK,SAAS,WACV,GAAG,KAAK,kCACR,GAAG,KAAK;AAAA,EAEhB;AAAA,EACA,IAAI,OAAO;AA1Db;AA2DI,aAAO,UAAK,SAAL,mBAAW,SAAQ,KAAK,SAAS;AAAA,EAC1C;AAAA,EACA,IAAI,YAAY;AACd,WAAO,KAAK,SAAS,WAC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