@9of9solutions/replikator 1.0.13 → 1.0.16

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 +200 -35
  2. package/package.json +2 -8
package/main.js CHANGED
@@ -4,6 +4,7 @@ import fs from 'fs-extra';
4
4
  import chokidar from 'chokidar';
5
5
  import inquirer from 'inquirer';
6
6
  import url from 'url';
7
+ import { execa } from 'execa';
7
8
  const projectRoot = process.cwd();
8
9
  const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
9
10
  const pkgPath = path.join(__dirname, 'package.json');
@@ -12,6 +13,20 @@ async function getVersion() {
12
13
  const pkg = await fs.readJson(pkgPath, 'utf8');
13
14
  return pkg.version;
14
15
  }
16
+
17
+ async function getReplicatedFileHeader(path) {
18
+ return `/******************************************************
19
+ * RPK / Replikator CLI tool / version ${await getVersion()}
20
+ *
21
+ * File replicated by Replicator
22
+ * DO NOT EDIT
23
+ *
24
+ * Edit at '${path}'
25
+ *
26
+ ******************************************************/\n`
27
+
28
+ }
29
+
15
30
  //We save configuration in root package.json
16
31
  const PACKAGE_JSON_ROOT_PATH = path.resolve(projectRoot, 'package.json');
17
32
  const SHARED_PATH = 'shared';
@@ -195,71 +210,221 @@ async function loadConfigOrPrompt(prompt) {
195
210
  return { src: absSrc, targets: absTargets, ignore: [] };
196
211
  }
197
212
 
213
+ /**
214
+ * Replikator run command
215
+ * @param {*} prompt - Should init config or no
216
+ */
217
+ async function run(prompt) {
218
+ const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
219
+ await Promise.all(
220
+ targets.map(async dest => {
221
+ await fs.remove(dest)
222
+ await fs.ensureDir(dest);
223
+ const relDest = path.relative(projectRoot, dest);
224
+ const patterns = ignore?.[relDest] || [];
225
+
226
+ const filterFn = srcFile => {
227
+ const rel = path.relative(src, srcFile) + "/";
228
+ return patterns.filter(p => rel.startsWith(p)).length === 0;
229
+ };
230
+
231
+ console.log(dest)
232
+ await fs.copy(src, dest, { overwrite: true, filter: filterFn });
233
+
234
+ if ((await fs.lstat(src)).isFile()) {
235
+ const data = await fs.readFile(src);
236
+ const fd = await fs.open(dest, 'w+');
237
+ const header = Buffer.from(await getReplicatedFileHeader(src));
238
+ await fs.write(fd, header, 0, header.length, 0);
239
+ await fs.write(fd, data, 0, data.length, header.length);
240
+ await fs.chmod(dest, 0o444);
241
+ }
242
+ })
243
+ );
244
+
245
+ console.log('Initial copy completed.');
246
+
247
+ const watcher = chokidar.watch(src, { persistent: true });
248
+ watcher
249
+ .on('add', p => syncFile('add', p, src, targets, ignore))
250
+ .on('change', p => syncFile('change', p, src, targets, ignore))
251
+ .on('unlink', p => syncFile('unlink', p, src, targets, ignore))
252
+ .on('error', e => console.error('Watcher error:', e));
253
+ }
254
+
255
+ /**
256
+ * Show infos of replikator
257
+ */
258
+ async function showInfo() {
259
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
260
+ console.log("");
261
+ console.log("Usage: rpk [command]");
262
+ console.log("");
263
+ console.log("Commands:");
264
+ console.log(" init Command used to init replikator configuration.");
265
+ console.log(" run Command used to run replikator.");
266
+ console.log(" update Command used to update replikator.");
267
+ console.log(" exclude Command used to exclude files for selected apps.");
268
+ process.exit(0);
269
+ }
270
+
198
271
  /**
199
272
  * Starts the initial copy and then sets up the watcher.
200
273
  */
