prettier/index.js

59 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-11-29 23:23:00 +03:00
const recast = require("recast");
const babylon = require("babylon");
const Printer = require("./src/printer").Printer;
const flowParser = require("flow-parser");
2016-11-29 23:23:00 +03:00
var babylonOptions = {
sourceType: 'module',
allowImportExportEverywhere: false,
allowReturnOutsideFunction: false,
plugins: [
'asyncFunctions',
'asyncGenerators',
'classConstructorCall',
'classProperties',
'decorators',
'doExpressions',
'exponentiationOperator',
'exportExtensions',
'flow',
'functionSent',
'functionBind',
'jsx',
'objectRestSpread',
'trailingFunctionCommas'
]
};
module.exports = {
format: function(text, opts={}) {
2016-11-30 18:02:23 +03:00
let { tabWidth = 2, printWidth = 80 } = opts;
let ast;
2016-11-29 23:23:00 +03:00
if(opts.useFlowParser) {
ast = flowParser.parse(text);
if(ast.errors.length > 0) {
let msg = ast.errors[0].message + " on line " + ast.errors[0].loc.start.line
if(opts.filename) {
msg += " in file " + opts.filename;
}
throw new Error(msg);
2016-12-30 21:32:43 +03:00
}
}
else {
ast = recast.parse(text, {
parser: {
parse: function(source) {
return babylon.parse(source, babylonOptions);
}
}
});
2016-12-30 21:32:43 +03:00
}
2016-11-29 23:23:00 +03:00
ast.tokens = [];
const printer = new Printer({ tabWidth, wrapColumn: printWidth });
return printer.printGenerically(ast).code;
2016-11-29 23:23:00 +03:00
}
};