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 37eed9f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
58 changes: 58 additions & 0 deletions merge-cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/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'],
});

console.log(args);
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 37eed9f

Please sign in to comment.