201
274
  async function main() {
202
- let prompt = false;
203
275
  if (process.argv.length > 2) {
204
276
  switch (process.argv[2]) {
205
277
  case "init":
206
- prompt = true
278
+ await run(true);
207
279
  break;
208
280
  case "run":
209
- prompt = false
281
+ await run(false);
210
282
  break;
211
- case "clean":
212
- console.log('Cleaning...');
213
- console.log('\x1b[32mCleaning is complete.\x1b[0m');
214
- process.exit(0);
283
+ case "update":
284
+ await updateRpk();
285
+ break;
286
+ case "exclude":
287
+ await excludeRpk();
288
+ break;
289
+ default:
290
+ await showInfo();
291
+ break
215
292
  }
216
293
  } else {
217
- console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
218
- console.log("");
219
- console.log("Usage: rpk [command]");
220
- console.log("");
221
- console.log("Commands:");
222
- console.log(" init Command used to init replikator configuration.");
223
- console.log(" run Command used to run replikator.");
224
- process.exit(0);
294
+ await showInfo();
225
295
  }
226
- const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
227
296
 
228
- await Promise.all(
229
- targets.map(dest =>
230
- fs.ensureDir(dest).then(() =>
231
- fs.copy(src, dest, { overwrite: true })
232
- )
233
- )
234
- );
235
- console.log('Initial copy completed.');
236
297
 
237
- const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
238
- watcher
239
- .on('add', p => syncFile('add', p, src, targets))
240
- .on('change', p => syncFile('change', p, src, targets))
241
- .on('unlink', p => syncFile('unlink', p, src, targets))
242
- .on('error', e => console.error('Watcher error:', e));
243
298
  }
244
299
 
300
+ /**
301
+ * Update the CLI to the last available version.
302
+ */
303
+ async function updateRpk() {
304
+ const ua = process.env.npm_config_user_agent || '';
305
+ let cmd, args;
306
+
307
+ if (ua.startsWith('pnpm')) {
308
+ cmd = 'pnpm';
309
+ args = ['add', '-g', '@9of9solutions/replikator@latest'];
310
+ } else if (ua.startsWith('yarn')) {
311
+ cmd = 'yarn';
312
+ args = ['global', 'add', '@9of9solutions/replikator@latest'];
313
+ } else {
314
+ cmd = 'npm';
315
+ args = ['install', '-g', '@9of9solutions/replikator@latest'];
316
+ }
317
+
318
+ try {
319
+ await execa(cmd, args, { stdio: 'inherit' });
320
+ const newVersion = await getVersion();
321
+ console.log(green(`RPK CLI updated to version ${newVersion}`));
322
+ } catch (err) {
323
+ console.log(red(`Failed to update RPK CLI: ${err.message}`));
324
+ process.exit(1);
325
+ }
326
+ }
327
+
328
+ const green = txt => `\x1b[32m${txt}\x1b[0m`;
329
+ const red = txt => `\x1b[31m${txt}\x1b[0m`;
330
+
245
331
  /**
246
332
  * Syncs a file that was added/modified/deleted to all targets.
247
333
  */
