Files
test-repo/index.js
T

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-01-10 12:18:22 -05:00
"use strict";
const comments = require("./src/comments");
2017-01-18 15:31:46 -08:00
const version = require("./package.json").version;
const printAstToDoc = require("./src/printer").printAstToDoc;
const printDocToString = require("./src/doc-printer").printDocToString;
const normalizeOptions = require("./src/options").normalize;
2017-01-19 13:23:04 -08:00
const parser = require("./src/parser");
2017-01-20 09:54:32 -08:00
const printDocToDebug = require("./src/doc-debug").printDocToDebug;
2016-11-29 15:23:00 -05:00
2017-01-19 14:18:22 -08:00
function parse(text, opts) {
2017-01-20 10:12:37 -08:00
if (opts.parser === "flow") {
2017-01-19 14:18:22 -08:00
return parser.parseWithFlow(text, opts.filename);
}
2017-01-19 14:18:22 -08:00
return parser.parseWithBabylon(text);
}
2017-01-19 14:18:22 -08:00
function attachComments(text, ast, opts) {
2017-01-13 15:03:53 -05:00
if (ast.comments) {
comments.attach(ast.comments, ast, text);
ast.comments = [];
}
ast.tokens = [];
opts.originalText = text;
2017-01-19 14:18:22 -08:00
}
2017-01-19 14:18:22 -08:00
function format(text, opts) {
const ast = parse(text, opts);
2017-01-20 09:54:32 -08:00
attachComments(text, ast, opts);
const doc = printAstToDoc(ast, opts);
const str = printDocToString(doc, opts.printWidth);
return str;
}
function formatWithShebang(text, opts) {
if (!text.startsWith("#!")) {
return format(text, opts);
}
const index = text.indexOf("\n");
const shebang = text.slice(0, index + 1);
const programText = text.slice(index + 1);
const nextChar = text.charAt(index + 1);
const addNewline = nextChar == "\n" || nextChar == "\r";
return shebang + (addNewline ? "\n" : "") + format(programText, opts);
}
2016-11-29 15:23:00 -05:00
module.exports = {
2017-01-10 12:18:22 -05:00
format: function(text, opts) {
2017-01-19 14:18:22 -08:00
return formatWithShebang(text, normalizeOptions(opts));
2017-01-18 12:45:44 -08:00
},
2017-01-20 09:54:32 -08:00
version: version,
__debug: {
// Doesn't handle shebang for now
formatDoc: function(doc, opts) {
opts = normalizeOptions(opts);
const debug = printDocToDebug(doc);
const str = format(debug, opts);
return str;
},
printToDoc: function(text, opts) {
opts = normalizeOptions(opts);
const ast = parse(text, opts);
attachComments(text, ast, opts);
const doc = printAstToDoc(ast, opts);
return doc;
},
printDocToString: function(doc, opts) {
opts = normalizeOptions(opts);
const str = printDocToString(doc, opts.printWidth);
return str;
}
}
2016-11-29 15:23:00 -05:00
};