generated from silverbulletmd/silverbullet-plug-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrep.ts
288 lines (255 loc) · 8.07 KB
/
grep.ts
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { datastore, editor, shell, system } from "$sb/syscalls.ts";
import { FileMeta } from "$sb/types.ts";
const VERSION = "2.3.1";
const resultPageSaved = "GREP RESULT";
const resultPageVirtual = "GREP RESULT 🔍";
export async function showVersion() {
try {
const { stdout } = await shell.run("git", ["--version"]);
// Version info is in the first line
const gitVersion = stdout.split("\n")[0];
await editor.flashNotification(`Grep Plug ${VERSION} ${gitVersion}`);
} catch {
await commandError();
}
}
async function grep(
pattern: string,
literal: boolean = false,
folder: string = ".",
): Promise<string | undefined> {
console.log(`grep("${pattern}", ${literal}, "${folder}")`);
const config = await system.getSpaceConfig("grep", {});
let smartCase = true;
if (config && config.smartCase === false) smartCase = false;
let surroundLeft = ">>>";
let surroundRight = "<<<";
if (config && config.surround !== undefined) {
if (config.surround === false) {
surroundLeft = "";
surroundRight = "";
} else {
if (config.surround.left) {
surroundLeft = config.surround.left;
}
if (config.surround.right) {
surroundRight = config.surround.right;
}
}
}
const caseSensitive = smartCase ? pattern.toLowerCase() !== pattern : true;
let output: string;
try {
const result = await shell.run("git", [
"-c", // modify config to this command
"core.quotePath=false", // handle non-ASCII paths
"grep",
"--heading", // group by file
"--break", // separate files with empty line
"--line-number",
"--column",
"--no-color", // can't use terminal color here anyway
"--no-index", // search like normal grep, no git-specific features
...(caseSensitive ? [] : ["--ignore-case"]),
literal ? "--fixed-strings" : "--extended-regexp",
pattern,
"--",
folder + (folder.endsWith("/") ? "" : "/") + "*.md",
]);
if (result) {
output = result.stdout;
} else {
editor.flashNotification(
`${literal ? "Text" : "Pattern"} "${pattern}" produced no results`,
);
return;
}
} catch (err) {
console.error(err);
commandError();
return;
}
if (!output) {
editor.flashNotification(
`${literal ? "Text" : "Pattern"} "${pattern}" produced no results`,
);
return;
}
// --break separates files by an empty line
const fileOutputs = output.split("\n\n");
// git-grep doesn't count multiple matches, we'll search inside each line
const innerRegex = new RegExp(
literal ? escapeRegExp(pattern) : pattern,
caseSensitive ? "g" : "gi",
);
const fileMatches = [];
for (const fileOutput of fileOutputs) {
const lines = fileOutput.split("\n");
// ensure it's a markdown file and normalize to page name
if (!lines[0].endsWith(".md")) continue;
const page = normalizePath(lines[0].slice(0, -3));
// don't consider hits in results
if (page === resultPageSaved) continue;
if (page === resultPageVirtual) continue;
const matches = [];
for (const line of lines.slice(1)) {
const locationMatch = line.match(/^(\d)+:(\d)+:/);
if (!locationMatch) continue;
// HACK: regex kept losing the first digit
const lineNum = parseInt(line.split(":")[0]);
const context = line.substring(
lineNum.toString().length + line.split(":")[1].length + 2,
);
const innerMatches = context.matchAll(innerRegex);
for (const innerMatch of innerMatches) {
const columnNum = innerMatch.index + 1;
const start = innerMatch.index;
const end = innerMatch.index + innerMatch[0].length;
const surrounded = [
context.substring(0, start),
surroundLeft,
context.substring(start, end),
surroundRight,
context.substring(end),
].join("");
matches.push({ lineNum, columnNum, context: surrounded });
}
}
fileMatches.push({ page, matches });
}
fileMatches.sort((a, b) => {
// descending sort by match count
return -(a.matches.length - b.matches.length);
});
const text = `Search results for ${
literal ? "text" : "pattern"
} **\`${pattern}\`**${
folder !== "." ? "\n**found inside folder:** " + folder + "\n" : ""
}\n${
fileMatches
.map(
(fm) =>
`\n## [[${fm.page}]] (${fm.matches.length} ${
fm.matches.length > 1 ? "matches" : "match"
})\n` +
fm.matches
.map(
(m) =>
`* [[${fm.page}@L${m.lineNum}C${m.columnNum}|L${m.lineNum}C${m.columnNum}]]: ${m.context}`,
)
.join("\n"),
)
.join("\n")
}
`;
return text;
}
async function openGrep(
pattern: string,
literal: boolean = false,
folder: string = ".",
) {
const config = await system.getSpaceConfig("grep", {});
let saveResults = false;
if (config && config.saveResults === true) saveResults = true;
if (saveResults) {
const text = await grep(pattern, literal, folder);
if (text) {
await editor.navigate({ page: resultPageSaved });
const textLength = (await editor.getText()).length;
await editor.replaceRange(0, textLength, `#meta\n\n${text}`);
}
} else {
await datastore.set(["grep", "arguments"], { pattern, literal, folder });
await editor.navigate({ page: resultPageVirtual });
}
}
export async function readFileGrepResult(
name: string,
): Promise<{ data: Uint8Array; meta: FileMeta }> {
let text = "Did not produce any results";
const args = await datastore.get(["grep", "arguments"]);
try {
const grepText = await grep(args.pattern, args.literal, args.folder);
if (grepText) text = grepText;
} catch {
text =
`Could not call grep implementation, make sure to only open "${resultPageVirtual}" using Grep Plug commands`;
}
return {
data: new TextEncoder().encode(text),
meta: {
name,
contentType: "text/markdown",
size: text.length,
created: 0,
lastModified: 0,
perm: "ro",
},
};
}
export function writeFileGrepResult(
name: string,
): FileMeta {
// Never actually writing this
return getFileMetaGrepResult(name);
}
export function getFileMetaGrepResult(name: string): FileMeta {
return {
name,
contentType: "text/markdown",
size: -1,
created: 0,
lastModified: 0,
perm: "ro",
};
}
export async function searchText() {
const pattern = await editor.prompt("Literal text:", "");
if (!pattern) {
return;
}
await openGrep(pattern, true);
}
export async function searchRegex() {
const pattern = await editor.prompt("Regular expression pattern:", "");
if (!pattern) {
return;
}
await openGrep(pattern, false);
}
export async function searchRegexInFolder() {
const pageName = await editor.getCurrentPage();
// Get the folder it's nested in, keeping the trailing /
const folderPath = pageName.slice(0, pageName.lastIndexOf("/") + 1);
const pattern = await editor.prompt("Regular expression pattern:", "");
if (!pattern) {
return;
}
await openGrep(pattern, false, folderPath !== "" ? folderPath : ".");
}
export async function searchTextInFolder() {
const pageName = await editor.getCurrentPage();
// Get the folder it's nested in, keeping the trailing /
const folderPath = pageName.slice(0, pageName.lastIndexOf("/") + 1);
const pattern = await editor.prompt("Literal text:", "");
if (!pattern) {
return;
}
await openGrep(pattern, false, folderPath !== "" ? folderPath : ".");
}
function normalizePath(path: string): string {
const forward = path.replaceAll("\\", "/");
if (forward.startsWith("./")) return forward.substring(2);
else return forward;
}
// from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
function escapeRegExp(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
async function commandError() {
await editor.flashNotification(
"Error running command, ensure 'git' is in PATH and server allows shell commands",
"error",
);
}