Skip to content

Commit f5c064f

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

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

merge-cli.mjs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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'],
13+
});
14+
15+
const inputFiles = args._;
16+
17+
// Why to avoid `process.exit()`: https://stackoverflow.com/a/37592669/521957.
18+
if (args.help) {
19+
20+
const help = `\
21+
npx merge
22+
[--shallow or -s] # If merge is shallow then recursion won't be used.
23+
[--help or -h]
24+
[file1.json file2.json ...]
25+
`;
26+
process.stdout.write(help);
27+
28+
} else if (!inputFiles.length) {
29+
30+
console.log({});
31+
32+
} else {
33+
34+
const objects = inputFiles.map(
35+
(path) => {
36+
const json = fs.readFileSync(path, 'utf-8');
37+
return JSON.parse(json);
38+
}
39+
);
40+
const ifToClone = false;
41+
let merged;
42+
if (args.shallow) {
43+
merged = merge(ifToClone, ...objects);
44+
} else {
45+
merged = recursive(ifToClone, ...objects);
46+
}
47+
console.log(merged);
48+
49+
}

package.json

+6
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)