2

Now in the package.json I set "precommit": "lint node internal/scripts/precommit", and I want to get all the commited files path in my precommit.js, is there any way to solve this?

SmallTown NE
  • 543
  • 1
  • 7
  • 25

2 Answers2

1

In your script, you can use git command to get a list of committed files.

var cp=require('child_process')
var output=cp.execSync('cmd /c git show --pretty="" --name-only HEAD').toString()
var files=output.split('\n')
console.log(files)

The files variable will contain an array of all the files in the last commit.

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
1

From "Git pre-commit hook : changed/added files", the actual Git command would be:

git diff --cached --name-only --diff-filter=ACM -z | xargs -0 ...

You can see one possible usage in comes from templates/hooks--pre-commit.sample.
It is also actually used in the JavaScript Standard Style GitHub repo.

Finally, do use spawnSync, as in "Catching Fatal Errors with Node.js child_process"

The best way to catch errors without letting your app brick is by using the process' spawn (or in this case spawnSync) method:

var childProcess = require('child_process');

var commitMessage = (function() {
    var spawn = childProcess.spawnSync('git', ['log', '--format=%B', '-n', '1']);
    var errorText = spawn.stderr.toString().trim();

    if (errorText) {
      console.log('Fatal error from `git log`.  You must have one commit before deploying.');
      throw new Error(errorText);
    }
    else {
      return spawn.stdout.toString().trim();
    }
})();

With this method you can check the stderr buffer first; if there's a String from it you know it errored out, if no error text then the process was clean!

Adapt this method to your hook case, and change its Git command by the one suggested above.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250