Preserve shebang in CLI output (#1899)

This fixes https://github.com/prettier/prettier/issues/1890, albeit in a
quick-and-dirty way. Note also that the cursor offset may be incorrect
when there is a shebang, but that's a separate issue.
master
Joseph Frazier 2017-06-02 15:46:20 -04:00 committed by Christopher Chedeau
parent 26e829b987
commit c15091bea6
1 changed files with 10 additions and 6 deletions

View File

@ -252,9 +252,9 @@ function formatRange(text, opts, ast) {
}
}
function formatWithShebang(text, opts) {
function fixShebang(text, formatted) {
if (!text.startsWith("#!")) {
return format(text, opts);
return formatted;
}
const index = text.indexOf("\n");
@ -262,19 +262,23 @@ function formatWithShebang(text, opts) {
const nextChar = text.charAt(index + 1);
const newLine = nextChar === "\n" ? "\n" : nextChar === "\r" ? "\r\n" : "";
return shebang + newLine + format(text, opts);
return shebang + newLine + formatted;
}
module.exports = {
formatWithCursor: function(text, opts) {
return formatWithCursor(text, normalizeOptions(opts));
const result = formatWithCursor(text, normalizeOptions(opts));
return {
formatted: fixShebang(text, result.formatted),
cursorOffset: result.cursorOffset
};
},
format: function(text, opts) {
return formatWithShebang(text, normalizeOptions(opts));
return fixShebang(text, format(text, normalizeOptions(opts)));
},
check: function(text, opts) {
try {
const formatted = formatWithShebang(text, normalizeOptions(opts));
const formatted = fixShebang(text, format(text, normalizeOptions(opts)));
return formatted === text;
} catch (e) {
return false;