-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
170 lines (145 loc) · 6.82 KB
/
index.js
File metadata and controls
170 lines (145 loc) · 6.82 KB
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
const { spawn } = require("child_process");
const { rgPath } = require("@vscode/ripgrep");
const path = require("path");
const fs = require("fs").promises;
const { createBlock, createResultLine, createFileResult } = require('./types.js');
/**
* Helper function to run a ripgrep command and return its stdout.
* @param {string} cwd The working directory.
* @param {string[]} args The arguments for ripgrep.
* @returns {Promise<string>} The stdout from the command.
*/
function runRg(cwd, args) {
return new Promise((resolve, reject) => {
const proc = spawn(rgPath, args, { cwd });
let stdout = '';
let stderr = '';
proc.stdout.on('data', data => stdout += data.toString());
proc.stderr.on('data', data => stderr += data.toString());
proc.on('close', code => {
// Code 1 is OK when no matches are found.
if (code !== 0 && code !== 1) {
return reject(new Error(`ripgrep process exited with code ${code}, stderr: ${stderr}`));
}
resolve(stdout);
});
proc.on('error', err => reject(err));
});
}
/**
* Searches for a term in a directory using ripgrep.
*
* @param {string} working_dir The directory to search in.
* @param {boolean} match_case Whether the search should be case-sensitive.
* @param {boolean} match_whole_word Whether to match whole words only.
* @param {boolean} use_regex Whether the search term is a regular expression.
* @param {string} search_term The term to search for.
* @param {string} [files_to_include] A space-separated list of glob patterns to include.
* @param {string} [files_to_exclude] A space-separated list of glob patterns to exclude.
* @returns {Promise<FileResult[]>} A promise that resolves with the search results.
*/
async function search(working_dir, match_case, match_whole_word, use_regex, search_term, files_to_include, files_to_exclude) {
if (typeof working_dir !== typeof '') throw new Error('working_dir must be a string');
if (typeof match_case !== typeof true) throw new Error('match_case must be a boolean');
if (typeof match_whole_word !== typeof true) throw new Error('match_whole_word must be a boolean');
if (typeof use_regex !== typeof true) throw new Error('use_regex must be a boolean');
if (typeof search_term !== typeof '') throw new Error('search_term must be a string');
const rgArgs = ['--json'];
// Options
if (match_case) rgArgs.push('--case-sensitive');
else rgArgs.push('--ignore-case');
if (match_whole_word) rgArgs.push('--word-regexp');
if (files_to_include) files_to_include.split(' ').forEach(glob => rgArgs.push('-g', glob));
if (files_to_exclude) files_to_exclude.split(' ').forEach(glob => rgArgs.push('-g', `!${glob}`));
// Pattern
if (!use_regex) rgArgs.push('--fixed-strings');
rgArgs.push(search_term);
// Path
rgArgs.push('.');
const stdout = await runRg(working_dir, rgArgs);
if (!stdout) return [];
const results = [];
const lines = stdout.trim().split('\n');
lines.forEach(line => {
try {
const jsonLine = JSON.parse(line);
if (jsonLine.type === 'match') {
const data = jsonLine.data;
const filePath = data.path.text;
const filename = path.basename(filePath);
let fileResult = results.find(r => r.path === filePath);
if (!fileResult) {
fileResult = createFileResult(filePath, filename);
results.push(fileResult);
}
const submatches = data.submatches;
const lineText = data.lines.text.replace(/\n$/, '');
const lineNumber = data.line_number;
const resultLine = createResultLine([], lineNumber, submatches);
let lastEnd = 0;
submatches.forEach((match) => {
const start = match.start;
const end = match.end;
if (start > lastEnd) {
resultLine.line.push(createBlock(lineText.substring(lastEnd, start), false));
}
resultLine.line.push(createBlock(lineText.substring(start, end), true));
lastEnd = end;
});
if (lastEnd < lineText.length) {
resultLine.line.push(createBlock(lineText.substring(lastEnd), false));
}
fileResult.results.push(resultLine);
}
} catch (e) {
// Ignore lines that are not valid JSON
}
});
return results;
}
/**
* Searches for a term and replaces it with another term in a directory using ripgrep.
*
* @param {string} working_dir The directory to search in.
* @param {boolean} match_case Whether the search should be case-sensitive.
* @param {boolean} match_whole_word Whether to match whole words only.
* @param {boolean} use_regex Whether the search term is a regular expression.
* @param {string} search_term The term to search for.
* @param {string} replace_term The term to replace matches with.
* @param {string} [files_to_include] A space-separated list of glob patterns to include.
* @param {string} [files_to_exclude] A space-separated list of glob patterns to exclude.
* @returns {Promise<void>} A promise that resolves when the replacement is complete.
*/
async function replace(working_dir, match_case, match_whole_word, use_regex, search_term, replace_term, files_to_include, files_to_exclude) {
if (typeof working_dir !== typeof '') throw new Error('working_dir must be a string');
if (typeof match_case !== typeof true) throw new Error('match_case must be a boolean');
if (typeof match_whole_word !== typeof true) throw new Error('match_whole_word must be a boolean');
if (typeof use_regex !== typeof true) throw new Error('use_regex must be a boolean');
if (typeof search_term !== typeof '') throw new Error('search_term must be a string');
if (typeof replace_term !== typeof '') throw new Error('replace_term must be a string');
const listArgs = ['--files-with-matches'];
if (match_case) listArgs.push('--case-sensitive'); else listArgs.push('--ignore-case');
if (match_whole_word) listArgs.push('--word-regexp');
if (files_to_include) files_to_include.split(' ').forEach(glob => listArgs.push('-g', glob));
if (files_to_exclude) files_to_exclude.split(' ').forEach(glob => listArgs.push('-g', `!${glob}`));
if (!use_regex) listArgs.push('--fixed-strings');
listArgs.push(search_term);
listArgs.push('.');
const fileListOutput = await runRg(working_dir, listArgs);
if (!fileListOutput) return;
const filesToChange = fileListOutput.trim().split('\n');
// 2. For each file, run rg with --passthru to get the full replaced content, then overwrite the file.
for (const file of filesToChange) {
if (!file) continue;
const replaceArgs = ['--passthru', '--replace', replace_term];
if (match_case) replaceArgs.push('--case-sensitive'); else replaceArgs.push('--ignore-case');
if (match_whole_word) replaceArgs.push('--word-regexp');
if (!use_regex) replaceArgs.push('--fixed-strings');
replaceArgs.push(search_term);
replaceArgs.push(file);
const newContent = await runRg(working_dir, replaceArgs);
// ripgrep adds a trailing newline; trim it to avoid altering files that don't have one.
await fs.writeFile(path.join(working_dir, file), newContent.trimEnd(), 'utf-8');
}
}
module.exports = { search, replace };