Skip to content

Commit

Permalink
feat: add executable for npx. See #59
Browse files Browse the repository at this point in the history
Usage example: `npx merge ./foo.json ./bar.json`.
  • Loading branch information
ilyaigpetrov committed Feb 6, 2024
1 parent 9356e2f commit a0d0e4d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
57 changes: 57 additions & 0 deletions merge-cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env node
import mri from 'mri';
import fs from 'fs';

import { merge, recursive } from "./lib/index.js";

const args = mri(process.argv.slice(2), {
alias: {
s: 'shallow',
h: 'help',
},
boolean: ['shallow', 'help'],
});

const inputFiles = args._;

/*
Why to avoid `process.exit()`:
see https://stackoverflow.com/a/37592669/521957
or https://nodejs.org/api/process.html#processexitcode.
*/
if (args.help) {
if (inputFiles.length) {
process.exitCode = 1;
console.error("You can't provide `--help` or `-h` flags and input files at the same time.")
} else {
const help = `\
npx merge
[--shallow or -s] # If merge is shallow then recursion won't be used.
[--help or -h]
[file1.json file2.json ...]
`;
process.stdout.write(help);
}

} else if (!inputFiles.length) {

console.log({});

} else {

const objects = inputFiles.map(
(path) => {
const json = fs.readFileSync(path, 'utf-8');
return JSON.parse(json);
}
);
const ifToClone = false;
let merged;
if (args.shallow) {
merged = merge(ifToClone, ...objects);
} else {
merged = recursive(ifToClone, ...objects);
}
console.log(merged);

}
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
"files": [
"lib/index.d.ts"
],
"bin": {
"merge": "./merge-cli.mjs"
},
"scripts": {
"build": "tsc --build tsconfig.build.json",
"check": "prettier --cache -c .",
Expand All @@ -46,5 +49,8 @@
"prettier-plugin-sort-json": "^3.0.1",
"typescript": "^5.2.2",
"vitest": "^0.34.4"
},
"dependencies": {
"mri": "^1.2.0"
}
}

0 comments on commit a0d0e4d

Please sign in to comment.