forked from gtg092x/gulp-sftp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
342 lines (266 loc) · 10.5 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
'use strict';
var path = require('path');
var fs = require('fs');
var util = require('util');
var through = require('through2');
var Connection = require('ssh2');
var async = require('async');
var parents = require('parents');
var Stream = require('stream');
var assign = require('object-assign');
var PluginError = require('plugin-error');
var log = require('fancy-log');
var colors = require('ansi-colors');
var normalizePath = function(path){
return path.replace(/\\/g, '/');
};
module.exports = function (options) {
options = assign({}, options);// credit sindresorhus
if (options.host === undefined) {
throw new PluginError('gulp-sftp', '`host` required.');
}
var fileCount = 0;
var remotePath = options.remotePath || '/';
var remotePlatform = options.remotePlatform || options.platform || 'unix';
options.authKey = options.authKey||options.auth;
var authFilePath = options.authFile || '.ftppass';
var authFile=path.join('./',authFilePath);
if(options.authKey && fs.existsSync(authFile)){
var auth = JSON.parse(fs.readFileSync(authFile,'utf8'))[options.authKey];
if(!auth)
this.emit('error', new PluginError('gulp-sftp', 'Could not find authkey in .ftppass'));
if(typeof auth == "string" && auth.indexOf(":")!=-1){
var authparts = auth.split(":");
auth = {user:authparts[0],pass:authparts[1]};
}
for (var attr in auth) { options[attr] = auth[attr]; }
}
//option aliases
options.password = options.password||options.pass;
options.username = options.username||options.user||'anonymous';
/*
* Lots of ways to present key info
*/
var key = options.key || options.keyLocation || null;
if(key&&typeof key == "string")
key = {location:key};
//check for other options that imply a key or if there is no password
if(!key && (options.passphrase||options.keyContents||!options.password)){
key = {};
}
if(key){
//aliases
key.contents=key.contents||options.keyContents;
key.passphrase=key.passphrase||options.passphrase;
//defaults
key.location=key.location||["~/.ssh/id_rsa","/.ssh/id_rsa","~/.ssh/id_dsa","/.ssh/id_dsa"];
//type normalization
if(!util.isArray(key.location))
key.location=[key.location];
//resolve all home paths
if(key.location){
var home = process.env.HOME||process.env.USERPROFILE;
for(var i=0;i<key.location.length;i++)
if (key.location[i].substr(0,2) === '~/')
key.location[i] = path.resolve(home,key.location[i].replace(/^~\//,""));
for(var i=0,keyPath;keyPath=key.location[i++];){
if(fs.existsSync(keyPath)){
key.contents = fs.readFileSync(keyPath);
break;
}
}
}else if(!key.contents){
this.emit('error', new PluginError('gulp-sftp', 'Cannot find RSA key, searched: '+key.location.join(', ')));
}
}
/*
* End Key normalization, key should now be of form:
* {location:Array,passphrase:String,contents:String}
* or null
*/
var logFiles = options.logFiles === false ? false : true;
delete options.remotePath;
delete options.localPath;
delete options.user;
delete options.pass;
delete options.logFiles;
var mkDirCache = {};
var finished=false;
var sftpCache = null;//sftp connection cache
var connectionCache = null;//ssh connection cache
var pool = function(remotePath, uploader){ // method to get cache or create connection
if(sftpCache)
return uploader(sftpCache);
if(options.password){
log('Authenticating with password.');
}else if(key){
log('Authenticating with private key.');
}
var c = new Connection();
connectionCache = c;
c.on('ready', function() {
c.sftp(function(err, sftp) {
if (err)
throw err;
sftp.on('end', function() {
log('SFTP :: SFTP session closed');
sftpCache=null;
if(!finished)
this.emit('error', new PluginError('gulp-sftp', "SFTP abrupt closure"));
});
sftpCache = sftp;
uploader(sftpCache);
});//c.sftp
});//c.on('ready')
var self = this;
c.on('error', function(err) {
self.emit('error', new PluginError('gulp-sftp', err));
//return cb(err);
});
c.on('end', function() {
log('Connection :: end');
});
c.on('close', function(err) {
if(!finished){
log('gulp-sftp', "SFTP abrupt closure");
self.emit('error', new PluginError('gulp-sftp', "SFTP abrupt closure"));
}
if (err) {
log('Connection :: close, ', colors.red('Error: ' + err));
} else {
log('Connection :: closed');
}
});
/*
* connection options, may be a key
*/
var connection_options = {
host : options.host,
port : options.port||22,
username : options.username
};
if(options.password){
connection_options.password = options.password;
}else if(options.agent) {
connection_options.agent = options.agent;
connection_options.agentForward = options.agentForward || false;
}else if(key){
connection_options.privateKey = key.contents;
connection_options.passphrase = key.passphrase;
}
if(options.timeout){
connection_options.readyTimeout = options.timeout;
}
c.connect(connection_options);
/*
* end connection options
*/
};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
// have to create a new connection for each file otherwise they conflict, pulled from sindresorhus
var finalRemotePath = normalizePath(path.join(remotePath, file.relative));
//connection pulled from pool
pool.call(this, finalRemotePath, function(sftp){
/*
* Create Directories
*/
//get dir name from file path
var dirname=path.dirname(finalRemotePath);
//get parents of the target dir
var fileDirs = parents(dirname)
.map(function(d){return d.replace(/^\/~/,"~");})
.map(normalizePath);
if(dirname.search(/^\//) === 0){
fileDirs = fileDirs.map(function(dir){
if(dir.search(/^\//) === 0){
return dir;
}
return '/' + dir;
});
}
//get filter out dirs that are closer to root than the base remote path
//also filter out any dirs made during this gulp session
fileDirs = fileDirs.filter(function(d){return d.length>=remotePath.length&&!mkDirCache[d];});
//while there are dirs to create, create them
//https://github.com/caolan/async#whilst - not the most commonly used async control flow
async.whilst(function(){
return fileDirs && fileDirs.length;
},function(next){
var d= fileDirs.pop();
mkDirCache[d]=true;
//mdrake - TODO: use a default file permission instead of defaulting to 755
if(remotePlatform && remotePlatform.toLowerCase().indexOf('win')!==-1) {
d = d.replace('/','\\');
}
sftp.exists(d, function(exist) {
if (!exist) {
sftp.mkdir(d, {mode: '0755'}, function(err){//REMOTE PATH
if(err){
log('SFTP Mkdir Error:', colors.red(err + " " +d));
}else{
log('SFTP Created:', colors.green(d));
}
next();
});
} else {
next();
}
});
},function(){
var stream = sftp.createWriteStream(finalRemotePath,{//REMOTE PATH
flags: 'w',
encoding: null,
mode: '0666',
autoClose: true
});
//var readStream = fs.createReadStream(fileBase+localRelativePath);
var uploadedBytes = 0;
var highWaterMark = stream.highWaterMark||(16*1000);
var size = file.stat.size;
//file.pipe(stream); // start upload
if ( file.isStream() ) {
file.contents.pipe( stream );
} else if ( file.isBuffer() ) {
stream.end( file.contents );
}
stream.on('drain',function(){
uploadedBytes+=highWaterMark;
var p = Math.round((uploadedBytes/size)*100);
p = Math.min(100,p);
log('gulp-sftp:',finalRemotePath,"uploaded",(uploadedBytes/1000)+"kb");
});
stream.on('close', function(err) {
if(err)
this.emit('error', new PluginError('gulp-sftp', err));
else{
if (logFiles) {
log('gulp-sftp:', colors.green('Uploaded: ') +
file.relative +
colors.green(' => ') +
finalRemotePath);
}
fileCount++;
}
return cb(err);
});
});//async.whilst
});
this.push(file);
}, function (cb) {
if (fileCount > 0) {
log('gulp-sftp:', colors.green(fileCount, fileCount === 1 ? 'file' : 'files', 'uploaded successfully'));
} else {
log('gulp-sftp:', colors.yellow('No files uploaded'));
}
finished=true;
if(sftpCache)
sftpCache.end();
if(connectionCache)
connectionCache.end();
cb();
});
};