Skip to content

Commit

Permalink
Merge pull request #4 from codelicia/fix_code_style
Browse files Browse the repository at this point in the history
Fix file when option is passed
  • Loading branch information
airtonzanon committed Aug 26, 2019
2 parents ff1bf04 + a850ec4 commit 2679a6b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 17 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
48 changes: 35 additions & 13 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,42 +10,64 @@ const jsdiff = require("diff");
const program = new commander.Command();

let jsonFile = "";
let hasErrors = false;

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;

showDiff(diff);
fixJson(filePath, formatted);

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

process.exit(0);
}

function fixJson(filePath, formatted) {
if (!program.fix) {
return;
}

fs.writeFile(filePath, formatted, (err) => {
if (err) {
process.exit(1);
}
});
console.log(filePath + " - has been fixed");
hasErrors = false;
}

function showDiff(diff) {
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) {
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 2679a6b

Please sign in to comment.