From 130b36b699e12aea4a7724d2b3cfc7891e06c0eb Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Wed, 10 May 2017 21:33:20 +0100 Subject: [PATCH] fix(gitUtils): support new repos / unborn branches This is not tested at the moment due to a mock-git limitation. --- .../__snapshots__/index.test.js.snap | 6 ++--- src/gitUtils.js | 22 +++++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/__tests__/__snapshots__/index.test.js.snap b/src/__tests__/__snapshots__/index.test.js.snap index 81b26ac..255217a 100644 --- a/src/__tests__/__snapshots__/index.test.js.snap +++ b/src/__tests__/__snapshots__/index.test.js.snap @@ -4,7 +4,7 @@ exports[`git-exec-and-restage no command, no args and no files staged 1`] = `[Er exports[`git-exec-and-restage with command and arguments, no files 1`] = ` Array [ - "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD", + "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD --", "git diff --name-only --diff-filter=ACDMRTUXB", "prettier --write", ] @@ -20,7 +20,7 @@ Array [ exports[`git-exec-and-restage with command+args, files implicit 1`] = ` Array [ - "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD", + "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD --", "git diff --name-only --diff-filter=ACDMRTUXB fullystaged.js partiallystaged.js", "prettier --write", "git add fullystaged.js", @@ -53,7 +53,7 @@ Array [ exports[`git-exec-and-restage with command, no args and no files 1`] = ` Array [ - "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD", + "git diff-index --cached --name-only --diff-filter=ACDMRTUXB HEAD --", "git diff --name-only --diff-filter=ACDMRTUXB", "prettier", ] diff --git a/src/gitUtils.js b/src/gitUtils.js index c17bae7..f4cdb92 100644 --- a/src/gitUtils.js +++ b/src/gitUtils.js @@ -8,7 +8,9 @@ function ensureRelativePath(s) { return s; } -async function getAllStaged() { +const GIT_EMPTY_HASH = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; + +async function getAllStagedFromRevision(revision) { const diffOut = (await spawn( "git", @@ -17,7 +19,8 @@ async function getAllStaged() { "--cached", "--name-only", "--diff-filter=ACDMRTUXB", - "HEAD" + revision, + "--" ], { encoding: "utf8" @@ -26,6 +29,21 @@ async function getAllStaged() { return diffOut.split("\n").filter(s => s !== ""); } +async function getAllStaged() { + try { + return await getAllStagedFromRevision("HEAD"); + } catch (e) { + // istanbul ignore else: simple exception passthrough + if ( + e.stderr && + e.stderr.toString().indexOf("fatal: bad revision 'HEAD'") !== -1 + ) { + return await getAllStagedFromRevision(GIT_EMPTY_HASH); + } + throw e; + } +} + async function getFullyStaged( /* istanbul ignore next: convenience default */ files = []