Skip to content

Instantly share code, notes, and snippets.

@zanona
Created March 2, 2016 17:10
Show Gist options
  • Save zanona/e8eed7ffcd92727c8018 to your computer and use it in GitHub Desktop.
Save zanona/e8eed7ffcd92727c8018 to your computer and use it in GitHub Desktop.
Swagger Linter outputting line and column numbers
/*jslint node:true, stupid:true*/
module.exports = function (src) {
'use strict';
src = require('path').resolve(src);
var tapi = require('sway'),
YAML = require('yaml-js'),
fs = require('fs'),
file = fs.readFileSync(src).toString();
function positionRangeForPath(yaml, path, cb) {
var invalidRange = {
start: {line: -1, column: -1},
end: {line: -1, column: -1}
},
i = 0,
ast = YAML.compose(yaml);
function find(current) {
var pair, key, value, item;
if (current.tag === 'tag:yaml.org,2002:map') {
for (i = 0; i < current.value.length; i += 1) {
pair = current.value[i];
key = pair[0];
value = pair[1];
if (key.value === path[0]) {
path.shift();
return find(value);
}
}
}
if (current.tag === 'tag:yaml.org,2002:seq') {
item = current.value[path[0]];
if (item && item.tag) {
path.shift();
return find(item);
}
}
if (path.length) { return cb(invalidRange); }
return cb({
start: {
line: current.start_mark.line,
column: current.start_mark.column
},
end: {
line: current.end_mark.line,
column: current.end_mark.column
}
});
}
find(ast);
}
tapi.create({definition: src})
.then(function (api) {
var validation = api.validate(),
error = validation.errors[0],
//warning = validation.warnings[0],
paths;
if (error) {
paths = error.path;
positionRangeForPath(file, paths, function (range) {
console.error(
error.message
+ ' in ' + src
+ ' on line ' + (range.start.line + 1)
+ ', column ' + range.start.column
);
});
}
}, function (err) {
console.error(err.stack);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment