Add test for shebang and move to index.js (#170)

When looking into adding a test, I realized that the logic was inside of bin/prettier.js and therefore only applying to the cli. Moving it to index.js and adding a test so that it's more robust :)
This commit is contained in:
Christopher Chedeau authored and James Long committed 2017-01-13 13:39:07 -05:00
1 parent ec5b0f7c76
commit df99ae56b0
5 files changed
+54 -35

No files matched your search

+1 -8
View File
@@ -33,13 +33,6 @@ if (!filenames.length && !stdin) {
process.exit(1);
}
function formatWithShebang(input) {
const index = input.indexOf("\n");
const shebang = input.slice(0, index + 1);
const programInput = input.slice(index + 1);
return shebang + format(programInput);
}
function format(input) {
return jscodefmt.format(input, {
printWidth: argv["print-width"],
@@ -77,7 +70,7 @@ if (stdin) {
let output;
try {
output = input.startsWith("#!") ? formatWithShebang(input) : format(input);
output = format(input);
} catch (e) {
process.exitCode = 2;
console.error(e);
+42 -27
View File
@@ -23,34 +23,49 @@ var babylonOptions = {
]
};
function format(text, opts) {
opts = opts || {};
let ast;
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);
}
}
else {
ast = babylon.parse(text, babylonOptions);
}
// Interleave comment nodes
if(ast.comments) {
comments.attach(ast.comments, ast, text);
ast.comments = [];
}
ast.tokens = [];
opts.originalText = text;
const printer = new Printer(opts);
return printer.printGenerically(ast).code;
}
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);
return shebang + format(programText, opts);
}
module.exports = {
format: function(text, opts) {
opts = opts || {};
let ast;
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);
}
}
else {
ast = babylon.parse(text, babylonOptions);
}
// Interleave comment nodes
if(ast.comments) {
comments.attach(ast.comments, ast, text);
ast.comments = [];
}
ast.tokens = [];
opts.originalText = text;
const printer = new Printer(opts);
return printer.printGenerically(ast).code;
return formatWithShebang(text, opts);
}
};
@@ -0,0 +1,8 @@
exports[`test shebang.js 1`] = `
"#!/usr/bin/env node
function a() {}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#!/usr/bin/env node
function a() {}
"
`;
+1
View File
@@ -0,0 +1 @@
run_spec(__dirname);
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
function a() {}