@kousaku-maron/diffshape 0.2.0 → 0.4.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.
package/README.md CHANGED
@@ -1,11 +1,12 @@
1
1
  # diffshape
2
2
 
3
- git の差分の「形」を、push 前のローカルレビューで確かめるためのアプリです。差分を2つの見方で、ブラウザに並べて見せます。
3
+ git の差分の「形」を、push 前のローカルレビューで確かめるためのアプリです。差分を3つの見方で、ブラウザに並べて見せます。
4
4
 
5
+ - **ファイル**([fileshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/fileshape)): 変更された各ファイルの行の差分を、GitHub の Files changed と同じ形で見せます
5
6
  - **依存**([depshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/depshape)): フォルダ・ファイル間の依存関係がどう変わったかを、既存の構造と並べて見せます(Go / TypeScript / JavaScript)
6
7
  - **DB**([dbshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/dbshape)): PostgreSQL のスキーマ(テーブル・カラム・制約・外部キー・CHECK の値)がどう変わったかを、ER 図の差分で見せます
7
8
 
8
- どちらも git から直接ファイルを読みます。ビルドツールのインストール、DB への接続、外部サービスは要りません。事実だけを見せ、判断はレビューする人が行います。
9
+ どれも git から直接ファイルを読みます。ビルドツールのインストール、DB への接続、外部サービスは要りません。事実だけを見せ、判断はレビューする人が行います。
9
10
 
10
11
  ## 使い方
11
12
 
@@ -15,15 +16,16 @@ git の差分の「形」を、push 前のローカルレビューで確かめ
15
16
  npx @kousaku-maron/diffshape . main --merge-base
16
17
  ```
17
18
 
18
- よく使うなら `npm install -g @kousaku-maron/diffshape` で入れておくと、次の3つのコマンドが使えます。
19
+ よく使うなら `npm install -g @kousaku-maron/diffshape` で入れておくと、次の4つのコマンドが使えます。
19
20
 
20
21
  | コマンド | 開くもの |
21
22
  |---|---|
22
- | `diffshape` | 依存と DB の両方(左のアイコンバーで切り替え) |
23
+ | `diffshape` | ファイル・依存・DB のすべて(左のアイコンバーで切り替え) |
24
+ | `fileshape` | ファイルだけ(`--json` で差分を標準出力へ) |
23
25
  | `depshape` | 依存だけ(`--json` で解析結果を標準出力へ) |
24
26
  | `dbshape` | DB だけ(`--text` で要約、`--json` で差分を標準出力へ) |
25
27
 
26
- 比較の指定は3つとも同じです。
28
+ 比較の指定はどれも同じです。
27
29
 
28
30
  | 例 | 比較内容 |
29
31
  |---|---|
@@ -33,19 +35,19 @@ npx @kousaku-maron/diffshape . main --merge-base
33
35
  | `diffshape abc1234` | そのコミット単体の変更 |
34
36
  | `diffshape staged` / `diffshape working` | ステージ済み / 未ステージの変更のみ |
35
37
 
36
- オプション: `--merge-base`、`--schema <glob>`(スキーマの SQL ファイル。省略時はリポジトリ内のすべての `atlas.hcl` の `src` を読みます。DB が複数あるときは `--schema billing=services/billing/**/*.sql` のように名前を付けます)、`--only <dep|db>`、`--port <n>`(デフォルト 4977、使用中なら +1)、`--host`、`--no-open`
38
+ オプション: `--merge-base`、`--schema <glob>`(スキーマの SQL ファイル。省略時はリポジトリ内のすべての `atlas.hcl` の `src` を読みます。DB が複数あるときは `--schema billing=services/billing/**/*.sql` のように名前を付けます)、`--only <file|dep|db>`、`--port <n>`(デフォルト 4977、使用中なら +1)、`--host`、`--no-open`
37
39
 
38
40
  サーバーはデフォルトで `127.0.0.1` だけで待ち受け、`localhost` / `127.0.0.1` 宛て以外のリクエストは拒否します。`--host 0.0.0.0` などを指定すると、同じネットワークの他の端末からリポジトリの構成とスキーマが見えるので注意してください。
39
41
 
40
42
  ## 画面
41
43
 
42
- - **左のアイコンバー**: 「依存」と「DB」を切り替えます。アイコンの数字は変更の件数、青い点は未対応のコメントがあることを示します。読むものがないモジュール(SQL ファイルがないリポジトリの DB など)は薄く表示します。表示中のモジュールは URL(`#dep` / `#db`)に残るので、再読み込みしても同じ画面が開きます
44
+ - **左のアイコンバー**: 「ファイル」「依存」「DB」を切り替えます。アイコンの数字は変更の件数、青い点は未対応のコメントがあることを示します。読むものがないモジュール(SQL ファイルがないリポジトリの DB など)は薄く表示します。表示中のモジュールは URL(`#file` / `#dep` / `#db`)に残るので、再読み込みしても同じ画面が開きます
43
45
  - **ヘッダー**: 比較の対象、「AI 用にコピー」、「再読み込み」。切り替えても、各モジュールで開いていた箱・選んだテーブル・書きかけのコメントはそのまま残ります
