@cerema/cadriciel 1.4.24 → 1.4.29-a

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.
@@ -1,50 +1,22 @@
1
1
  module.exports = (args) => {
2
- const { nanoid } = require('nanoid');
3
- var UID = nanoid();
4
- const { error } = require('../../lib/message');
5
- const inquirer = require('inquirer');
6
- const chalk = require('chalk-v2');
7
- const path = require('path');
8
- const AdmZip = require('adm-zip');
9
- const ora = require('ora');
10
- const { exec: execCallback } = require('child_process');
11
- const exec = (command) =>
12
- new Promise((resolve, reject) => {
13
- execCallback(command, (error, stdout, stderr) => {
14
- if (error) {
15
- reject({ error, stderr });
16
- } else {
17
- resolve(stdout);
18
- }
19
- });
20
- });
21
- const os = require('os');
22
- const recursive = require('recursive-readdir');
2
+ const { promisify } = require('util');
3
+ const { exec } = require('child_process');
4
+ const execPromise = promisify(exec);
23
5
  const fs = require('fs');
6
+ const ora = require('ora');
7
+ const chalk = require('chalk-v2');
24
8
  const log = require('log-beautify');
25
- const isBinary = require('isbinaryfile').isBinaryFile;
26
- const userHomeDir = os.homedir();
27
- var sep = path.sep;
28
- var templates = [];
29
- const {
30
- capitalizeFirstLetter,
31
- getAccount,
32
- getTemplates,
33
- } = require('../../lib/util');
34
- var spinner;
35
-
36
- const unzipFile = (zipFilePath, outputPath, callback) => {
37
- const zip = new AdmZip(zipFilePath);
38
-
39
- try {
40
- zip.extractAllTo(outputPath, true);
41
- callback();
42
- } catch (err) {
43
- error("Une erreur s'est produite lors de la décompression");
44
- process.exit(1);
45
- }
46
- };
47
-
9
+ const inquirer = require('inquirer');
10
+ const path = require('path');
11
+ const cliProgress = require('cli-progress');
12
+ const userHome = require('os').homedir();
13
+ const error = require(path.join('..', '..', 'lib', 'message')).error;
14
+ const { getAccount, getTemplates } = require(path.join(
15
+ '..',
16
+ '..',
17
+ 'lib',
18
+ 'util'
19
+ ));
48
20
  const link = (url, name) => {
49
21
  if (!name) name = url;
50
22
  if (url.includes('localhost')) url = 'http://' + url + '/';
@@ -57,207 +29,152 @@ module.exports = (args) => {
57
29
  '\u001b]8;;\u0007\u001b[0m\n'
58
30
  );
59
31
  };
60
-
61
- const download = async (name, cb) => {
62
- const CadricielAPI = require(path.join('..', '..', 'lib', 'cadriciel'));
63
- const cadriciel = new CadricielAPI();
64
- try {
65
- await cadriciel.downloadFile(
66
- '/template?key=' + name + '.zip',
67
- `${os.tmpdir()}${sep}${name}.zip`
68
- );
69
- } catch (e) {
70
- spinner.stop();
71
- error('Erreur lors du téléchargement du cadriciel');
72
- return process.exit(1);
73
- }
32
+ const sshtemplate = `
33
+ # cadriciel -- 87c7dfbf-172a-4084-a862-4a23f35a5b79 --
34
+ Host cadriciel
35
+ HostName gitlab.cerema.fr
36
+ User git
37
+ IdentityFile ~/.cadriciel/id_rsa
38
+ IdentitiesOnly yes
39
+ # -----------------------------------------------------
40
+ `;
41
+ const CadricielAPI = require(path.join('..', '..', 'lib', 'cadriciel'));
42
+ const cadriciel = new CadricielAPI();
43
+ var templates = [];
44
+ const progress = async (bar1, response, cb) => {
74
45
  try {
75
- unzipFile(
76
- `${os.tmpdir()}${sep}${name}.zip`,
77
- `${os.tmpdir()}${sep}${UID}`,
78
- () => {
79
- DEFAULT_TEMPLATE = name;
80
- fs.unlink(`${os.tmpdir()}${sep}${name}.zip`, cb);
81
- }
82
- );
83
- } catch (e) {
84
- spinner.stop();
85
- error('Erreur dans le modèle du cadriciel');
86
- return process.exit(1);
87
- }
88
- };
89
-
90
- const changefs = (o, files, ndx, cb) => {
91
- if (!files[ndx]) return cb();
92
-
93
- var input = files[ndx];
94
- var data = fs.readFileSync(input);
95
- var stat = fs.lstatSync(input);
96
- isBinary(data, stat.size).then((result) => {
97
- if (result === false) {
98
- var text = fs.readFileSync(input, 'utf-8');
99
- text = text.replace(/§§project§§/g, o.project);
100
- text = text.replace(/§§projectUpper§§/g, o.project.toUpperCase());
101
- text = text.replace(/§§projectID§§/g, capitalizeFirstLetter(o.project));
102
- text = text.replace(/§§projectNS§§/g, capitalizeFirstLetter(o.project));
103
- text = text.replace(/§§pg_port§§/g, o.pg_port);
104
- text = text.replace(/§§inbucket_port§§/g, o.inbucket_port);
105
- text = text.replace(/§§keycloak_port§§/g, o.keycloak_port);
106
- text = text.replace(/§§pgadmin_port§§/g, o.pgadmin_port);
107
- text = text.replace(/§§pgadmin_email§§/g, o.pgadmin_email);
108
- text = text.replace(/§§pgadmin_password§§/g, o.pgadmin_password);
109
- var output =
110
- OUTPUT_DIRECTORY +
111
- sep +
112
- input.split(UID + sep)[1].replace(/§§project§§/g, o.project);
113
- var dir = require('path').dirname(output);
114
- fs.mkdirSync(dir, { recursive: true });
115
- fs.writeFileSync(output, text);
116
- changefs(o, files, ndx + 1, cb);
117
- } else {
118
- if (input.indexOf('.DS_Store') > -1)
119
- return changefs(o, files, ndx + 1, cb);
120
- var output =
121
- OUTPUT_DIRECTORY +
122
- sep +
123
- input.split(UID + sep)[1].replace(/§§project§§/g, o.project);
124
- var dir = require('path').dirname(output);
125
- fs.mkdirSync(dir, { recursive: true });
126
- fs.copyFileSync(input, output);
127
- changefs(o, files, ndx + 1, cb);
46
+ const p = await cadriciel.get(`status/jobs/projects/${response.prj.id}`);
47
+ bar1.update(p.progress);
48
+ if (p.progress < 100)
49
+ setTimeout(() => {
50
+ progress(bar1, response, cb);
51
+ }, 1000);
52
+ else {
53
+ bar1.stop();
54
+ cb();
128
55
  }
129
- });
130
- };
131
-
132
- const install_dependencies = async (name) => {
133
- console.log(' ');
134
- const spinner = ora('Installation des dépendances').start();
135
- const projectPath = `${process.cwd()}/${name}`;
136
-
137
- // Check if directory exists
138
- if (!fs.existsSync(projectPath)) {
139
- spinner.fail(`Le répertoire ${projectPath} n'existe pas !`);
140
- return;
141
- }
142
-
143
- // Change to the directory
144
- process.chdir(projectPath);
145
-
146
- // Check if git and pnpm are installed
147
- try {
148
- await exec('git --version');
149
56
  } catch (e) {
150
- spinner.fail(`git n'est pas installé sur votre système !`);
151
- return;
57
+ error('Erreur lors de la création du projet');
152
58
  }
59
+ };
60
+ const updatePK = async () => {
153
61
  try {
154
- await exec('pnpm -v');
62
+ var pk = await cadriciel.get(`privatekey`);
63
+ const pkey = Buffer.from(pk.private_key, 'base64').toString();
64
+ fs.writeFileSync(userHome + '/.cadriciel/id_rsa', pkey);
65
+ fs.chmodSync(userHome + '/.cadriciel/id_rsa', 0o600);
66
+ try {
67
+ fs.mkdirSync(userHome + '/.ssh');
68
+ } catch (e) {}
69
+ var ssh = fs.readFileSync(userHome + '/.ssh/config', 'utf-8');
70
+ if (!ssh.includes('87c7dfbf-172a-4084-a862-4a23f35a5b79 ')) {
71
+ ssh += '\n\n' + sshtemplate;
72
+ fs.writeFileSync(userHome + '/.ssh/config', ssh, { flag: 'a' });
73
+ fs.chmodSync(userHome + '/.ssh/config', 0o600);
74
+ }
155
75
  } catch (e) {
156
- spinner.fail(
157
- `pnpm n'est pas installé sur votre système ! (https://pnpm.js.org/installation)`
76
+ console.log(e);
77
+ error(
78
+ "Une erreur s'est produite lors de la récupération de la clé privée"
158
79
  );
159
- return;
160
- }
161
- try {
162
- await exec('pnpm i');
163
- } catch (errorInstall) {
164
- spinner.fail(
165
- `Problème pendant l'installation des dépendances :\n`,
166
- errorInstall
167
- );
168
- return;
169
80
  }
81
+ };
82
+ const launch = async (answers) => {
83
+ const data = {
84
+ name: answers.project,
85
+ title: answers.project,
86
+ template: answers.template,
87
+ group: 'PERSO',
88
+ disabled: true,
89
+ };
170
90
  try {
171
- await exec(
172
- 'git init && git add --all && git commit -m "first commit [ci skip]" && git checkout -b dev'
173
- );
91
+ var response = await cadriciel.post(`studio/projects`, data);
174
92
  } catch (e) {
175
- spinner.fail('Erreurs git', errorGit);
176
- return;
93
+ if (e.response.data.error == 'PROJECT_ALREADY_EXISTS')
94
+ error(
95
+ "Le nom du projet n'est pas disponible. Veuillez choisir un autre titre."
96
+ );
97
+ else error('Erreur lors de la création du projet');
98
+ return process.exit(1);
177
99
  }
178
- spinner.succeed('🚀 Votre projet a été correctement installé.\n');
179
- console.log(' ');
180
- console.log(`
100
+ console.log(`${chalk.bold('\n 🚀 Création du projet en cours...')}\n`);
101
+ const bar1 = new cliProgress.SingleBar(
102
+ {},
103
+ cliProgress.Presets.shades_classic
104
+ );
105
+ bar1.start(100, 0);
106
+ progress(bar1, response, async () => {
107
+ console.log(' ');
108
+ const step1 = ora('📥 Téléchargement du projet en cours...').start();
109
+ try {
110
+ await updatePK();
111
+ const git = await execPromise('git clone ' + response.prj.uri, {
112
+ cwd: process.cwd(),
113
+ });
114
+ step1.succeed(chalk.bold('Téléchargement OK.'));
115
+ console.log(' ');
116
+ const step2 = ora('📦 Installation des dépendances...').start();
117
+ try {
118
+ try {
119
+ await execPromise('pnpm i', {
120
+ cwd: process.cwd() + '/' + response.prj.title,
121
+ });
122
+ } catch (e) {
123
+ try {
124
+ await execPromise('yarn', {
125
+ cwd: process.cwd() + '/' + response.prj.title,
126
+ });
127
+ } catch (e) {
128
+ await execPromise('npm i', {
129
+ cwd: process.cwd() + '/' + response.prj.title,
130
+ });
131
+ }
132
+ }
133
+
134
+ try {
135
+ await execPromise(
136
+ `git config --local user.email "${response.prj.owner.email}" && git config --local user.name "${response.prj.owner.name}" && git add --all && git checkout -b ${response.prj.owner.trigram}`,
137
+ {
138
+ cwd: process.cwd() + '/' + response.prj.title,
139
+ }
140
+ );
141
+ step2.succeed(
142
+ '🎉 ' + chalk.bold('Votre projet a été correctement installé')
143
+ );
144
+ console.log(' ');
145
+ console.log(`
181
146
  ──────────────────────────────────────────────────────────────
147
+ URL du projet : ${link(response.prj.url.split('https://')[1])}
182
148
 
183
- Pour lancer l'environnement local de développement :
184
-
185
- ${chalk.magenta(' 📦 nécessite docker et docker-compose\n')}
149
+ Vous trouverez votre projet dans le dossier :
186
150
 
187
- cd ${chalk.green(name)}
188
- ${chalk.cyan('cad start')} .............. 🚀 ${chalk.bold(
189
- "démarre l'environnement de développement"
190
- )}
151
+ cd ${chalk.green(response.prj.title)}
152
+
153
+ 🚀 ${chalk.bold("Pour lancer l'environnement de développement :")}
154
+
155
+ ${chalk.green('cad start')}
156
+
157
+ 🚦 ${chalk.bold("Pour arrêter l'environnement de développement :")}
191
158
 
192
- ${chalk.cyan('cad stop')} ............... 🚦 ${chalk.bold(
193
- "arrête l'environnement."
194
- )}
159
+ ${chalk.green('cad stop')}
160
+
161
+ 💻 ${chalk.bold('Pour manager votre projet :')}
195
162
 
196
- 👉 ${link(
197
- 'https://studio.k8-dev.cerema.fr',
198
- 'studio.k8-dev.cerema.fr'
199
- )}
163
+ 👉 ${link('studio.k8-dev.cerema.fr', 'studio.k8-dev.cerema.fr')}
200
164
 
201
165
  ──────────────────────────────────────────────────────────────`);
202
- console.log(' ');
203
- };
204
-
205
- const createProject = async (o) => {
206
- spinner = ora('Téléchargement du cadriciel').start();
207
- const account = await getAccount();
208
-
209
- return download(o.template.dir, function () {
210
- spinner.succeed();
211
- spinner = ora('Création du projet ' + o.project).start();
212
- recursive(`${os.tmpdir()}/${UID}`, async function (err, files) {
213
- spinner.succeed();
214
- changefs(o, files, 0, function () {
215
- fs.rmSync(os.tmpdir() + '/' + UID, {
216
- recursive: true,
217
- force: true,
218
- });
219
- fs.writeFileSync(
220
- process.cwd() + '/' + o.project + '/.project',
221
- JSON.stringify(o)
222
- );
223
- spinner.succeed(`projet ${o.project} crée avec succès.`);
224
- install_dependencies(o.project);
225
- });
226
- });
166
+ console.log(' ');
167
+ } catch (e) {
168
+ console.log(e);
169
+ }
170
+ } catch (e) {}
171
+ } catch (e) {
172
+ console.log(e);
173
+ step1.fail(chalk.red('Déploiement échoué'));
174
+ return process.exit(1);
175
+ }
227
176
  });
228
177
  };
229
-
230
- const toCamelCase = (str) => {
231
- return (
232
- str
233
- // Remplacez tout caractère non-alphanumérique par un espace
234
- .replace(/[^a-zA-Z0-9]+/g, ' ')
235
- // Supprimez les espaces ou autres caractères non alphanumériques au début ou à la fin
236
- .trim()
237
- // Convertissez la première lettre de chaque mot en majuscule, sauf pour le premier mot
238
- .replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) =>
239
- index === 0 ? word.toLowerCase() : word.toUpperCase()
240
- )
241
- // Supprimez les espaces
242
- .replace(/\s+/g, '')
243
- );
244
- };
245
-
246
- const launch = (response) => {
247
- response.project = toCamelCase(response.project);
248
- if (!response.template) var index = 0;
249
- else var index = templates.findIndex((p) => p.title == response.template);
250
- response.template = templates[index];
251
-
252
- try {
253
- var stat = fs.statSync(process.cwd() + '/' + response.project);
254
- return log.error('Ce projet existe déjà !');
255
- } catch (e) {}
256
-
257
- OUTPUT_DIRECTORY = `${process.cwd()}`;
258
- createProject(response);
259
- };
260
-
261
178
  return {
262
179
  info: {
263
180
  title: 'completion',
@@ -268,6 +185,7 @@ module.exports = (args) => {
268
185
  try {
269
186
  templates = await getTemplates();
270
187
  } catch (e) {
188
+ console.log(e);
271
189
  spinner.stop();
272
190
  error('Mise à jour impossible... Vérifier votre connexion internet');
273
191
  return process.exit(1);
@@ -276,7 +194,6 @@ module.exports = (args) => {
276
194
  var tpl = [];
277
195
  if (!templates) return process.exit(1);
278
196
  for (let i = 0; i < templates.length; i++) tpl.push(templates[i].title);
279
-
280
197
  const questions = [
281
198
  {
282
199
  type: 'input',
@@ -298,14 +215,25 @@ module.exports = (args) => {
298
215
  if (tpl.length == 1) questions.splice(1, 1);
299
216
  if (process.argv[1]) {
300
217
  if (questions.length == 1)
301
- return launch({ project: process.argv[1], template: tpl[0] });
218
+ return launch({
219
+ project: process.argv[1],
220
+ template: templates[0].dir,
221
+ });
302
222
  }
303
223
  console.log(
304
224
  '\n😃 ' + chalk.bold('Tout grand projet commence par un nom !\n')
305
225
  );
306
226
  inquirer
307
227
  .prompt(questions)
308
- .then(launch)
228
+ .then((answers) => {
229
+ if (!answers.template) answers.template = templates[0].dir;
230
+ else {
231
+ for (let i = 0; i < templates.length; i++)
232
+ if (templates[i].title == answers.template)
233
+ answers.template = templates[i].dir;
234
+ }
235
+ launch(answers);
236
+ })
309
237
  .catch((error) => {
310
238
  log.error(error);
311
239
  });
package/cli.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- const figlet = require('figlet');
3
- const chalk = require('chalk-v2');
4
- const fs = require('fs');
5
- const log = require('log-beautify');
6
- const path = require('path');
7
- const { spawn } = require('child_process');
8
- const os = require('os');
9
- const userHomeDir = os.homedir();
10
- const boxen = require('boxen');
11
-
2
+ const figlet = require('figlet'); // Importing figlet for ASCII art.
3
+ const chalk = require('chalk-v2'); // Importing chalk for colored text output.
4
+ const fs = require('fs'); // File system module for file operations.
5
+ const log = require('log-beautify'); // Enhanced logging.
6
+ const path = require('path'); // Path module for handling file paths.
7
+ const { spawn } = require('child_process'); // For executing shell commands.
8
+ const os = require('os'); // Operating system-related utilities.
9
+ const userHomeDir = os.homedir(); // Fetching the user's home directory.
10
+ const boxen = require('boxen'); // For creating boxes in the console.
11
+
12
+ // Locating the '.cadriciel' directory starting from the current working directory.
12
13
  const CADRICIEL_PATH = findCadricielDir(process.cwd());
13
14
  const CADRICIEL_COMMAND = 'cad';
14
15
  global.CADRICIEL_URI = 'https://cadriciel.k8-dev.cerema.fr/api';
16
+ //global.CADRICIEL_URI = 'http://localhost:3000/api';
15
17
 
18
+ // Initialize command storage objects.
16
19
  var CADRICIEL_GLOBAL_COMMANDS = {};
17
20
  var CADRICIEL_COMMANDS = {};
18
21
 
19
- /** efface les anciens credentials s'ils existent */
20
- try {
21
- fs.unlinkSync(`${userHomeDir}/.cadriciel/account.json`);
22
- } catch (e) {}
23
-
22
+ // Path for version checking file.
24
23
  const VERSION_CHECK_FILE = path.join(userHomeDir, '.cadriciel_last_check.json');
25
24
 
25
+ // Function to decide whether a version check is needed.
26
26
  const shouldCheckVersion = async () => {
27
27
  try {
28
28
  const data = fs.readFileSync(VERSION_CHECK_FILE, 'utf8');
@@ -37,11 +37,13 @@ const shouldCheckVersion = async () => {
37
37
  }
38
38
  };
39
39
 
40
+ // Function to update the date of the last version check.
40
41
  const updateLastCheckDate = () => {
41
42
  const data = JSON.stringify({ date: new Date() });
42
43
  fs.writeFileSync(VERSION_CHECK_FILE, data, 'utf8');
43
44
  };
44
45
 
46
+ // Function to check the current version of the package.
45
47
  const checkVersion = async () => {
46
48
  if (!(await shouldCheckVersion())) {
47
49
  return Promise.resolve(null); // Aucune version à vérifier, renvoie null
@@ -85,15 +87,15 @@ const checkVersion = async () => {
85
87
  };
86
88
 
87
89
  /**
88
- * Recherche récursivement le répertoire '.cadriciel' à partir du chemin donné, en remontant vers les répertoires parents.
89
- * @param {string} startPath - Le chemin de départ pour la recherche.
90
- * @returns {string|null} Le chemin du répertoire '.cadriciel' trouvé, ou null si non trouvé.
90
+ * Recursively searches for the '.cadriciel' directory.
91
+ * @param {string} startPath - Starting path for the search.
92
+ * @returns {string|null} Path of the found directory or null.
91
93
  */
92
94
  function findCadricielDir(startPath) {
93
95
  let currentPath = startPath;
94
96
 
95
97
  while (currentPath !== path.parse(currentPath).root) {
96
- const potentialPath = path.join(currentPath, '.cadriciel/bin');
98
+ const potentialPath = path.join(currentPath, '.cadriciel/cli');
97
99
  if (
98
100
  fs.existsSync(potentialPath) &&
99
101
  fs.statSync(potentialPath).isDirectory()
@@ -106,6 +108,7 @@ function findCadricielDir(startPath) {
106
108
  return null;
107
109
  }
108
110
 
111
+ // Function to load global commands.
109
112
  const loadGlobalCommands = () => {
110
113
  let dir = fs.readdirSync(__dirname + '/cli/global');
111
114
  for (let i = 0; i < dir.length; i++) {
@@ -116,18 +119,71 @@ const loadGlobalCommands = () => {
116
119
  }
117
120
  };
118
121
 
122
+ // Function to load project specific commands.
119
123
  const loadCadricielCommands = (path) => {
120
124
  try {
121
- let dir = fs.readdirSync(path);
122
- for (let i = 0; i < dir.length; i++) {
123
- if (dir[i].indexOf('.js') > -1)
124
- CADRICIEL_COMMANDS[dir[i].split('.')[0]] = require(path + dir[i])();
125
+ const cli = require(path + 'cli');
126
+ for (let el in cli) {
127
+ if (cli[el].description) {
128
+ let subs = [];
129
+ for (let s in cli[el]) {
130
+ if (s !== 'description') subs.push({ title: s });
131
+ }
132
+ let description = '';
133
+ if (cli[el].description.indexOf(']') > -1) {
134
+ description = cli[el].description.split('] ')[1];
135
+ let lbl = cli[el].description
136
+ .split('] ')[0]
137
+ .replace('[', '')
138
+ .replace(']', '');
139
+ CADRICIEL_COMMANDS[el] = {
140
+ info: {
141
+ title: el,
142
+ description: description,
143
+ label: lbl.toLowerCase(),
144
+ sub: subs,
145
+ },
146
+ };
147
+ } else {
148
+ description = cli[el].description;
149
+ CADRICIEL_COMMANDS[el] = {
150
+ info: {
151
+ title: el,
152
+ description: cli[el].description,
153
+ sub: subs,
154
+ },
155
+ };
156
+ }
157
+ } else {
158
+ let description = '';
159
+ if (cli[el].indexOf(']') > -1) {
160
+ description = cli[el].split('] ')[1];
161
+ let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
162
+ CADRICIEL_COMMANDS[el] = {
163
+ info: {
164
+ title: el,
165
+ description: description,
166
+ label: lbl.toLowerCase(),
167
+ },
168
+ };
169
+ } else {
170
+ description = cli[el];
171
+ CADRICIEL_COMMANDS[el] = {
172
+ info: {
173
+ title: el,
174
+ description: description,
175
+ },
176
+ };
177
+ }
178
+ }
125
179
  }
126
180
  } catch (e) {}
127
181
  };
128
182
 
183
+ // Function to format command labels with chalk for color coding.
129
184
  const label = (caption) => {
130
185
  if (caption === 'experimental') return chalk.red(' (' + caption + ') ');
186
+ if (caption === 'alpha') return chalk.cyan(' (' + caption + ') ');
131
187
  if (caption === 'beta') return chalk.magenta(' (' + caption + ') ');
132
188
  if (caption === 'docker') return chalk.green(' (' + caption + ') ');
133
189
  if (caption === 'ai')
@@ -135,6 +191,7 @@ const label = (caption) => {
135
191
  return '';
136
192
  };
137
193
 
194
+ // Function to format command descriptions.
138
195
  const formatDescription = (description, maxLength) => {
139
196
  if (description.length <= maxLength) return description;
140
197
 
@@ -145,6 +202,7 @@ const formatDescription = (description, maxLength) => {
145
202
  return firstPart + '\n ' + secondPart;
146
203
  };
147
204
 
205
+ // Function to display commands.
148
206
  const display = (commands) => {
149
207
  const maxWidth = 30;
150
208
  const maxDescriptionLength = 50;
@@ -186,49 +244,16 @@ const display = (commands) => {
186
244
  }
187
245
  };
188
246
 
189
- const displaySub = (commands) => {
190
- const maxWidth = 30;
191
- const maxDescriptionLength = 50;
192
-
193
- for (let el in commands) {
194
- let title = el;
195
-
196
- if (commands[el].info) {
197
- let description = commands[el].info.description;
198
- console.log(' ' + chalk.bold(commands[el].info.title));
199
- console.log(' ' + chalk.cyan(description));
200
- console.log(' ');
201
-
202
- for (let i = 0; i < commands[el].info.sub.length; i++) {
203
- let sub = commands[el].info.sub[i];
204
- const formattedDesc = formatDescription(
205
- sub.description,
206
- maxDescriptionLength
207
- );
208
- const dots = '.'.repeat(maxWidth - sub.title.length);
209
- console.log(
210
- ' ' +
211
- chalk.cyanBright(sub.title) +
212
- ' ' +
213
- chalk.grey(dots) +
214
- ' ' +
215
- label(sub.label) +
216
- ' ' +
217
- chalk.white(formattedDesc)
218
- );
219
- }
220
- }
221
- }
222
- };
223
-
247
+ // Function to display the banner and the list of commands.
224
248
  const displayBanner = () => {
225
249
  figlet('Cadriciel', function (err, data) {
226
250
  if (err) {
251
+ console.log(err);
227
252
  log.error('Something went wrong...');
228
253
  return;
229
254
  }
230
255
  try {
231
- let info = require(CADRICIEL_PATH + '/version.json');
256
+ let info = require(CADRICIEL_PATH + '/../version.json');
232
257
  version_cadriciel =
233
258
  ` - ${chalk.green('Cadriciel v')} ` +
234
259
  chalk.green.bold(info.version) +
@@ -258,7 +283,7 @@ const displayBanner = () => {
258
283
  console.log(`\n Vous n'êtes pas à l'intérieur d'un projet. `);
259
284
  console.log(' ');
260
285
  } else {
261
- loadCadricielCommands(CADRICIEL_PATH + '/../cli/');
286
+ loadCadricielCommands(CADRICIEL_PATH + '/../');
262
287
  console.log(' ');
263
288
  display(CADRICIEL_COMMANDS);
264
289
  console.log(' ');
@@ -267,9 +292,12 @@ const displayBanner = () => {
267
292
  });
268
293
  };
269
294
 
295
+ // Function to process entered commands.
270
296
  const processCommands = (args) => {
271
297
  const command = args[0];
272
- loadCadricielCommands(CADRICIEL_PATH + '/../cli/');
298
+ const maxWidth = 30;
299
+ const maxDescriptionLength = 50;
300
+ loadCadricielCommands(CADRICIEL_PATH + '/../');
273
301
  if (!CADRICIEL_COMMANDS[command]) {
274
302
  if (!CADRICIEL_GLOBAL_COMMANDS[command]) {
275
303
  log.error('Commande inconnue : ' + command);
@@ -278,21 +306,142 @@ const processCommands = (args) => {
278
306
  CADRICIEL_GLOBAL_COMMANDS[command].start(args);
279
307
  } else {
280
308
  console.log(' ');
281
- const cmd = `node`;
282
- const fullArgs = [`${CADRICIEL_PATH}/${command}`, ...args.splice(1)];
283
- const unit = require(`${CADRICIEL_PATH}/../cli/${args[0]}`)();
309
+ const dir = args.join('/');
310
+ return parseCommand(args);
311
+ }
312
+ };
284
313
 
285
- if (unit.info.sub) return displaySub({ unit });
314
+ /**
315
+ * Displays the subcommands and their descriptions for a given command.
316
+ *
317
+ * @param {string} path - The path of the command.
318
+ * @param {string} title - The title of the command.
319
+ * @param {string} description - The description of the command.
320
+ * @param {object} cli - The command line interface object.
321
+ */
322
+ const displaySub = (path, title, description, cli) => {
323
+ CADRICIEL_COMMANDS = {};
324
+ delete cli.description;
325
+ for (let el in cli) {
326
+ if (cli[el].description) {
327
+ let subs = [];
328
+ for (let s in cli[el]) {
329
+ if (s !== 'description') subs.push({ title: s });
330
+ }
331
+ let description = '';
332
+ if (cli[el].description.indexOf(']') > -1) {
333
+ description = cli[el].description.split('] ')[1];
334
+ let lbl = cli[el].description
335
+ .split('] ')[0]
336
+ .replace('[', '')
337
+ .replace(']', '');
338
+ CADRICIEL_COMMANDS[el] = {
339
+ info: {
340
+ title: el,
341
+ description: description,
342
+ label: lbl.toLowerCase(),
343
+ sub: subs,
344
+ },
345
+ };
346
+ } else {
347
+ description = cli[el].description;
348
+ CADRICIEL_COMMANDS[el] = {
349
+ info: {
350
+ title: el,
351
+ description: cli[el].description,
352
+ sub: subs,
353
+ },
354
+ };
355
+ }
356
+ } else {
357
+ let description = '';
358
+ if (cli[el].indexOf(']') > -1) {
359
+ description = cli[el].split('] ')[1];
360
+ let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
361
+ CADRICIEL_COMMANDS[el] = {
362
+ info: {
363
+ title: el,
364
+ description: description,
365
+ label: lbl.toLowerCase(),
366
+ },
367
+ };
368
+ } else {
369
+ CADRICIEL_COMMANDS[el] = {
370
+ info: {
371
+ title: el,
372
+ description: cli[el],
373
+ },
374
+ };
375
+ }
376
+ }
377
+ }
378
+ figlet('Cadriciel', function (err, data) {
379
+ if (err) {
380
+ console.log(err);
381
+ log.error('Something went wrong...');
382
+ return;
383
+ }
384
+ try {
385
+ let info = require(CADRICIEL_PATH + '/../version.json');
386
+ version_cadriciel =
387
+ ` - ${chalk.green('Cadriciel v')} ` +
388
+ chalk.green.bold(info.version) +
389
+ chalk.green(' (' + info.name + ')');
390
+ } catch (e) {
391
+ version_cadriciel = '';
392
+ }
393
+ console.log(
394
+ chalk.cyan(data) +
395
+ chalk.bold('\n CLI v' + require('./package.json').version) +
396
+ version_cadriciel
397
+ );
398
+ console.log(' ');
399
+ console.log(' ' + chalk.bold(description));
400
+ console.log(' ');
401
+ console.log(
402
+ `${chalk.bold(' Usage :')} ${chalk.cyanBright(
403
+ CADRICIEL_COMMAND + path + ' <commande>'
404
+ )} ${chalk.cyan('[<args>]')}`
405
+ );
406
+ console.log(' ');
407
+ display(CADRICIEL_COMMANDS);
408
+ console.log(' ');
409
+ });
410
+ };
286
411
 
287
- const child = spawn(cmd, fullArgs, {
288
- stdio: 'inherit',
289
- shell: true,
290
- });
412
+ // Function to execute commands.
413
+ const ExecCommand = (p, args) => {
414
+ const unit = require(CADRICIEL_PATH + p);
415
+ const params = {
416
+ dir: {
417
+ home: `${userHomeDir}/.cadriciel`,
418
+ cadriciel: path.normalize(CADRICIEL_PATH + '/..'),
419
+ root: path.normalize(CADRICIEL_PATH + '/../..'),
420
+ },
421
+ };
422
+ unit(args, params);
423
+ };
291
424
 
292
- child.on('close', (code) => {});
425
+ // Function to parse commands.
426
+ const parseCommand = (args) => {
427
+ const cli = require(CADRICIEL_PATH + '/../cli');
428
+ let cmd = cli;
429
+ let arguments = [];
430
+ let title = '';
431
+ let path = '';
432
+ for (let i = 0; i < args.length; i++) {
433
+ if (!cmd[args[i]]) arguments.push(args[i]);
434
+ else {
435
+ cmd = cmd[args[i]];
436
+ title = args[i];
437
+ path += ' ' + title;
438
+ }
293
439
  }
440
+ if (cmd.description) displaySub(path, title, cmd.description, cmd);
441
+ else ExecCommand(path.replace(/ /g, '/'), arguments);
294
442
  };
295
443
 
444
+ // Main function.
296
445
  checkVersion()
297
446
  .then((version) => {
298
447
  const current_version = require(__dirname + '/package.json').version;
@@ -335,9 +484,10 @@ checkVersion()
335
484
  }
336
485
  })
337
486
  .catch((error) => {
338
- loadGlobalCommands();
487
+ console.log(error);
488
+ /*loadGlobalCommands();
339
489
  process.argv.shift();
340
490
  process.argv.shift();
341
491
  if (process.argv.length <= 2) return displayBanner();
342
- processCommands(process.argv.splice(2));
492
+ processCommands(process.argv.splice(2));*/
343
493
  });
package/lib/cadriciel.js CHANGED
@@ -5,9 +5,7 @@ const fs = require('fs');
5
5
  const os = require('os');
6
6
  const HomeDir = os.homedir() + '/.cadriciel';
7
7
  const { error } = require('./message');
8
- //var baseURL = 'http://localhost:3000/api';
9
- var baseURL = 'https://cadriciel.k8-dev.cerema.fr/api';
10
-
8
+ var baseURL = global.CADRICIEL_URI;
11
9
  class CadricielAPI {
12
10
  constructor(token) {
13
11
  if (!token) {
@@ -24,7 +22,6 @@ class CadricielAPI {
24
22
  return process.exit(1);
25
23
  }
26
24
  }
27
-
28
25
  this.client = axios.create({
29
26
  baseURL: baseURL,
30
27
  timeout: 10000,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cerema/cadriciel",
3
- "version": "1.4.24",
3
+ "version": "1.4.29a",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "npm": ">=8.0.0",
@@ -14,6 +14,7 @@
14
14
  "axios": "^1.5.1",
15
15
  "boxen": "5.1.2",
16
16
  "chalk-v2": "^1.0.2",
17
+ "cli-progress": "^3.12.0",
17
18
  "commander": "^10.0.0",
18
19
  "dotenv": "^16.3.1",
19
20
  "express": "^4.18.2",
@@ -27,6 +28,7 @@
27
28
  "ora": "^5.4.1",
28
29
  "prompts": "^2.4.2",
29
30
  "recursive-readdir": "^2.2.3",
31
+ "semver": "^7.5.4",
30
32
  "terminal-link": "2.1.1",
31
33
  "unzipper": "^0.10.11",
32
34
  "yauzl": "^2.10.0"