Skip to content

Commit 37eed9f

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

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

merge-cli.mjs

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
console.log(args);
16+
const inputFiles = args._;
17+
18+
/*
19+
Why to avoid `process.exit()`:
20+
see https://stackoverflow.com/a/37592669/521957
21+
or https://nodejs.org/api/process.html#processexitcode.
22+
*/
23+
if (args.help) {
24+
if (inputFiles.length) {
25+
process.exitCode = 1;
26+
console.error("You can't provide `--help` or `-h` flags and input files at the same time.")
27+
} else {
28+
const help = `\
29+
npx merge
30+
[--shallow or -s] # If merge is shallow then recursion won't be used.
31+
[--help or -h]
32+
[file1.json file2.json ...]
33+
`;
34+
process.stdout.write(help);
35+
}
36+
37+
} else if (!inputFiles.length) {
38+
39+
console.log({});
40+
41+
} else {
42+
43+
const objects = inputFiles.map(
44+
(path) => {
45+
const json = fs.readFileSync(path, 'utf-8');
46+
return JSON.parse(json);
47+
}
48+
);
49+
const ifToClone = false;
50+
let merged;
51+
if (args.shallow) {
52+
merged = merge(ifToClone, ...objects);
53+
} else {
54+
merged = recursive(ifToClone, ...objects);
55+
}
56+
console.log(merged);
57+
58+
}

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)