1 | var path = require('path');
|
2 | var fs = require('fs');
|
3 | var common = require('./common');
|
4 | var glob = require('glob');
|
5 |
|
6 | var globPatternRecursive = path.sep + '**';
|
7 |
|
8 | common.register('ls', _ls, {
|
9 | cmdOptions: {
|
10 | 'R': 'recursive',
|
11 | 'A': 'all',
|
12 | 'L': 'link',
|
13 | 'a': 'all_deprecated',
|
14 | 'd': 'directory',
|
15 | 'l': 'long',
|
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 | function _ls(options, paths) {
|
44 | if (options.all_deprecated) {
|
45 |
|
46 |
|
47 |
|
48 | common.log('ls: Option -a is deprecated. Use -A instead');
|
49 | options.all = true;
|
50 | }
|
51 |
|
52 | if (!paths) {
|
53 | paths = ['.'];
|
54 | } else {
|
55 | paths = [].slice.call(arguments, 1);
|
56 | }
|
57 |
|
58 | var list = [];
|
59 |
|
60 | function pushFile(abs, relName, stat) {
|
61 | if (process.platform === 'win32') {
|
62 | relName = relName.replace(/\\/g, '/');
|
63 | }
|
64 | if (options.long) {
|
65 | stat = stat || (options.link ? common.statFollowLinks(abs) : common.statNoFollowLinks(abs));
|
66 | list.push(addLsAttributes(relName, stat));
|
67 | } else {
|
68 |
|
69 | list.push(relName);
|
70 | }
|
71 | }
|
72 |
|
73 | paths.forEach(function (p) {
|
74 | var stat;
|
75 |
|
76 | try {
|
77 | stat = options.link ? common.statFollowLinks(p) : common.statNoFollowLinks(p);
|
78 |
|
79 | if (stat.isSymbolicLink()) {
|
80 | try {
|
81 | var _stat = common.statFollowLinks(p);
|
82 | if (_stat.isDirectory()) {
|
83 | stat = _stat;
|
84 | }
|
85 | } catch (_) {}
|
86 | }
|
87 | } catch (e) {
|
88 | common.error('no such file or directory: ' + p, 2, { continue: true });
|
89 | return;
|
90 | }
|
91 |
|
92 |
|
93 | if (stat.isDirectory() && !options.directory) {
|
94 | if (options.recursive) {
|
95 |
|
96 | glob.sync(p + globPatternRecursive, { dot: options.all, follow: options.link })
|
97 | .forEach(function (item) {
|
98 |
|
99 | if (path.relative(p, item)) {
|
100 | pushFile(item, path.relative(p, item));
|
101 | }
|
102 | });
|
103 | } else if (options.all) {
|
104 |
|
105 | fs.readdirSync(p).forEach(function (item) {
|
106 | pushFile(path.join(p, item), item);
|
107 | });
|
108 | } else {
|
109 |
|
110 | fs.readdirSync(p).forEach(function (item) {
|
111 | if (item[0] !== '.') {
|
112 | pushFile(path.join(p, item), item);
|
113 | }
|
114 | });
|
115 | }
|
116 | } else {
|
117 | pushFile(p, p, stat);
|
118 | }
|
119 | });
|
120 |
|
121 |
|
122 | return list;
|
123 | }
|
124 |
|
125 | function addLsAttributes(pathName, stats) {
|
126 |
|
127 | stats.name = pathName;
|
128 | stats.toString = function () {
|
129 |
|
130 | return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' ');
|
131 | };
|
132 | return stats;
|
133 | }
|
134 |
|
135 | module.exports = _ls;
|