@9of9solutions/replikator 1.0.5 → 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 +175 -109
  2. package/package.json +1 -1
package/main.js CHANGED
@@ -1,133 +1,142 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // --- Pour recréer __dirname en ESM ---
3
+ // --- Pour recréer __dirname en ESM (utile pour localiser ce fichier) ---
4
4
  import { fileURLToPath } from 'url';
5
- import path from 'path';
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = path.dirname(__filename);
8
- // --- Imports ESM ---
9
- import fs from 'fs-extra';
10
- import chokidar from 'chokidar';
11
- import inquirer from 'inquirer';
12
- import { Command } from 'commander';
13
- import winston from 'winston';
14
-
15
- // --- Constantes ---
5
+ import path from 'path';
6
+ import fs from 'fs-extra';
7
+ import chokidar from 'chokidar';
8
+ import inquirer from 'inquirer';
9
+ import winston from 'winston';
10
+ import { Command } from 'commander';
11
+ import degit from 'degit';
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = path.dirname(__filename);
15
+
16
+ // On stocke la config dans le dossier de ce script
16
17
  const CONFIG_PATH = path.resolve(__dirname, 'config.json');
17
18
 
18
- // --- Logger Winston (console + fichier) ---
19
+ // Logger console + fichier (sync.log)
19
20
  const logger = winston.createLogger({
20
21
  transports: [
21
22
  new winston.transports.Console({ format: winston.format.simple() })
22
23
  ]
23
24
  });
24
25
 