248
- async function syncFile(event, filePath, srcDir, targets) {
334
+ async function syncFile(event, filePath, srcDir, targets, ignore) {
249
335
  const rel = path.relative(srcDir, filePath);
250
336
  await Promise.all(targets.map(async destRoot => {
251
337
  const destPath = path.join(destRoot, rel);
252
338
  if (event === 'unlink') {
253
339
  await fs.remove(destPath);
254
- console.log(`Deleted: ${rel}`);
255
340
  } else {
256
- await fs.ensureDir(path.dirname(destPath));
257
- await fs.copy(filePath, destPath, { overwrite: true });
258
- console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
341
+ const relDest = path.relative(projectRoot, destRoot);
342
+ const patterns = ignore?.[relDest] || [];
343
+ if (patterns.filter(p => (rel+"/").startsWith(p)).length === 0) {
344
+ await fs.ensureDir(path.dirname(destPath));
345
+ await fs.copy(filePath, destPath, { overwrite: true });
346
+ if ((await fs.lstat(filePath)).isFile()) {
347
+ const data = await fs.readFile(filePath);
348
+ const fd = await fs.open(destPath, 'w+');
349
+ const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
350
+ await fs.write(fd, buffer, 0, buffer.length, 0);
351
+ await fs.write(fd, data, 0, data.length, buffer.length);
352
+ await fs.chmod(destPath, 0o444)
353
+ }
354
+ }
355
+
259
356
  }
260
357
  }));
261
358
  }
262
359
 
360
+ /**
361
+ * Setup excluded files or directories for apps
362
+ */
363
+ async function excludeRpk() {
364
+ const rawPkg = await fs.readJson(PACKAGE_JSON_ROOT_PATH, 'utf8');
365
+ const cfg = rawPkg.replikator;
366
+ if (!cfg || !cfg.src || !Array.isArray(cfg.targets)) {
367
+ console.log(red('No Replikator configuration found. Please run `rpk init` first.'));
368
+ process.exit(1);
369
+ }
370
+
371
+ const absSrc = path.resolve(projectRoot, cfg.src);
372
+ const absTargets = cfg.targets.map(rel => path.resolve(projectRoot, rel));
373
+
374
+ const apps = await findApplications(projectRoot);
375
+ const choicesApps = absTargets.map(absT => {
376
+ const match = apps.find(a => path.join(a.src, SHARED_PATH) === absT);
377
+ return {
378
+ name: match ? match.name : path.relative(projectRoot, absT),
379
+ value: absT
380
+ };
381
+ });
382
+
383
+ const { selectedApps } = await inquirer.prompt([{
384
+ type: 'checkbox',
385
+ name: 'selectedApps',
386
+ message: 'Select applications on which to apply exclusions:',
387
+ choices: choicesApps,
388
+ validate(ans) {
389
+ return ans.length > 0 ? true : 'You must choose at least one application.';
390
+ }
391
+ }]);
392
+
393
+ async function walk(dir, base = '') {
394
+ const entries = [];
395
+ for (const ent of await fs.readdir(dir, { withFileTypes: true })) {
396
+ const rel = path.join(base, ent.name);
397
+ const full = path.join(dir, ent.name);
398
+ entries.push(rel + (ent.isDirectory() ? '/' : ''));
399
+ if (ent.isDirectory()) {
400
+ entries.push(...await walk(full, rel));
401
+ }
402
+ }
403
+ return entries;
404
+ }
405
+ const allEntries = await walk(absSrc);
406
+
407
+ const { toExclude } = await inquirer.prompt([{
408
+ type: 'checkbox',
409
+ name: 'toExclude',
410
+ message: 'Select files/directories (relative to src) to exclude:',
411
+ choices: allEntries.map(rel => ({ name: rel, value: rel })),
412
+ validate(ans) {
413
+ return ans.length > 0 ? true : 'You must choose at least one entry to exclude.';
414
+ }
415
+ }]);
416
+
417
+ rawPkg.replikator.ignore = rawPkg.replikator.ignore || {};
418
+ for (const absT of selectedApps) {
419
+ const relT = path.relative(projectRoot, absT);
420
+ rawPkg.replikator.ignore[relT] = toExclude;
421
+ }
422
+ console.log(PACKAGE_JSON_ROOT_PATH)
423
+ console.log(rawPkg)
424
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, rawPkg, { spaces: 2 });
425
+ console.log(green(`Exclusion config updated for ${selectedApps.length} app(s).`));
426
+ }
427
+
263
428
  main().catch(err => {
264
429
  console.error('Fatal error:', err);
265
430
  process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@9of9solutions/replikator",
3
- "version": "1.0.13",
3
+ "version": "1.0.16",
4
4
  "type": "module",
5
5
  "main": "main.js",
6
6
  "bin": {
@@ -25,14 +25,8 @@
25
25
  "dependencies": {
26
26
  "commander": "^13.1.0",
27
27
  "degit": "^2.8.4",
28
+ "execa": "^9.5.2",
28
29
  "inquirer": "^8.2.6",
29
30
  "winston": "^3.17.0"
30
- },
31
- "replikator": {
32
- "src": "packages/shared",
33
- "targets": [
34
- "apps/app1/src/shared"
35
- ],
36
- "ignore": []
37
31
  }
38
32
  }