| 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
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
1
 
  | /*jslint node:true*/
'use strict';
/**
 * This is a bootstrapper for dependency
 * injection. It is used so we can require or
 * mock the modules outside of this file and
 * pass them in at runtime. This makes testing
 * MUCH simpler as we can mock objects in
 * tests and pass them in.
 *
 * @param {object} exec - child_process.exec
 * @param {object} path - The path module.
 * @returns {object} P4 - The P4 module constructor.
 */
module.exports = function(exec,path){
 
    /**
     * @callback
     */
 
    /**
     * Takes output from p4 fstat and parses it to an object.
     * @param {string} stats - The output
     * @returns {object} the stats object, may be instanceof Array
     */
    function parseStats(stats) {
        var statsArr = [];
        stats = stats.split('\n\n');
        var validStat = stats.every(function(stat){
            var statsObj = {}, idx;
            if(stat === '' || stats === '\n'){
                // Return true to continue the loop
                return true;
            }
            var valid = stat.split('\n').every(function(line){
                var level = 0
                , key = ''
                , value = ''
                , obj = [];
                // Line has 3 dots and a space at the beginning, pull that off and determine the "indentation" level
                do{
                    line = line.slice(4);
                    level++;
                } while(line.indexOf('... ') === 0);
                obj = line.split(' ');
                obj[1] = obj.slice(1).join(' ');
                key = obj[0];
                value = obj[1];
                if(!key){
                    // Continue the loop, ignore it
                    return true;
                }
                if(value === ''){
                    value = true;
                }
                if(level === 1){
                    statsObj[key] = value;
                } else if(level === 2){
                    if(!statsObj.other){
                        statsObj.other = [];
                    }
                    if(key === 'otherOpen'){
                        // We are at the end of the others
                        if(statsObj.other.length !== Number(value)){
                            // Return false here because the input is invalid
                            return false;
                        }
                        return true;
                    }
                    // Get the array index of the key
                    idx = key.match(/other[a-zA-Z]+(\d+)$/)[1];
                    // Now remove `other` from the beginning and the idx from the end
                    key = key.slice(5,-idx.length);
                    if(!statsObj.other[idx]){
                        // Extend the array one more
                        statsObj.other.push({});
                    }
                    if(statsObj.other.length !== Number(idx)+1){
                        // Invalid output, not ordered properly!
                        return false;
                    }
                    statsObj.other[idx][key] = value;
                } else {
                    // level is not 1 or 2, weird output
                    return false;
                }
                // Continue
                return true;
            });
            if(valid){
                statsArr.push(statsObj);
            }
            // Continue if last was valid
            return valid;
        });
        if(!validStat){
            return new Error('Invalid fstat output!');
        }
        if(statsArr.length === 1){
            return statsArr[0];
        }
        return statsArr;
    }
 
    /**
     * @constructor
     */
    function P4(){
        if(!(this instanceof P4)){
            return new P4();
        }
        this.cwd = __dirname;
        this.options = {};
    }
 
    /**
     * This function changes the cwd property
     * and behaves much like unix cd. It resolves
     * the new path based on the current CWD, and
     * handles absolute paths too.
     * Supports chaining.
     *
     * @param {string} dir - The directory to cd
     * @returns {object} this
     */
    P4.prototype.cd = function(dir){
        this.cwd = path.resolve(this.cwd,dir);
        // Allow chaining by returning this
        // i.e. p4.cd('dir').edit('file')
        // or p4.cd('path').cd('to').cd('dir')
        return this;
    };
 
    /**
     * Set options for the exec context.
     * Supports all optinos supported by child_process.exec.
     * Supports chaining.
     *
     * @param {object} opts - The options object
     * @returns {object} this
     */
    P4.prototype.setOpts = function(opts){
        var self = this;
        Object.keys(opts).forEach(function(key){
            if(key === 'cwd'){
                // Don't allow changing cwd via setOpts...
                return;
            }
            self.options[key] = opts[key];
        });
        return this;
    };
 
    /**
     * Run a command, used internally but public.
     * @param {string} command - The command to run
     * @param {array|string} args - The arguments for the command
     * @param {function} done - The done callback
     * @param {boolean} recursive - Whether this is calling itself recursively after login
     * @returns {object} the child process object
     */
    P4.prototype.runCommand = function(command, args, done, recursive) {
        var self = this;
        if(typeof args === 'function') {
            done = args;
            args = '';
        }
        if(args instanceof Array) {
            args = args.join(' ');
        }
 
        this.options.cwd = this.cwd;
        this.options.env = this.options.env || {};
        this.options.env.PWD = this.cwd;
        try{
            return exec('p4 ' + command + ' ' + (args || ''), this.options, function(err, stdOut, stdErr) {
                if(err) {
                    return done(err);
                }
                if('Perforce password (P4PASSWD) invalid or unset.' === stdErr && !recursive){
                    return self.login(self.username,self.password,function(err,stdout,stderr){
                        if(err){
                            return done(err,stdout,stderr);
                        }
                        // Retry same command
                        return self.runCommand(command,args,done,true);
                    });
                }
                // When we run p4 fstat *, it will say no such file(s) on dirs
                // fix this by reducing the error string and omitting matching lines
                // when calling join() on an empty array, it returns an empty string which is *falsy*
                stdErr = stdErr.split('\n').reduce(function(pval,line){
                    if(!/no such file/.test(line)){
                        // Only include if it doesn't match our test
                        pval.push(line);
                    }
                    return pval;
                },[]).join('\n');
                // This could more easily be done with this:
                // stdErr = _.reject(stdErr.split('\n'),function(line){return /no such file/.test(line)}).join('\n')
                // but learning reduce is a _good thing_ (TM) and the algorithm is arguably more descriptive and
                // self-documenting when using reduce
                if(stdErr) {
                    return done(new Error(stdErr));
                }
 
                return done(null, stdOut);
            });
        } catch(e){
            return done(e);
        }
    };
 
    /**
     * Runs an arbitrary shell command.
     * @warning DOES NOT SHELL ESCAPE ANYTHING
     * @param {string} command - The command to run
     * @param {array|string} args - The arguments to pass
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.runShellCommand = function(command, args, done) {
        if(typeof args === 'function') {
            done = args;
            args = '';
        }
        if(args instanceof Array) {
            args = args.join(' ');
        }
 
        try{
        return exec(command + ' ' + (args || ''), {cwd:this.cwd}, function(err, stdOut, stdErr) {
            if(err) {
                return done(err);
            }
            if(stdErr) {
                return done(new Error(stdErr),stdOut);
            }
 
            return done(null, stdOut);
        });
        } catch(e){
            return done(e);
        }
    };
 
    /**
     * Calls p4 edit on the filepath passed.
     * @param {string} filepath - The filepath, can be absolute or relative to cwd
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.edit = function(filepath, done) {
        return this.runCommand('edit', filepath, done);
    };
 
    /**
     * Calls p4 add on the filepath passed.
     * @param {string} filepath - The filepath, can be absolute or relative to cwd
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.add = function(filepath, done) {
        return this.runCommand('add', filepath, done);
    };
 
    /**
     * Calls p4 edit on the filepath. If an error is thrown, calls p4 add on the filepath.
     * @param {string} filepath - The filepath, can be absolute or relative to cwd
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.smartEdit = function(filepath, done) {
        var self = this;
        return this.edit(filepath, function(err, out) {
            if(!err) {
                return done(null, out);
            }
 
            return self.add(filepath, done);
        });
    };
 
    /**
     * Calls p4 revert -a. Ignores filepath arg.
     * @param {string} filepath - The filepath, ignored
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.revertUnchanged = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        filepath = filepath || '';
        return this.runCommand('revert', '-a', done);
    };
 
    /**
     * Calls p4 fstat *. If filepath is passed, it will first cd to that path.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.statDir = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(filepath){
            this.cd(filepath);
        }
        return this.runCommand('fstat','*', function(err,out){
            if(err){
                return done(err);
            }
            var output = parseStats(out);
            if(output instanceof Error){
                return done(output);
            }
            return done(null,output);
        });
    };
 
    /**
     * Calls `p4 fstat ...`. If filepath is passed, it will first cd to that path.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.recursiveStatDir = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(filepath){
            this.cd(filepath);
        }
        return this.runCommand('fstat','...', function(err,out){
            if(err){
                return done(err);
            }
            var output = parseStats(out);
            if(output instanceof Error){
                return done(output);
            }
            return done(null,output);
        });
    };
 
    /**
     * Calls `p4 fstat` on `path.basename(filepath)`.
     * If filepath is not passed, it will call the cb with an error.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.stat = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(!filepath){
            return done(new Error('Please pass a file to stat!'));
        }
        this.cd(path.dirname(filepath));
        return this.runCommand('fstat', path.basename(filepath), function(err,out){
            if(err){
                return done(err);
            }
            var output = parseStats(out);
            if(output instanceof Error){
                return done(output);
            }
            return done(null,output);
        });
    };
 
    /**
     * Calls `p4 have` on `filepath`.
     * If filepath is not passed, it will call the cb with an error.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.have = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(!filepath){
            return done(new Error('Please pass a file to inspect!'));
        }
        return this.stat(filepath, function(err,stats){
            if(err){
                return done(err);
            }
            return done(null,stats.haveRev);
        });
    };
 
    /**
     * Calls `p4 revert` on `filepath`.
     * If filepath is not passed, it will call the cb with an error.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.revert = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(!filepath){
            return done(new Error('Please pass a file to revert!'));
        }
        return this.runCommand('revert', filepath, done);
    };
 
    /**
     * Calls `p4 submit` on `filepath`.
     * @param {string} filepath - The filepath
     * @param {string} desc - The changelist description
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.submit = function(filepath, desc, done) {
        return this.runCommand('submit', ['-d', '"' + desc + '"',filepath], done);
    };
 
    /**
     * Calls `p4 sync` on `filepath`.
     * If filepath is not passed, calls sync in cwd.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.sync = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        return this.runCommand('sync', filepath, done);
    };
 
    /**
     * Calls `p4 sync *` in `filepath`.
     * If filepath is not passed, calls `p4 sync *` in cwd.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.syncDir = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(filepath){
            this.cd(filepath);
        }
        return this.runCommand('sync', '*', done);
    };
 
    /**
     * Calls `p4 sync ...` in `filepath`.
     * If filepath is not passed, calls `p4 sync ...` in cwd.
     * @param {string} filepath - The filepath
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.recursiveSyncDir = function(filepath, done) {
        if(!done){
            done = filepath;
            filepath = null;
        }
        if(filepath){
            this.cd(filepath);
        }
        return this.runCommand('sync', '...', done);
    };
 
    /**
     * Calls `p4 login`.
     * Important, this happens in the cwd so whatever P4CONFIG is found will be used.
     * @param {string} username - The username
     * @param {string} password - The password
     * @param {function} done - The done callback
     * @returns {object} the child process object
     */
    P4.prototype.login = function(username, password, done) {
        // Cache the username and password for refreshing login later if necessary.
        if(username && password){
            this.username = username;
            this.password = password;
        }
        // Let the username and password be optional so they only ever have to be passed once.
        if(typeof username === 'function'){
            done = username;
        }
        return this.runShellCommand('echo "' + this.password + '" | p4 login -u "' + this.username + '"', done);
    };
 
    /**
     * Returns the cwd.
     * @returns {string} The current cwd
     */
    P4.prototype.pwd = function(){
        return this.cwd;
    };
 
    return P4;
};
  |