Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support globs and fix some issues #104

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 72 additions & 104 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,87 +2,80 @@

var fs = require("fs");
var path = require("path");
var parser = require("./jsonlint").parser;
var program = require("commander");
var JSV = require("JSV").JSV;
var parser = require("./jsonlint").parser;
var formatter = require("./formatter.js").formatter;

var options = require("nomnom")
.script("jsonlint")
.options({
file: {
position: 0,
help: "file to parse; otherwise uses stdin"
},
version: {
flag : true,
string: '-v, --version',
help: 'print version and exit',
callback: function() {
return require("../package").version;
var pkg = require('../package.json');

var hasError = false;

program
.version(pkg.version, '-v, --version')
.description(pkg.description)
.name(pkg.name)
.arguments('[file...]')
.action(main)
.option('-s, --sort-keys', 'sort object keys')
.option('-i, --in-place', 'overwrite the file')
.option('-t, --indent <char>', 'character(s) to use for indentation', ' ')
.option('-c, --compact', 'compact error display')
.option('-V, --validate', 'a JSON schema to use for validation')
.option('-e, --environment <schema>', 'which specification of JSON Schema the validation file uses', 'json-schema-draft-03')
.option('-q, --quiet', 'do not print the parsed json to STDOUT')
.option('-p, --pretty-print', 'force pretty printing even if invalid')
.allowUnknownOption()
.parse(process.argv);

function main(files) {
var options = program.opts();

if (files) {
files.forEach(function (file) {
var filePath = path.normalize(file);
var code = parse(fs.readFileSync(filePath, 'utf8'), file, options);

if (options.inPlace) {
fs.writeSync(fs.openSync(json, 'w+'), code, 0, "utf8");
} else {
if (!options.quiet) { console.log(code) };
}
},
sort : {
flag : true,
string: '-s, --sort-keys',
help: 'sort object keys'
},
inplace : {
flag : true,
string: '-i, --in-place',
help: 'overwrite the file'
},
indent : {
string: '-t CHAR, --indent CHAR',
"default": " ",
help: 'character(s) to use for indentation'
},
compact : {
flag : true,
string: '-c, --compact',
help : 'compact error display'
},
validate : {
string: '-V, --validate',
help : 'a JSON schema to use for validation'
},
env : {
string: '-e, --environment',
"default": "json-schema-draft-03",
help: 'which specification of JSON Schema the validation file uses'
},
quiet: {
flag: true,
key: "value",
string: '-q, --quiet',
"default": false,
help: 'do not print the parsed json to STDOUT'
},
forcePrettyPrint: {
flag: true,
string: '-p, --pretty-print',
help: 'force pretty printing even if invalid'
}
}).parse();
});
} else {
var stdin = process.openStdin();
var code = '';

if (options.compact) {
var fileName = options.file? options.file + ': ' : '';
parser.parseError = parser.lexer.parseError = function(str, hash) {
console.error(fileName + 'line '+ hash.loc.first_line +', col '+ hash.loc.last_column +', found: \''+ hash.token +'\' - expected: '+ hash.expected.join(', ') +'.');
throw new Error(str);
};
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
code += chunk.toString('utf8');
});
stdin.on('end', function () {
if (!options.quiet) { console.log(parse(code, null, options)) };
});
}

hasError && process.exit(1);
}

function parse (source) {
function parse(source, file, options) {
var parsed,
formatted;
formatted;

if (options.compact) {
var fileName = file ? file + ': ' : '';
parser.parseError = parser.lexer.parseError = function (str, hash) {
console.error(fileName + 'line ' + hash.loc.first_line + ', col ' + hash.loc.last_column + ', found: \'' + hash.token + '\' - expected: ' + hash.expected.join(', ') + '.');
throw new Error(str);
};
}

try {
parsed = options.sort ?
parsed = options.sortKeys ?
sortObject(parser.parse(source)) :
parser.parse(source);

if (options.validate) {
var env = JSV.createEnvironment(options.env);
var env = JSV.createEnvironment(options.environment);
var schema = JSON.parse(fs.readFileSync(path.normalize(options.validate), "utf8"));
var report = env.validate(parsed, schema);
if (report.errors.length) {
Expand All @@ -92,7 +85,7 @@ function parse (source) {

return JSON.stringify(parsed, null, options.indent);
} catch (e) {
if (options.forcePrettyPrint) {
if (options.prettyPrint) {
/* From https://github.com/umbrae/jsonlintdotcom:
* If we failed to validate, run our manual formatter and then re-validate so that we
* can get a better line number. On a successful validate, we don't want to run our
Expand All @@ -104,51 +97,28 @@ function parse (source) {
// Re-parse so exception output gets better line numbers
parsed = parser.parse(formatted);
} catch (e) {
if (! options.compact) {
if (!options.compact) {
console.error(e);
}
// force the pretty print before exiting
console.log(formatted);
}
} else {
if (! options.compact) {
if (!options.compact) {
console.error(e);
}
}
process.exit(1);
hasError = true;
}
}

function schemaError (str, err) {
function schemaError(str, err) {
return str +
"\n\n"+err.message +
"\nuri: " + err.uri +
"\nschemaUri: " + err.schemaUri +
"\nattribute: " + err.attribute +
"\ndetails: " + JSON.stringify(err.details);
}

function main (args) {
var source = '';
if (options.file) {
var json = path.normalize(options.file);
source = parse(fs.readFileSync(json, "utf8"));
if (options.inplace) {
fs.writeSync(fs.openSync(json,'w+'), source, 0, "utf8");
} else {
if (! options.quiet) { console.log(source)};
}
} else {
var stdin = process.openStdin();
stdin.setEncoding('utf8');

stdin.on('data', function (chunk) {
source += chunk.toString('utf8');
});
stdin.on('end', function () {
if (! options.quiet) {console.log(parse(source))};
});
}
"\n\n" + err.message +
"\nuri: " + err.uri +
"\nschemaUri: " + err.schemaUri +
"\nattribute: " + err.attribute +
"\ndetails: " + JSON.stringify(err.details);
}

// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
Expand All @@ -160,7 +130,7 @@ function sortObject(o) {
}

var sorted = {},
key, a = [];
key, a = [];

for (key in o) {
if (o.hasOwnProperty(key)) {
Expand All @@ -175,5 +145,3 @@ function sortObject(o) {
}
return sorted;
}

main(process.argv.slice(1));
Loading