@9of9solutions/replikator 1.0.6 → 1.0.7

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 (2) hide show
  1. package/main.js +123 -79
  2. package/package.json +1 -1
package/main.js CHANGED
@@ -7,6 +7,8 @@ import fs from 'fs-extra';
7
7
  import chokidar from 'chokidar';
8
8
  import inquirer from 'inquirer';
9
9
  import winston from 'winston';
10
+ import { Command } from 'commander';
11
+ import degit from 'degit';
10
12
 
11
13
  const __filename = fileURLToPath(import.meta.url);
12
14
  const __dirname = path.dirname(__filename);
@@ -55,88 +57,76 @@ async function findSrcWithPkg(root, folderName) {
55
57
  }
56
58
 
57
59
  /**
58
- * Charge la config si elle existe, ou la crée via prompt.
59
- * La config stockée contient des chemins relatifs à process.cwd().
60
- * Renvoie un objet { src, targets, ignore } où src/targets sont absolus.
60
+ * Copie initiale + mise en place du watcher.
61
61
  */
62
- async function loadConfigOrPrompt() {
62
+ async function watchCommand() {
63
63
  const projectRoot = process.cwd();
64
64
 
65
- // 1) si config.json existe, on la lit et on rebuild les absolus
65
+ // --- loadConfigOrPrompt() inlined here pour clarté ---
66
+ let src, targets, ignore;
67
+ // 1) si config existe
66
68
  if (await fs.pathExists(CONFIG_PATH)) {
67
69
  const raw = await fs.readJson(CONFIG_PATH);
68
- return {
69
- src: path.resolve(projectRoot, raw.src),
70
- targets: raw.targets.map(rel => path.resolve(projectRoot, rel)),
71
- ignore: raw.ignore
72
- };
73
- }
74
-
75
- // 2) Sinon on demande les infos
76
- const answers = await inquirer.prompt([
77
- {
78
- name: 'src',
79
- type: 'input',
80
- message: 'Chemin du répertoire à copier (depuis la racine du projet) ?',
81
- default: 'packages/shared',
82
- validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'Le dossier n’existe pas'
83
- },
84
- {
85
- name: 'count',
86
- type: 'number',
87
- message: `Combien d'applications cibles ?`,
88
- default: 1,
89
- validate: n => n > 0 || 'Au moins 1'
90
- },
91
- {
92
- name: 'targets',
93
- type: 'input',
94
- message: a => `Entrez les ${a.count} noms d'applications cibles (virgule séparatrice) :`,
95
- filter: i => i.split(',').map(s => s.trim()),
96
- validate: (input, a) =>
97
- input.length === a.count || `Il faut ${a.count} applications.`
70
+ src = path.resolve(projectRoot, raw.src);
71
+ targets = raw.targets.map(rel => path.resolve(projectRoot, rel));
72
+ ignore = raw.ignore;
73
+ } else {
74
+ // 2) sinon prompt
75
+ const answers = await inquirer.prompt([
76
+ {
77
+ name: 'src',
78
+ type: 'input',
79
+ message: 'Chemin du répertoire à copier (depuis la racine du projet) ?',
80
+ default: 'packages/shared',
81
+ validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'Le dossier n’existe pas'
82
+ },
83
+ {
84
+ name: 'count',
85
+ type: 'number',
86
+ message: `Combien d'applications cibles ?`,
87
+ default: 1,
88
+ validate: n => n > 0 || 'Au moins 1'
89
+ },
90
+ {
91
+ name: 'targets',
92
+ type: 'input',
93
+ message: a => `Entrez les ${a.count} noms d'applications cibles (virgule séparatrice) :`,
94
+ filter: i => i.split(',').map(s => s.trim()),
95
+ validate: (input, a) =>
96
+ input.length === a.count || `Il faut ${a.count} applications.`
97
+ }
98
+ ]);
99
+
100
+ const absSrc = path.resolve(projectRoot, answers.src);
101
+ let absTargets;
102
+ try {
103
+ absTargets = await Promise.all(
104
+ answers.targets.map(async t => {
105
+ const folder = await findSrcWithPkg(projectRoot, t);
106
+ if (!folder) {
107
+ throw new Error(`Impossible de trouver l'application "${t}"`);
108
+ }
109
+ return path.join(folder, 'shared');
110
+ })
111
+ );
112
+ } catch (err) {
113
+ console.error(`\n⚠️ Erreur : ${err.message}\n`);
114
+ process.exit(1);
98
115
  }
99
- ]);
100
-
101
- // 3) On résout les chemins absolus
102
- const absSrc = path.resolve(projectRoot, answers.src);
103
- let absTargets;
104
- try {
105
- absTargets = await Promise.all(
106
- answers.targets.map(async t => {
107
- const folder = await findSrcWithPkg(projectRoot, t);
108
- if (!folder) {
109
- throw new Error(`Impossible de trouver l'application "${t}"`);
110
- }
111
- // on prend le dossier "shared" à l'intérieur de folder
112
- return path.join(folder, 'shared');
113
- })
114
- );
115
- } catch (err) {
116
- console.error(`\n⚠️ Erreur : ${err.message}\n`);
117
- process.exit(1);
118
- }
119
116
 
120
- // 4) On convertit en relatifs **par rapport à projectRoot**
121
- const relSrc = path.relative(projectRoot, absSrc);
122
- const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
117
+ // store relative paths
118
+ const relSrc = path.relative(projectRoot, absSrc);
119
+ const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
120
+ await fs.writeJson(CONFIG_PATH, { src: relSrc, targets: relTargets, ignore: [] }, { spaces: 2 });
121
+ logger.info(`Configuration enregistrée dans ${CONFIG_PATH}`);
123
122
 
124
- // 5) On écrit la config une fois, en relatif
125
- const config = { src: relSrc, targets: relTargets, ignore: [] };
126
- await fs.writeJson(CONFIG_PATH, config, { spaces: 2 });
127
- logger.info(`Configuration enregistrée dans ${CONFIG_PATH}`);
128
-
129
- // 6) On renvoie les chemins absolus pour la suite
130
- return { src: absSrc, targets: absTargets, ignore: [] };
131
- }
132
-
133
- /**
134
- * Lance la copie initiale puis met en place le watcher.
135
- */
136
- async function main() {
137
- const { src, targets, ignore } = await loadConfigOrPrompt();
123
+ // use absolutes from now on
124
+ src = absSrc;
125
+ targets = absTargets;
126
+ ignore = [];
127
+ }
138
128
 
139
- // Copie initiale
129
+ // --- Copie initiale ---
140
130
  await Promise.all(
141
131
  targets.map(dest =>
142
132
  fs.ensureDir(dest).then(() =>
@@ -146,7 +136,7 @@ async function main() {
146
136
  );
147
137
  logger.info('Copie initiale terminée.');
148
138
 
149
- // Watcher
139
+ // --- Watcher ---
150
140
  const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
151
141
  watcher
152
142
  .on('add', p => syncFile('add', p, src, targets))
@@ -173,8 +163,62 @@ async function syncFile(event, filePath, srcDir, targets) {
173
163
  }));
174
164
  }
175
165
 
176
- // Lancement du script
177
- main().catch(err => {
178
- logger.error('Erreur fatale :', err);
179
- process.exit(1);
180
- });
166
+ // --- Scaffolding "init" via degit ---
167
+ async function initCommand(projectName) {
168
+ const projectPath = path.resolve(process.cwd(), projectName);
169
+ if (await fs.pathExists(projectPath)) {
170
+ console.error(`Le dossier "${projectName}" existe déjà.`);
171
+ process.exit(1);
172
+ }
173
+
174
+ console.log(`\n📂 Création du dossier ${projectName}…`);
175
+ const emitter = degit('9of9solutions/replikator-template', {
176
+ cache: false,
177
+ force: true,
178
+ verbose: true
179
+ });
180
+
181
+ try {
182
+ await emitter.clone(projectPath);
183
+ console.log('✔️ Template cloné dans', projectName);
184
+ console.log('\n📦 Installation des dépendances…');
185
+ process.chdir(projectPath);
186
+ // installe via pnpm si disponible, sinon npm
187
+ const installer = fs.existsSync('pnpm-lock.yaml') ? 'pnpm install' : 'npm install';
188
+ require('child_process').execSync(installer, { stdio: 'inherit' });
189
+ console.log('\n✅ Projet initialisé !');
190
+ } catch (err) {
191
+ console.error('✖️ Échec du scaffolding:', err);
192
+ process.exit(1);
193
+ }
194
+ }
195
+
196
+ // --- CLI setup via Commander ---
197
+ const program = new Command();
198
+
199
+ program
200
+ .name('replikator')
201
+ .description('CLI de sync et scaffolding Replikator')
202
+ .version('1.0.0');
203
+
204
+ // commande `init`
205
+ program
206
+ .command('init <projectName>')
207
+ .description('Scaffold un nouveau projet depuis le template Replikator')
208
+ .action(initCommand);
209
+
210
+ // commande `watch` (identique au default)
211
+ program
212
+ .command('watch')
213
+ .description('Lance la synchronisation (copy & watch)')
214
+ .action(async () => { await watchCommand(); });
215
+
216
+ // si aucun sous‑commande, on fait la watch
217
+ if (process.argv.length <= 2) {
218
+ watchCommand().catch(err => {
219
+ logger.error('Erreur fatale :', err);
220
+ process.exit(1);
221
+ });
222
+ } else {
223
+ program.parseAsync(process.argv);
224
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@9of9solutions/replikator",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "bin": {