44
- - **AI 用にコピー**: 両方のモジュールの未対応のコメントを、1つのプロンプトにまとめてコピーします(依存は import の状態と既存の依存のパターン、DB は SQL ファイルの定義位置つき)。Claude Code / Codex などにそのまま貼れます
45
- - **再読み込み**: AI がファイルを書き換えたあとに、両方を解析し直します。開いていた状態はそのまま残ります
46
+ - **AI 用にコピー**: すべてのモジュールの未対応のコメントを、1つのプロンプトにまとめてコピーします(ファイルは `path:L12` とその行のコード、依存は import の状態と既存の依存のパターン、DB は SQL ファイルの定義位置つき)。Claude Code / Codex などにそのまま貼れます
47
+ - **再読み込み**: AI がファイルを書き換えたあとに、すべてを解析し直します。開いていた状態はそのまま残ります
46
48
  - **DB が複数ある monorepo**: DB モジュールの中で DB を切り替えます(`atlas.hcl` ごと、または名前付きの `--schema` ごと)
47
49
 
48
- それぞれの画面の見方は、[depshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/depshape) と [dbshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/dbshape) の README を見てください。
50
+ それぞれの画面の見方は、[fileshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/fileshape)、[depshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/depshape)、[dbshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/dbshape) の README を見てください。
49
51
 
50
52
  ## ライセンス
51
53
 
