Skip to content

Commit

Permalink
Update grep method to support both rg and grep
Browse files Browse the repository at this point in the history
  • Loading branch information
tobeno committed Jul 16, 2023
1 parent bb5c51a commit 2e6fdbf
Showing 1 changed file with 40 additions and 14 deletions.
54 changes: 40 additions & 14 deletions src/wrappers/shell.wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Wrapper } from './wrapper.wrapper';
import { Directory } from './directory.wrapper';
import { Text } from './text.wrapper';
import { Data } from './data.wrapper';
import { isArray, isBoolean, isNotEmpty } from '../utils/core.utils';
import { inspect } from 'util';
import { isArray, isBoolean, isNotEmpty } from '../utils/core.utils';
import { execCommand } from '../utils/shell.utils';
import { Data } from './data.wrapper';
import { Directory } from './directory.wrapper';
import { Text } from './text.wrapper';
import { Wrapper } from './wrapper.wrapper';

export interface ShellGrepOptions {
/**
Expand Down Expand Up @@ -43,6 +43,11 @@ export interface ShellTailOptions {
}

export class Shell extends Wrapper<Directory> {
/**
* Flag indicating whether ripgrep is available on the system
*/
private ripgrepAvailable: boolean | null = null;

cat(files: string | string[]): Text {
return this.exec(`cat ${this.createShellPaths(files)}`);
}
Expand Down Expand Up @@ -127,15 +132,36 @@ export class Shell extends Wrapper<Directory> {
pattern = pattern.source;
}

const output = this.exec(
`rg ${this.createShellOptions({
l: options.list,
i: options.insensitive,
'sort-files': options.sort ?? true,
})} -e '${pattern.replace(/'/g, "\\'").replace('\n', '\\n')}' ${
this.createShellPaths(paths) || '.'
}`,
);
// Check if rg is available
if (this.ripgrepAvailable === null) {
try {
this.ripgrepAvailable = !!this.exec('which rg').length;
} catch (e) {
this.ripgrepAvailable = false;
}
}

let output: Text;
if (this.ripgrepAvailable) {
output = this.exec(
`rg ${this.createShellOptions({
l: options.list,
i: options.insensitive,
'sort-files': options.sort ?? true,
})} -e '${pattern.replace(/'/g, "\\'").replace('\n', '\\n')}' ${
this.createShellPaths(paths) || '.'
}`,
);
} else {
output = this.exec(
`grep ${this.createShellOptions({
l: options.list,
i: options.insensitive,
})} -R -E '${pattern.replace(/'/g, "\\'").replace('\n', '\\n')}' ${
this.createShellPaths(paths) || '.'
} | sort`,
);
}

return output.lines;
}
Expand Down

0 comments on commit 2e6fdbf

Please sign in to comment.