26
+ /**
27
+ * Recherche récursive d'un dossier `folderName` contenant à la fois
28
+ * un sous-dossier `src` et un `package.json`, à partir de `root`.
29
+ * Renvoie le chemin absolu du dossier/src, ou null si introuvable.
30
+ */
25
31
  async function findSrcWithPkg(root, folderName) {
26
- for (const entry of await fs.readdir(root, { withFileTypes: true })) {
27
- if (!entry.isDirectory()) continue;
28
- const fullPath = path.join(root, entry.name);
29
- if (entry.name === folderName) {
30
- const srcDir = path.join(fullPath, 'src');
31
- const pkgFile = path.join(fullPath, 'package.json');
32
-
33
- // Vérifier que src existe et est un dossier
34
- // et que package.json existe et est un fichier
35
- try {
36
- const [srcStat, pkgStat] = await Promise.all([
37
- fs.stat(srcDir),
38
- fs.stat(pkgFile)
39
- ]);
40
- if (srcStat.isDirectory() && pkgStat.isFile()) {
41
- return srcDir;
42
- }
43
- } catch {
44
- // soit src n'existe pas, soit package.json n'existe pas
32
+ for (const entry of await fs.readdir(root, { withFileTypes: true })) {
33
+ if (!entry.isDirectory()) continue;
34
+ const fullPath = path.join(root, entry.name);
35
+
36
+ if (entry.name === folderName) {
37
+ const srcDir = path.join(fullPath, 'src');
38
+ const pkgFile = path.join(fullPath, 'package.json');
39
+ try {
40
+ const [srcStat, pkgStat] = await Promise.all([
41
+ fs.stat(srcDir),
42
+ fs.stat(pkgFile)
43
+ ]);
44
+ if (srcStat.isDirectory() && pkgStat.isFile()) {
45
+ return srcDir;
45
46
  }
47
+ } catch {
48
+ // src ou package.json pas présent → on continue
46
49
  }
47
-
48
- // Sinon on descend plus bas
49
- const nested = await findSrcWithPkg(fullPath, folderName);
50
- if (nested) return nested;
51
50
  }
52
- return null;
53
- }
54
51
 
55
- // --- Chargement ou prompt interactif ---
56
- async function loadConfigOrPrompt() {
57
- if (await fs.pathExists(CONFIG_PATH)) {
58
- return fs.readJson(CONFIG_PATH);
59
- }
60
-
61
- const answers = await inquirer.prompt([
62
- {
63
- name: 'src',
64
- type: 'input',
65
- message: 'Chemin du répertoire à copier ?',
66
- default: 'packages/shared',
67
- validate: i => fs.pathExistsSync(path.resolve(i)) || 'Le dossier n’existe pas'
68
- },
69
- {
70
- name: 'count',
71
- type: 'number',
72
- message: `Combien d'applications cibles ?`,
73
- default: 1,
74
- validate: n => n > 0 || 'Au moins 1'
75
- },
76
- {
77
- name: 'targets',
78
- type: 'input',
79
- message: a => `Entrez les ${a.count} noms d'applications cibles (virgule séparatrice) :`,
80
- filter: i => i.split(',').map(s => s.trim()),
81
- validate: (input, a) =>
82
- input.length === a.count || `Il faut ${a.count} applications.`
83
- }
84
- ]);
85
- let targets
86
- try {
87
- targets = await Promise.all(
88
- answers.targets.map(async t => {
89
- const folder = await findSrcWithPkg(process.cwd(), t);
90
- if (!folder) {
91
- throw new Error(`Impossible de trouver l'application "${t}"`);
92
- }
93
- return path.join(folder, 'shared');
94
- })
95
- );
96
- } catch (err) {
97
- console.error(`\nErreur : ${err.message}\n`);
98
- process.exit(1);
52
+ // descendre plus bas
53
+ const nested = await findSrcWithPkg(fullPath, folderName);
54
+ if (nested) return nested;
99
55
  }
56
+ return null;
57
+ }
100
58
 
59
+ /**
60
+ * Copie initiale + mise en place du watcher.
61
+ */
62
+ async function watchCommand() {
63
+ const projectRoot = process.cwd();
101
64
 
102
- const baseDir = __dirname;
65
+ // --- loadConfigOrPrompt() inlined here pour clarté ---
66
+ let src, targets, ignore;
67
+ // 1) si config existe
68
+ if (await fs.pathExists(CONFIG_PATH)) {
69
+ const raw = await fs.readJson(CONFIG_PATH);
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
+ ]);
103
99
 
104
- const relSrc = path.relative(baseDir, path.resolve(answers.src));
105
- const relTargets = targets.map(abs => path.relative(baseDir, abs));
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);
115
+ }
106
116
 
107
- const config = {
108
- src: relSrc,
109
- targets: relTargets,
110
- ignore: []
111
- };
112
- await fs.writeJson(CONFIG_PATH, config, { spaces: 2 });
113
- await fs.writeJson(CONFIG_PATH, config, { spaces: 2 });
114
- logger.info(`Configuration enregistrée dans ${CONFIG_PATH}`);
115
- return config;
116
- }
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}`);
117
122
 
118
- // --- Synchronisation initiale et watch ---
119
- async function main() {
120
- const { src, targets, ignore } = await loadConfigOrPrompt();
123
+ // use absolutes from now on
124
+ src = absSrc;
125
+ targets = absTargets;
126
+ ignore = [];
127
+ }
121
128
 
122
- // copie initiale
123
- await Promise.all(targets.map(dest =>
124
- fs.ensureDir(dest).then(() =>
125
- fs.copy(src, dest, { overwrite: true })
129
+ // --- Copie initiale ---
130
+ await Promise.all(
131
+ targets.map(dest =>
132
+ fs.ensureDir(dest).then(() =>
133
+ fs.copy(src, dest, { overwrite: true })
134
+ )
126
135
  )
127
- ));
136
+ );
128
137
  logger.info('Copie initiale terminée.');
129
138
 
130
- // watcher
139
+ // --- Watcher ---
131
140
  const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
132
141
  watcher
133
142
  .on('add', p => syncFile('add', p, src, targets))
@@ -136,6 +145,9 @@ async function main() {
136
145
  .on('error', e => logger.error('Watcher error:', e));
137
146
  }
138
147
 
148
+ /**
149
+ * Synchronise un fichier ajouté/modifié/supprimé auprès de toutes les targets.
150
+ */
139
151
  async function syncFile(event, filePath, srcDir, targets) {
140
152
  const rel = path.relative(srcDir, filePath);
141
153
  await Promise.all(targets.map(async destRoot => {
@@ -151,8 +163,62 @@ async function syncFile(event, filePath, srcDir, targets) {
151
163
  }));
152
164
  }
153
165
 
154
- //--- Lancement ---
155
- main().catch(err => {
156
- logger.error('Erreur fatale :', err);
157
- process.exit(1);
158
- });
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.5",
3
+ "version": "1.0.7",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "bin": {