Skip to content

Commit

Permalink
Fix file when option is passed
Browse files Browse the repository at this point in the history
Save the formatted JSON on the file that it came from.

Signed-off-by: Airton Zanon <me@airton.dev>
  • Loading branch information
airtonzanon committed Aug 25, 2019
1 parent ff1bf04 commit 9819c6f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@ Verify if the code style is fine:

./node_modules/.bin/jsoncs my/file.json

Fix the code style of a file:

./node_modules/.bin/jsoncs --fix my/file.json

### Options

$ jsoncs -h

Usage: jsoncs [file]

Options:
-f, --fix Fix the file
-v, --version print version and exit

### Example
Expand All @@ -31,6 +36,5 @@ Verify if the code style is fine:

## TO-DO

* Fix the errors found by the JSONCS
* Make it multiple files
* Leave the code style to the user
* Make it accept multiple files
* Leave the code style to the user in a config file
29 changes: 22 additions & 7 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,52 @@ program.
version(packageVersion,
"-v, --version",
"json code style version")
.option("-f, --fix",
"fix json file")
.arguments("[json]")
.action(function (json) {
jsonFile = json;
});

program.parse(process.argv);

function parse(source) {
function parse(filePath) {
let source = fs.readFileSync(filePath, "utf8");

let formatted = formatter.formatJson(source);
let diff = jsdiff.diffJson(source, formatted);
let hasChanges = false;
let hasErrors = false;

diff.forEach((part) => {
let color = part.added ? "\x1b[34m" : part.removed ? "\x1b[31m" : "\x1b[37m";

if (part.added || part.removed) {
console.log(color, part.value);
hasChanges = true;
hasErrors = true;
}
});

if (hasChanges) {
if (program.fix) {
fs.writeFile(filePath, formatted, (err) => {
if (err) {
process.exit(1);
}
});

console.log(filePath + ' - has been fixed');
hasErrors = false;
}

if (hasErrors) {
process.exit(1);
}

process.exit(0);
}

function main(args) {
let json = path.normalize(args);
parse(fs.readFileSync(json, "utf8"));
function main(jsonFilePath) {
let filePath = path.normalize(jsonFilePath);
parse(filePath);
}

main(jsonFile);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"code",
"style"
],
"version": "0.0.2",
"version": "0.1.0",
"preferGlobal": true,
"repository": {
"type": "git",
Expand Down

0 comments on commit 9819c6f

Please sign in to comment.