Skip to content

Commit bd48247

Browse files
committed
feat: support option parsing for grep -C flag
This adds support for shelljs/shelljs#1206. This requires special parsing logic on the shx side. Test: npm test Test: ./lib/cli.js grep -A 1 'foo' ~/foobartest.txt Test: cat ~/foobartest.txt | ./lib/cli.js grep -A 1 'foo'
1 parent 241e1ff commit bd48247

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/config.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ export const shouldReadStdin = (args) => {
5454
if (parsedArgs.n && (cmd === 'head' || cmd === 'tail')) {
5555
requiredNumArgs++;
5656
}
57+
if ((parsedArgs.A || parsedArgs.B || parsedArgs.C) && cmd === 'grep') {
58+
requiredNumArgs++;
59+
}
5760

58-
return Boolean(!process.stdin.isTTY && parsedArgs._.length < requiredNumArgs);
61+
if (process.stdin.isTTY) {
62+
return false;
63+
}
64+
if (parsedArgs._.length >= requiredNumArgs) {
65+
return false;
66+
}
67+
return true;
5968
};

test/specs/cli.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,9 @@ describe('cli', () => {
193193
shouldReadStdin(['head', '-n', '1']).should.equal(true);
194194
shouldReadStdin(['tail', '-n', '1']).should.equal(true);
195195
shouldReadStdin(['grep', '-i', 'a.*z']).should.equal(true);
196+
shouldReadStdin(['grep', '-A', 2, 'a.*z']).should.equal(true);
197+
shouldReadStdin(['grep', '-B', 2, 'a.*z']).should.equal(true);
198+
shouldReadStdin(['grep', '-C', 2, 'a.*z']).should.equal(true);
196199
});
197200

198201
it('does not read stdin if process.stdin is a TTY', () => {
@@ -433,10 +436,20 @@ describe('cli', () => {
433436
afterEach(() => {
434437
shell.rm('-f', testFileName);
435438
});
439+
436440
it('works with regex syntax', () => {
437441
const ret = cli('grep', 'fo*', testFileName);
438442
ret.stdout.should.equal('foo\nf\nsomething foo\n');
439443
});
444+
445+
it('correctly parses -A/-B/-C flags', () => {
446+
let ret = cli('grep', '-A', '1', 'foo', testFileName);
447+
ret.stdout.should.equal('foo\nf\n--\nsomething foo\n');
448+
ret = cli('grep', '-B', '1', 'foo', testFileName);
449+
ret.stdout.should.equal('1st line\nfoo\n--\ndoes not match\nsomething foo\n');
450+
ret = cli('grep', '-C', '1', 'foo', testFileName);
451+
ret.stdout.should.equal('1st line\nfoo\nf\ndoes not match\nsomething foo\n');
452+
});
440453
});
441454

442455
describe('chmod', () => {

0 commit comments

Comments
 (0)