autoforce 0.1.3 → 0.1.5

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.
Files changed (48) hide show
  1. package/README.md +85 -7
  2. package/commands/modelA/new/issue.json +40 -0
  3. package/commands/modelA/new/process.json +21 -0
  4. package/commands/modelA/subtasks/checkout-branch.json +60 -0
  5. package/commands/modelA/subtasks/create-pull.json +20 -0
  6. package/commands/modelA/subtasks/create-scratch.json +84 -0
  7. package/commands/modelA/subtasks/deploy-code.json +17 -0
  8. package/commands/modelA/subtasks/drop-scratch.json +17 -0
  9. package/commands/modelA/subtasks/package-code.json +3 -0
  10. package/commands/modelA/subtasks/publish-branch.json +20 -0
  11. package/commands/modelA/subtasks/update-documentation.json +8 -0
  12. package/commands/modelA/subtasks/validate-code.json +29 -0
  13. package/commands/modelA/subtasks/validate-scratch.json +14 -0
  14. package/commands/modelA/tasks/cancel.json +6 -0
  15. package/commands/modelA/tasks/deploy.json +6 -0
  16. package/commands/modelA/tasks/finish.json +41 -0
  17. package/commands/modelA/tasks/rollback.json +6 -0
  18. package/commands/modelA/tasks/start.json +60 -0
  19. package/commands/modelA/tasks/stop.json +32 -0
  20. package/commands/modelA/tasks/switch.json +53 -0
  21. package/commands/modelA/tasks/view.json +12 -0
  22. package/lib/auto.js +30 -15
  23. package/lib/helpers/class.js +2 -2
  24. package/lib/helpers/color.d.ts +1 -0
  25. package/lib/helpers/color.js +4 -1
  26. package/lib/helpers/context.d.ts +14 -2
  27. package/lib/helpers/context.js +60 -35
  28. package/lib/helpers/lwc.js +2 -2
  29. package/lib/helpers/metadata.js +2 -2
  30. package/lib/helpers/object.js +2 -2
  31. package/lib/helpers/tasks.js +10 -5
  32. package/lib/helpers/util.d.ts +18 -4
  33. package/lib/helpers/util.js +104 -5
  34. package/package.json +12 -4
  35. package/templates/dictionary/class-all.md +9 -0
  36. package/templates/dictionary/class-diagrama.md +13 -0
  37. package/templates/dictionary/class-inner.md +19 -0
  38. package/templates/dictionary/class-metodos.md +15 -0
  39. package/templates/dictionary/class-public.md +13 -0
  40. package/templates/dictionary/class-referencias.md +5 -0
  41. package/templates/dictionary/class.md +29 -0
  42. package/templates/dictionary/classes.md +52 -0
  43. package/templates/dictionary/object.md +35 -0
  44. package/templates/dictionary/objects.md +63 -0
  45. package/templates/intro.md +20 -0
  46. package/templates/process.md +23 -0
  47. package/templates/story.md +32 -0
  48. package/templates/usecase.md +52 -0
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "switch",
3
+ "guards": ["isGitApi"],
4
+ "arguments": ["newIssueNumber"],
5
+ "description": "Comando para cambiar el requerimiento a desarrollar",
6
+ "steps": [
7
+ {
8
+ "name": "validate issue",
9
+ "function": "validateIssue",
10
+ "arguments": ["${newIssueNumber}", "In Progress"],
11
+ "description": "Valida que Issue este en la Columna In Progress",
12
+ "errorMessage": "Por favor verifique que el issue ${newIssueNumber} este en la columna In Progress"
13
+ },
14
+ {
15
+ "name": "check Issue type based on Labels",
16
+ "function": "checkIssueType",
17
+ "arguments": ["${newIssueNumber}"],
18
+ "description": "Verifica si el issueType es de Desarrollo o No segun los labels (no desa son automation, documentation)"
19
+ },
20
+ {
21
+ "name": "Se fija que este parado en ${newBranchName}",
22
+ "function": "validaNoseaBranchActual",
23
+ "arguments": ["${newBranchName}"],
24
+ "description": "Valida que no sea la branch actual",
25
+ "errorMessage": "Ya esta parado sobre la branch ${newBranchName}"
26
+ },
27
+ {
28
+ "criteria": { "field": "isDevelopment", "value": true },
29
+ "subtask": "update-documentation"
30
+ },
31
+ {
32
+ "criteria": { "field": "isDevelopment", "value": true },
33
+ "subtask": "validate-scratch"
34
+ },
35
+ { "subtask": "checkout-branch", "arguments": ["${newBranchName}"] },
36
+ {
37
+ "criteria": { "field": "isNewDevelopment", "value": true },
38
+ "name": "switch scratch",
39
+ "command": "sf force config set target-org",
40
+ "arguments": { "--target-org": "${newBranchName}" },
41
+ "description": "Cambia la scratch",
42
+ "errorMessage": "No se pudo mover al scratch ${newBranchName}. Hagalo manualmente ${command}"
43
+ },
44
+ {
45
+ "criteria": { "field": "isNewDevelopment", "value": true },
46
+ "name": "deploy scratch localmente",
47
+ "command": "sf project deploy start",
48
+ "arguments": { "--target-org": "${newBranchName}" },
49
+ "description": "Deploy por si hubo cambios en main",
50
+ "errorMessage": "No se pudo mover al scratch ${newBranchName}. Hagalo manualmente ${command}"
51
+ }
52
+ ]
53
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "view",
3
+ "guards": ["isGitApi"],
4
+ "description": "Comando para ver en detalle el requerimiento",
5
+ "steps": [
6
+ {
7
+ "name": "Ver datos del issue",
8
+ "function": "viewIssue",
9
+ "arguments": ["${issueNumber}"]
10
+ }
11
+ ]
12
+ }
package/lib/auto.js CHANGED
@@ -10,32 +10,47 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  // Comandos validos
11
11
  import { createObject, validateTask, getTasks, helpTask, runTask, getTaskFolder } from "./helpers/tasks.js";
