@9of9solutions/replikator 1.0.9 → 1.0.10

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 +187 -180
  2. package/package.json +31 -32
package/main.js CHANGED
@@ -1,180 +1,187 @@
1
- #!/usr/bin/env node
2
-
3
- // --- Pour recréer __dirname en ESM (utile pour localiser ce fichier) ---
4
- import { fileURLToPath } from 'url';
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
-
11
- const __filename = fileURLToPath(import.meta.url);
12
- const __dirname = path.dirname(__filename);
13
-
14
- // On stocke la config dans le dossier de ce script
15
- const CONFIG_PATH = path.resolve(__dirname, 'config.json');
16
-
17
- // Logger console + fichier (sync.log)
18
- const logger = winston.createLogger({
19
- transports: [
20
- new winston.transports.Console({ format: winston.format.simple() })
21
- ]
22
- });
23
-
24
- /**
25
- * Recherche récursive d'un dossier `folderName` contenant à la fois
26
- * un sous-dossier `src` et un `package.json`, à partir de `root`.
27
- * Renvoie le chemin absolu du dossier/src, ou null si introuvable.
28
- */
29
- async function findSrcWithPkg(root, folderName) {
30
- for (const entry of await fs.readdir(root, { withFileTypes: true })) {
31
- if (!entry.isDirectory()) continue;
32
- const fullPath = path.join(root, entry.name);
33
-
34
- if (entry.name === folderName) {
35
- const srcDir = path.join(fullPath, 'src');
36
- const pkgFile = path.join(fullPath, 'package.json');
37
- try {
38
- const [srcStat, pkgStat] = await Promise.all([
39
- fs.stat(srcDir),
40
- fs.stat(pkgFile)
41
- ]);
42
- if (srcStat.isDirectory() && pkgStat.isFile()) {
43
- return srcDir;
44
- }
45
- } catch {
46
- // src ou package.json pas présent → on continue
47
- }
48
- }
49
-
50
- // descendre plus bas
51
- const nested = await findSrcWithPkg(fullPath, folderName);
52
- if (nested) return nested;
53
- }
54
- return null;
55
- }
56
-
57
- /**
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.
61
- */
62
- async function loadConfigOrPrompt() {
63
- const projectRoot = process.cwd();
64
-
65
- // 1) si config.json existe, on la lit et on rebuild les absolus
66
- if (await fs.pathExists(CONFIG_PATH)) {
67
- 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.`
98
- }
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
-
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));
123
-
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();
138
-
139
- // Copie initiale
140
- await Promise.all(
141
- targets.map(dest =>
142
- fs.ensureDir(dest).then(() =>
143
- fs.copy(src, dest, { overwrite: true })
144
- )
145
- )
146
- );
147
- logger.info('Copie initiale terminée.');
148
-
149
- // Watcher
150
- const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
151
- watcher
152
- .on('add', p => syncFile('add', p, src, targets))
153
- .on('change', p => syncFile('change', p, src, targets))
154
- .on('unlink', p => syncFile('unlink', p, src, targets))
155
- .on('error', e => logger.error('Watcher error:', e));
156
- }
157
-
158
- /**
159
- * Synchronise un fichier ajouté/modifié/supprimé auprès de toutes les targets.
160
- */
161
- async function syncFile(event, filePath, srcDir, targets) {
162
- const rel = path.relative(srcDir, filePath);
163
- await Promise.all(targets.map(async destRoot => {
164
- const destPath = path.join(destRoot, rel);
165
- if (event === 'unlink') {
166
- await fs.remove(destPath);
167
- logger.info(`Supprimé : ${rel}`);
168
- } else {
169
- await fs.ensureDir(path.dirname(destPath));
170
- await fs.copy(filePath, destPath, { overwrite: true });
171
- logger.info(`${event === 'add' ? 'Ajouté' : 'Mis à jour'} : ${rel}`);
172
- }
173
- }));
174
- }
175
-
176
- // Lancement du script
177
- main().catch(err => {
178
- logger.error('Erreur fatale :', err);
179
- process.exit(1);
180
- });
1
+
2
+ import path from 'path';
3
+ import fs from 'fs-extra';
4
+ import chokidar from 'chokidar';
5
+ import inquirer from 'inquirer';
6
+ import url from 'url';
7
+ const projectRoot = process.cwd();
8
+ const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
9
+ const pkgPath = path.join(__dirname, 'package.json');
10
+
11
+ async function getVersion() {
12
+ const pkg = await fs.readJson(pkgPath, 'utf8');
13
+ return pkg.version;
14
+ }
15
+ //We save configuration in root package.json
16
+ const PACKAGE_JSON_ROOT_PATH = path.resolve(projectRoot, 'package.json');
17
+
18
+ /**
19
+ * Recursively searches for folders that contain both
20
+ * a `src` subfolder and a `package.json` file, starting from `root`.
21
+ * Returns an array of objects: { name, src }.
22
+ */
23
+ async function findApplications(root) {
24
+ const applications= [];
25
+ async function recurse(dir) {
26
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
27
+ if (!entry.isDirectory()) continue;
28
+ if(entry.name == "node_modules") continue;
29
+ const fullPath = path.join(dir, entry.name);
30
+ const srcDir = path.join(fullPath, 'src');
31
+ const pkgFile = path.join(fullPath, 'package.json');
32
+ let hasSrcAndPkg = false;
33
+ try {
34
+ const [srcStat, pkgStat] = await Promise.all([
35
+ fs.stat(srcDir),
36
+ fs.stat(pkgFile)
37
+ ]);
38
+ hasSrcAndPkg = srcStat.isDirectory() && pkgStat.isFile();
39
+ } catch {
40
+ // either src or package.json doesn't exist, skip
41
+ }
42
+ if (hasSrcAndPkg) {
43
+ // read package.json to get the "name" field
44
+ let appName = entry.name;
45
+ try {
46
+ const pkg = JSON.parse(await fs.readFile(pkgFile, 'utf8'));
47
+ if (pkg.name) appName = pkg.name;
48
+ } catch {
49
+ // if JSON parse fails, stick with folder name
50
+ }
51
+ applications.push({ name: appName, src: srcDir });
52
+ }
53
+ // dive deeper
54
+ await recurse(fullPath);
55
+ }
56
+ }
57
+ await recurse(root);
58
+ return applications;
59
+ }
60
+
61
+
62
+ /**
63
+ * Loads the config if it exists, or creates it via prompt.
64
+ * The stored config contains paths relative to process.cwd().
65
+ * Returns an object { src, targets, ignore } where src/targets are absolute paths.
66
+ */
67
+ async function loadConfigOrPrompt(prompt) {
68
+ if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
69
+ if(!prompt) {
70
+ const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
71
+ if(raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.ignore) {
72
+ return {
73
+ src: path.resolve(projectRoot, raw.replikator.src),
74
+ targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
75
+ ignore: raw.replikator.ignore
76
+ };
77
+ }
78
+ }
79
+ } else {
80
+ throw new Error(`Unable to find root package.json`);
81
+ }
82
+
83
+ const applications = await findApplications(projectRoot);
84
+ const answers = await inquirer.prompt([
85
+ {
86
+ name: 'src',
87
+ type: 'input',
88
+ message: 'Path to the directory to replicate:',
89
+ default: 'packages/shared',
90
+ validate: i => fs.pathExistsSync(path.resolve(projectRoot, i)) || 'The folder does not exist'
91
+ },
92
+ {
93
+ name: 'targets',
94
+ type: 'checkbox',
95
+ message: 'Select the targeted applications:',
96
+ choices: applications.map(a => { return {name: a.name, value: a.src}}),
97
+ validate(ans) {
98
+ if (ans.length < 1) {
99
+ return 'You must choose at least one application.';
100
+ }
101
+ return true;
102
+ }
103
+ }
104
+ ]);
105
+
106
+ const absSrc = path.resolve(projectRoot, answers.src);
107
+ const absTargets = await Promise.all(answers.targets.map(async t => path.join(t, 'shared')));
108
+ const relSrc = path.relative(projectRoot, absSrc);
109
+ const relTargets = absTargets.map(abs => path.relative(projectRoot, abs));
110
+
111
+ const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
112
+ const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, ignore: []} };
113
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
114
+ console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
115
+
116
+ return { src: absSrc, targets: absTargets, ignore: [] };
117
+ }
118
+
119
+ /**
120
+ * Starts the initial copy and then sets up the watcher.
121
+ */
122
+ async function main() {
123
+ let prompt = false;
124
+ if(process.argv.length > 2) {
125
+ switch (process.argv[2]) {
126
+ case "init":
127
+ prompt = true
128
+ break;
129
+ case "run":
130
+ prompt = false
131
+ break;
132
+ case "clean":
133
+ console.log('Cleaning...');
134
+ console.log('\x1b[32mCleaning is complete.\x1b[0m');
135
+ process.exit(0);
136
+ }
137
+ } else {
138
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
139
+ console.log("");
140
+ console.log("Usage: rpk [command]");
141
+ console.log("");
142
+ console.log("Commands:");
143
+ console.log(" init Command used to init replikator configuration.");
144
+ console.log(" run Command used to run replikator.");
145
+ process.exit(0);
146
+ }
147
+ const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
148
+
149
+ await Promise.all(
150
+ targets.map(dest =>
151
+ fs.ensureDir(dest).then(() =>
152
+ fs.copy(src, dest, { overwrite: true })
153
+ )
154
+ )
155
+ );
156
+ console.log('Initial copy completed.');
157
+
158
+ const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
159
+ watcher
160
+ .on('add', p => syncFile('add', p, src, targets))
161
+ .on('change', p => syncFile('change', p, src, targets))
162
+ .on('unlink', p => syncFile('unlink', p, src, targets))
163
+ .on('error', e => console.error('Watcher error:', e));
164
+ }
165
+
166
+ /**
167
+ * Syncs a file that was added/modified/deleted to all targets.
168
+ */
169
+ async function syncFile(event, filePath, srcDir, targets) {
170
+ const rel = path.relative(srcDir, filePath);
171
+ await Promise.all(targets.map(async destRoot => {
172
+ const destPath = path.join(destRoot, rel);
173
+ if (event === 'unlink') {
174
+ await fs.remove(destPath);
175
+ console.log(`Deleted: ${rel}`);
176
+ } else {
177
+ await fs.ensureDir(path.dirname(destPath));
178
+ await fs.copy(filePath, destPath, { overwrite: true });
179
+ console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
180
+ }
181
+ }));
182
+ }
183
+
184
+ main().catch(err => {
185
+ console.error('Fatal error:', err);
186
+ process.exit(1);
187
+ });
package/package.json CHANGED
@@ -1,32 +1,31 @@
1
- {
2
- "name": "@9of9solutions/replikator",
3
- "version": "1.0.9",
4
- "type": "module",
5
- "main": "index.js",
6
- "bin": {
7
- "replikator": "main.js",
8
- "rpk": "main.js"
9
- },
10
- "scripts": {
11
- "replikator": "node main.js --src --targets ",
12
- "rpk": "npm run replikator"
13
- },
14
- "files": [
15
- "main.js",
16
- "config.json"
17
- ],
18
- "keywords": [],
19
- "author": "Germain LESPINGAL",
20
- "license": "ISC",
21
- "description": "",
22
- "devDependencies": {
23
- "chokidar": "^4.0.3",
24
- "fs-extra": "^11.3.0"
25
- },
26
- "dependencies": {
27
- "commander": "^13.1.0",
28
- "degit": "^2.8.4",
29
- "inquirer": "^8.2.6",
30
- "winston": "^3.17.0"
31
- }
32
- }
1
+ {
2
+ "name": "@9of9solutions/replikator",
3
+ "version": "1.0.10",
4
+ "type": "module",
5
+ "main": "main.js",
6
+ "bin": {
7
+ "replikator": "main.js",
8
+ "rpk": "main.js"
9
+ },
10
+ "scripts": {
11
+ "replikator": "node main.js",
12
+ "rpk": "node main.js"
13
+ },
14
+ "files": [
15
+ "main.js"
16
+ ],
17
+ "keywords": [],
18
+ "author": "Germain LESPINGAL",
19
+ "license": "ISC",
20
+ "description": "",
21
+ "devDependencies": {
22
+ "chokidar": "^4.0.3",
23
+ "fs-extra": "^11.3.0"
24
+ },
25
+ "dependencies": {
26
+ "commander": "^13.1.0",
27
+ "degit": "^2.8.4",
28
+ "inquirer": "^8.2.6",
29
+ "winston": "^3.17.0"
30
+ }
31
+ }