git.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict'
  2. const BB = require('bluebird')
  3. const exec = require('child_process').execFile
  4. const spawn = require('./spawn')
  5. const npm = require('../npm.js')
  6. const which = require('which')
  7. const git = npm.config.get('git')
  8. const assert = require('assert')
  9. const log = require('npmlog')
  10. const noProgressTillDone = require('./no-progress-while-running.js').tillDone
  11. exports.spawn = spawnGit
  12. exports.exec = BB.promisify(execGit)
  13. exports.chainableExec = chainableExec
  14. exports.whichAndExec = whichAndExec
  15. function prefixGitArgs () {
  16. return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : []
  17. }
  18. function execGit (args, options, cb) {
  19. log.info('git', args)
  20. const fullArgs = prefixGitArgs().concat(args || [])
  21. return exec(git, fullArgs, options, noProgressTillDone(cb))
  22. }
  23. function spawnGit (args, options) {
  24. log.info('git', args)
  25. // If we're already in a git command (eg, running test as an exec
  26. // line in an interactive rebase) then these environment variables
  27. // will force git to operate on the current project, instead of
  28. // checking out/fetching/etc. whatever the user actually intends.
  29. options.env = options.env || Object.keys(process.env)
  30. .filter(k => !/^GIT/.test(k))
  31. .reduce((set, k) => {
  32. set[k] = process.env[k]
  33. return set
  34. }, {})
  35. return spawn(git, prefixGitArgs().concat(args || []), options)
  36. }
  37. function chainableExec () {
  38. var args = Array.prototype.slice.call(arguments)
  39. return [execGit].concat(args)
  40. }
  41. function whichAndExec (args, options, cb) {
  42. assert.equal(typeof cb, 'function', 'no callback provided')
  43. // check for git
  44. which(git, function (err) {
  45. if (err) {
  46. err.code = 'ENOGIT'
  47. return cb(err)
  48. }
  49. execGit(args, options, cb)
  50. })
  51. }