forked from shelljs/shelljs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.js
1892 lines (1595 loc) · 50.1 KB
/
shell.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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ShellJS
// Unix shell commands on top of Node's API
//
// Copyright (c) 2012 Artur Adib
// http://github.com/arturadib/shelljs
//
var fs = require('fs'),
path = require('path'),
util = require('util'),
vm = require('vm'),
child = require('child_process'),
os = require('os');
// Node shims for < v0.7
fs.existsSync = fs.existsSync || path.existsSync;
var config = {
silent: false,
fatal: false
};
var state = {
error: null,
currentCmd: 'shell.js',
tempDir: null
},
platform = os.type().match(/^Win/) ? 'win' : 'unix';
//@
//@ All commands run synchronously, unless otherwise stated.
//@
//@
//@ ### cd('dir')
//@ Changes to directory `dir` for the duration of the script
function _cd(options, dir) {
if (!dir)
error('directory not specified');
if (!fs.existsSync(dir))
error('no such file or directory: ' + dir);
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory())
error('not a directory: ' + dir);
process.chdir(dir);
}
exports.cd = wrap('cd', _cd);
//@
//@ ### pwd()
//@ Returns the current directory.
function _pwd(options) {
var pwd = path.resolve(process.cwd());
return ShellString(pwd);
}
exports.pwd = wrap('pwd', _pwd);
//@
//@ ### ls([options ,] path [,path ...])
//@ ### ls([options ,] path_array)
//@ Available options:
//@
//@ + `-R`: recursive
//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`)
//@
//@ Examples:
//@
//@ ```javascript
//@ ls('projs/*.js');
//@ ls('-R', '/users/me', '/tmp');
//@ ls('-R', ['/users/me', '/tmp']); // same as above
//@ ```
//@
//@ Returns array of files in the given path, or in current directory if no path provided.
function _ls(options, paths) {
options = parseOptions(options, {
'R': 'recursive',
'A': 'all',
'a': 'all_deprecated'
});
if (options.all_deprecated) {
// We won't support the -a option as it's hard to image why it's useful
// (it includes '.' and '..' in addition to '.*' files)
// For backwards compatibility we'll dump a deprecated message and proceed as before
log('ls: Option -a is deprecated. Use -A instead');
options.all = true;
}
if (!paths)
paths = ['.'];
else if (typeof paths === 'object')
paths = paths; // assume array
else if (typeof paths === 'string')
paths = [].slice.call(arguments, 1);
var list = [];
// Conditionally pushes file to list - returns true if pushed, false otherwise
// (e.g. prevents hidden files to be included unless explicitly told so)
function pushFile(file, query) {
// hidden file?
if (path.basename(file)[0] === '.') {
// not explicitly asking for hidden files?
if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1))
return false;
}
if (platform === 'win')
file = file.replace(/\\/g, '/');
list.push(file);
return true;
}
paths.forEach(function(p) {
if (fs.existsSync(p)) {
// Simple file?
if (fs.statSync(p).isFile()) {
pushFile(p, p);
return; // continue
}
// Simple dir?
if (fs.statSync(p).isDirectory()) {
// Iterate over p contents
fs.readdirSync(p).forEach(function(file) {
if (!pushFile(file, p))
return;
// Recursive?
if (options.recursive) {
var oldDir = _pwd();
_cd('', p);
if (fs.statSync(file).isDirectory())
list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*'));
_cd('', oldDir);
}
});
return; // continue
}
}
// p does not exist - possible wildcard present
var basename = path.basename(p);
var dirname = path.dirname(p);
// Wildcard present on an existing dir? (e.g. '/tmp/*.js')
if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) {
// Escape special regular expression chars
var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1');
// Translates wildcard into regex
regexp = '^' + regexp.replace(/\*/g, '.*') + '$';
// Iterate over directory contents
fs.readdirSync(dirname).forEach(function(file) {
if (file.match(new RegExp(regexp))) {
if (!pushFile(path.normalize(dirname+'/'+file), basename))
return;
// Recursive?
if (options.recursive) {
var pp = dirname + '/' + file;
if (fs.lstatSync(pp).isDirectory())
list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*'));
} // recursive
} // if file matches
}); // forEach
return;
}
error('no such file or directory: ' + p, true);
});
return list;
}
exports.ls = wrap('ls', _ls);
//@
//@ ### find(path [,path ...])
//@ ### find(path_array)
//@ Examples:
//@
//@ ```javascript
//@ find('src', 'lib');
//@ find(['src', 'lib']); // same as above
//@ find('.').filter(function(file) { return file.match(/\.js$/); });
//@ ```
//@
//@ Returns array of all files (however deep) in the given paths.
//@
//@ The main difference from `ls('-R', path)` is that the resulting file names
//@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`.
function _find(options, paths) {
if (!paths)
error('no path specified');
else if (typeof paths === 'object')
paths = paths; // assume array
else if (typeof paths === 'string')
paths = [].slice.call(arguments, 1);
var list = [];
function pushFile(file) {
if (platform === 'win')
file = file.replace(/\\/g, '/');
list.push(file);
}
// why not simply do ls('-R', paths)? because the output wouldn't give the base dirs
// to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory
paths.forEach(function(file) {
pushFile(file);
if (fs.statSync(file).isDirectory()) {
_ls('-RA', file+'/*').forEach(function(subfile) {
pushFile(subfile);
});
}
});
return list;
}
exports.find = wrap('find', _find);
//@
//@ ### cp([options ,] source [,source ...], dest)
//@ ### cp([options ,] source_array, dest)
//@ Available options:
//@
//@ + `-f`: force
//@ + `-r, -R`: recursive
//@
//@ Examples:
//@
//@ ```javascript
//@ cp('file1', 'dir1');
//@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp');
//@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above
//@ ```
//@
//@ Copies files. The wildcard `*` is accepted.
function _cp(options, sources, dest) {
options = parseOptions(options, {
'f': 'force',
'R': 'recursive',
'r': 'recursive'
});
// Get sources, dest
if (arguments.length < 3) {
error('missing <source> and/or <dest>');
} else if (arguments.length > 3) {
sources = [].slice.call(arguments, 1, arguments.length - 1);
dest = arguments[arguments.length - 1];
} else if (typeof sources === 'string') {
sources = [sources];
} else if ('length' in sources) {
sources = sources; // no-op for array
} else {
error('invalid arguments');
}
// Dest is not existing dir, but multiple sources given
if ((!fs.existsSync(dest) || !fs.statSync(dest).isDirectory()) && sources.length > 1)
error('dest is not a directory (too many sources)');
// Dest is an existing file, but no -f given
if (fs.existsSync(dest) && fs.statSync(dest).isFile() && !options.force)
error('dest file already exists: ' + dest);
if (options.recursive) {
// Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*"
// (see Github issue #15)
sources.forEach(function(src, i) {
if (src[src.length - 1] === '/')
sources[i] += '*';
});
// Create dest
try {
fs.mkdirSync(dest, parseInt('0777', 8));
} catch (e) {
// like Unix's cp, keep going even if we can't create dest dir
}
}
sources = expand(sources);
sources.forEach(function(src) {
if (!fs.existsSync(src)) {
error('no such file or directory: '+src, true);
return; // skip file
}
// If here, src exists
if (fs.statSync(src).isDirectory()) {
if (!options.recursive) {
// Non-Recursive
log(src + ' is a directory (not copied)');
} else {
// Recursive
// 'cp /a/source dest' should create 'source' in 'dest'
var newDest = path.join(dest, path.basename(src)),
checkDir = fs.statSync(src);
try {
fs.mkdirSync(newDest, checkDir.mode);
} catch (e) {
//if the directory already exists, that's okay
if (e.code !== 'EEXIST') throw e;
}
cpdirSyncRecursive(src, newDest, {force: options.force});
}
return; // done with dir
}
// If here, src is a file
// When copying to '/path/dir':
// thisDest = '/path/dir/file1'
var thisDest = dest;
if (fs.existsSync(dest) && fs.statSync(dest).isDirectory())
thisDest = path.normalize(dest + '/' + path.basename(src));
if (fs.existsSync(thisDest) && !options.force) {
error('dest file already exists: ' + thisDest, true);
return; // skip file
}
copyFileSync(src, thisDest);
}); // forEach(src)
}
exports.cp = wrap('cp', _cp);
//@
//@ ### rm([options ,] file [, file ...])
//@ ### rm([options ,] file_array)
//@ Available options:
//@
//@ + `-f`: force
//@ + `-r, -R`: recursive
//@
//@ Examples:
//@
//@ ```javascript
//@ rm('-rf', '/tmp/*');
//@ rm('some_file.txt', 'another_file.txt');
//@ rm(['some_file.txt', 'another_file.txt']); // same as above
//@ ```
//@
//@ Removes files. The wildcard `*` is accepted.
function _rm(options, files) {
options = parseOptions(options, {
'f': 'force',
'r': 'recursive',
'R': 'recursive'
});
if (!files)
error('no paths given');
if (typeof files === 'string')
files = [].slice.call(arguments, 1);
// if it's array leave it as it is
files = expand(files);
files.forEach(function(file) {
if (!fs.existsSync(file)) {
// Path does not exist, no force flag given
if (!options.force)
error('no such file or directory: '+file, true);
return; // skip file
}
// If here, path exists
// Remove simple file
if (fs.statSync(file).isFile()) {
// Do not check for file writing permissions
if (options.force) {
_unlinkSync(file);
return;
}
if (isWriteable(file))
_unlinkSync(file);
else
error('permission denied: '+file, true);
return;
} // simple file
// Path is an existing directory, but no -r flag given
if (fs.statSync(file).isDirectory() && !options.recursive) {
error('path is a directory', true);
return; // skip path
}
// Recursively remove existing directory
if (fs.statSync(file).isDirectory() && options.recursive) {
rmdirSyncRecursive(file, options.force);
}
}); // forEach(file)
} // rm
exports.rm = wrap('rm', _rm);
//@
//@ ### mv(source [, source ...], dest')
//@ ### mv(source_array, dest')
//@ Available options:
//@
//@ + `f`: force
//@
//@ Examples:
//@
//@ ```javascript
//@ mv('-f', 'file', 'dir/');
//@ mv('file1', 'file2', 'dir/');
//@ mv(['file1', 'file2'], 'dir/'); // same as above
//@ ```
//@
//@ Moves files. The wildcard `*` is accepted.
function _mv(options, sources, dest) {
options = parseOptions(options, {
'f': 'force'
});
// Get sources, dest
if (arguments.length < 3) {
error('missing <source> and/or <dest>');
} else if (arguments.length > 3) {
sources = [].slice.call(arguments, 1, arguments.length - 1);
dest = arguments[arguments.length - 1];
} else if (typeof sources === 'string') {
sources = [sources];
} else if ('length' in sources) {
sources = sources; // no-op for array
} else {
error('invalid arguments');
}
sources = expand(sources);
// Dest is not existing dir, but multiple sources given
if ((!fs.existsSync(dest) || !fs.statSync(dest).isDirectory()) && sources.length > 1)
error('dest is not a directory (too many sources)');
// Dest is an existing file, but no -f given
if (fs.existsSync(dest) && fs.statSync(dest).isFile() && !options.force)
error('dest file already exists: ' + dest);
sources.forEach(function(src) {
if (!fs.existsSync(src)) {
error('no such file or directory: '+src, true);
return; // skip file
}
// If here, src exists
// When copying to '/path/dir':
// thisDest = '/path/dir/file1'
var thisDest = dest;
if (fs.existsSync(dest) && fs.statSync(dest).isDirectory())
thisDest = path.normalize(dest + '/' + path.basename(src));
if (fs.existsSync(thisDest) && !options.force) {
error('dest file already exists: ' + thisDest, true);
return; // skip file
}
if (path.resolve(src) === path.dirname(path.resolve(thisDest))) {
error('cannot move to self: '+src, true);
return; // skip file
}
fs.renameSync(src, thisDest);
}); // forEach(src)
} // mv
exports.mv = wrap('mv', _mv);
//@
//@ ### mkdir([options ,] dir [, dir ...])
//@ ### mkdir([options ,] dir_array)
//@ Available options:
//@
//@ + `p`: full path (will create intermediate dirs if necessary)
//@
//@ Examples:
//@
//@ ```javascript
//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g');
//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above
//@ ```
//@
//@ Creates directories.
function _mkdir(options, dirs) {
options = parseOptions(options, {
'p': 'fullpath'
});
if (!dirs)
error('no paths given');
if (typeof dirs === 'string')
dirs = [].slice.call(arguments, 1);
// if it's array leave it as it is
dirs.forEach(function(dir) {
if (fs.existsSync(dir)) {
if (!options.fullpath)
error('path already exists: ' + dir, true);
return; // skip dir
}
// Base dir does not exist, and no -p option given
var baseDir = path.dirname(dir);
if (!fs.existsSync(baseDir) && !options.fullpath) {
error('no such file or directory: ' + baseDir, true);
return; // skip dir
}
if (options.fullpath)
mkdirSyncRecursive(dir);
else
fs.mkdirSync(dir, parseInt('0777', 8));
});
} // mkdir
exports.mkdir = wrap('mkdir', _mkdir);
//@
//@ ### test(expression)
//@ Available expression primaries:
//@
//@ + `'-b', 'path'`: true if path is a block device
//@ + `'-c', 'path'`: true if path is a character device
//@ + `'-d', 'path'`: true if path is a directory
//@ + `'-e', 'path'`: true if path exists
//@ + `'-f', 'path'`: true if path is a regular file
//@ + `'-L', 'path'`: true if path is a symboilc link
//@ + `'-p', 'path'`: true if path is a pipe (FIFO)
//@ + `'-S', 'path'`: true if path is a socket
//@
//@ Examples:
//@
//@ ```javascript
//@ if (test('-d', path)) { /* do something with dir */ };
//@ if (!test('-f', path)) continue; // skip if it's a regular file
//@ ```
//@
//@ Evaluates expression using the available primaries and returns corresponding value.
function _test(options, path) {
if (!path)
error('no path given');
// hack - only works with unary primaries
options = parseOptions(options, {
'b': 'block',
'c': 'character',
'd': 'directory',
'e': 'exists',
'f': 'file',
'L': 'link',
'p': 'pipe',
'S': 'socket'
});
var canInterpret = false;
for (var key in options)
if (options[key] === true) {
canInterpret = true;
break;
}
if (!canInterpret)
error('could not interpret expression');
if (options.link) {
try {
return fs.lstatSync(path).isSymbolicLink();
} catch(e) {
return false;
}
}
if (!fs.existsSync(path))
return false;
if (options.exists)
return true;
var stats = fs.statSync(path);
if (options.block)
return stats.isBlockDevice();
if (options.character)
return stats.isCharacterDevice();
if (options.directory)
return stats.isDirectory();
if (options.file)
return stats.isFile();
if (options.pipe)
return stats.isFIFO();
if (options.socket)
return stats.isSocket();
} // test
exports.test = wrap('test', _test);
//@
//@ ### cat(file [, file ...])
//@ ### cat(file_array)
//@
//@ Examples:
//@
//@ ```javascript
//@ var str = cat('file*.txt');
//@ var str = cat('file1', 'file2');
//@ var str = cat(['file1', 'file2']); // same as above
//@ ```
//@
//@ Returns a string containing the given file, or a concatenated string
//@ containing the files if more than one file is given (a new line character is
//@ introduced between each file). Wildcard `*` accepted.
function _cat(options, files) {
var cat = '';
if (!files)
error('no paths given');
if (typeof files === 'string')
files = [].slice.call(arguments, 1);
// if it's array leave it as it is
files = expand(files);
files.forEach(function(file) {
if (!fs.existsSync(file))
error('no such file or directory: ' + file);
cat += fs.readFileSync(file, 'utf8') + '\n';
});
if (cat[cat.length-1] === '\n')
cat = cat.substring(0, cat.length-1);
return ShellString(cat);
}
exports.cat = wrap('cat', _cat);
//@
//@ ### 'string'.to(file)
//@
//@ Examples:
//@
//@ ```javascript
//@ cat('input.txt').to('output.txt');
//@ ```
//@
//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as
//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_
function _to(options, file) {
if (!file)
error('wrong arguments');
if (!fs.existsSync( path.dirname(file) ))
error('no such file or directory: ' + path.dirname(file));
try {
fs.writeFileSync(file, this.toString(), 'utf8');
} catch(e) {
error('could not write to file (code '+e.code+'): '+file, true);
}
}
// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings.
// For now, this is a dummy function to bookmark places we need such strings
function ShellString(str) {
return str;
}
String.prototype.to = wrap('to', _to);
//@
//@ ### sed([options ,] search_regex, replace_str, file)
//@ Available options:
//@
//@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
//@
//@ Examples:
//@
//@ ```javascript
//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
//@ ```
//@
//@ Reads an input string from `file` and performs a JavaScript `replace()` on the input
//@ using the given search regex and replacement string. Returns the new string after replacement.
function _sed(options, regex, replacement, file) {
options = parseOptions(options, {
'i': 'inplace'
});
if (typeof replacement === 'string')
replacement = replacement; // no-op
else if (typeof replacement === 'number')
replacement = replacement.toString(); // fallback
else
error('invalid replacement string');
if (!file)
error('no file given');
if (!fs.existsSync(file))
error('no such file or directory: ' + file);
var result = fs.readFileSync(file, 'utf8').replace(regex, replacement);
if (options.inplace)
fs.writeFileSync(file, result, 'utf8');
return ShellString(result);
}
exports.sed = wrap('sed', _sed);
//@
//@ ### grep([options ,] regex_filter, file [, file ...])
//@ ### grep([options ,] regex_filter, file_array)
//@ Available options:
//@
//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria.
//@
//@ Examples:
//@
//@ ```javascript
//@ grep('-v', 'GLOBAL_VARIABLE', '*.js');
//@ grep('GLOBAL_VARIABLE', '*.js');
//@ ```
//@
//@ Reads input string from given files and returns a string containing all lines of the
//@ file that match the given `regex_filter`. Wildcard `*` accepted.
function _grep(options, regex, files) {
options = parseOptions(options, {
'v': 'inverse'
});
if (!files)
error('no paths given');
if (typeof files === 'string')
files = [].slice.call(arguments, 2);
// if it's array leave it as it is
files = expand(files);
var grep = '';
files.forEach(function(file) {
if (!fs.existsSync(file)) {
error('no such file or directory: ' + file, true);
return;
}
var contents = fs.readFileSync(file, 'utf8'),
lines = contents.split(/\r*\n/);
lines.forEach(function(line) {
var matched = line.match(regex);
if ((options.inverse && !matched) || (!options.inverse && matched))
grep += line + '\n';
});
});
return ShellString(grep);
}
exports.grep = wrap('grep', _grep);
//@
//@ ### which(command)
//@
//@ Examples:
//@
//@ ```javascript
//@ var nodeExec = which('node');
//@ ```
//@
//@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions.
//@ Returns string containing the absolute path to the command.
function _which(options, cmd) {
if (!cmd)
error('must specify command');
var pathEnv = process.env.path || process.env.Path || process.env.PATH,
pathArray = splitPath(pathEnv),
where = null;
// No relative/absolute paths provided?
if (cmd.search(/\//) === -1) {
// Search for command in PATH
pathArray.forEach(function(dir) {
if (where)
return; // already found it
var attempt = path.resolve(dir + '/' + cmd);
if (fs.existsSync(attempt)) {
where = attempt;
return;
}
if (platform === 'win') {
var baseAttempt = attempt;
attempt = baseAttempt + '.exe';
if (fs.existsSync(attempt)) {
where = attempt;
return;
}
attempt = baseAttempt + '.cmd';
if (fs.existsSync(attempt)) {
where = attempt;
return;
}
attempt = baseAttempt + '.bat';
if (fs.existsSync(attempt)) {
where = attempt;
return;
}
} // if 'win'
});
}
// Command not found anywhere?
if (!fs.existsSync(cmd) && !where)
return null;
where = where || path.resolve(cmd);
return ShellString(where);
}
exports.which = wrap('which', _which);
//@
//@ ### echo(string [,string ...])
//@
//@ Examples:
//@
//@ ```javascript
//@ echo('hello world');
//@ var str = echo('hello world');
//@ ```
//@
//@ Prints string to stdout, and returns string with additional utility methods
//@ like `.to()`.
function _echo() {
var messages = [].slice.call(arguments, 0);
console.log.apply(this, messages);
return ShellString(messages.join(' '));
}
exports.echo = _echo; // don't wrap() as it could parse '-options'
// Pushd/popd/dirs internals
var _dirStack = [];
function _isStackIndex(index) {
return (/^[\-+]\d+$/).test(index);
}
function _parseStackIndex(index) {
if (_isStackIndex(index)) {
if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd
return (/^-/).test(index) ? Number(index) - 1 : Number(index);
} else {
error(index + ': directory stack index out of range');
}
} else {
error(index + ': invalid number');
}
}
function _actualDirStack() {
return [process.cwd()].concat(_dirStack);
}
//@
//@ ### dirs([options | '+N' | '-N'])
//@
//@ Available options:
//@
//@ + `-c`: Clears the directory stack by deleting all of the elements.
//@
//@ Arguments:
//@
//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.
//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.
//@
//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified.
//@
//@ See also: pushd, popd
function _dirs(options, index) {
if (_isStackIndex(options)) {
index = options;
options = '';
}
options = parseOptions(options, {
'c' : 'clear'
});
if (options['clear']) {
_dirStack = [];
return _dirStack;
}
var stack = _actualDirStack();
if (index) {
index = _parseStackIndex(index);
if (index < 0) {
index = stack.length + index;
}
log(stack[index]);
return stack[index];
}
log(stack.join(' '));
return stack;
}
exports.dirs = wrap("dirs", _dirs);
//@
//@ ### pushd([options,] [dir | '-N' | '+N'])
//@
//@ Available options:
//@
//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.
//@
//@ Arguments:
//@
//@ + `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`.
//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
//@
//@ Examples:
//@
//@ ```javascript
//@ // process.cwd() === '/usr'
//@ pushd('/etc'); // Returns /etc /usr
//@ pushd('+1'); // Returns /usr /etc
//@ ```
//@
//@ Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack.
function _pushd(options, dir) {
if (_isStackIndex(options)) {
dir = options;
options = '';
}
options = parseOptions(options, {
'n' : 'no-cd'
});
var dirs = _actualDirStack();
if (dir === '+0') {
return dirs; // +0 is a noop
} else if (!dir) {
if (dirs.length > 1) {
dirs = dirs.splice(1, 1).concat(dirs);
} else {
return error('no other directory');
}
} else if (_isStackIndex(dir)) {
var n = _parseStackIndex(dir);
dirs = dirs.slice(n).concat(dirs.slice(0, n));
} else {
if (options['no-cd']) {
dirs.splice(1, 0, dir);
} else {
dirs.unshift(dir);
}
}
if (options['no-cd']) {
dirs = dirs.slice(1);
} else {
dir = path.resolve(dirs.shift());
_cd('', dir);
}