-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.js
More file actions
502 lines (388 loc) · 16.7 KB
/
Copy pathcli.js
File metadata and controls
502 lines (388 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
const { isSomeString } = require("@locustjs/base");
const { FolderUtil, FolderChangeType, FolderNavigationEvent } = require("./dist");
const { version } = require("./package.json");
const fs = require("fs");
const path = require("path");
const { Exception } = require("@locustjs/exception");
const chalk = require("chalk");
const os = require('os');
const readline = require("readline");
const moment = require("jalali-moment");
const workingDir = process.cwd();
function promptUser(question, toLower = true) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
const result = toLower ? answer.trim().toLowerCase() : answer.trim();
resolve(result);
});
});
}
function showHelp(examples) {
console.log(`Folder Hash v${version}`);
if (examples) {
console.log(`
Examples:
${examples == "hash" ? `
create hash for current directory
fh
create hash for /publish folder in current directory
fh hash -d ./publish
create hash for /publish folder as output.json
fh hash -d ./publish -o output.json
create hash for /publish folder in current directory, do not sort file/folders
fh hash -d ./publish -ns
create hash for /publish folder in current directory, quiet mode
fh hash -d ./publish -q`: ``}${examples == "diff" ? `
compare ./dev to ./prod directories, report changes
fh diff -f ./dev -t ./prod
compare dev.json to prod.json hash files, report changes
fh diff -f dev.json -t prod.json
compare ./dev to prod.json, report changes
fh diff -f ./dev -t prod.json
compare ./dev to ./prod directories, generate cmd batch file
fh diff -f ./dev -t ./prod -k cmd
compare ./dev to ./prod directories, generate bash file named ch20250512.sh
fh diff -f ./dev -t ./prod -k bash -o ch20250512.sh
compare ./dev to prod.json, generate cmd batch file named ch20250512.bat relative to './publish' dir
fh diff -f ./dev -t prod.json -rt ./publish -k cmd -o ch20250512.bat`: ``}${examples == "apply" ? `
compare ./dev to ./prod directories, apply changes from './dev' into './prod'.
fh apply -f ./dev -t ./prod
compare ./dev to prod.json, copy into -rt
fh apply -f ./dev -t ./prod -rt ./publish
compare ./dev to prod.json, create a compressed file
fh apply -f ./dev -t prod.json -c
compare ./dev to prod.json, create a compressed file, use fa locale in output filename
fh apply -f ./dev -t prod.json -c -l fa
compare ./dev to prod.json, create a compressed file named my-changes.zip
fh apply -f ./dev -t prod.json -c -o my-changes.zip
compare ./dev to prod.json, create a compressed file with compression level 9
fh apply -f ./dev -t prod.json -c -cl 9`: ``}`);
} else {
console.log(`
Usage: fh [cmd] [args] [options]
cmd
hash create hash for the given directory (default commad)
args
-d or --dir directory to generate hash for (default = current directory)
-o or --output name of generated output file
-io or --ignore-output ignores generating output
diff show differences of two folder hash files or create a batch file
based on differences between the two specified directories
args
-f or --from from dir
-t or --to to dir
-rf or --relative-from change 'from' paths relative to value of -rf
-rt or --relative-to change 'to' paths relative to value of -rt
-k or --kind kind of diff: 'cmd', 'bash', 'report'
notes:
it ignores extra dir/files in 'to' dir that are not found in 'from' dir
if -rf is not specified, it uses current dir "./"
if -rt is not specified, it uses 'to' dir. if 'to' dir
is not distinguishable, it uses current dir "./"
apply copy detected changes based on 'from' dir to 'to' dir into '-rt' dir
args same as 'diff' command
notes: this command is best used when -rt is specified.
options:
-? or --help help
args
'hash' show examples for 'hash' command
'diff' show examples for 'diff' command
'apply' show examples for 'apply' command
-v or --version show app version
-q or --quiet quiet mode. do not produce console messages.
-ed or --exclude-dirs excluded directories (ignore specified directories)
-ef or --exclude-files excluded files (ignore specified files)
-id or --include-dirs included directories (do not ignore specified directories)
-if or --include-files included files (do not ignore specified files)
-ns or --no-sort do not sort files/directories by name
-dbm or --debug-mode debug mode
-dp or --deep deep details
notes:
directory structure is created by default.
existing files are overwritten by default.
extra folder/files in 'to' dir that are not found in 'from' dir are not removed`);
}
}
async function FolderHashCLI(args) {
function getArg(arg, altArg, defaultValue) {
let index = args.indexOf(arg);
if (index < 0 && altArg) {
index = args.indexOf(altArg);
}
let result = index >= 0 ? args[index + 1] : undefined;
if (!isSomeString(result)) {
result = defaultValue;
}
return result;
}
function initPath(argName, altArgName, useDefaultPath = true) {
let result = getArg(argName, altArgName);
if (!isSomeString(result) && useDefaultPath) {
result = workingDir;
}
if (isSomeString(result)) {
if (!path.isAbsolute(result)) {
result = path.join(workingDir, result);
}
}
return result;
}
function initOutput(defaultName) {
let output = getArg("-o", "--output");
if (!isSomeString(output)) {
output = defaultName;
}
if (!path.isAbsolute(output)) {
output = path.join(workingDir, output);
}
return output;
}
const debugMode = args.includes("-dbm") || args.includes("--debug-mode");
const quiet = args.includes("-q") || args.includes("--quiet");
const deep = args.includes("-dp") || args.includes("--deep");
try {
if (args.includes("--help") || args.includes("-?") || args.includes("/?")) {
showHelp(getArg("--help"));
return;
}
if (args.includes("--version") || args.includes("-v")) {
console.log(version);
return;
}
const options = { debugMode }
let command = args[0];
if (!command || command.startsWith("-")) {
command = "hash";
}
let dir, changes, output, from, to, result, relFrom, relTo, kind, ignoreOutput;
options.excludeDirs = getArg("-ed", "--exclude-dirs");
options.excludeFiles = getArg("-ef", "--exclude-files");
options.includeDirs = getArg("-id", "--include-dirs");
options.includeFiles = getArg("-if", "--include-files");
options.sort = !(args.includes("-ns") || args.includes("--no-sort"));
options.compress = args.includes("-c") || args.includes("--compress")
options.compressionLevel = args.includes("-cl") || args.includes("--compress-level")
options.quiet = quiet;
options.deep = deep;
const showDetails = args.includes("-sd") || args.includes("--show-details");
ignoreOutput = args.includes("-io") || args.includes("--ignore-output");
const onProgress = (silent) => ({ fullPath, dir, state }) => {
if (!silent) {
if (dir) {
if (state == FolderNavigationEvent.onFolderNavigating) {
console.log(fullPath)
} else if (state == FolderNavigationEvent.onFolderIgnored) {
console.log(chalk.yellow(`${fullPath}: folder ignored`))
}
} else {
if (deep) {
if (state != FolderNavigationEvent.onFileIgnored) {
console.log(fullPath)
} else {
console.log(chalk.yellow(`${fullPath}: file ignored`))
}
}
}
}
}
if (debugMode) {
console.log({ options })
}
switch (command) {
case 'hash':
dir = initPath("-d", "--dir", false);
if (!isSomeString(dir)) {
const answer = await promptUser(`Generate hash for current directory (y/n)? `);
if (answer == "n") {
return;
} else {
dir = workingDir;
}
}
output = initOutput(path.parse(dir).base + ".json");
result = await FolderUtil.getHash(dir, onProgress(quiet), options);
if (!ignoreOutput) {
fs.writeFileSync(output, JSON.stringify(result, null, 4));
}
console.log((quiet ? "" : "\n") + result.hash);
if (!quiet) {
console.log(`\ngenerated ${path.parse(output).base}`);
}
break;
case 'diff':
from = initPath("-f", "--from");
to = initPath("-t", "--to");
relFrom = initPath("-rf", "--relative-from", false);
if (!isSomeString(relFrom)) {
if (!fs.statSync(from).isFile()) {
relFrom = from;
}
}
relTo = initPath("-rt", "--relative-to", false);
if (!isSomeString(relTo)) {
if (!fs.statSync(to).isFile()) {
relTo = to;
}
}
kind = getArg("-k", "--kind");
if (debugMode && deep) {
console.log({
from,
to,
relFrom,
relTo,
kind
})
}
if (!isSomeString(kind)) {
kind = "report";
}
if (!["cmd", "bash", "json", "report"].contains(kind)) {
throw `invalid output kind`;
}
if (kind == "report") {
options.onChange = (change) => {
let _path = os.platform() === 'win32' ? change.path.replace(/\//g, "\\") : change.path;
if (_path.indexOf(workingDir) >= 0) {
_path = "." + _path.substr(workingDir.length)
}
switch (change.type) {
case FolderChangeType.MissingSubDir:
console.log(chalk.magenta(`Missing sub-ir: ${_path}`));
break;
case FolderChangeType.MissingFiles:
console.log(chalk.cyan(`Empty dir: ${_path}`));
break;
case FolderChangeType.FileMismatch:
console.log(chalk.yellow(`File mismatch: ${_path}`));
break;
case FolderChangeType.MissingFile:
console.log(chalk.red(`Missing file: ${_path}`));
break;
}
}
if (showDetails) {
options.onFromProgress = options.onToProgress = onProgress(false);
}
}
changes = await FolderUtil.diff(from, to, relFrom, relTo, options);
if (debugMode) {
console.log({ changes })
}
switch (kind) {
case "cmd":
output = initOutput("sync.bat");
result = changes
.filter(x => isSomeString(x.from))
.map(x => ({
...x,
from: x.from.replace(/\//g, "\\"),
to: x.to.replace(/\//g, "\\"),
}))
.map(x => {
if (debugMode) {
console.log(x)
}
if (x.all) {
return `
xcopy "${x.from}" "${x.to}" /T/Q/Y/I/R
xcopy "${x.from}\\*.*" "${x.to}" /S/Q/Y/H/I/R`
}
if (x.dir) {
return `xcopy "${x.from}" "${x.to}" /S/Q/Y/H/I/R`
}
return `xcopy "${x.from}" "${path.parse(x.to).dir}" /S/Q/Y/H/I/R`
})
.join("\n");
if (result) {
result = `@echo off
${result}
${changes.length ? `echo ${changes.length} file(s)/dir(s) copied.` : `.`}
`;
}
break;
case "bash":
output = initOutput("sync.sh");
result = changes
.filter(x => isSomeString(x.from))
.map(x => `cp "${x.from}${x.all ? "/*" : ""}" "${x.to}" ${x.dir ? "-r" : ""} -f`)
.join("\n");
if (result) {
result = `
${result}
${changes.length ? `echo "${changes.length} file(s)/dir(s) copied."` : `echo "no changes found."`}
`;
}
break;
case "json":
output = initOutput("sync.json");
result = JSON.stringify(changes, null, 4);
break;
case "report":
output = "";
break;
}
if (output && result) {
fs.writeFileSync(output, result);
}
if (!quiet && !changes.length) {
console.log(`no changes found.`)
}
break;
case 'apply':
from = initPath("-f", "--from");
to = initPath("-t", "--to");
relFrom = initPath("-rf", "--relative-from", false);
if (!isSomeString(relFrom)) {
if (!fs.statSync(from).isFile()) {
relFrom = from;
}
}
relTo = initPath("-rt", "--relative-to", false);
if (!isSomeString(relTo)) {
if (!fs.statSync(to).isFile()) {
relTo = to;
}
}
if (options.compress) {
const locale = getArg("-l", "--locale", "en");
const now = moment().locale(locale).format('YYYYMMDDHHmmss')
options.output = initOutput(`changeset-${now}.zip`);
relTo = path.parse(options.output).dir;
}
if (debugMode && deep) {
console.log({
from,
to,
relFrom,
relTo,
options
})
}
changes = await FolderUtil.apply(from, to, relFrom, relTo, options);
if (!quiet) {
if (changes.length) {
console.log(`${changes.length} file(s)/dir(s) copied.`)
} else {
console.log(`no changes found.`)
}
}
break;
default:
console.log(`unknown command ${command}`);
break;
}
} catch (error) {
const ex = new Exception(error)
console.error(`Error: ${ex.toString()}`);
if (debugMode) {
console.log(ex.stackTrace)
}
}
}
FolderHashCLI(process.argv.slice(2))