ripgrep.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { EOL } from "os"
  2. import { Ripgrep } from "../../../file/ripgrep"
  3. import { Instance } from "../../../project/instance"
  4. import { bootstrap } from "../../bootstrap"
  5. import { cmd } from "../cmd"
  6. export const RipgrepCommand = cmd({
  7. command: "rg",
  8. builder: (yargs) => yargs.command(TreeCommand).command(FilesCommand).command(SearchCommand).demandCommand(),
  9. async handler() {},
  10. })
  11. const TreeCommand = cmd({
  12. command: "tree",
  13. builder: (yargs) =>
  14. yargs.option("limit", {
  15. type: "number",
  16. }),
  17. async handler(args) {
  18. await bootstrap(process.cwd(), async () => {
  19. process.stdout.write(await Ripgrep.tree({ cwd: Instance.directory, limit: args.limit }) + EOL)
  20. })
  21. },
  22. })
  23. const FilesCommand = cmd({
  24. command: "files",
  25. builder: (yargs) =>
  26. yargs
  27. .option("query", {
  28. type: "string",
  29. description: "Filter files by query",
  30. })
  31. .option("glob", {
  32. type: "string",
  33. description: "Glob pattern to match files",
  34. })
  35. .option("limit", {
  36. type: "number",
  37. description: "Limit number of results",
  38. }),
  39. async handler(args) {
  40. await bootstrap(process.cwd(), async () => {
  41. const files: string[] = []
  42. for await (const file of Ripgrep.files({
  43. cwd: Instance.directory,
  44. glob: args.glob ? [args.glob] : undefined,
  45. })) {
  46. files.push(file)
  47. if (args.limit && files.length >= args.limit) break
  48. }
  49. process.stdout.write(files.join(EOL) + EOL)
  50. })
  51. },
  52. })
  53. const SearchCommand = cmd({
  54. command: "search <pattern>",
  55. builder: (yargs) =>
  56. yargs
  57. .positional("pattern", {
  58. type: "string",
  59. demandOption: true,
  60. description: "Search pattern",
  61. })
  62. .option("glob", {
  63. type: "array",
  64. description: "File glob patterns",
  65. })
  66. .option("limit", {
  67. type: "number",
  68. description: "Limit number of results",
  69. }),
  70. async handler(args) {
  71. const results = await Ripgrep.search({
  72. cwd: process.cwd(),
  73. pattern: args.pattern,
  74. glob: args.glob as string[] | undefined,
  75. limit: args.limit,
  76. })
  77. process.stdout.write(JSON.stringify(results, null, 2) + EOL)
  78. },
  79. })