donbot-cli 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/deploy.js CHANGED
@@ -1,4 +1,3 @@
1
- const { Client } = require("ssh2");
2
1
  const path = require("path");
3
2
  const { exec, execSync } = require("child_process");
4
3
  const readline = require('readline');
@@ -8,178 +7,108 @@ let config;
8
7
  function getGitBranch() {
9
8
  return new Promise((resolve, reject) => {
10
9
  exec('git rev-parse --abbrev-ref HEAD', (error, stdout, stderr) => {
11
- if (error) {
12
- reject(stderr);
13
- } else {
14
- resolve(stdout.trim()); // La salida de git es la rama actual
15
- }
10
+ if (error) reject(stderr);
11
+ else resolve(stdout.trim());
16
12
  });
17
13
  });
18
14
  }
19
15
 
20
16
  function validCode() {
21
17
  return new Promise((resolve, reject) => {
22
- execSync('npm run lint', (error, stdout, stderr) => {
23
- if (error) {
24
- reject(`Error: ${stderr}`);
25
- } else {
26
- resolve(stdout.trim());
27
- }
28
- });
18
+ try {
19
+ const output = execSync('npm run lint');
20
+ resolve(output.toString().trim());
21
+ } catch (error) {
22
+ reject(error);
23
+ }
29
24
  });
30
25
  }
31
26
 