@@ -55,3 +57,5 @@ MIT([LICENSE](LICENSE))。次のものを同梱・利用しています。
55
57
  - [dagre](https://github.com/dagrejs/dagre)(MIT): ER 図の配置
56
58
  - [libpg-query](https://github.com/constructive-io/libpg-query-node)(MIT): SQL の解析
57
59
  - [Feather](https://github.com/feathericons/feather)(MIT): アイコンの線画
60
+ - [Prism](https://prismjs.com/)(MIT): ファイルの差分のシンタックスハイライト
61
+ - [react-markdown](https://github.com/remarkjs/react-markdown) / [remark-gfm](https://github.com/remarkjs/remark-gfm)(MIT): Markdown のプレビュー
@@ -1,6 +1,6 @@
1
1
  // ../core/src/git.ts
2
2
  import { execFile, spawn } from "node:child_process";
3
- import { readFile } from "node:fs/promises";
3
+ import { readFile, stat } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  var execFileAsync = promisify(execFile);
@@ -61,6 +61,42 @@ async function readFiles(root, source, paths) {
61
61
  });
62
62
  return result;
63
63
  }
64
+ async function diffPatch(root, base, target) {
65
+ const args = ["-c", "core.quotePath=false", "diff", "--no-ext-diff", "--no-color", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative"];
66
+ if (target.kind === "worktree" && base.kind === "index") return git(root, [...args, "--"]);
67
+ if (base.kind !== "rev") throw new Error("\u6BD4\u8F03\u5143\u306F\u30B3\u30DF\u30C3\u30C8\u304B\u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u72B6\u614B\u3067\u3059");
68
+ if (target.kind === "rev") return git(root, [...args, base.rev, target.rev, "--"]);
69
+ if (target.kind === "index") return git(root, [...args, "--cached", base.rev, "--"]);
70
+ return git(root, [...args, base.rev, "--"]);
71
+ }
72
+ async function untrackedFiles(root) {
73
+ const out = await git(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
74
+ const paths = out.split("\0").filter((p) => p && !p.endsWith("/"));
75
+ const files = await Promise.all(
76
+ paths.map(async (path) => {
77
+ try {
78
+ const s = await stat(join(root, path));
79
+ return s.isFile() ? { path, size: s.size } : null;
80
+ } catch {
81
+ return null;
82
+ }
83
+ })
84
+ );
85
+ return files.filter((f) => f !== null);
86
+ }
87
+ async function readBlob(root, source, path) {
88
+ if (source.kind === "worktree") {
89
+ try {
90
+ return await readFile(join(root, path));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ const spec = `${source.kind === "rev" ? source.rev : ""}:${path}`;
96
+ return new Promise((resolve) => {
97
+ execFile("git", ["cat-file", "blob", spec], { cwd: root, encoding: "buffer", maxBuffer: 512 * 1024 * 1024 }, (err, stdout) => resolve(err ? null : stdout));
98
+ });
99
+ }
64
100
  function catFileBatch(root, specs) {
65
101
  return new Promise((resolve, reject) => {
66
102
  const proc = spawn("git", ["cat-file", "--batch"], { cwd: root });
@@ -142,6 +178,22 @@ import { spawn as spawn2 } from "node:child_process";
142
178
  import { readFile as readFile2 } from "node:fs/promises";
143
179
  import { createServer } from "node:http";
144
180
  import { extname, join as join2, normalize } from "node:path";
181
+
182
+ // ../core/src/module.ts
183
+ var RawBody = class {
184
+ constructor(body, type) {
185
+ this.body = body;
186
+ this.type = type;
187
+ }
188
+ };
189
+ var HttpError = class extends Error {
190
+ constructor(status, message2) {
191
+ super(message2);
192
+ this.status = status;
193
+ }
194
+ };
195
+
196
+ // ../core/src/server.ts
145
197
  var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
146
198
  function hostAllowed(listenHost, hostHeader) {
147
199
  if (!LOOPBACK.has(listenHost)) return true;
@@ -170,6 +222,11 @@ async function startServer(opts) {
170
222
  const handler = opts.api[url.pathname];
171
223
  if (handler) {
172
224
  const body2 = await handler(url);
225
+ if (body2 instanceof RawBody) {
226
+ res.writeHead(200, { "content-type": body2.type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox" });
227
+ res.end(body2.body);
228
+ return;
229
+ }
173
230
  res.writeHead(200, { "content-type": MIME[".json"], "cache-control": "no-store" });
174
231
  res.end(JSON.stringify(body2));
175
232
  return;
@@ -188,7 +245,7 @@ async function startServer(opts) {
188
245
  res.writeHead(200, { "content-type": MIME[extname(rel)] ?? "application/octet-stream", ...cache });
189
246
  res.end(body);
190
247
  } catch (e) {
191
- res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
248
+ res.writeHead(e instanceof HttpError ? e.status : 500, { "content-type": "text/plain; charset=utf-8" });
192
249
  res.end(e instanceof Error ? e.message : String(e));
193
250
  }
194
251
  });
@@ -2105,6 +2162,306 @@ async function analyzeSources2({ root, target, base, targetLabel, baseLabel }) {
2105
2162
  // ../depshape/src/index.ts
2106
2163
  var depAnalyzer = { id: "dep", analyze: analyzeSources2 };
2107
2164
 
2165
+ // ../fileshape/src/diff.ts
2166
+ function parseUnifiedDiff(text) {
2167
+ const files = [];
2168
+ for (const block of text.split(/^diff --git /m).slice(1)) {
2169
+ const file = parseFileBlock(`diff --git ${block}`);
2170
+ if (file) files.push(file);
2171
+ }
2172
+ return files;
2173
+ }
2174
+ function parseFileBlock(block) {
2175
+ const lines = block.split("\n");
2176
+ const firstHunk = lines.findIndex((l) => l.startsWith("@@"));
2177
+ const head = firstHunk === -1 ? lines : lines.slice(0, firstHunk);
2178
+ const find = (prefix) => head.find((l) => l.startsWith(prefix));
2179
+ const minus = find("--- ");
2180
+ const plus = find("+++ ");
2181
+ const fromHeader = parseHeaderPaths(lines[0]);
2182
+ const newPath = pathAfter(find("rename to "), "rename to ", false) ?? pathAfter(plus, "+++ ") ?? fromHeader?.newPath;
2183
+ const oldPath = pathAfter(find("rename from "), "rename from ", false) ?? pathAfter(minus, "--- ") ?? fromHeader?.oldPath;
2184
+ const path = newPath ?? oldPath;
2185
+ if (!path) return null;
2186
+ let status = "modified";
2187
+ if (find("new file mode") || minus === "--- /dev/null") status = "added";
2188
+ else if (find("deleted file mode") || plus === "+++ /dev/null") status = "removed";
2189
+ else if (oldPath && oldPath !== path) status = "renamed";
2190
+ const chunks = firstHunk === -1 ? [] : parseChunks(lines.slice(firstHunk));
2191
+ let additions = 0;
2192
+ let deletions = 0;
2193
+ for (const c of chunks)
2194
+ for (const l of c.lines) {
2195
+ if (l.type === "add") additions++;
2196
+ else if (l.type === "delete") deletions++;
2197
+ }
2198
+ const file = { path, status, additions, deletions, chunks };
2199
+ if (status === "renamed") file.oldPath = oldPath;
2200
+ if (head.some((l) => l.startsWith("Binary files ") || l === "GIT binary patch")) file.binary = true;
2201
+ const oldMode = find("old mode ")?.slice(9);
2202
+ const newMode = find("new mode ")?.slice(9);
2203
+ if (oldMode && newMode) file.modeChange = `${oldMode} \u2192 ${newMode}`;
2204
+ return file;
2205
+ }
2206
+ var HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/;
2207
+ function parseChunks(lines) {
2208
+ const chunks = [];
2209
+ let chunk = null;
2210
+ let oldLine = 0;
2211
+ let newLine = 0;
2212
+ for (const raw of lines) {
2213
+ if (raw.startsWith("@@")) {
2214
+ const m = raw.match(HUNK);
2215
+ if (!m) continue;
2216
+ oldLine = Number(m[1]);
2217
+ newLine = Number(m[3]);
2218
+ chunk = { section: m[5].trim(), oldStart: oldLine, oldLines: Number(m[2] ?? "1"), newStart: newLine, newLines: Number(m[4] ?? "1"), lines: [] };
2219
+ chunks.push(chunk);
2220
+ continue;
2221
+ }
2222
+ if (!chunk) continue;
2223
+ const sign = raw[0];
2224
+ if (sign !== "+" && sign !== "-" && sign !== " ") continue;
2225
+ const content = raw.slice(1).replace(/\r$/, "");
2226
+ let line;
2227
+ if (sign === "+") line = { type: "add", content, newLine: newLine++ };
2228
+ else if (sign === "-") line = { type: "delete", content, oldLine: oldLine++ };
2229
+ else line = { type: "normal", content, oldLine: oldLine++, newLine: newLine++ };
2230
+ chunk.lines.push(line);
2231
+ }
2232
+ return chunks;
2233
+ }
2234
+ function addedFile(path, content) {
2235
+ if (content.includes("\0")) return { path, status: "added", additions: 0, deletions: 0, chunks: [], binary: true };
2236
+ const lines = content.split("\n");
2237
+ if (lines[lines.length - 1] === "") lines.pop();
2238
+ const chunks = lines.length ? [{ section: "", oldStart: 0, oldLines: 0, newStart: 1, newLines: lines.length, lines: lines.map((l, i) => ({ type: "add", content: l.replace(/\r$/, ""), newLine: i + 1 })) }] : [];
2239
+ return { path, status: "added", additions: lines.length, deletions: 0, chunks };
2240
+ }
2241
+ function pathAfter(line, prefix, stripPrefix = true) {
2242
+ return line?.startsWith(prefix) ? decodeGitPath(line.slice(prefix.length), stripPrefix) : void 0;
2243
+ }
2244
+ function parseHeaderPaths(header) {
2245
+ const raw = header.slice("diff --git ".length);
2246
+ const parts = [];
2247
+ let cur = "";
2248
+ let quoted = false;
2249
+ for (let i = 0; i < raw.length; i++) {
2250
+ const ch = raw[i];
2251
+ if (ch === '"' && raw[i - 1] !== "\\") quoted = !quoted;
2252
+ if (ch === " " && !quoted) {
2253
+ if (cur) parts.push(cur);
2254
+ cur = "";
2255
+ continue;
2256
+ }
2257
+ cur += ch;
2258
+ }
2259
+ if (cur) parts.push(cur);
2260
+ if (parts.length !== 2) {
2261
+ const m = raw.match(/^a\/(.+) b\/\1$/);
2262
+ return m ? { oldPath: m[1], newPath: m[1] } : null;
2263
+ }
2264
+ return { oldPath: decodeGitPath(parts[0]), newPath: decodeGitPath(parts[1]) };
2265
+ }
2266
+ var ESCAPES = { t: 9, n: 10, r: 13, b: 8, f: 12, v: 11, a: 7, "\\": 92, '"': 34 };
2267
+ function decodeGitPath(raw, stripPrefix = true) {
2268
+ const tab = raw.indexOf(" ");
2269
+ let s = tab === -1 ? raw : raw.slice(0, tab);
2270
+ const quoted = s.startsWith('"') && s.endsWith('"') && s.length >= 2;
2271
+ if (quoted) s = s.slice(1, -1);
2272
+ if (stripPrefix && (s.startsWith("a/") || s.startsWith("b/"))) s = s.slice(2);
2273
+ if (s === "/dev/null" || s === "dev/null") return void 0;
2274
+ if (!quoted) return s;
2275
+ const bytes = [];
2276
+ for (let i = 0; i < s.length; i++) {
2277
+ const ch = s[i];
2278
+ if (ch === "\\" && i + 1 < s.length) {
2279
+ const oct = s.slice(i + 1).match(/^[0-7]{1,3}/);
2280
+ if (oct) {
2281
+ bytes.push(parseInt(oct[0], 8));
2282
+ i += oct[0].length;
2283
+ continue;
2284
+ }
2285
+ const next = s[i + 1];
2286
+ if (next in ESCAPES) bytes.push(ESCAPES[next]);
2287
+ else bytes.push(...Buffer.from(next, "utf8"));
2288
+ i++;
2289
+ continue;
2290
+ }
2291
+ bytes.push(...Buffer.from(ch, "utf8"));
2292
+ }
2293
+ return Buffer.from(bytes).toString("utf8");
2294
+ }
2295
+
2296
+ // ../fileshape/src/generated.ts
2297
+ var EXACT_FILENAMES = /* @__PURE__ */ new Set([
2298
+ "package-lock.json",
2299
+ "pnpm-lock.yaml",
2300
+ "yarn.lock",
2301
+ "Gemfile.lock",
2302
+ "Pipfile.lock",
2303
+ "composer.lock",
2304
+ "Cargo.lock",
2305
+ "poetry.lock",
2306
+ "go.sum",
2307
+ "pubspec.lock",
2308
+ "flake.lock",
2309
+ "Package.resolved",
2310
+ "packages.lock.json",
2311
+ ".terraform.lock.hcl",
2312
+ "bun.lockb",
2313
+ "bun.lock",
2314
+ "gradle.lockfile",
2315
+ "uv.lock",
2316
+ "pdm.lock"
2317
+ ]);
2318
+ var FILENAME_SUFFIXES = [
2319
+ ".min.js",
2320
+ ".min.css",
2321
+ ".bundle.js",
2322
+ ".bundle.css",
2323
+ "-min.js",
2324
+ ".map",
2325
+ ".pb.go",
2326
+ ".pb.rb",
2327
+ ".pb.py",
2328
+ ".pb.js",
2329
+ ".pb.cc",
2330
+ ".pb.h",
2331
+ "_pb2.py",
2332
+ ".pb2.py",
2333
+ ".grpc.pb.go",
2334
+ "_string.go",
2335
+ ".graphql.ts",
2336
+ ".graphql.js",
2337
+ ".g.dart",
2338
+ ".freezed.dart",
2339
+ ".g.cs",
2340
+ ".designer.cs"
2341
+ ];
2342
+ var ROOT_PREFIXES = ["vendor/", "node_modules/", "dist/", "build/", "out/"];
2343
+ var PATH_SEGMENTS = ["/generated/", "/gen/", "/__generated__/"];
2344
+ var GENERATED_EXT = /\.(generated|gen)\.\w+$/;
2345
+ var HEADER_PATTERNS = [
2346
+ /@generated\b/,
2347
+ /\bDO NOT EDIT\b/i,
2348
+ /\bDO NOT MODIFY\b/i,
2349
+ /\bAUTO[- ]?GENERATED\b/i,
2350
+ /\bTHIS FILE IS GENERATED\b/i,
2351
+ /\bGENERATED CODE\b/i,
2352
+ /\bMACHINE GENERATED\b/i,
2353
+ /This file was generated/i,
2354
+ /This is a generated file/i,
2355
+ /<auto-generated\s*\/?>/i,
2356
+ /^\/\/ Code generated .* DO NOT EDIT\.$/m
2357
+ ];
2358
+ function generatedByPath(path) {
2359
+ const name = path.split("/").pop() ?? "";
2360
+ return EXACT_FILENAMES.has(name) || FILENAME_SUFFIXES.some((s) => name.endsWith(s)) || GENERATED_EXT.test(name) || name.startsWith("mock_") && name.endsWith(".go") || (path.startsWith("mocks/") || path.includes("/mocks/")) && name.endsWith(".go") || ROOT_PREFIXES.some((p) => path.startsWith(p)) || PATH_SEGMENTS.some((s) => path.includes(s));
2361
+ }
2362
+ function headerLines(file) {
2363
+ const first = file.chunks[0];
2364
+ if (!first || first.newStart > 1 || file.status === "removed") return [];
2365
+ return first.lines.filter((l) => l.type !== "delete").slice(0, 20).map((l) => l.content);
2366
+ }
2367
+ function isGenerated(file) {
2368
+ if (generatedByPath(file.path)) return true;
2369
+ if (/\.(md|markdown|mdx)$/i.test(file.path)) return false;
2370
+ const header = headerLines(file).join("\n");
2371
+ return header !== "" && HEADER_PATTERNS.some((p) => p.test(header));
2372
+ }
2373
+
2374
+ // ../fileshape/src/analyze.ts
2375
+ var MAX_UNTRACKED = 2 * 1024 * 1024;
2376
+ async function analyzeFiles(sources) {
2377
+ const { root, base, target } = sources;
2378
+ const files = parseUnifiedDiff(await diffPatch(root, base, target));
2379
+ if (target.kind === "worktree") files.push(...await untracked(root, target));
2380
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2381
+ const attr = await linguistGenerated(root, target, files.map((f) => f.path));
2382
+ for (const f of files) if (attr.has(f.path) || isGenerated(f)) f.generated = true;
2383
+ return { repoRoot: root, targetLabel: sources.targetLabel, baseLabel: sources.baseLabel, files };
2384
+ }
2385
+ async function untracked(root, worktree) {
2386
+ const list = await untrackedFiles(root);
2387
+ const small = list.filter((f) => f.size <= MAX_UNTRACKED).map((f) => f.path);
2388
+ const contents = await readFiles(root, worktree, small);
2389
+ return list.flatMap((f) => {
2390
+ if (f.size > MAX_UNTRACKED) return [{ path: f.path, status: "added", additions: 0, deletions: 0, chunks: [], large: true }];
2391
+ const c = contents.get(f.path);
2392
+ return c === void 0 ? [] : [addedFile(f.path, c)];
2393
+ });
2394
+ }
2395
+ async function linguistGenerated(root, target, paths) {
2396
+ const found = /* @__PURE__ */ new Set();
2397
+ const from = target.kind === "rev" ? ["--source", target.rev] : target.kind === "index" ? ["--cached"] : [];
2398
+ try {
2399
+ for (let i = 0; i < paths.length; i += 200) {
2400
+ const out = await git(root, ["check-attr", "-z", ...from, "linguist-generated", "--", ...paths.slice(i, i + 200)]);
2401
+ const f = out.split("\0");
2402
+ for (let j = 0; j + 2 < f.length; j += 3) if (f[j + 2] === "true" || f[j + 2] === "set") found.add(f[j]);
2403
+ }
2404
+ } catch {
2405
+ }
2406
+ return found;
2407
+ }
2408
+
2409
+ // ../fileshape/src/api.ts
2410
+ var IMAGE_TYPES = {
2411
+ png: "image/png",
2412
+ jpg: "image/jpeg",
2413
+ jpeg: "image/jpeg",
2414
+ gif: "image/gif",
2415
+ webp: "image/webp",
2416
+ avif: "image/avif",
2417
+ bmp: "image/bmp",
2418
+ ico: "image/x-icon",
2419
+ svg: "image/svg+xml"
2420
+ };
2421
+ var imageType = (path) => IMAGE_TYPES[path.split(".").pop()?.toLowerCase() ?? ""];
2422
+ function safePath(raw) {
2423
+ const p = (raw ?? "").replace(/\\/g, "/");
2424
+ if (!p || p.startsWith("/") || /^[a-zA-Z]:/.test(p) || p.split("/").some((s) => s === ".." || s === "")) throw new HttpError(400, "bad path");
2425
+ return p;
2426
+ }
2427
+ var sideOf = (url) => {
2428
+ const s = url.searchParams.get("side");
2429
+ if (s !== "old" && s !== "new") throw new HttpError(400, "side must be old or new");
2430
+ return s;
2431
+ };
2432
+ function diffPath(data, path, side) {
2433
+ const f = data.files.find((x) => x.path === path);
2434
+ if (!f) throw new HttpError(404, `not in the diff: ${path}`);
2435
+ if (side === "old" && f.status === "added" || side === "new" && f.status === "removed") throw new HttpError(404, `${path} is not on the ${side} side`);
2436
+ return side === "old" ? f.oldPath ?? f.path : f.path;
2437
+ }
2438
+ var fileApi = {
2439
+ /** `?path=&side=` → { lines } of a file of the diff */
2440
+ async content(url, { sources, data }) {
2441
+ const side = sideOf(url);
2442
+ const path = diffPath(data, safePath(url.searchParams.get("path")), side);
2443
+ const blob = await readBlob(sources.root, side === "old" ? sources.base : sources.target, path);
2444
+ if (!blob) throw new HttpError(404, `not found: ${path}`);
2445
+ const text = blob.toString("utf8");
2446
+ const lines = text.split("\n").map((l) => l.replace(/\r$/, ""));
2447
+ if (lines[lines.length - 1] === "") lines.pop();
2448
+ return { lines };
2449
+ },
2450
+ /** `?path=&side=` → the bytes of an image in the repository */
2451
+ async raw(url, { sources }) {
2452
+ const side = sideOf(url);
2453
+ const path = safePath(url.searchParams.get("path"));
2454
+ const type = imageType(path);
2455
+ if (!type) throw new HttpError(400, "only images");
2456
+ const blob = await readBlob(sources.root, side === "old" ? sources.base : sources.target, path);
2457
+ if (!blob) throw new HttpError(404, `not found: ${path}`);
2458
+ return new RawBody(blob, type);
2459
+ }
2460
+ };
2461
+
2462
+ // ../fileshape/src/index.ts
2463
+ var fileAnalyzer = { id: "file", analyze: analyzeFiles, api: fileApi };
2464
+
2108
2465
  // src/app.ts
2109
2466
  var message = (e) => (e instanceof Error ? e.stderr || e.message : String(e)).trim();
2110
2467
  var App = class {
@@ -2136,6 +2493,15 @@ var App = class {
2136
2493
  result(id) {
2137
2494
  return this.results.get(id) ?? Promise.resolve({ error: `unknown module: ${id}` });
2138
2495
  }
2496
+ /** One of a module's own endpoints, on the current comparison and the module's data */
2497
+ async call(id, name, url) {
2498
+ const a = this.analyzers.find((x) => x.id === id);
2499
+ const handler = a?.api?.[name];
2500
+ if (!handler) throw new HttpError(404, `unknown endpoint: ${id}/${name}`);
2501
+ const r = await this.result(id);
2502
+ if ("error" in r) throw new HttpError(409, r.error);
2503
+ return handler(url, { sources: this.sources, data: r.data });
2504
+ }
2139
2505
  };
2140
2506
 
2141
2507
  // src/server.ts
@@ -2145,11 +2511,15 @@ function startServer2(app, host, port) {
2145
2511
  const api = {
2146
2512
  "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info()
2147
2513
  };
2148
- for (const a of app.analyzers) api[`/api/module/${a.id}`] = () => app.result(a.id);
2514
+ for (const a of app.analyzers) {
2515
+ api[`/api/module/${a.id}`] = () => app.result(a.id);
2516
+ for (const name of Object.keys(a.api ?? {})) api[`/api/module/${a.id}/${name}`] = (url) => app.call(a.id, name, url);
2517
+ }
2149
2518
  return startServer({ uiDir: UI_DIR, host, port, api });
2150
2519
  }
2151
2520
 
2152
2521
  // src/cli.ts
2522
+ var COMMAND_MODULE = { diffshape: void 0, fileshape: "file", depshape: "dep", dbshape: "db" };
2153
2523
  var TARGETS = `target:
2154
2524
  . \u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\uFF08\u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4\u3059\u3079\u3066\uFF09 \u203B\u30C7\u30D5\u30A9\u30EB\u30C8
2155
2525
  staged \u30B9\u30C6\u30FC\u30B8\u6E08\u307F\u306E\u5909\u66F4
@@ -2166,7 +2536,7 @@ var COMMON = ` --merge-base compare-with \u3068 target \u306E\u5206\u5C90
2166
2536
  var SCHEMA = ` --schema <glob> \u30B9\u30AD\u30FC\u30DE\u306E SQL \u30D5\u30A1\u30A4\u30EB\uFF08\u8907\u6570\u6307\u5B9A\u53EF\uFF09\u3002\u7701\u7565\u6642\u306F\u30EA\u30DD\u30B8\u30C8\u30EA\u5185\u306E\u3059\u3079\u3066\u306E atlas.hcl \u306E src \u3092\u8AAD\u3080
2167
2537
  DB \u304C\u8907\u6570\u3042\u308B\u3068\u304D\u306F --schema billing=services/billing/**/*.sql \u306E\u3088\u3046\u306B\u540D\u524D\u3092\u4ED8\u3051\u308B`;
2168
2538
  var HELP = {
2169
- all: `diffshape - git \u306E\u5DEE\u5206\u3092\u3001\u30B3\u30FC\u30C9\u306E\u4F9D\u5B58\u95A2\u4FC2\uFF08depshape\uFF09\u3068 DB \u30B9\u30AD\u30FC\u30DE\uFF08dbshape\uFF09\u306E\u5F62\u3067\u898B\u305B\u307E\u3059
2539
+ all: `diffshape - git \u306E\u5DEE\u5206\u3092\u3001\u30D5\u30A1\u30A4\u30EB\u306E\u5DEE\u5206\uFF08fileshape\uFF09\u3001\u30B3\u30FC\u30C9\u306E\u4F9D\u5B58\u95A2\u4FC2\uFF08depshape\uFF09\u3001DB \u30B9\u30AD\u30FC\u30DE\uFF08dbshape\uFF09\u306E\u5F62\u3067\u898B\u305B\u307E\u3059
2170
2540
 
2171
2541
  \u4F7F\u3044\u65B9:
2172
2542
  diffshape [target] [compare-with] [options]
@@ -2176,13 +2546,27 @@ ${TARGETS}
2176
2546
  options:
2177
2547
  ${COMMON}
2178
2548
  ${SCHEMA}
2179
- --only <dep|db> \u7247\u65B9\u306E\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u8868\u793A\u3059\u308B\uFF08depshape / dbshape \u30B3\u30DE\u30F3\u30C9\u3068\u540C\u3058\uFF09
2549
+ --only <file|dep|db>
2550
+ 1\u3064\u306E\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u8868\u793A\u3059\u308B\uFF08fileshape / depshape / dbshape \u30B3\u30DE\u30F3\u30C9\u3068\u540C\u3058\uFF09
2180
2551
  -h, --help \u3053\u306E\u30D8\u30EB\u30D7\u3092\u8868\u793A
2181
2552
 
2182
2553
  \u4F8B:
2183
2554
  diffshape \u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4 vs HEAD
2184
2555
  diffshape . main --merge-base \u672A\u30B3\u30DF\u30C3\u30C8\u306E\u5909\u66F4\u3092\u542B\u3080\u73FE\u5728\u306E\u72B6\u614B vs main \u304B\u3089\u306E\u5206\u5C90\u70B9
2185
2556
  diffshape @ abc1234 HEAD vs \u7279\u5B9A\u306E\u30B3\u30DF\u30C3\u30C8
2557
+ `,
2558
+ file: `fileshape - git \u306E\u5DEE\u5206\u3092\u3001\u5909\u66F4\u3055\u308C\u305F\u5404\u30D5\u30A1\u30A4\u30EB\u306E\u884C\u306E\u5DEE\u5206\u3068\u3057\u3066\u898B\u305B\u307E\u3059\uFF08GitHub \u306E Files changed \u3068\u540C\u3058\u5F62\uFF09
2559
+ \uFF08diffshape \u306E\u30D5\u30A1\u30A4\u30EB\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u958B\u304D\u307E\u3059\uFF09
2560
+
2561
+ \u4F7F\u3044\u65B9:
2562
+ fileshape [target] [compare-with] [options]
2563
+
2564
+ ${TARGETS}
2565
+
2566
+ options:
2567
+ ${COMMON}
2568
+ --json \u30B5\u30FC\u30D0\u30FC\u3092\u8D77\u52D5\u305B\u305A\u3001\u5DEE\u5206\u3092 JSON \u3067\u6A19\u6E96\u51FA\u529B\u306B\u51FA\u3059
2569
+ -h, --help \u3053\u306E\u30D8\u30EB\u30D7\u3092\u8868\u793A
2186
2570
  `,
2187
2571
  dep: `depshape - git \u306E\u5DEE\u5206\u306B\u3088\u308B\u4F9D\u5B58\u95A2\u4FC2\u306E\u5909\u5316\u3092\u3001\u65E2\u5B58\u306E\u69CB\u9020\u3068\u4E26\u3079\u3066\u53EF\u8996\u5316\u3057\u307E\u3059\uFF08Go / TypeScript / JavaScript \u5BFE\u5FDC\uFF09
2188
2572
  \uFF08diffshape \u306E\u4F9D\u5B58\u30E2\u30B8\u30E5\u30FC\u30EB\u3060\u3051\u3092\u958B\u304D\u307E\u3059\uFF09
@@ -2215,7 +2599,7 @@ ${SCHEMA}
2215
2599
  `
2216
2600
  };
2217
2601
  function parseArgs(argv, command) {
2218
- const fixed = command === "depshape" ? "dep" : command === "dbshape" ? "db" : void 0;
2602
+ const fixed = COMMAND_MODULE[command];
2219
2603
  const fail = (msg) => {
2220
2604
  throw new UsageError(msg);
2221
2605
  };
@@ -2243,13 +2627,13 @@ function parseArgs(argv, command) {
2243
2627
  args.open = false;
2244
2628
  break;
2245
2629
  case "--schema":
2246
- allowed(a, fixed !== "dep");
2630
+ allowed(a, !fixed || fixed === "db");
2247
2631
  args.schema.push(argv[++i] ?? fail("--schema \u306B\u306F glob \u304C\u5FC5\u8981\u3067\u3059"));
2248
2632
  break;
2249
2633
  case "--only": {
2250
2634
  allowed(a, !fixed);
2251
2635
  const v = argv[++i];
2252
- if (v !== "dep" && v !== "db") fail("--only \u306B\u306F dep \u304B db \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
2636
+ if (v !== "file" && v !== "dep" && v !== "db") fail("--only \u306B\u306F file / dep / db \u306E\u3069\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
2253
2637
  args.only = v;
2254
2638
  break;
2255
2639
  }
@@ -2289,7 +2673,7 @@ async function run(command, argv) {
2289
2673
  } catch (e) {
2290
2674
  return fail(e.message);
2291
2675
  }
2292
- const all = [depAnalyzer, dbAnalyzer({ schema: args.schema })];
2676
+ const all = [fileAnalyzer, depAnalyzer, dbAnalyzer({ schema: args.schema })];
2293
2677
  const analyzers = args.only ? all.filter((a) => a.id === args.only) : all;
2294
2678
  const app = new App(process.cwd(), args, analyzers);
2295
2679
  try {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-OC4BEU5P.js";
4
+ } from "./chunk-EAWLY4IY.js";
5
5
 
6
6
  // src/bin/dbshape.ts
7
7
  void run("dbshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-OC4BEU5P.js";
4
+ } from "./chunk-EAWLY4IY.js";
5
5
 
6
6
  // src/bin/depshape.ts
7
7
  void run("depshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-OC4BEU5P.js";
4
+ } from "./chunk-EAWLY4IY.js";
5
5
 
6
6
  // src/bin/diffshape.ts
7
7
  void run("diffshape", process.argv.slice(2));
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ run
4
+ } from "./chunk-EAWLY4IY.js";
5
+
6
+ // src/bin/fileshape.ts
7
+ void run("fileshape", process.argv.slice(2));