diff --git a/README.md b/README.md index 20b987a..9a7e7b8 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ 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 @@ -20,6 +24,7 @@ Verify if the code style is fine: Usage: jsoncs [file] Options: + -f, --fix Fix the file -v, --version print version and exit ### Example @@ -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 diff --git a/lib/cli.js b/lib/cli.js index cf8cdb4..1d51a8b 100755 --- a/lib/cli.js +++ b/lib/cli.js @@ -15,6 +15,8 @@ program. version(packageVersion, "-v, --version", "json code style version") + .option("-f, --fix", + "fix json file") .arguments("[json]") .action(function (json) { jsonFile = json; @@ -22,30 +24,43 @@ program. 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); diff --git a/package.json b/package.json index 6cc47c4..4f10fc2 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "code", "style" ], - "version": "0.0.2", + "version": "0.1.0", "preferGlobal": true, "repository": { "type": "git",