-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
224 lines (197 loc) · 5.86 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
#!/usr/bin/env node
"use strict"
const shell = require('shelljs');
const pjson = require('./package.json');
const fs = require('fs');
const { promisify } = require('util');
const promisifiedStat = promisify(fs.stat);
const promisifiedExec = promisify(shell.exec);
const args = process.argv.slice(2);
// --------------- Validation ---------------
if (args.length === 0) {
shell.echo('No arguments found');
process.exit(9);
}
// -------------- Help Section --------------
if (isHelpCmd(args[0])) {
help();
}
// ------------- Version Section -------------
if (isVersionCmd(args[0])) {
getVersion();
}
// -------------- Grep Section --------------
if (!isHelpCmd(args[0]) && !isVersionCmd(args[0])) {
const [grepArgs, grepOrdArg] = splitArgs(args);
const usersCommand = `grep ${grepArgs.join(' ').trimStart()}`;
const [sortBy, sortOrd, limit] = getSortArgs(grepOrdArg);
const sortedResultsArray = sortResults(usersCommand, sortBy, sortOrd);
const limitedResultsArray = limitResults(sortedResultsArray, limit);
echoResults(limitedResultsArray);
}
// ------------ Functions Section ------------
function isHelpCmd(firstArg) {
return ['-h', '--help'].includes(firstArg);
}
function help(man = false) {
const readmePath = `${__dirname}/README.md`;
fs.readFile(readmePath, 'utf8', (err, data) => {
if (err) throw err;
const helpText =
`${data.split("\n").slice(16).join("\n").replace(/`/g, '')}\n\n` +
`Author: ${pjson.author.name}\n` +
`Contact: ${pjson.author.email}\n` +
`License: ${pjson.license}\n` +
`Bugs: ${pjson.bugs.url}\n`;
if (man) {
const resultsPromise = promisifiedExec(`
echo "${helpText}" > ./man/grepord.1.ronn
ronn man/*.ronn
`, {silent:false});
resultsPromise.then(() => {
shell.echo('Man files generated');
process.exit(0);
}, (err) => {
shell.echo(`Error generating man files: ${err}`);
process.exit(0);
});
} else {
shell.echo(helpText);
process.exit(0);
}
});
}
function isVersionCmd(firstArg) {
return ['-v', '--version'].includes(firstArg.toLowerCase());
}
function getVersion() {
shell.echo(pjson.version);
process.exit(0);
}
function splitArgs(args) {
let splitArgsArray = [args, ''];
let lastArg = args.slice(-1)[0].trimStart();
if (lastArg.startsWith('-sort:')) {
lastArg = lastArg.replace('-sort:', '');
args.pop();
splitArgsArray = [args, lastArg];
}
return splitArgsArray;
}
function getSortArgs(grepOrdArg) {
const sortArgs = [];
const [sortBy, sortOrd, limit] = grepOrdArg.split(',');
if (sortBy && (sortBy.length > 0)) {
sortArgs.push(sortBy);
} else {
sortArgs.push('mtime');
}
if (sortOrd && (sortOrd.length > 0)) {
sortArgs.push(sortOrd);
} else {
sortArgs.push('desc');
}
if (limit && (limit.length > 0)) {
sortArgs.push(parseInt(limit));
} else {
sortArgs.push(0);
}
return sortArgs;
}
async function getResults(usersCommand) {
let resultsArray = [];
try {
const results = await promisifiedExec(usersCommand, { silent:true });
resultsArray = results.split('\n').filter(p => p);
} catch(err) {
// shell.echo(err); // debug
}
return resultsArray;
}
function sortByTypeCheck(statResult, sortBy) {
if (!statResult.hasOwnProperty(sortBy)) {
shell.echo(`Can not sort by: ${sortBy}`);
process.exit(9);
}
}
function getSortValue(sortByResult, sortBy) {
let sortValue = sortByResult;
if (['atime', 'mtime', 'ctime', 'birthtime'].includes(sortBy)) {
sortValue = sortByResult.getTime();
}
return sortValue;
}
function getSortDisplay(sortByResult, sortBy) {
let sortDisplay = sortByResult;
switch (sortBy) {
case 'atime':
case 'mtime':
case 'ctime':
case 'birthtime':
sortDisplay = sortByResult.toLocaleString().replace(/ /g, '_');
break;
}
return sortDisplay;
}
function getSortingNumber(x) {
return parseFloat(x.split(' ').shift());
}
async function sortResults(usersCommand, sortBy = 'mtime', sortOrd = 'desc') {
let sortedArray = '';
try {
const resultsArray = await getResults(usersCommand);
const sortAndResultsArray = await Promise.all(resultsArray.map(async (resultPath, index) => {
const statResult = await promisifiedStat(resultPath);
if (index === 0) {
sortByTypeCheck(statResult, sortBy);
}
const sortByResult = statResult[sortBy];
const sortValue = getSortValue(sortByResult, sortBy);
const sortDisplay = getSortDisplay(sortByResult, sortBy);
return `${sortValue} ${sortDisplay} ${resultPath}`;
}));
if (sortOrd === 'desc') {
sortAndResultsArray.sort((a, b) => getSortingNumber(b) - getSortingNumber(a));
} else {
sortAndResultsArray.sort((a, b) => getSortingNumber(a) - getSortingNumber(b));
}
sortedArray = sortAndResultsArray.map((sortAndPath) => {
const sortAndPathSplit = sortAndPath.split(' ');
sortAndPathSplit.shift();
const sortDisplay = sortAndPathSplit.shift().replace(/_/g, ' ');
return `${sortAndPathSplit.join(' ')} ${sortDisplay}`;
});
} catch(err) {
if ((err.syscall === 'stat') && (err.code === 'ENOENT')) {
shell.echo('Grepord requires valid file path(s) to be returned (use l)');
process.exit(9);
} else {
shell.echo(err);
}
}
return sortedArray;
}
async function limitResults(resultsArrayPromise, limit) {
let resultsArray = [];
try {
resultsArray = await resultsArrayPromise;
if (limit > 0) {
resultsArray = resultsArray.slice(0, limit);
}
} catch(err) {
// shell.echo(err); // debug
}
return resultsArray;
}
async function echoResults(resultsArrayPromise) {
try {
const resultsArray = await resultsArrayPromise;
if (resultsArray && (resultsArray.length > 0)) {
shell.echo(resultsArray.join('\n'));
} else {
shell.echo('No results');
}
} catch(err) {
shell.echo(err);
}
}