12
12
  import { logError } from "./helpers/color.js";
13
- import { createConfigurationFile } from "./helpers/context.js";
14
13
  import prompts from "prompts";
15
- const proxyCommnad = {
14
+ import { createConfigurationFile } from "./helpers/util.js";
15
+ const proxyCommand = {
16
+ 'version': showVersion,
17
+ 'config': createConfigurationFile
18
+ };
19
+ const taskCommand = {
16
20
  'help': helpTask,
17
21
  'task': runTask,
18
22
  'new': runTask,
19
- 'config': createConfigurationFile,
20
23
  'subtask': runTask
21
24
  };
25
+ function showVersion() {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ console.log('AutoForce v0.1.4');
28
+ return true;
29
+ });
30
+ }
22
31
  export default function main() {
23
32
  return __awaiter(this, void 0, void 0, function* () {
24
33
  try {
25
34
  const config = getConfigFromArgs(process.argv.slice(2));
26
- const tasks = getTasks(config.taskFolder);
27
- const taskName = yield askForTaskName(config.taskName, tasks);
28
- if (taskName) {
29
- const task = tasks[taskName];
30
- const options = config.arguments && task.arguments ? Object.assign(Object.assign({}, config.options), createObject(task.arguments, config.arguments)) : config.options;
31
- // Valida los json de task y subtask
32
- if (validateTask(task)) {
33
- yield proxyCommnad[config.command](task, options);
34
- }
35
- else {
36
- logError('Verifique que los json de task y subtask esten validos');
35
+ const taskCommandKeys = Object.keys(taskCommand);
36
+ if (taskCommandKeys.includes(config.command)) {
37
+ const tasks = getTasks(config.taskFolder);
38
+ const taskName = yield askForTaskName(config.taskName, tasks);
39
+ if (taskName) {
40
+ const task = tasks[taskName];
41
+ const options = config.arguments && task.arguments ? Object.assign(Object.assign({}, config.options), createObject(task.arguments, config.arguments)) : config.options;
42
+ // Valida los json de task y subtask
43
+ if (validateTask(task)) {
44
+ yield taskCommand[config.command](task, options);
45
+ }
46
+ else {
47
+ logError('Verifique que los json de task y subtask esten validos');
48
+ }
37
49
  }
38
50
  }
51
+ else {
52
+ yield proxyCommand[config.command]();
53
+ }
39
54
  }
40
55
  catch (error) {
41
56
  if (error instanceof Error) {
@@ -59,7 +74,7 @@ export function getConfigFromArgs(processArgs) {
59
74
  }
60
75
  // De acuerdo a args separa comando[help, preview, task o subtask] de taskName
61
76
  let currentArgument = args.shift();
62
- const comandosValidos = Object.keys(proxyCommnad);
77
+ const comandosValidos = [...Object.keys(proxyCommand), ...Object.keys(taskCommand)];
63
78
  if (currentArgument && comandosValidos.includes(currentArgument)) {
64
79
  config.command = currentArgument;
65
80
  currentArgument = args.shift();
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import sf from "./connect.js";
11
11
  import templateGenerator from "./template.js";
12
12
  const templateEngine = templateGenerator("dictionary", "md");
13
- import { sortByName, getNamesByExtension, verFecha, splitFilename, DICTIONARY_FOLDER, DOCS_FOLDER } from "./util.js";
13
+ import { sortByName, getNamesByExtension, verFecha, splitFilename, DICTIONARY_FOLDER, TEMPLATES_FOLDER } from "./util.js";
14
14
  function getMetadata(clases) {
15
15
  return __awaiter(this, void 0, void 0, function* () {
16
16
  try {
@@ -189,7 +189,7 @@ function executeClasses(items, filename, folder) {
189
189
  classLink
190
190
  }
191
191
  });
192
- templateEngine.save(filename, DOCS_FOLDER + "/" + folder);
192
+ templateEngine.save(filename, TEMPLATES_FOLDER + "/" + folder);
193
193
  });
194
194
  }
195
195
  const classModule = {
@@ -1,3 +1,4 @@
1
1
  export declare function logError(message: string, tabs?: string): void;
2
+ export declare function logWarning(message: string, tabs?: string): void;
2
3
  export declare function logStep(message: string, tabs?: string): void;
3
4
  export declare function getColored(text: string, colorName: string): string;
@@ -24,7 +24,10 @@ const FgGray = "\x1b[90m";
24
24
  // const BgWhite = "\x1b[47m"
25
25
  // const BgGray = "\x1b[100m"
26
26
  export function logError(message, tabs = '') {
27
- console.error(getColored(`[ERROR] ${tabs}${message}`, "red"));
27
+ console.error(getColored(`[Error] ${tabs}${message}`, "red"));
28
+ }
29
+ export function logWarning(message, tabs = '') {
30
+ console.error(getColored(`[Warning] ${tabs}${message}`, "yellow"));
28
31
  }
29
32
  export function logStep(message, tabs = '') {
30
33
  console.info(getColored(`${tabs}${message}`, "green"));
@@ -1,9 +1,20 @@
1
1
  import type { PromptChoices } from "../types/helpers/context.js";
2
2
  import type { IProcessHeader, Processes, AnyValue, IProcessInfo, ObjectRecord, IObjectRecord } from "../types/auto.js";
3
3
  import type { TaskArguments, TaskArgument, StepArguments } from "../types/helpers/tasks.js";
4
- export declare function createConfigurationFile(): Promise<boolean>;
4
+ export declare enum GitServices {
5
+ GitHub = "github",
6
+ GitLab = "gitlab",
7
+ None = "none"
8
+ }
9
+ export declare enum GitProjects {
10
+ GitHub = "github",
11
+ GitLab = "gitlab",
12
+ Jira = "Jira",
13
+ None = "none"
14
+ }
5
15
  declare class Context implements IObjectRecord {
6
16
  [s: string]: AnyValue | undefined;
17
+ gitServices: GitServices;
7
18
  isGitApi: boolean;
8
19
  gitApi: IGitApi | undefined;
9
20
  projectApi: IProjectApi | undefined;
@@ -32,7 +43,7 @@ declare class Context implements IObjectRecord {
32
43
  repositoryType: string | undefined;
33
44
  repositoryOwner: string | undefined;
34
45
  repositoryRepo: string | undefined;
35
- projectNumber: number | undefined;
46
+ projectId: string | undefined;
36
47
  loadGitApi(): void;
37
48
  loadPackage(): void;
38
49
  loadConfig(): void;
@@ -77,4 +88,5 @@ declare class Context implements IObjectRecord {
77
88
  merge(text: string): string;
78
89
  }
79
90
  declare const context: Context;
91
+ export declare function initializeContext(): void;
80
92
  export default context;
@@ -8,35 +8,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { executeShell, getOrganizationObject, getCurrentOrganization, getBranchName, getTargetOrg } from "./taskFunctions.js";
11
- import { convertNameToKey, convertKeyToName, getFiles, filterDirectory, addNewItems } from "./util.js";
11
+ import { convertNameToKey, convertKeyToName, getFiles, filterDirectory, addNewItems, CONFIG_FILE, createConfigurationFile } from "./util.js";
12
12
  import { GitHubApi } from "./github-graphql.js";
13
13
  import { GitLabApi } from "./gitlab-graphql.js";
14
14
  import prompts from "prompts";
15
15
  import matter from 'gray-matter';
16
16
  import fs from "fs";
17
- import { logError } from "./color.js";
17
+ import { logError, logWarning } from "./color.js";
18
+ export var GitServices;
19
+ (function (GitServices) {
20
+ GitServices["GitHub"] = "github";
21
+ GitServices["GitLab"] = "gitlab";
22
+ GitServices["None"] = "none";
23
+ })(GitServices = GitServices || (GitServices = {}));
24
+ export var GitProjects;
25
+ (function (GitProjects) {
26
+ GitProjects["GitHub"] = "github";
27
+ GitProjects["GitLab"] = "gitlab";
28
+ GitProjects["Jira"] = "Jira";
29
+ GitProjects["None"] = "none";
30
+ })(GitProjects = GitProjects || (GitProjects = {}));
18
31
  const filterProcesses = (fullPath) => fullPath.endsWith(".md"); // && !fullPath.endsWith("intro.md")
19
32
  const ISSUES_TYPES = [{ value: 'feature', title: 'feature' }, { value: 'bug', title: 'bug' }, { value: 'documentation', title: 'documentation' }, { value: 'automation', title: 'automation' }];
20
- const CONFIG_FILE = process.cwd() + '/.autoforce.json';
21
- export function createConfigurationFile() {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- console.log('Preguntar por GitHub o GitLab');
24
- console.log('Chequear las variables de entorno');
25
- console.log('Tema proyecto guardar la referencia');
26
- console.log('Genera documentacion');
27
- console.log('Direccion de las carpetas');
28
- const config = { projectNumber: 1 };
29
- try {
30
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
31
- }
32
- catch (_a) {
33
- throw new Error(`No se pudo guardar la configuracion en ${CONFIG_FILE}`);
34
- }
35
- return true;
36
- });
37
- }
38
33
  class Context {
39
34
  constructor() {
35
+ this.gitServices = GitServices.None;
40
36
  this.isGitApi = false;
41
37
  this.sfInstalled = true;
42
38
  this.sfToken = true;
@@ -48,20 +44,33 @@ class Context {
48
44
  this.salida = '';
49
45
  }
50
46
  loadGitApi() {
51
- if (!this.repositoryOwner || !this.repositoryRepo || !this.repositoryUrl) {
52
- throw new Error("Falta agregue repository en el package.json para obtener el Owner or Repo");
47
+ if (!this.gitServices && this.repositoryUrl) {
48
+ if (this.repositoryUrl.indexOf('github') > 0) {
49
+ this.gitServices = GitServices.GitHub;
50
+ }
51
+ else if (this.repositoryUrl.indexOf('gitlab') > 0) {
52
+ this.gitServices = GitServices.GitLab;
53
+ }
53
54
  }
54
- const isGithub = this.repositoryUrl.indexOf('github') > 0;
55
- const isGitlab = this.repositoryUrl.indexOf('gitlab') > 0;
56
- if (isGithub && process.env.GITHUB_TOKEN) {
57
- const token = process.env.GITHUB_TOKEN;
58
- this.gitApi = new GitHubApi(token, this.repositoryOwner, this.repositoryRepo, this.projectNumber);
59
- this.isGitApi = true;
55
+ if (this.gitServices == GitServices.GitHub && process.env.GITHUB_TOKEN) {
56
+ if (this.repositoryOwner && this.repositoryRepo && this.projectId && Number.isInteger(this.projectId)) {
57
+ const token = process.env.GITHUB_TOKEN;
58
+ this.gitApi = new GitHubApi(token, this.repositoryOwner, this.repositoryRepo, Number.parseInt(this.projectId));
59
+ this.isGitApi = true;
60
+ }
61
+ else {
62
+ logWarning(`No se pudo inicializar el conector a GitHub, Verifique repositoryOwner: ${this.repositoryOwner} o repositoryRepo: ${this.repositoryRepo} o projectId: ${this.projectId}`);
63
+ }
60
64
  }
61
- if (isGitlab && process.env.GITLAB_TOKEN) {
62
- const token = process.env.GITLAB_TOKEN;
63
- this.gitApi = new GitLabApi(token, this.repositoryOwner, this.repositoryRepo, this.projectNumber);
64
- this.isGitApi = true;
65
+ if (this.gitServices == GitServices.GitLab && process.env.GITLAB_TOKEN) {
66
+ if (this.repositoryOwner && this.repositoryRepo && this.projectId && Number.isInteger(this.projectId)) {
67
+ const token = process.env.GITLAB_TOKEN;
68
+ this.gitApi = new GitLabApi(token, this.repositoryOwner, this.repositoryRepo, Number.parseInt(this.projectId));
69
+ this.isGitApi = true;
70
+ }
71
+ else {
72
+ logWarning(`No se pudo inicializar el conector a GitLab, Verifique repositoryOwner: ${this.repositoryOwner} o repositoryRepo: ${this.repositoryRepo} o projectId: ${this.projectId}`);
73
+ }
65
74
  }
66
75
  }
67
76
  loadPackage() {
@@ -97,7 +106,9 @@ class Context {
97
106
  }
98
107
  loadConfig() {
99
108
  if (!fs.existsSync(CONFIG_FILE)) {
100
- logError('Aun no ha configurado autoforce, lo puede hacer mas tarde manualmente creando .autoforce.json en el root del proyecto o asisitido corriendo yarn init autoforce. O bien puede hacerlo ahora mismo :) ');
109
+ logWarning('Bienvenido! Antes de usar la herramienta, tenemos que configurarla.');
110
+ logWarning('Lo puedes hacer mas tarde manualmente leyendo la documentacion y creando .autoforce.json en el root del proyecto');
111
+ logWarning('O bien ahora con el asistente, el mismo lo puedes llamar todas las veces que necesites corriendo npx autoforce config!');
101
112
  createConfigurationFile();
102
113
  return;
103
114
  }
@@ -114,8 +125,8 @@ class Context {
114
125
  }
115
126
  init() {
116
127
  // Busca variables de entorno
117
- this.loadPackage();
118
128
  this.loadConfig();
129
+ this.loadPackage();
119
130
  this.loadGitApi();
120
131
  //
121
132
  this.branchName = getBranchName();
@@ -484,5 +495,19 @@ class Context {
484
495
  }
485
496
  }
486
497
  const context = new Context();
487
- context.init();
498
+ let initialized = false;
499
+ export function initializeContext() {
500
+ try {
501
+ if (!initialized) {
502
+ context.init();
503
+ initialized = true;
504
+ }
505
+ }
506
+ catch (error) {
507
+ if (error instanceof Error) {
508
+ logError(error.message);
509
+ }
510
+ process.exit(1);
511
+ }
512
+ }
488
513
  export default context;
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import sf from "./connect.js";
11
11
  import templateGenerator from "./template.js";
12
12
  const templateEngine = templateGenerator("dictionary", "md");
13
- import { sortByName, splitFilename, DICTIONARY_FOLDER, DOCS_FOLDER } from "./util.js";
13
+ import { sortByName, splitFilename, DICTIONARY_FOLDER, TEMPLATES_FOLDER } from "./util.js";
14
14
  function getMetadata(lwc) {
15
15
  return __awaiter(this, void 0, void 0, function* () {
16
16
  try {
@@ -59,7 +59,7 @@ function executeLwc(items, filename, folder) {
59
59
  templateEngine.render(lwcContext, {
60
60
  helpers: {}
61
61
  });
62
- templateEngine.save(filename, DOCS_FOLDER + "/" + folder);
62
+ templateEngine.save(filename, TEMPLATES_FOLDER + "/" + folder);
63
63
  });
64
64
  }
65
65
  const lwcModule = {
@@ -10,7 +10,7 @@ const helpers = {
10
10
  export default helpers;
11
11
  /*
12
12
  import context from "./context.js";
13
- import { DOCS_FOLDER } from "./util.js";
13
+ import { TEMPLATES_FOLDER } from "./util.js";
14
14
  import type { DocumentationModule, IProcessInfo, IMetadataNode, IMetadataComponentNode } from "../types/auto.js";
15
15
  function getMetadataFromContext(components: string[]) {
16
16
  return getMetadataArray(context.getProcessMetadata(), components);
@@ -66,7 +66,7 @@ function getMetadataArray(metadata: IProcessInfo[], props: string[]) {
66
66
  return items;
67
67
  };
68
68
 
69
- return getItemsFromTree({ folder: DOCS_FOLDER, childs: metadata });
69
+ return getItemsFromTree({ folder: TEMPLATES_FOLDER, childs: metadata });
70
70
  }
71
71
 
72
72
  export async function execute() {
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import sf from "./connect.js";
11
11
  import templateGenerator from "./template.js";
12
12
  const templateEngine = templateGenerator("dictionary", "md");
13
- import { sortByLabel, DICTIONARY_FOLDER, DOCS_FOLDER, } from "./util.js";
13
+ import { sortByLabel, DICTIONARY_FOLDER, TEMPLATES_FOLDER, } from "./util.js";
14
14
  function getMetadata(objetos) {
15
15
  return __awaiter(this, void 0, void 0, function* () {
16
16
  try {
@@ -123,7 +123,7 @@ function executeObjects(items, filename, folder) {
123
123
  templateEngine.render(objectContext, {
124
124
  helpers: { isManaged, isMetadataFormula, attributesFormula }
125
125
  });
126
- templateEngine.save(filename, DOCS_FOLDER + "/" + folder);
126
+ templateEngine.save(filename, TEMPLATES_FOLDER + "/" + folder);
127
127
  });
128
128
  }
129
129
  const objectModule = {
@@ -7,15 +7,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import context from "./context.js";
10
+ import context, { initializeContext } from "./context.js";
11
11
  import { logError, logStep } from "./color.js";
12
12
  import fs from "fs";
13
- import { getFiles, filterJson } from "./util.js";
13
+ import { getFiles, filterJson, searchInFolderHierarchy } from "./util.js";
14
14
  import { validateCommand, validateFunction, executeFunction, executeCommand, taskFunctions } from "./taskFunctions.js";
15
15
  import prompts from "prompts";
16
- export const TASKS_FOLDER = process.cwd() + "/commands/tasks";
17
- export const SUBTASKS_FOLDER = process.cwd() + "/commands/subtasks";
18
- export const NEW_FOLDER = process.cwd() + "/commands/new";
16
+ import { fileURLToPath } from 'url';
17
+ const COMMAND_FOLDER = searchInFolderHierarchy('commands', fileURLToPath(import.meta.url));
18
+ export const TASKS_FOLDER = `${COMMAND_FOLDER}/tasks`;
19
+ export const SUBTASKS_FOLDER = `${COMMAND_FOLDER}/subtasks`;
20
+ export const NEW_FOLDER = `${COMMAND_FOLDER}/new`;
19
21
  export function getTaskFolder(command) {
20
22
  const folders = {
21
23
  'task': TASKS_FOLDER,
@@ -70,6 +72,7 @@ export function helpTask(task) {
70
72
  });
71
73
  }
72
74
  export function validateTask(task) {
75
+ initializeContext();
73
76
  if (task.guards) {
74
77
  // Valida que sea
75
78
  }
@@ -103,6 +106,7 @@ export function validateTask(task) {
103
106
  }
104
107
  export function runTask(task, taskContext, tabs = '') {
105
108
  return __awaiter(this, void 0, void 0, function* () {
109
+ initializeContext();
106
110
  // Valida que este ya esten las variables de enotorno y configuracion
107
111
  if (task.guards) {
108
112
  yield context.validate(task.guards);
@@ -128,6 +132,7 @@ export function runTask(task, taskContext, tabs = '') {
128
132
  }
129
133
  export function previewTask(task, tabs = '') {
130
134
  return __awaiter(this, void 0, void 0, function* () {
135
+ initializeContext();
131
136
  logStep(`${task.name}: ${task.description}`, tabs);
132
137
  for (const step of task.steps) {
133
138
  previewStep(step, tabs);
@@ -1,6 +1,22 @@
1
- export declare const DOCS_FOLDER: string;
1
+ export declare const TEMPLATES_FOLDER: string;
2
2
  export declare const DICTIONARY_FOLDER: string;
3
3
  export declare const WORKING_FOLDER: string;
4
+ export declare const CONFIG_FILE: string;
5
+ export declare const filterJson: (fullPath: string) => boolean;
6
+ export declare const filterDirectory: (fullPath: string) => boolean;
7
+ export declare const filterFiles: (fullPath: string) => boolean;
8
+ export declare const camelToText: (s: string) => string;
9
+ export declare const kebabToText: (s: string) => string;
10
+ export declare const snakeToText: (s: string) => string;
11
+ export declare function valuesToChoices(list: string[], valueToTitle?: (value: string) => string): {
12
+ value: string;
13
+ title: string;
14
+ }[];
15
+ export declare function titlesToChoices(list: string[], titleToValue?: (title: string) => string): {
16
+ title: string;
17
+ value: string;
18
+ }[];
19
+ export declare function createConfigurationFile(): Promise<boolean>;
4
20
  export declare function sortByName(objA: {
5
21
  Name: string;
6
22
  }, objB: {
@@ -17,15 +33,13 @@ export declare function splitFilename(fullname: string, defaultFolder?: string):
17
33
  filename: string;
18
34
  folder: string;
19
35
  };
20
- export declare const filterJson: (fullPath: string) => boolean;
21
- export declare const filterDirectory: (fullPath: string) => boolean;
22
- export declare const filterFiles: (fullPath: string) => boolean;
23
36
  /**
24
37
  * Agrega los elementos de newArray a baseArray, si no existen previamente en baseArray.
25
38
  * @param {string[]} baseArray El array donde se agregan los elementos
26
39
  * @param {string[]} newArray El array de elementos a agregar
27
40
  */
28
41
  export declare function addNewItems(baseArray: string[], newArray: string[]): void;
42
+ export declare function searchInFolderHierarchy(element: string, parentFolder: string): string;
29
43
  export declare function getFiles(source: string, filter?: (file: string) => boolean, recursive?: boolean, ignoreList?: string[]): string[];
30
44
  export declare function convertNameToKey(name: string): string;
31
45
  export declare function convertKeyToName(key: string): string;
@@ -1,7 +1,94 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import fs from "fs";
2
- export const DOCS_FOLDER = process.cwd() + "/docs";
3
- export const DICTIONARY_FOLDER = process.cwd() + "/docs/diccionarios";
11
+ import { fileURLToPath } from 'url';
12
+ import prompts from "prompts";
13
+ import { GitProjects, GitServices } from "./context.js";
14
+ import { logWarning } from "./color.js";
15
+ const COMMAND_FOLDER = searchInFolderHierarchy('commands', fileURLToPath(import.meta.url));
16
+ export const TEMPLATES_FOLDER = searchInFolderHierarchy('templates', fileURLToPath(import.meta.url));
17
+ export const DICTIONARY_FOLDER = TEMPLATES_FOLDER + "/diccionarios";
4
18
  export const WORKING_FOLDER = process.env.INIT_CWD || ".";
19
+ export const CONFIG_FILE = process.cwd() + '/.autoforce.json';
20
+ export const filterJson = (fullPath) => fullPath.endsWith(".json");
21
+ export const filterDirectory = (fullPath) => fs.lstatSync(fullPath).isDirectory();
22
+ export const filterFiles = (fullPath) => !fs.lstatSync(fullPath).isDirectory();
23
+ export const camelToText = (s) => s.replace(/[A-Z]/g, x => ' ' + x);
24
+ export const kebabToText = (s) => s.replace(/-./g, x => ' ' + x[1].toUpperCase());
25
+ export const snakeToText = (s) => s.replace(/_./g, x => ' ' + x[1].toUpperCase());
26
+ export function valuesToChoices(list, valueToTitle = (value) => value) {
27
+ return list.map(value => { return { value, title: valueToTitle(value) }; });
28
+ }
29
+ export function titlesToChoices(list, titleToValue = (title) => title) {
30
+ return list.map(title => { return { title, value: titleToValue(title) }; });
31
+ }
32
+ export function createConfigurationFile() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ const models = valuesToChoices(getFiles(COMMAND_FOLDER, filterDirectory));
35
+ const automationModel = yield prompts([{
36
+ type: "select",
37
+ name: "model",
38
+ message: "Elija un modelo de automatizacion",
39
+ choices: [
40
+ { title: 'Orgs con Procesos de Negocio usando scratchs', value: 'modelA' },
41
+ { title: 'Custom', value: 'custom', description: 'En este caso los comandos son configurados fuera de la herramienta y los lee de la carpeta commands en el root del repo' }
42
+ ]
43
+ }]);
44
+ // Si es custom pregunta si quiere tomar de base alguno existente
45
+ if (automationModel.model === 'custom') {
46
+ const baseModel = yield prompts([{
47
+ type: "select",
48
+ name: "model",
49
+ message: "Quiere tomar algun modelo existente de base ? Este se copiara a la carpeta ",
50
+ choices: [
51
+ { title: 'Orgs con Procesos de Negocio usando scratchs', value: 'modelA' },
52
+ { title: 'Custom', value: 'custom' }
53
+ ]
54
+ }]);
55
+ }
56
+ // Preguntar por GitHub o GitLab
57
+ const gitServices = yield prompts([{
58
+ type: "select",
59
+ name: "git",
60
+ message: "Elija un servicio de Git",
61
+ choices: [{ title: 'Github', value: GitServices.GitHub }, { title: 'Gitlab', value: GitServices.GitLab }]
62
+ }]);
63
+ // Chequear las variables de entorno
64
+ if (gitServices.git === GitServices.GitHub && !process.env.GITHUB_TOKEN) {
65
+ logWarning('Debe configurar una variable de entorno GITHUB_TOKEN');
66
+ }
67
+ if (gitServices.git === GitServices.GitLab && !process.env.GITLAB_TOKEN) {
68
+ logWarning('Debe configurar una variable de entorno GITLAB_TOKEN');
69
+ }
70
+ const projectServices = yield prompts([{
71
+ type: "select",
72
+ name: "project",
73
+ message: "Gestion de proyecto",
74
+ choices: [{ title: 'Github Projects', value: GitProjects.GitHub }, { title: 'GitLab Projects', value: GitProjects.GitLab }, { title: 'Jira', value: GitProjects.Jira }, { title: 'None', value: GitProjects.None }]
75
+ }]);
76
+ const projectId = yield prompts([{
77
+ type: "text",
78
+ name: "projectId",
79
+ message: "Id del proyecto"
80
+ }]);
81
+ // console.log('Genera documentacion');
82
+ const config = { model: automationModel.model, gitServices: gitServices.git, projectServices: projectServices.project, projectId: projectId.projectId };
83
+ try {
84
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
85
+ }
86
+ catch (_a) {
87
+ throw new Error(`No se pudo guardar la configuracion en ${CONFIG_FILE}`);
88
+ }
89
+ return true;
90
+ });
91
+ }
5
92
  export function sortByName(objA, objB) {
6
93
  return objA.Name > objB.Name ? 1 : objA.Name < objB.Name ? -1 : 0;
7
94
  }
@@ -43,9 +130,6 @@ export function splitFilename(fullname, defaultFolder = '') {
43
130
  }
44
131
  return { filename, folder };
45
132
  }
46
- export const filterJson = (fullPath) => fullPath.endsWith(".json");
47
- export const filterDirectory = (fullPath) => fs.lstatSync(fullPath).isDirectory();
48
- export const filterFiles = (fullPath) => !fs.lstatSync(fullPath).isDirectory();
49
133
  /**
50
134
  * Agrega los elementos de newArray a baseArray, si no existen previamente en baseArray.
51
135
  * @param {string[]} baseArray El array donde se agregan los elementos
@@ -58,6 +142,21 @@ export function addNewItems(baseArray, newArray) {
58
142
  }
59
143
  }
60
144
  }
145
+ export function searchInFolderHierarchy(element, parentFolder) {
146
+ if (fs.existsSync(`${parentFolder}/${element}`)) {
147
+ return `${parentFolder}/${element}`;
148
+ }
149
+ else {
150
+ const lastIndex = parentFolder.lastIndexOf('/');
151
+ if (lastIndex !== -1) {
152
+ const newParentFolder = parentFolder.substring(0, lastIndex);
153
+ if (newParentFolder !== '') {
154
+ return searchInFolderHierarchy(element, newParentFolder);
155
+ }
156
+ }
157
+ }
158
+ return '';
159
+ }
61
160
  export function getFiles(source, filter = (file) => file !== undefined, recursive = false, ignoreList = []) {
62
161
  const files = [];
63
162
  for (const file of fs.readdirSync(source)) {