• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2var fs = require('graceful-fs')
3
4function extractPath (path, cmdshimContents) {
5  if (/[.]cmd$/.test(path)) {
6    return extractPathFromCmd(cmdshimContents)
7  } else if (/[.]ps1$/.test(path)) {
8    return extractPathFromPowershell(cmdshimContents)
9  } else {
10    return extractPathFromCygwin(cmdshimContents)
11  }
12}
13
14function extractPathFromPowershell (cmdshimContents) {
15  var matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+[$]args/)
16  return matches && matches[1]
17}
18
19function extractPathFromCmd (cmdshimContents) {
20  var matches = cmdshimContents.match(/"%(?:~dp0|dp0%)\\([^"]+?)"\s+%[*]/)
21  return matches && matches[1]
22}
23
24function extractPathFromCygwin (cmdshimContents) {
25  var matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+"[$]@"/)
26  return matches && matches[1]
27}
28
29function wrapError (thrown, newError) {
30  newError.message = thrown.message
31  newError.code = thrown.code
32  return newError
33}
34
35function notaShim (path, er) {
36  if (!er) {
37    er = new Error()
38    Error.captureStackTrace(er, notaShim)
39  }
40  er.code = 'ENOTASHIM'
41  er.message = "Can't read shim path from '" + path + "', it doesn't appear to be a cmd-shim"
42  return er
43}
44
45var readCmdShim = module.exports = function (path, cb) {
46  var er = new Error()
47  Error.captureStackTrace(er, readCmdShim)
48  fs.readFile(path, function (readFileEr, contents) {
49    if (readFileEr) return cb(wrapError(readFileEr, er))
50    var destination = extractPath(path, contents.toString())
51    if (destination) return cb(null, destination)
52    return cb(notaShim(path, er))
53  })
54}
55
56module.exports.sync = function (path) {
57  var contents = fs.readFileSync(path)
58  var destination = extractPath(path, contents.toString())
59  if (!destination) throw notaShim(path)
60  return destination
61}
62