Skip to content

Commit a0d0e4d

Browse files
committed
feat: add executable for npx. See #59
Usage example: `npx merge ./foo.json ./bar.json`.
1 parent 9356e2f commit a0d0e4d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

merge-cli.mjs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/env node
2+
import mri from 'mri';
3+
import fs from 'fs';
4+
5+
import { merge, recursive } from "./lib/index.js";
6+
7+
const args = mri(process.argv.slice(2), {
8+
alias: {
9+
s: 'shallow',
10+
h: 'help',
11+
},
12+
boolean: ['shallow', 'help'],
13+
});
14+
15+
const inputFiles = args._;
16+
17+
/*
18+
Why to avoid `process.exit()`:
19+
see https://stackoverflow.com/a/37592669/521957
20+
or https://nodejs.org/api/process.html#processexitcode.
21+
*/
22+
if (args.help) {
23+
if (inputFiles.length) {
24+
process.exitCode = 1;
25+
console.error("You can't provide `--help` or `-h` flags and input files at the same time.")
26+
} else {
27+
const help = `\
28+
npx merge
29+
[--shallow or -s] # If merge is shallow then recursion won't be used.
30+
[--help or -h]
31+
[file1.json file2.json ...]
32+
`;
33+
process.stdout.write(help);
34+
}
35+
36+
} else if (!inputFiles.length) {
37+
38+
console.log({});
39+
40+
} else {
41+
42+
const objects = inputFiles.map(
43+
(path) => {
44+
const json = fs.readFileSync(path, 'utf-8');
45+
return JSON.parse(json);
46+
}
47+
);
48+
const ifToClone = false;
49+
let merged;
50+
if (args.shallow) {
51+
merged = merge(ifToClone, ...objects);
52+
} else {
53+
merged = recursive(ifToClone, ...objects);
54+
}
55+
console.log(merged);
56+
57+
}

package.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@
2727
"files": [
2828
"lib/index.d.ts"
2929
],
30+
"bin": {
31+
"merge": "./merge-cli.mjs"
32+
},
3033
"scripts": {
3134
"build": "tsc --build tsconfig.build.json",
3235
"check": "prettier --cache -c .",
@@ -46,5 +49,8 @@
4649
"prettier-plugin-sort-json": "^3.0.1",
4750
"typescript": "^5.2.2",
4851
"vitest": "^0.34.4"
52+
},
53+
"dependencies": {
54+
"mri": "^1.2.0"
4955
}
5056
}

0 commit comments

Comments
 (0)