revgraph 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,308 @@
1
+ export const GENERIC_SYMBOLS = new Set([
2
+ "new",
3
+ "default",
4
+ "fmt",
5
+ "from",
6
+ "into",
7
+ "clone",
8
+ "drop",
9
+ "run",
10
+ "init",
11
+ "get",
12
+ "set",
13
+ "id",
14
+ "name",
15
+ "type",
16
+ "value",
17
+ "Value",
18
+ "Error",
19
+ "Item",
20
+ "Output",
21
+ "Target",
22
+ "Result",
23
+ "Option",
24
+ "State",
25
+ "Config",
26
+ "Params",
27
+ "Props",
28
+ "Response",
29
+ "Request",
30
+ "deserialize",
31
+ "serialize",
32
+ "data",
33
+ "error",
34
+ "index",
35
+ "main",
36
+ "test",
37
+ "tests",
38
+ "render",
39
+ "handle",
40
+ "update",
41
+ "delete",
42
+ "create",
43
+ "build",
44
+ "parse",
45
+ "load",
46
+ "save",
47
+ "String",
48
+ "Close",
49
+ "Read",
50
+ "Write",
51
+ "__init__",
52
+ "__str__",
53
+ "__repr__",
54
+ ]);
55
+
56
+ export function escapeRegExp(s) {
57
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
58
+ }
59
+
60
+ export function lineNumberAt(text, index) {
61
+ let line = 1;
62
+ for (let i = 0; i < index; i++) {
63
+ if (text.charCodeAt(i) === 10) line++;
64
+ }
65
+ return line;
66
+ }
67
+
68
+ export function dedupeImports(list) {
69
+ const byTarget = new Map();
70
+ for (const item of list) {
71
+ if (!byTarget.has(item.target)) {
72
+ byTarget.set(item.target, {
73
+ target: item.target,
74
+ symbols: new Set(item.symbols || []),
75
+ kind: item.kind,
76
+ });
77
+ } else {
78
+ const existing = byTarget.get(item.target);
79
+ for (const s of item.symbols || []) existing.symbols.add(s);
80
+ }
81
+ }
82
+ return Array.from(byTarget.values()).map((x) => ({
83
+ target: x.target,
84
+ symbols: Array.from(x.symbols),
85
+ kind: x.kind,
86
+ }));
87
+ }
88
+
89
+ export function findBraceBlockEndLine(lines, startLineIdx, maxScan = 500) {
90
+ let depth = 0;
91
+ let seenOpen = false;
92
+ const endLimit = Math.min(lines.length, startLineIdx + maxScan);
93
+ for (let i = startLineIdx; i < endLimit; i++) {
94
+ const line = lines[i];
95
+ for (let c = 0; c < line.length; c++) {
96
+ if (line[c] === "{") {
97
+ depth++;
98
+ seenOpen = true;
99
+ } else if (line[c] === "}") {
100
+ depth--;
101
+ if (seenOpen && depth <= 0) return i + 1;
102
+ } else if (!seenOpen && line[c] === ";") {
103
+ return i + 1;
104
+ }
105
+ }
106
+ }
107
+ return Math.min(lines.length, startLineIdx + 1);
108
+ }
109
+
110
+ /**
111
+ * Strip comments while preserving exact line count and string literals.
112
+ * lang: "ts" | "rust" | "go" | "python"
113
+ */
114
+ export function stripCommentsKeepLines(code, lang) {
115
+ if (lang === "python") return stripPythonComments(code);
116
+ const out = [];
117
+ const len = code.length;
118
+ let i = 0;
119
+
120
+ while (i < len) {
121
+ const ch = code[i];
122
+ const next = code[i + 1];
123
+
124
+ // Rust raw strings: r"...", r#"..."#, br#"..."#
125
+ if (lang === "rust" && (ch === "r" || (ch === "b" && next === "r"))) {
126
+ let j = ch === "b" ? i + 2 : i + 1;
127
+ let hashes = 0;
128
+ while (j < len && code[j] === "#") {
129
+ hashes++;
130
+ j++;
131
+ }
132
+ if (j < len && code[j] === '"') {
133
+ out.push(code.slice(i, j + 1));
134
+ i = j + 1;
135
+ const closing = '"' + "#".repeat(hashes);
136
+ const endIdx = code.indexOf(closing, i);
137
+ if (endIdx === -1) {
138
+ out.push(code.slice(i));
139
+ break;
140
+ }
141
+ out.push(code.slice(i, endIdx + closing.length));
142
+ i = endIdx + closing.length;
143
+ continue;
144
+ }
145
+ }
146
+
147
+ // Double-quoted strings
148
+ if (ch === '"') {
149
+ let j = i + 1;
150
+ while (j < len) {
151
+ if (code[j] === "\\") {
152
+ j += 2;
153
+ continue;
154
+ }
155
+ if (code[j] === '"') {
156
+ j++;
157
+ break;
158
+ }
159
+ j++;
160
+ }
161
+ out.push(code.slice(i, j));
162
+ i = j;
163
+ continue;
164
+ }
165
+
166
+ // Go raw backtick string (no backslash escapes)
167
+ if (lang === "go" && ch === "`") {
168
+ const endIdx = code.indexOf("`", i + 1);
169
+ if (endIdx === -1) {
170
+ out.push(code.slice(i));
171
+ break;
172
+ }
173
+ out.push(code.slice(i, endIdx + 1));
174
+ i = endIdx + 1;
175
+ continue;
176
+ }
177
+
178
+ // TS/JS single-quoted & template strings
179
+ if (lang === "ts" && (ch === "'" || ch === "`")) {
180
+ const quote = ch;
181
+ let j = i + 1;
182
+ while (j < len) {
183
+ if (code[j] === "\\") {
184
+ j += 2;
185
+ continue;
186
+ }
187
+ if (code[j] === quote) {
188
+ j++;
189
+ break;
190
+ }
191
+ j++;
192
+ }
193
+ out.push(code.slice(i, j));
194
+ i = j;
195
+ continue;
196
+ }
197
+
198
+ // Rust/Go char literals (avoid swallowing Rust lifetimes like 'a or 'static)
199
+ if ((lang === "rust" || lang === "go") && ch === "'") {
200
+ if (next === "\\" && i + 3 < len) {
201
+ const endChar = code.indexOf("'", i + 2);
202
+ if (endChar !== -1 && endChar - i <= 8) {
203
+ out.push(code.slice(i, endChar + 1));
204
+ i = endChar + 1;
205
+ continue;
206
+ }
207
+ } else if (i + 2 < len && code[i + 2] === "'" && next !== "\n") {
208
+ out.push(code.slice(i, i + 3));
209
+ i += 3;
210
+ continue;
211
+ }
212
+ }
213
+
214
+ // Line comment
215
+ if (ch === "/" && next === "/") {
216
+ let j = i + 2;
217
+ while (j < len && code[j] !== "\n") j++;
218
+ out.push(" ".repeat(j - i));
219
+ i = j;
220
+ continue;
221
+ }
222
+
223
+ // Block comment (nested in Rust)
224
+ if (ch === "/" && next === "*") {
225
+ let depth = 1;
226
+ let j = i + 2;
227
+ out.push(" ");
228
+ while (j < len && depth > 0) {
229
+ if (lang === "rust" && code[j] === "/" && code[j + 1] === "*") {
230
+ depth++;
231
+ out.push(" ");
232
+ j += 2;
233
+ } else if (code[j] === "*" && code[j + 1] === "/") {
234
+ depth--;
235
+ out.push(" ");
236
+ j += 2;
237
+ } else {
238
+ out.push(code[j] === "\n" ? "\n" : " ");
239
+ j++;
240
+ }
241
+ }
242
+ i = j;
243
+ continue;
244
+ }
245
+
246
+ out.push(ch);
247
+ i++;
248
+ }
249
+ return out.join("");
250
+ }
251
+
252
+ function stripPythonComments(code) {
253
+ const out = [];
254
+ const len = code.length;
255
+ let i = 0;
256
+
257
+ while (i < len) {
258
+ const ch = code[i];
259
+ // Triple-quoted strings
260
+ if ((ch === '"' || ch === "'") && code[i + 1] === ch && code[i + 2] === ch) {
261
+ const q3 = ch.repeat(3);
262
+ let j = i + 3;
263
+ while (j < len) {
264
+ if (code[j] === "\\") {
265
+ j += 2;
266
+ continue;
267
+ }
268
+ if (code.startsWith(q3, j)) {
269
+ j += 3;
270
+ break;
271
+ }
272
+ j++;
273
+ }
274
+ out.push(code.slice(i, j));
275
+ i = j;
276
+ continue;
277
+ }
278
+ // Single/double quoted strings
279
+ if (ch === '"' || ch === "'") {
280
+ let j = i + 1;
281
+ while (j < len && code[j] !== "\n") {
282
+ if (code[j] === "\\") {
283
+ j += 2;
284
+ continue;
285
+ }
286
+ if (code[j] === ch) {
287
+ j++;
288
+ break;
289
+ }
290
+ j++;
291
+ }
292
+ out.push(code.slice(i, j));
293
+ i = j;
294
+ continue;
295
+ }
296
+ // # comment
297
+ if (ch === "#") {
298
+ let j = i + 1;
299
+ while (j < len && code[j] !== "\n") j++;
300
+ out.push(" ".repeat(j - i));
301
+ i = j;
302
+ continue;
303
+ }
304
+ out.push(ch);
305
+ i++;
306
+ }
307
+ return out.join("");
308
+ }
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { dedupeImports, findBraceBlockEndLine, stripCommentsKeepLines } from "./common.mjs";
4
+
5
+ /**
6
+ * Index all go.mod files and Go package directories in the repo.
7
+ */
8
+ export function buildGoModuleIndex(repoRoot, allFiles) {
9
+ const modules = [];
10
+ for (const rel of allFiles) {
11
+ if (rel === "go.mod" || rel.endsWith("/go.mod")) {
12
+ const abs = path.join(repoRoot, rel);
13
+ if (!fs.existsSync(abs)) continue;
14
+ try {
15
+ const text = fs.readFileSync(abs, "utf8");
16
+ const m = text.match(/^\s*module\s+([^\s]+)/m);
17
+ if (m) {
18
+ const dir = path.posix.dirname(rel);
19
+ modules.push({ modulePath: m[1].replace(/^"|"$/g, ""), dir: dir === "." ? "" : dir });
20
+ }
21
+ } catch {
22
+ // Ignore unreadable go.mod
23
+ }
24
+ }
25
+ }
26
+ modules.sort((a, b) => b.modulePath.length - a.modulePath.length);
27
+
28
+ // Map directory -> non-test .go files in that package
29
+ const pkgFiles = new Map();
30
+ for (const rel of allFiles) {
31
+ if (!rel.endsWith(".go") || rel.endsWith("_test.go")) continue;
32
+ const dir = path.posix.dirname(rel);
33
+ const key = dir === "." ? "" : dir;
34
+ if (!pkgFiles.has(key)) pkgFiles.set(key, []);
35
+ pkgFiles.get(key).push(rel);
36
+ }
37
+ return { modules, pkgFiles };
38
+ }
39
+
40
+ function resolveGoImport(importPath, goIndex) {
41
+ for (const mod of goIndex.modules) {
42
+ if (importPath === mod.modulePath || importPath.startsWith(`${mod.modulePath}/`)) {
43
+ const sub = importPath.slice(mod.modulePath.length).replace(/^\//, "");
44
+ const targetDir = mod.dir ? (sub ? `${mod.dir}/${sub}` : mod.dir) : sub;
45
+ return goIndex.pkgFiles.get(targetDir) || [];
46
+ }
47
+ }
48
+ return [];
49
+ }
50
+
51
+ export function parseGoFile(relPath, content, goIndex) {
52
+ const clean = stripCommentsKeepLines(content, "go");
53
+ const lines = clean.split("\n");
54
+ const imports = [];
55
+ const symbols = [];
56
+
57
+ // Grouped import (...)
58
+ const groupRe = /(?:^|\n)\s*import\s*\(([\s\S]*?)\)/g;
59
+ for (const m of clean.matchAll(groupRe)) {
60
+ for (const line of m[1].split("\n")) {
61
+ const spec = line.match(/"([^"]+)"/);
62
+ if (!spec) continue;
63
+ for (const target of resolveGoImport(spec[1], goIndex)) {
64
+ if (target !== relPath) imports.push({ target, symbols: [], kind: "import" });
65
+ }
66
+ }
67
+ }
68
+
69
+ // Single-line import "pkg" or import alias "pkg"
70
+ const singleRe = /(?:^|\n)\s*import\s+(?:[A-Za-z0-9_.]+\s+)?"([^"]+)"/g;
71
+ for (const m of clean.matchAll(singleRe)) {
72
+ for (const target of resolveGoImport(m[1], goIndex)) {
73
+ if (target !== relPath) imports.push({ target, symbols: [], kind: "import" });
74
+ }
75
+ }
76
+
77
+ // Functions, methods, and types
78
+ for (let i = 0; i < lines.length; i++) {
79
+ const line = lines[i];
80
+
81
+ const methodMatch = line.match(/^func\s*\([^)]*?([A-Za-z_]\w*)\s*\)\s*([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\(/);
82
+ if (methodMatch) {
83
+ const endLine = findBraceBlockEndLine(lines, i, 400);
84
+ const recv = methodMatch[1];
85
+ const fnName = methodMatch[2];
86
+ symbols.push({
87
+ name: `${recv}.${fnName}`,
88
+ shortName: fnName,
89
+ kind: "method",
90
+ exported: /^[A-Z]/.test(fnName),
91
+ startLine: i + 1,
92
+ sigEndLine: i + 1,
93
+ endLine,
94
+ });
95
+ continue;
96
+ }
97
+
98
+ const fnMatch = line.match(/^func\s+([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s*\(/);
99
+ if (fnMatch) {
100
+ const endLine = findBraceBlockEndLine(lines, i, 400);
101
+ const fnName = fnMatch[1];
102
+ symbols.push({
103
+ name: fnName,
104
+ shortName: fnName,
105
+ kind: "func",
106
+ exported: /^[A-Z]/.test(fnName),
107
+ startLine: i + 1,
108
+ sigEndLine: i + 1,
109
+ endLine,
110
+ });
111
+ continue;
112
+ }
113
+
114
+ const typeMatch = line.match(/^type\s+([A-Za-z_]\w*)\s+(?:\[[^\]]*\]\s*)?(struct|interface|\S+)/);
115
+ if (typeMatch) {
116
+ const endLine = findBraceBlockEndLine(lines, i, 250);
117
+ const typeName = typeMatch[1];
118
+ const kind = typeMatch[2] === "struct" || typeMatch[2] === "interface" ? typeMatch[2] : "type";
119
+ symbols.push({
120
+ name: typeName,
121
+ shortName: typeName,
122
+ kind,
123
+ exported: /^[A-Z]/.test(typeName),
124
+ startLine: i + 1,
125
+ sigEndLine: i + 1,
126
+ endLine,
127
+ });
128
+ }
129
+ }
130
+
131
+ return {
132
+ lang: "go",
133
+ pkgDir: path.posix.dirname(relPath),
134
+ imports: dedupeImports(imports),
135
+ symbols,
136
+ };
137
+ }
@@ -0,0 +1,181 @@
1
+ import path from "node:path";
2
+ import { dedupeImports, stripCommentsKeepLines } from "./common.mjs";
3
+
4
+ function findPythonBlockEndLine(lines, startIdx) {
5
+ const baseIndent = lines[startIdx].match(/^(\s*)/)[1].length;
6
+ let lastBodyLine = startIdx + 1;
7
+ for (let i = startIdx + 1; i < lines.length; i++) {
8
+ const raw = lines[i];
9
+ if (!raw.trim()) continue;
10
+ const indent = raw.match(/^(\s*)/)[1].length;
11
+ if (indent <= baseIndent) break;
12
+ lastBodyLine = i + 1;
13
+ }
14
+ return lastBodyLine;
15
+ }
16
+
17
+ function findHeaderEndLine(lines, startIdx) {
18
+ let parens = 0;
19
+ for (let i = startIdx; i < Math.min(lines.length, startIdx + 12); i++) {
20
+ const line = lines[i];
21
+ for (let c = 0; c < line.length; c++) {
22
+ if (line[c] === "(" || line[c] === "[") parens++;
23
+ else if (line[c] === ")" || line[c] === "]") parens = Math.max(0, parens - 1);
24
+ else if (line[c] === ":" && parens === 0) return i + 1;
25
+ }
26
+ }
27
+ return startIdx + 1;
28
+ }
29
+
30
+ /**
31
+ * Resolve a Python module path (absolute or relative) to repo file path(s).
32
+ */
33
+ function resolvePythonModule(fromFile, dotCount, modName, importedNames, fileSet) {
34
+ const targets = [];
35
+ const tryModulePath = (basePath) => {
36
+ const norm = basePath.replace(/^\/+/, "");
37
+ if (!norm) return null;
38
+ if (fileSet.has(`${norm}.py`)) return `${norm}.py`;
39
+ if (fileSet.has(`${norm}/__init__.py`)) return `${norm}/__init__.py`;
40
+ return null;
41
+ };
42
+
43
+ let baseDirs = [];
44
+ if (dotCount > 0) {
45
+ let dir = path.posix.dirname(fromFile);
46
+ if (dir === ".") dir = "";
47
+ for (let i = 1; i < dotCount; i++) {
48
+ dir = dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
49
+ }
50
+ baseDirs = [dir];
51
+ } else {
52
+ // Support standard root layout and src/ layout (and monorepo package root)
53
+ baseDirs = ["", "src"];
54
+ const parts = fromFile.split("/");
55
+ if (parts.length >= 3) baseDirs.push(parts[0]);
56
+ }
57
+
58
+ const modSlashes = modName ? modName.replace(/\./g, "/") : "";
59
+
60
+ for (const root of baseDirs) {
61
+ const prefix = root ? `${root}/` : "";
62
+ if (modSlashes) {
63
+ const direct = tryModulePath(`${prefix}${modSlashes}`);
64
+ if (direct) {
65
+ targets.push({ target: direct, symbols: importedNames });
66
+ // Also resolve submodule imports like `from pkg import submod`
67
+ if (direct.endsWith("/__init__.py")) {
68
+ for (const sym of importedNames) {
69
+ const sub = tryModulePath(`${prefix}${modSlashes}/${sym}`);
70
+ if (sub) targets.push({ target: sub, symbols: [] });
71
+ }
72
+ }
73
+ return targets;
74
+ }
75
+ } else if (dotCount > 0) {
76
+ // `from . import foo, bar`
77
+ for (const sym of importedNames) {
78
+ const sub = tryModulePath(`${prefix}${sym}`);
79
+ if (sub) targets.push({ target: sub, symbols: [] });
80
+ }
81
+ const initFile = tryModulePath(root);
82
+ if (initFile && targets.length === 0) {
83
+ targets.push({ target: initFile, symbols: importedNames });
84
+ }
85
+ if (targets.length > 0) return targets;
86
+ }
87
+ }
88
+ return targets;
89
+ }
90
+
91
+ export function parsePythonFile(relPath, content, fileSet) {
92
+ const clean = stripCommentsKeepLines(content, "python");
93
+ const lines = clean.split("\n");
94
+ const imports = [];
95
+ const symbols = [];
96
+
97
+ // `from ... import ...` (single-line or parenthesized multi-line)
98
+ const fromRe = /(?:^|\n)[ \t]*from\s+(\.*)(\w+(?:\.\w+)*)?\s+import\s+(?:\(([\s\S]*?)\)|([^\n;]+))/g;
99
+ for (const m of clean.matchAll(fromRe)) {
100
+ const dotCount = (m[1] || "").length;
101
+ const modName = m[2] || "";
102
+ const rawList = (m[3] || m[4] || "").replace(/\\\n/g, " ");
103
+ const names = rawList
104
+ .split(",")
105
+ .map((s) => s.trim().split(/\s+as\s+/)[0]?.trim())
106
+ .filter((s) => s && s !== "*" && /^[A-Za-z_]\w*$/.test(s));
107
+ for (const resolved of resolvePythonModule(relPath, dotCount, modName, names, fileSet)) {
108
+ if (resolved.target !== relPath) {
109
+ imports.push({ target: resolved.target, symbols: resolved.symbols, kind: "import" });
110
+ }
111
+ }
112
+ }
113
+
114
+ // `import a.b, c as d`
115
+ const impRe = /(?:^|\n)[ \t]*import\s+([^\n;]+)/g;
116
+ for (const m of clean.matchAll(impRe)) {
117
+ for (const part of m[1].split(",")) {
118
+ const modName = part.trim().split(/\s+as\s+/)[0]?.trim();
119
+ if (!modName || !/^[A-Za-z_][\w.]*$/.test(modName)) continue;
120
+ for (const resolved of resolvePythonModule(relPath, 0, modName, [], fileSet)) {
121
+ if (resolved.target !== relPath) {
122
+ imports.push({ target: resolved.target, symbols: [], kind: "import" });
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ // Top-level classes, functions, and class methods
129
+ let currentClass = null;
130
+ let classEndLine = 0;
131
+
132
+ for (let i = 0; i < lines.length; i++) {
133
+ const line = lines[i];
134
+ if (i + 1 > classEndLine) currentClass = null;
135
+
136
+ const clsMatch = line.match(/^class\s+([A-Za-z_]\w*)/);
137
+ if (clsMatch) {
138
+ const endLine = findPythonBlockEndLine(lines, i);
139
+ const sigEnd = findHeaderEndLine(lines, i);
140
+ currentClass = clsMatch[1];
141
+ classEndLine = endLine;
142
+ symbols.push({
143
+ name: clsMatch[1],
144
+ shortName: clsMatch[1],
145
+ kind: "class",
146
+ exported: !clsMatch[1].startsWith("_"),
147
+ startLine: i + 1,
148
+ sigEndLine: sigEnd,
149
+ endLine,
150
+ });
151
+ continue;
152
+ }
153
+
154
+ const fnMatch = line.match(/^([ \t]*)(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/);
155
+ if (fnMatch) {
156
+ const indent = fnMatch[1].length;
157
+ const fnName = fnMatch[2];
158
+ // Track top-level functions and direct methods inside top-level classes
159
+ if (indent === 0 || (currentClass && indent > 0 && indent <= 4)) {
160
+ const endLine = findPythonBlockEndLine(lines, i);
161
+ const sigEnd = findHeaderEndLine(lines, i);
162
+ const isMethod = indent > 0 && Boolean(currentClass);
163
+ symbols.push({
164
+ name: isMethod ? `${currentClass}.${fnName}` : fnName,
165
+ shortName: fnName,
166
+ kind: isMethod ? "method" : "def",
167
+ exported: !fnName.startsWith("_"),
168
+ startLine: i + 1,
169
+ sigEndLine: sigEnd,
170
+ endLine,
171
+ });
172
+ }
173
+ }
174
+ }
175
+
176
+ return {
177
+ lang: "python",
178
+ imports: dedupeImports(imports),
179
+ symbols,
180
+ };
181
+ }