32
- const askPassphrase = () => {
33
- return new Promise((resolve) => {
34
- const rl = readline.createInterface({
35
- input: process.stdin,
36
- output: process.stdout,
37
- terminal: true,
38
- });
39
- rl.question('Introduce la passphrase para la clave SSH: ', (passphrase) => {
40
- rl.close();
41
- resolve(passphrase);
42
- });
43
- rl._writeToOutput = () => {};
44
- });
45
- };
46
-
47
27
  const uploadCodeToServer = async (uploadCodeToServer, options) => {
48
28
 
49
- console.log(`
50
- _____ _______ __ _ ______ _______ _______
51
- | | | || | | || _ | | || |
52
- | _ | | _ || || || | | | | _ ||_ _|
53
- | | | || | | || || | | | | | | |
54
- | |_| | | |_| || _ || _ | | |_| | | |
55
- | | | || | | || |_| | | | | |
56
- |____| |_______||_| |___||_____| |_______| |___|
57
-
58
- DonBot CLI - Herramienta para operaciones automatizadas.
59
- `);
60
-
61
- //Validamos codigo
62
- if (!options.novalidcode) {
63
-
64
- console.log("Validando codigo...");
65
-
66
- validCode()
67
- .then()
68
- .catch((err) => {
69
- console.log("❌ El codigo no es valido.");
70
- console.error(err.stdout.toString());
71
- process.exit(1);
72
- });
73
-
29
+ console.log(`
30
+ _____ _______ __ _ ______ _______ _______
31
+ | | | || | | || _ | | || |
32
+ | _ | | _ || || || | | | | _ ||_ _|
33
+ | | | || | | || || | | | | | | |
34
+ | |_| | | |_| || _ || _ | | |_| | | |
35
+ | | | || | | || |_| | | | | |
36
+ |____| |_______||_| |___||_____| |_______| |___|
37
+
38
+ DonBot CLI - Herramienta para operaciones automatizadas.
39
+ `);
40
+
41
+ if (!options.novalidcode) {
42
+ try {
43
+ console.log("Validando código...");
44
+ await validCode();
45
+ console.log("✅ Código válido.");
46
+ } catch (err) {
47
+ console.log("❌ El código no es válido.");
48
+ console.error(err.stdout?.toString() || err.message);
49
+ process.exit(1);
74
50
  }
51
+ }
52
+
53
+ let host, user, path_cert, password, port, path_dest, sourceDir, container_name;
54
+
55
+ try {
56
+ config = JSON.parse(fs.readFileSync('./.conf/config-donbot-cli.json', 'utf8'));
57
+ } catch (error) {
58
+ console.error('Error al leer el archivo de configuración:', error.message);
59
+ process.exit(1);
60
+ }
61
+
62
+ const branch = await getGitBranch();
63
+ if (branch !== uploadCodeToServer) {
64
+ console.log("No estás en la rama correcta para deploy.");
65
+ return;
66
+ }
67
+
68
+ ({ host, user, path_cert, password, port, path_dest, sourceDir, container_name } = config[uploadCodeToServer]);
69
+
70
+ if (!host || !user || !port || !path_dest || !sourceDir || !container_name) {
71
+ console.error('Faltan valores necesarios en el archivo de configuración.');
72
+ process.exit(1);
73
+ }
74
+
75
+ if (path_cert && !fs.existsSync(path_cert)) {
76
+ console.error(`La clave privada no existe en la ruta: ${path_cert}`);
77
+ process.exit(1);
78
+ }else if (password == ""){
79
+ console.error(`Falta ingresar el password`);
80
+ process.exit(1);
81
+ }
82
+
83
+ const excludeFile = './.conf/exclude-deploy-donbot-list.txt';
84
+
85
+ const rsyncCommand = path_cert
86
+ ? `rsync -avzh --progress -e "ssh -i ${path_cert}" --exclude-from="${excludeFile}" "${sourceDir}" ${user}@${host}:${path_dest}`
87
+ : `sshpass -p '${password}' rsync -avzh --progress --exclude-from="${excludeFile}" "${sourceDir}" ${user}@${host}:${path_dest}`;
88
+
89
+ console.log("🔁 Subiendo archivos al servidor...");
90
+
91
+ exec(rsyncCommand, (err, stdout, stderr) => {
92
+ if (err) {
93
+ console.error(`❌ Error al subir los archivos:\n${stderr}`);
94
+ return;
95
+ }
96
+ console.log("✅ Archivos subidos correctamente:\n" + stdout);
75
97
 
76
-
77
-
78
-
79
- let host, user, path_cert, port, path_dest, sourceDir;
80
-
81
- getGitBranch()
82
- .then(async (branch) => {
98
+ const dockerCommand = path_cert
99
+ ? `ssh -i ${path_cert} ${user}@${host} "docker restart ${container_name}"`
100
+ : `sshpass -p '${password}' ssh ${user}@${host} "docker restart ${container_name}"`;
83
101
 
84
- //No hubo error en codigo
85
- console.log("✅El codigo es valido.");
102
+ console.log("🐳 Reiniciando contenedor Docker...");
86
103
 
87
- try {
88
- config = JSON.parse(fs.readFileSync('./.conf/config-donbot-cli.json', 'utf8'));
89
- } catch (error) {
90
- console.error('Error al leer el archivo de configuración:', error.message);
91
- process.exit(1);
104
+ exec(dockerCommand, (dockerErr, dockerStdout, dockerStderr) => {
105
+ if (dockerErr) {
106
+ console.error(`❌ Error al reiniciar Docker:\n${dockerStderr}`);
107
+ return;
92
108
  }
93
-
94
- if(branch === uploadCodeToServer){
95
-
96
-
97
- ({ host, user, path_cert, port, path_dest, sourceDir, container_name } = config[uploadCodeToServer]);
98
-
99
- console.log("Actualizando codigo en: " + host)
100
-
101
- if (!host || !user || !path_cert || !port || !path_dest || !sourceDir || !container_name) {
102
- console.error('Faltan valores necesarios en el archivo de configuración.');
103
- console.error('Verifique que los siguientes valores estén definidos: host, user, path_cert, port, path_dest, sourceDir.');
104
- process.exit(1);
105
- }
106
-
107
- try {
108
- if (!fs.existsSync(path_cert)) {
109
- console.error(`La clave privada especificada no existe en la ruta: ${path_cert}`);
110
- process.exit(1);
111
- }
112
- } catch (error) {
113
- console.error('Error al verificar la ruta de la clave privada:', error.message);
114
- process.exit(1);
115
- }
116
-
117
- let rsyncCommand;
118
- let connectionConfig = {
119
- host,
120
- port,
121
- username: user,
122
- privateKey: fs.readFileSync(path_cert)
123
- };
124
-
125
- const ssh = new Client();
126
-
127
- ssh.on("ready", () => {
128
- console.log("Conectado al servidor");
129
-
130
- rsyncCommand = `rsync -avzh --progress -e "ssh -i ${path_cert}" --exclude-from="./.conf/exclude-deploy-donbot-list.txt" "${sourceDir}" ${user}@${host}:${path_dest}`;
131
-
132
- exec(rsyncCommand, (err, stdout, stderr) => {
133
- if (err) {
134
- console.error(`Error al subir los archivos: ${stderr}`);
135
- return;
136
- }
137
- console.log("Archivos subidos correctamente:");
138
- console.log(stdout);
139
-
140
- // Reiniciar Docker Compose después de la transferencia
141
- const dockerCommand = `ssh -i ${path_cert} ${user}@${host} "cd && docker restart ${container_name}"`;
142
- exec(dockerCommand, (dockerErr, dockerStdout, dockerStderr) => {
143
- if (dockerErr) {
144
- console.error(`Error al reiniciar Docker Compose: ${dockerStderr}`);
145
- return;
146
- }
147
- console.log("🐳 Contenedor de app reiniciado correctamente:");
148
- console.log(dockerStdout);
149
- });
150
-
151
- });
152
-
153
- ssh.end();
154
- })
155
- .on("error", (err) => {
156
- console.error("Error de conexión SSH:", err);
157
- })
158
- .on('close', () => {
159
- })
160
- .on('end', () => {
161
- });
162
-
163
- try {
164
- ssh.connect(connectionConfig);
165
- } catch (err) {
166
- if (err.message.includes("Encrypted OpenSSH private key detected")) {
167
- const passphrase = await askPassphrase();
168
- connectionConfig.passphrase = passphrase;
169
- ssh.connect(connectionConfig);
170
- }else{
171
- console.error("Error inesperado:", err.message);
172
- }
173
- }
174
-
175
- }else{
176
- console.log("No estas en la rama correcta para deploy.")
177
- }
178
-
179
- })
180
- .catch((err) => {
181
- console.error(err);
109
+ console.log("✅ Contenedor reiniciado:\n" + dockerStdout);
182
110
  });
111
+ });
183
112
  };
184
-
185
- module.exports = { uploadCodeToServer }
113
+
114
+ module.exports = { uploadCodeToServer };
package/cli/flows.js CHANGED
@@ -1,11 +1,13 @@
1
1
 
2
2
  const fs = require("fs");
3
3
  const path = require("path");
4
+ const process = require("process");
4
5
  const readline = require('readline');
5
6
 
6
7
  const addRouteToRoutesFile = (routeName) => {
7
8
 
8
- const routesFilePath = path.join(__dirname, "../routes/routes.js");
9
+ const routesDir = path.join(process.cwd(), "routes");
10
+ const routesFilePath = path.join(routesDir, "/routes.js");
9
11
  const routeFilePath = `./${routeName}.routes`;
10
12
 
11
13
  if (!fs.existsSync(routesFilePath)) {
@@ -81,8 +83,8 @@ const newflow = async (name,options) => {
81
83
  DonBot CLI - Herramienta para operaciones automatizadas.
82
84
  `);
83
85
 
84
- const controllersDir = path.join(__dirname, "../", "controllers");
85
- const routesDir = path.join(__dirname, "../", "routes");
86
+ const controllersDir = path.join(process.cwd(), "controllers");
87
+ const routesDir = path.join(process.cwd(), "routes");
86
88
 
87
89
  // Crear el controlador
88
90
  const controllerFileName = `${name}.controller.js`;
@@ -159,7 +161,7 @@ const newflow = async (name,options) => {
159
161
 
160
162
  addRouteToRoutesFile(name);
161
163
 
162
- }else {
164
+ }else if (options.controller) {
163
165
 
164
166
  controllerContent = `
165
167
  "use strict";
@@ -169,7 +171,7 @@ const newflow = async (name,options) => {
169
171
  try {
170
172
 
171
173
  } catch (error) {
172
-
174
+ DonBotLoger.error(error);
173
175
  }
174
176
  }
175
177
  }
@@ -177,7 +179,34 @@ const newflow = async (name,options) => {
177
179
  module.exports = ${name.charAt(0).toUpperCase() + name.slice(1)}Controller;
178
180
  `;
179
181
 
180
- }
182
+ }else if (options.cron) {
183
+
184
+ controllerContent = `
185
+ "use strict";
186
+
187
+ class ${name.charAt(0).toUpperCase() + name.slice(1)}Controller {
188
+ static async exampleAction() {
189
+ try {
190
+
191
+ } catch (error) {
192
+ DonBotLoger.error(error);
193
+ }
194
+ }
195
+ }
196
+
197
+ module.exports = ${name.charAt(0).toUpperCase() + name.slice(1)}Controller;
198
+ `;
199
+
200
+ //Almacenamos datos del cron en la tabla
201
+
202
+ //name
203
+ //tiemexecution
204
+ //description
205
+ //numberOfExecutions
206
+ //repet
207
+ //time_repeat
208
+
209
+ }
181
210
 
182
211
  fs.writeFileSync(controllerFilePath, controllerContent.trim());
183
212
  console.log(`Controlador '${controllerFileName}' creado exitosamente.`);
package/donbot.js CHANGED
@@ -76,11 +76,12 @@ program.
76
76
  // Flow
77
77
 
78
78
  program.
79
- command("newcontroller <name>").
80
- alias("nc").
79
+ command("newflow <name>").
80
+ alias("nf").
81
81
  description("Crea un nuevo flujo").
82
82
  option("--cron", "Genera también un archivo de crons para iniciar los flujos").
83
83
  option("--endpoint", "Genera también un archivo de rutas para el controlador").
84
+ option("--controller", "Genera también un archivo de crons para iniciar los flujos").
84
85
  action((name,options) => {
85
86
  flows.newflow(name,options);
86
87
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "donbot-cli",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "Cli de donbot",
5
5
  "main": "donbot.js",
6
6
  "bin": {
@@ -17,6 +17,7 @@
17
17
  "jsonwebtoken": "^9.0.2",
18
18
  "mongodb": "^6.13.0",
19
19
  "path": "^0.12.7",
20
+ "process": "^0.11.10",
20
21
  "readline": "^1.3.0",
21
22
  "ssh2": "^1.16.0"
22
23
  }