revParse.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. var log = require('fancy-log');
  3. var exec = require('child_process').exec;
  4. /*
  5. great examples:
  6. `git rev-parse HEAD`: get current git hash
  7. `git rev-parse --short HEAD`: get short git hash
  8. `git rev-parse --abbrev-ref HEAD`: get current branch name
  9. `git rev-parse --show-toplevel`: working directory path
  10. see https://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
  11. */
  12. module.exports = function (opt, cb) {
  13. if (!cb && typeof opt === 'function') {
  14. // optional options
  15. cb = opt;
  16. opt = {};
  17. }
  18. if (!cb || typeof cb !== 'function') cb = function () {};
  19. if (!opt) opt = {};
  20. if (!opt.args) opt.args = ' '; // it will likely not give you what you want
  21. if (!opt.cwd) opt.cwd = process.cwd();
  22. var maxBuffer = opt.maxBuffer || 200 * 1024;
  23. var cmd = 'git rev-parse ' + opt.args;
  24. return exec(cmd, {cwd: opt.cwd, maxBuffer: maxBuffer}, function(err, stdout, stderr) {
  25. if (err) return cb(err);
  26. if (stdout) stdout = stdout.trim(); // Trim trailing cr-lf
  27. if (!opt.quiet) log(stdout, stderr);
  28. cb(err, stdout); // return stdout to the user
  29. });
  30. };