-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
376 lines (324 loc) · 10.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
'use strict'
/*
* gulp-ssh
* https://github.com/teambition/gulp-ssh
*
* Licensed under the MIT license.
*/
const colors = require('ansicolors')
const log = require('fancy-log')
const fs = require('fs')
const os = require('os')
const path = require('path')
const EventEmitter = require('events').EventEmitter
const File = require('vinyl')
const PluginError = require('plugin-error')
const through = require('through2')
const SSH2Client = require('ssh2').Client
const packageName = require('./package.json').name
class Client extends SSH2Client {
gulpFlushReady () {
this.gulpConnected = true
while (this.gulpQueue.length) this.gulpQueue.shift().call(this)
}
gulpReady (cb) {
if (this.gulpConnected) cb.call(this)
else this.gulpQueue.push(cb)
}
}
Client.prototype.gulpId = null
Client.prototype.gulpQueue = null
Client.prototype.gulpConnected = false
var gulpId = 0
class GulpSSH extends EventEmitter {
constructor (options) {
if (!options || !options.sshConfig) throw new Error('options.sshConfig required!')
super()
this.options = options
this.connections = Object.create(null)
}
getClient () {
const ctx = this
const ssh = new Client()
const options = this.options
ssh.gulpId = gulpId++
ssh.gulpQueue = []
ssh.gulpConnected = false
this.connections[ssh.gulpId] = ssh
ssh
.on('error', function (err) {
ctx.emit('error', new PluginError(packageName, err))
})
.on('end', function () {
delete ctx.connections[this.gulpId]
})
.on('close', function () {
delete ctx.connections[this.gulpId]
})
.on('ready', ssh.gulpFlushReady)
let sshConfig = options.sshConfig
let privateKeyFile = sshConfig.privateKeyFile
if (privateKeyFile) {
if (privateKeyFile.charAt() === '~' && (path.sep === '\\'
? /\/|\\/.test(privateKeyFile.charAt(1)) : privateKeyFile.charAt(1) === '/')) {
privateKeyFile = os.homedir() + privateKeyFile.substr(1)
}
const gulpSSH = this
fs.readFile(privateKeyFile, function (err, privateKey) {
if (err) throw err
sshConfig = Object.assign({}, sshConfig, { privateKey })
delete sshConfig.privateKeyFile
gulpSSH.options = Object.assign({}, options, { sshConfig })
ssh.connect(sshConfig)
})
} else {
if (sshConfig.useAgent) {
sshConfig = Object.assign({}, sshConfig, { agent: process.env.SSH_AUTH_SOCK })
delete sshConfig.useAgent
this.options = Object.assign({}, options, { sshConfig })
}
ssh.connect(sshConfig)
}
return ssh
}
close () {
for (let id of Object.keys(this.connections)) {
this.connections[id].end()
delete this.connections[id]
}
}
exec (commands, options) {
const ctx = this
const ssh = this.getClient()
const outStream = through.obj()
const chunks = []
let chunkSize = 0
if (!commands) throw new PluginError(packageName, '`commands` required.')
options = options || {}
commands = Array.isArray(commands) ? commands.slice() : [commands]
ssh.gulpReady(execCommand)
function endStream () {
outStream.push(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, options.filePath || 'gulp-ssh.exec.log'),
contents: Buffer.concat(chunks, chunkSize)
}))
ssh.end()
outStream.end()
}
function execCommand () {
if (!commands.length) return endStream()
const command = commands.shift()
if (typeof command !== 'string') return execCommand()
log(packageName + ' :: Executing :: ' + command)
ssh.exec(command, options, function (err, stream) {
if (err) return outStream.emit('error', new PluginError(packageName, err))
stream
.on('data', function (chunk) {
chunkSize += chunk.length
chunks.push(chunk)
outStream.emit('ssh2Data', chunk)
})
.on('exit', function (code, signalName, didCoreDump, description) {
if (ctx.ignoreErrors === false && code == null) {
const message = signalName + ', ' + didCoreDump + ', ' + description
outStream.emit('error', new PluginError(packageName, message))
}
})
.on('close', execCommand)
.stderr.on('data', function (data) {
outStream.emit('error', new PluginError(packageName, data + ''))
})
})
}
return outStream
}
sftp (command, filePath, options) {
const ssh = this.getClient()
let outStream
options = options || {}
if (!command) throw new PluginError(packageName, '`command` required.')
if (!filePath) throw new PluginError(packageName, '`filePath` required.')
if (command === 'write') {
outStream = through.obj(function (file, encoding, callback) {
ssh.gulpReady(function () {
ssh.sftp(function (err, sftp) {
if (err) return callback(new PluginError(packageName, err))
options.autoClose = true
const write = sftp.createWriteStream(filePath, options)
write
.on('error', function (error) {
err = error
})
.on('finish', function () {
sftp.end()
if (err) callback(err)
else callback(null, file)
})
if (file.isStream()) file.contents.pipe(write)
else if (file.isBuffer()) write.end(file.contents)
else {
err = new PluginError(packageName, 'file error!')
write.end()
}
})
})
}, function (callback) {
ssh.end()
callback()
})
} else if (command === 'read') {
const chunks = []
let chunkSize = 0
outStream = through.obj()
ssh.gulpReady(function () {
ssh.sftp(function (err, sftp) {
if (err) return outStream.emit('error', new PluginError(packageName, err))
const read = sftp.createReadStream(filePath, options)
options.base = options.base || ''
read
.on('data', function (chunk) {
chunkSize += chunk.length
chunks.push(chunk)
})
.on('error', function (err) {
outStream.emit('error', err)
})
.on('end', function () {
outStream.push(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, options.filePath || filePath),
contents: Buffer.concat(chunks, chunkSize)
}))
this.close()
})
.on('close', function () {
sftp.end()
ssh.end()
outStream.end()
})
})
})
} else throw new PluginError(packageName, 'Command "' + command + '" not supported.')
return outStream
}
// Acts similarly to Gulp dest, will make dirs if not exist and copy the files
// to the glob path
dest (destDir, options) {
if (!destDir) throw new PluginError(packageName, '`destDir` required.')
let sftpClient = null
const ssh = this.getClient()
options = options || {}
options.autoClose = false
function getSftp (callback) {
if (sftpClient) return callback(null, sftpClient)
ssh.gulpReady(function () {
ssh.sftp(function (err, sftp) {
if (err) return callback(err)
sftpClient = sftp
callback(null, sftp)
})
})
}
function end (err, callback) {
if (sftpClient) {
sftpClient.end()
sftpClient = null
}
ssh.end()
if (err) err = new PluginError(packageName, err)
callback(err)
}
return through.obj(function (file, encoding, callback) {
if (file.isNull()) {
log('"' + colors.cyan(file.path) + '" has no content. Skipping.')
return callback()
}
getSftp(function (err, sftp) {
if (err) return end(err, callback)
let outPath = path.join(destDir, file.relative)
if (path.sep === '\\') outPath = outPath.replace(/\\/g, '/')
log('Preparing to write "' + colors.cyan(outPath) + '"')
internalMkDirs(sftp, outPath, function (err) {
if (err) return end(err, callback)
log('Writing \'' + colors.cyan(outPath) + '\'')
const write = sftp.createWriteStream(outPath, options)
write
.on('error', done)
.on('finish', done)
if (file.isStream()) {
file.contents.pipe(write)
} else if (file.isBuffer()) {
write.end(file.contents)
}
function done (err) {
if (err) return end(err, callback)
log('Finished writing \'' + colors.cyan(outPath) + '\'')
callback()
}
})
})
}, function (callback) {
end(null, callback)
})
}
shell (commands, options) {
const ssh = this.getClient()
const outStream = through.obj()
const chunks = []
let chunkSize = 0
if (!commands) throw new PluginError(packageName, '`commands` required.')
options = options || {}
commands = Array.isArray(commands) ? commands.slice() : [commands]
function endStream () {
outStream.push(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, options.filePath || 'gulp-ssh.exec.log'),
contents: Buffer.concat(chunks, chunkSize)
}))
ssh.end()
outStream.end()
}
ssh.gulpReady(function () {
if (commands.length === 0) return endStream()
ssh.shell(function (err, stream) {
if (err) return outStream.emit('error', new PluginError(packageName, err))
stream
.on('data', function (chunk) {
chunkSize += chunk.length
chunks.push(chunk)
outStream.emit('ssh2Data', chunk)
})
.on('close', endStream)
.stderr.on('data', function (data) {
outStream.emit('error', new PluginError(packageName, data + ''))
})
let lastCommand
commands.forEach(function (command) {
if (command[command.length - 1] !== '\n') command += '\n'
log(packageName + ' :: shell :: ' + command)
stream.write(command)
lastCommand = command
})
if (options.autoExit !== false) stream.end(lastCommand === 'exit\n' ? null : 'exit\n')
})
})
return outStream
}
}
function internalMkDirs (sftp, filePath, callback) {
const outPathDir = path.dirname(filePath).replace(/\\/g, '/')
sftp.exists(outPathDir, function (result) {
if (result) return callback()
// recursively make parent directories as required
internalMkDirs(sftp, outPathDir, function (err) {
if (err) return callback(err)
log('Creating directory \'' + colors.cyan(outPathDir) + '\'')
sftp.mkdir(outPathDir, callback)
})
})
}
module.exports = GulpSSH