1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var fs = require('fs')
|
9 | var path = require('path')
|
10 | var spawn = require('child_process').spawn
|
11 | var Promise = require('es6-promise').Promise
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | try {
|
19 | var location = require('./location')
|
20 | exports.path = path.resolve(__dirname, location.location)
|
21 | exports.platform = location.platform
|
22 | exports.arch = location.arch
|
23 | } catch(e) {
|
24 |
|
25 | exports.path = null
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | exports.version = '2.1.1'
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | exports.cleanPath = function (path) {
|
43 | return path
|
44 | .replace(/:[^:]*node_modules[^:]*/g, '')
|
45 | .replace(/(^|:)\.\/bin(\:|$)/g, ':')
|
46 | .replace(/^:+/, '')
|
47 | .replace(/:+$/, '')
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | if (exports.path) {
|
54 | try {
|
55 |
|
56 | var st = fs.statSync(exports.path)
|
57 | var mode = st.mode | parseInt('0555', 8)
|
58 | if (mode !== st.mode) {
|
59 | fs.chmodSync(exports.path, mode)
|
60 | }
|
61 | } catch (e) {
|
62 |
|
63 |
|
64 | }
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | exports.exec = function () {
|
71 | var args = Array.prototype.slice.call(arguments)
|
72 | return spawn(exports.path, args)
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | exports.run = function () {
|
86 | var args = arguments
|
87 | return new Promise(function (resolve, reject) {
|
88 | try {
|
89 | var program = exports.exec.apply(null, args)
|
90 | var isFirst = true
|
91 | var stderr = ''
|
92 | program.stdout.on('data', function () {
|
93 |
|
94 | if (!isFirst) return
|
95 | isFirst = false
|
96 | resolve(program)
|
97 | })
|
98 | program.stderr.on('data', function (data) {
|
99 | stderr = stderr + data.toString('utf8')
|
100 | })
|
101 | program.on('error', function (err) {
|
102 | if (!isFirst) return
|
103 | isFirst = false
|
104 | reject(err)
|
105 | })
|
106 | program.on('exit', function (code) {
|
107 | if (!isFirst) return
|
108 | isFirst = false
|
109 | if (code == 0) {
|
110 |
|
111 | if (stderr.indexOf('Error:') == 0) {
|
112 | reject(new Error(stderr))
|
113 | } else {
|
114 | resolve(program)
|
115 | }
|
116 | } else {
|
117 | reject(new Error('Exit code: ' + code))
|
118 | }
|
119 | })
|
120 | } catch (err) {
|
121 | reject(err)
|
122 | }
|
123 | })
|
124 | }
|