From bc9b1fde1958b551abdf0f916d7c86e3490b8236 Mon Sep 17 00:00:00 2001 From: Benjamin Tan Date: Wed, 18 Jan 2017 06:16:40 +0800 Subject: [PATCH] Add newline after shebang if necessary. (#215) --- bin/prettier.js | 1 + index.js | 9 ++++++--- tests/shebang/__snapshots__/jsfmt.spec.js.snap | 12 ++++++++++++ tests/shebang/shebang-newline.js | 3 +++ 4 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 tests/shebang/shebang-newline.js diff --git a/bin/prettier.js b/bin/prettier.js index 05202c8f..11b81588 100755 --- a/bin/prettier.js +++ b/bin/prettier.js @@ -1,4 +1,5 @@ #!/usr/bin/env node + "use strict"; const fs = require("fs"); const getStdin = require("get-stdin"); diff --git a/index.js b/index.js index 546c60ac..d74d07ed 100644 --- a/index.js +++ b/index.js @@ -34,8 +34,8 @@ function format(text, opts) { esproposal_export_star_as: true, }); if (ast.errors.length > 0) { - let msg = ast.errors[(0)].message + " on line " + - ast.errors[(0)].loc.start.line; + let msg = ast.errors[0].message + " on line " + + ast.errors[0].loc.start.line; if (opts.filename) { msg += " in file " + opts.filename; } @@ -65,7 +65,10 @@ function formatWithShebang(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); + const nextChar = text.charAt(index + 1); + const addNewline = nextChar == "\n" || nextChar == "\r"; + + return shebang + (addNewline ? "\n" : "") + format(programText, opts); } module.exports = { diff --git a/tests/shebang/__snapshots__/jsfmt.spec.js.snap b/tests/shebang/__snapshots__/jsfmt.spec.js.snap index db7ecc65..13e40e39 100644 --- a/tests/shebang/__snapshots__/jsfmt.spec.js.snap +++ b/tests/shebang/__snapshots__/jsfmt.spec.js.snap @@ -7,3 +7,15 @@ function a() { } " `; + +exports[`test shebang-newline.js 1`] = ` +"#!/usr/bin/env node + +function a() {} +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +#!/usr/bin/env node + +function a() { +} +" +`; diff --git a/tests/shebang/shebang-newline.js b/tests/shebang/shebang-newline.js new file mode 100644 index 00000000..91d8bb20 --- /dev/null +++ b/tests/shebang/shebang-newline.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node + +function a() {}