tazuna 0.22.1 → 0.26.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 +7 -2
- package/dist/assets/protocol.js +9 -4
- package/dist/cli.js +8 -1
- package/dist/commands/apply.js +76 -4
- package/dist/commands/commit-apply.js +113 -0
- package/dist/commands/commit.js +81 -0
- package/dist/commands/list.js +2 -1
- package/dist/commands/show.js +59 -7
- package/dist/commands/undo.js +8 -0
- package/dist/commands/watch.js +100 -9
- package/dist/core/commit-message.js +143 -0
- package/dist/core/diff.js +16 -0
- package/dist/infra/config.js +12 -1
- package/dist/infra/git.js +154 -0
- package/dist/infra/history.js +49 -2
- package/dist/infra/watch-lock.js +180 -0
- package/package.json +7 -8
package/dist/commands/watch.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
* 二重適用の防止・成功後の履歴への移動は `tazuna` (引数なし) と同じ。Ctrl+C で終了する。
|
|
5
5
|
* 結果はターミナルのタイトルでも知らせ (--bell でベルも。既定は鳴らさない)、
|
|
6
6
|
* 当てなかった Downloads の changes.md は少し待ってから状態ディレクトリの unapplied/ へ移す。
|
|
7
|
+
* 同じダウンロードフォルダを見る watch は 1 つだけ (後から始めた watch に切り替わり、前の watch は自分で終了する。
|
|
8
|
+
* 1 つの changes.md が 2 か所に当たらないように。infra/watch-lock.ts)。
|
|
7
9
|
*/
|
|
8
10
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
9
11
|
import { basename, relative } from "node:path";
|
|
@@ -17,13 +19,15 @@ import { listChangesFiles, resolveDownloadsDir } from "../infra/downloads.js";
|
|
|
17
19
|
import { findProjectRoot } from "../infra/root.js";
|
|
18
20
|
import { err, out, outEmphasis, restoreTerminalTitle, ringBell, setTerminalTitle } from "../infra/term.js";
|
|
19
21
|
import { moveToUnapplied, unappliedDir } from "../infra/unapplied.js";
|
|
22
|
+
import { acquireWatchLock, checkWatchLock, releaseWatchLock, watchLockPath, } from "../infra/watch-lock.js";
|
|
20
23
|
import { runApply } from "./apply.js";
|
|
21
24
|
const DEFAULT_INTERVAL_MS = 1000;
|
|
22
25
|
/**
|
|
23
|
-
* 当てなかった changes.md を移すまでの猶予。Downloads
|
|
24
|
-
* watch
|
|
25
|
-
*
|
|
26
|
-
*
|
|
26
|
+
* 当てなかった changes.md を移すまでの猶予。Downloads は複数のリポジトリで共通なので、別のリポジトリで
|
|
27
|
+
* 同じファイルを当てに行くものがあり得る (0.26.0 より前の版の watch や、手で実行した tazuna。このリポジトリにも
|
|
28
|
+
* 同じ名前のファイルがあって別のリポジトリ向けと見分けられなかったとき、すぐ移すとそちらが当てられなくなる)。
|
|
29
|
+
* 0.26.0 からの watch どうしは同じ Downloads に 1 つだけ (後から始めた方に切り替わる) なので、ここでは競わない。
|
|
30
|
+
* watch は 1 秒間隔の 2 回の観測で渡すので、15 秒あれば向こうの適用が先に終わる
|
|
27
31
|
*/
|
|
28
32
|
const DEFAULT_TIDY_DELAY_MS = 15_000;
|
|
29
33
|
const pad2 = (n) => String(n).padStart(2, "0");
|
|
@@ -41,7 +45,7 @@ export function describeWatchResult(result, file) {
|
|
|
41
45
|
return {
|
|
42
46
|
title: `✓ 適用 ${result.files} ファイル`,
|
|
43
47
|
headline: `✓ 適用しました (${result.files} ファイル)`,
|
|
44
|
-
details: [
|
|
48
|
+
details: [`差分を VS Code のソース管理か ${TOOL_NAME} show で確認してからビルドしてください`],
|
|
45
49
|
};
|
|
46
50
|
case "already-applied":
|
|
47
51
|
return {
|
|
@@ -77,6 +81,15 @@ export function describeWatchResult(result, file) {
|
|
|
77
81
|
`このリポジトリ向けなら ${TOOL_NAME} ${quoted(file.path)}${rootSuffix(file.rootOption)} で失敗の理由を確かめられます`,
|
|
78
82
|
],
|
|
79
83
|
};
|
|
84
|
+
case "commit-failed":
|
|
85
|
+
return {
|
|
86
|
+
title: "✗ コミットできず止めました",
|
|
87
|
+
headline: "✗ 前回の適用をコミットできなかったため、この changes.md は当てていません (理由は上)",
|
|
88
|
+
details: [
|
|
89
|
+
`git の問題を直してから ${TOOL_NAME} ${quoted(file.path)}${rootSuffix(file.rootOption)} で当ててください`,
|
|
90
|
+
`changes.md は ${file.path} に残しています`,
|
|
91
|
+
],
|
|
92
|
+
};
|
|
80
93
|
case "dry-run":
|
|
81
94
|
return {
|
|
82
95
|
title: "dry-run: 検証しました",
|
|
@@ -115,6 +128,43 @@ export function describeTidy(kind, file) {
|
|
|
115
128
|
lines.push(forceLine(file.movedTo ?? file.path, file.rootOption));
|
|
116
129
|
return lines;
|
|
117
130
|
}
|
|
131
|
+
/** 開始時刻の表示 (同じ日なら時刻だけ) */
|
|
132
|
+
function startedLabel(iso, now) {
|
|
133
|
+
const at = new Date(iso);
|
|
134
|
+
if (Number.isNaN(at.getTime()))
|
|
135
|
+
return iso;
|
|
136
|
+
const hm = `${pad2(at.getHours())}:${pad2(at.getMinutes())}`;
|
|
137
|
+
return at.toDateString() === now.toDateString() ? hm : `${at.getMonth() + 1}/${at.getDate()} ${hm}`;
|
|
138
|
+
}
|
|
139
|
+
/** 同じルートか (Windows・macOS は大文字小文字を区別しないのが普通) */
|
|
140
|
+
function sameRoot(a, b, platform) {
|
|
141
|
+
return platform === "win32" || platform === "darwin" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* 始めたときに、前に動いていた watch から切り替えたことを知らせる行。前の watch が動いていなければ (ウィンドウを
|
|
145
|
+
* 閉じて印だけが残っていた) 何も出さない。純粋関数
|
|
146
|
+
*/
|
|
147
|
+
export function describeHandover(previous, root, now, platform = process.platform) {
|
|
148
|
+
if (previous === null || !previous.alive)
|
|
149
|
+
return [];
|
|
150
|
+
const where = sameRoot(previous.root, root, platform) ? "このリポジトリで" : `${previous.root} で`;
|
|
151
|
+
return [
|
|
152
|
+
`${where}動いていた ${TOOL_NAME} watch (PID ${previous.pid}、${startedLabel(previous.startedAt, now)} から) から、ここに切り替えます`,
|
|
153
|
+
"同じダウンロードフォルダを見る watch は 1 つだけです (1 つの changes.md が 2 か所に当たらないように、あちらは自動で終了します)",
|
|
154
|
+
];
|
|
155
|
+
}
|
|
156
|
+
/** 後から始めた watch に切り替わったとき (この watch が終了するとき) の行。純粋関数 */
|
|
157
|
+
export function describeTakeover(by, root, platform = process.platform) {
|
|
158
|
+
return {
|
|
159
|
+
headline: sameRoot(by.root, root, platform)
|
|
160
|
+
? `このリポジトリで別の ${TOOL_NAME} watch が始まりました (PID ${by.pid})`
|
|
161
|
+
: `別の場所で ${TOOL_NAME} watch が始まりました: ${by.root}`,
|
|
162
|
+
details: [
|
|
163
|
+
"同じダウンロードフォルダを見る watch は 1 つだけにするため、ここでの監視を終了します (1 つの changes.md が 2 か所に当たらないように)",
|
|
164
|
+
`ここで続けるときは、もう一度 ${TOOL_NAME} watch を実行してください (あちらの watch が終了します)`,
|
|
165
|
+
],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
118
168
|
export async function watchCommand(argv, options = {}) {
|
|
119
169
|
const { values } = parseArgs({
|
|
120
170
|
args: argv,
|
|
@@ -176,7 +226,7 @@ export async function watchCommand(argv, options = {}) {
|
|
|
176
226
|
pendingTidy.splice(i, 1);
|
|
177
227
|
const current = stampOf(p.path);
|
|
178
228
|
if (current === null) {
|
|
179
|
-
out(`(${clock(new Date())}) ${p.path} は移す前に無くなっていました (
|
|
229
|
+
out(`(${clock(new Date())}) ${p.path} は移す前に無くなっていました (別のリポジトリで当てたか、手で動かしたようです)`);
|
|
180
230
|
continue;
|
|
181
231
|
}
|
|
182
232
|
if (current !== p.stamp)
|
|
@@ -195,9 +245,34 @@ export async function watchCommand(argv, options = {}) {
|
|
|
195
245
|
out(` ${line}`);
|
|
196
246
|
}
|
|
197
247
|
};
|
|
248
|
+
// 同じダウンロードフォルダを見る watch は 1 つだけにする。印を置き換え、前の watch には自分で終了してもらう
|
|
249
|
+
// (印は開始時の一覧より先に書く。前の watch はこの後に届いたものを当てる前に切り替わりに気づき、この watch は
|
|
250
|
+
// それより前からあるものを当てないので、同じ changes.md を 2 つの watch が当てることはない)
|
|
251
|
+
const me = { pid: process.pid, root, startedAt: new Date().toISOString() };
|
|
252
|
+
let lock = null;
|
|
253
|
+
let previous = null;
|
|
254
|
+
let lockError = null;
|
|
255
|
+
let takenBy = null;
|
|
256
|
+
/** 後から始めた watch に切り替わっていれば true */
|
|
257
|
+
const handedOver = () => {
|
|
258
|
+
if (takenBy === null && lock !== null) {
|
|
259
|
+
const check = checkWatchLock(lock, me);
|
|
260
|
+
if (check.state === "taken")
|
|
261
|
+
takenBy = check.by;
|
|
262
|
+
}
|
|
263
|
+
return takenBy !== null;
|
|
264
|
+
};
|
|
198
265
|
try {
|
|
266
|
+
try {
|
|
267
|
+
({ lock, previous } = acquireWatchLock(watchLockPath(downloadsDir, options.lockDir), me));
|
|
268
|
+
}
|
|
269
|
+
catch (e) {
|
|
270
|
+
lockError = e instanceof Error ? e.message : String(e);
|
|
271
|
+
}
|
|
199
272
|
// 開始時に既にあるファイルは対象外 (古い changes.md を黙って当てない)
|
|
200
273
|
const state = initialWatchState(list());
|
|
274
|
+
for (const line of describeHandover(previous, root, new Date()))
|
|
275
|
+
out(line);
|
|
201
276
|
out("changes*.md の到着を待っています。届いたら確認なしで適用します (Ctrl+C で終了)");
|
|
202
277
|
out(` Downloads: ${downloadsDir}`);
|
|
203
278
|
out(` プロジェクト直下: ${root}`);
|
|
@@ -208,20 +283,27 @@ export async function watchCommand(argv, options = {}) {
|
|
|
208
283
|
}
|
|
209
284
|
out(` 結果はこのターミナルのタイトル${values.bell ? "とベル" : ""}でも知らせます。` +
|
|
210
285
|
`当てなかった Downloads の changes.md は少し待ってから ${tidyRel} へ移します`);
|
|
286
|
+
if (lockError !== null) {
|
|
287
|
+
out(` (ほかの watch と重ならないようにする印を書けませんでした: ${lockError}。` +
|
|
288
|
+
"同じダウンロードフォルダを見る watch をほかに起動しないでください)");
|
|
289
|
+
}
|
|
211
290
|
title("待機中");
|
|
212
291
|
const interval = options.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
213
|
-
while (!stop.signal.aborted) {
|
|
292
|
+
while (!stop.signal.aborted && takenBy === null) {
|
|
214
293
|
try {
|
|
215
294
|
await delay(interval, undefined, { signal: stop.signal });
|
|
216
295
|
}
|
|
217
296
|
catch {
|
|
218
297
|
break; // 中断
|
|
219
298
|
}
|
|
299
|
+
if (handedOver())
|
|
300
|
+
break;
|
|
220
301
|
tidyDue();
|
|
221
302
|
for (const f of observeWatch(state, list())) {
|
|
222
|
-
|
|
303
|
+
// 後から始めた watch に切り替わっていたら当てない (そちらが当てる)
|
|
304
|
+
if (stop.signal.aborted || handedOver())
|
|
223
305
|
break;
|
|
224
|
-
//
|
|
306
|
+
// 別のリポジトリで先に当てて履歴へ移したもの (手で実行した tazuna や前の版の watch) は、黙って見送る
|
|
225
307
|
if (!existsSync(f.path))
|
|
226
308
|
continue;
|
|
227
309
|
// 移すのを待っていたものが書き換わって渡し直されたら、前の結果では移さない
|
|
@@ -280,10 +362,19 @@ export async function watchCommand(argv, options = {}) {
|
|
|
280
362
|
out("引き続き待っています (Ctrl+C で終了)");
|
|
281
363
|
}
|
|
282
364
|
}
|
|
365
|
+
if (takenBy !== null) {
|
|
366
|
+
const report = describeTakeover(takenBy, root);
|
|
367
|
+
out("");
|
|
368
|
+
outEmphasis(`━━ ${clock(new Date())} ${report.headline}`);
|
|
369
|
+
for (const line of report.details)
|
|
370
|
+
out(` ${line}`);
|
|
371
|
+
}
|
|
283
372
|
}
|
|
284
373
|
finally {
|
|
285
374
|
process.removeListener("SIGINT", onSigint);
|
|
286
375
|
options.signal?.removeEventListener("abort", onAbort);
|
|
376
|
+
if (lock !== null)
|
|
377
|
+
releaseWatchLock(lock);
|
|
287
378
|
restoreTerminalTitle();
|
|
288
379
|
}
|
|
289
380
|
for (const p of pendingTidy)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* changes.md の概要 (## CHANGES と最初の ### FILE: の間) からコミットメッセージを作る (純粋関数)。
|
|
3
|
+
* 1 回の適用 = 1 コミット (config の git.commitEachApply と tazuna commit) で使う。
|
|
4
|
+
*
|
|
5
|
+
* - 件名: 概要の最初の内容のある行。最初の「。」の前まで、長ければ切り詰める。規約文 v6 から、概要の 1 行目は
|
|
6
|
+
* AI が件名として書く (40 文字以内の「〜を追加」の形)。「変更概要:」のような見出しは外す
|
|
7
|
+
* - 本文: 概要の全文 (件名がその行そのものなら、その次の行から)。Mermaid などのコードブロックと
|
|
8
|
+
* 「影響ファイル:」の一覧は除く (ファイルの一覧はコミット自体に残る)
|
|
9
|
+
* - 末尾: 履歴 ID のトレーラー (コミットと tazuna の履歴を突き合わせるため)
|
|
10
|
+
*
|
|
11
|
+
* 概要は AI の書いたテキストなので、制御文字 (改行とタブを除く) と双方向制御文字を除く
|
|
12
|
+
*/
|
|
13
|
+
import { TOOL_NAME } from "../brand.js";
|
|
14
|
+
/** 件名の長さの上限 (文字数) */
|
|
15
|
+
export const SUBJECT_MAX_CHARS = 60;
|
|
16
|
+
/** コミットメッセージの末尾に付けるトレーラーの名前 */
|
|
17
|
+
export const HISTORY_TRAILER = "Tazuna-History";
|
|
18
|
+
// 改行 (\n) とタブ以外の C0、DEL、C1、双方向制御文字 (Trojan Source)
|
|
19
|
+
const UNSAFE_CHARS = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F--]/g;
|
|
20
|
+
function cleanSummary(header) {
|
|
21
|
+
const lines = header.replace(/\r\n?/g, "\n").replace(UNSAFE_CHARS, "").split("\n");
|
|
22
|
+
const kept = [];
|
|
23
|
+
let fence = null;
|
|
24
|
+
let inFileList = false;
|
|
25
|
+
for (const raw of lines) {
|
|
26
|
+
const line = raw.trimEnd();
|
|
27
|
+
const trimmed = line.trim();
|
|
28
|
+
if (fence !== null) {
|
|
29
|
+
if (trimmed.startsWith(fence))
|
|
30
|
+
fence = null;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed);
|
|
34
|
+
if (fenceMatch !== null) {
|
|
35
|
+
fence = fenceMatch[1];
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (/^影響ファイル\s*[::]/.test(trimmed)) {
|
|
39
|
+
inFileList = true;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (inFileList) {
|
|
43
|
+
if (/^[-*+]\s/.test(trimmed))
|
|
44
|
+
continue;
|
|
45
|
+
inFileList = false;
|
|
46
|
+
}
|
|
47
|
+
kept.push(line);
|
|
48
|
+
}
|
|
49
|
+
// 前後の空行を落とし、続く空行は 1 つにまとめる
|
|
50
|
+
const collapsed = [];
|
|
51
|
+
for (const line of kept) {
|
|
52
|
+
if (line.trim() === "" && (collapsed.length === 0 || collapsed[collapsed.length - 1]?.trim() === ""))
|
|
53
|
+
continue;
|
|
54
|
+
collapsed.push(line);
|
|
55
|
+
}
|
|
56
|
+
while (collapsed.length > 0 && collapsed[collapsed.length - 1]?.trim() === "")
|
|
57
|
+
collapsed.pop();
|
|
58
|
+
return collapsed;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 概要の見出しのような書き出し (「**変更概要**」「## 概要」「変更概要: 」)。AI がよく付けるが件名にはならないので外す。
|
|
62
|
+
* 見出しだけの行は空の行として扱う
|
|
63
|
+
*/
|
|
64
|
+
const SUMMARY_LABEL = /^(?:変更の?概要|変更内容|概要|要約|summary)\s*(?:[::]\s*|$)/i;
|
|
65
|
+
/** Markdown の見出し・箇条書き・引用・強調の記号と、概要の見出しを件名から外す */
|
|
66
|
+
function plainSubject(line) {
|
|
67
|
+
return line
|
|
68
|
+
.trim()
|
|
69
|
+
.replace(/^(#{1,6}\s+|[-*+]\s+|>\s*|\d+[.)]\s+)/, "")
|
|
70
|
+
.replace(/\*\*|__/g, "")
|
|
71
|
+
.trim()
|
|
72
|
+
.replace(SUMMARY_LABEL, "")
|
|
73
|
+
.trim();
|
|
74
|
+
}
|
|
75
|
+
function truncate(text, max) {
|
|
76
|
+
const chars = [...text];
|
|
77
|
+
return chars.length <= max ? text : `${chars.slice(0, max - 1).join("")}…`;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* @param header ChangeSet.header (概要)
|
|
81
|
+
* @param historyId 適用の履歴 ID
|
|
82
|
+
* @param fileCount コミットするファイル数 (概要が空のときの件名に使う)
|
|
83
|
+
*/
|
|
84
|
+
export function buildCommitMessage(header, historyId, fileCount) {
|
|
85
|
+
const lines = cleanSummary(header);
|
|
86
|
+
const firstIndex = lines.findIndex((l) => plainSubject(l) !== "");
|
|
87
|
+
let subject;
|
|
88
|
+
let body;
|
|
89
|
+
if (firstIndex === -1) {
|
|
90
|
+
subject = `${TOOL_NAME} で changes.md を適用 (${fileCount} ファイル)`;
|
|
91
|
+
body = [];
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
const first = plainSubject(lines[firstIndex]);
|
|
95
|
+
const period = first.indexOf("。");
|
|
96
|
+
const head = period > 0 ? first.slice(0, period) : first;
|
|
97
|
+
const rest = period > 0 ? first.slice(period + 1).trim() : "";
|
|
98
|
+
subject = truncate(head, SUBJECT_MAX_CHARS);
|
|
99
|
+
// 件名が最初の行 (の 1 文) そのものなら本文はその次の行から。途中で切ったなら、情報を落とさないよう
|
|
100
|
+
// その行から本文に入れる
|
|
101
|
+
const cut = rest !== "" || subject !== head;
|
|
102
|
+
body = cut ? lines.slice(firstIndex) : lines.slice(firstIndex + 1);
|
|
103
|
+
while (body.length > 0 && body[0]?.trim() === "")
|
|
104
|
+
body.shift();
|
|
105
|
+
}
|
|
106
|
+
const parts = [subject];
|
|
107
|
+
if (body.length > 0)
|
|
108
|
+
parts.push("", ...body);
|
|
109
|
+
parts.push("", `${HISTORY_TRAILER}: ${historyId}`);
|
|
110
|
+
return { subject, message: `${parts.join("\n")}\n` };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 前回のコミットの後に当てた複数の changes.md を 1 つにまとめたメッセージ (tazuna commit)。
|
|
114
|
+
* 件名は最初の回の件名、本文は各回の件名の箇条書き、末尾に各回の履歴 ID のトレーラー。1 回だけなら buildCommitMessage と同じ
|
|
115
|
+
*/
|
|
116
|
+
export function buildBatchCommitMessage(entries) {
|
|
117
|
+
const [first, ...rest] = entries;
|
|
118
|
+
if (first === undefined)
|
|
119
|
+
return buildCommitMessage("", "", 0);
|
|
120
|
+
if (rest.length === 0)
|
|
121
|
+
return buildCommitMessage(first.header, first.historyId, first.fileCount);
|
|
122
|
+
const subjects = entries.map((e) => buildCommitMessage(e.header, e.historyId, e.fileCount).subject);
|
|
123
|
+
const subject = subjects[0];
|
|
124
|
+
const lines = [
|
|
125
|
+
subject,
|
|
126
|
+
"",
|
|
127
|
+
...subjects.map((s) => `- ${s}`),
|
|
128
|
+
"",
|
|
129
|
+
...entries.map((e) => `${HISTORY_TRAILER}: ${e.historyId}`),
|
|
130
|
+
];
|
|
131
|
+
return { subject, message: `${lines.join("\n")}\n` };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* 件名を利用者の指定 (tazuna commit -m) に替える。改行と制御文字は除く。空になれば null
|
|
135
|
+
*/
|
|
136
|
+
export function withSubject(message, subject) {
|
|
137
|
+
const cleaned = subject.replace(/[\r\n]+/g, " ").replace(UNSAFE_CHARS, "").trim();
|
|
138
|
+
if (cleaned === "")
|
|
139
|
+
return null;
|
|
140
|
+
const newline = message.message.indexOf("\n");
|
|
141
|
+
const rest = newline === -1 ? "\n" : message.message.slice(newline);
|
|
142
|
+
return { subject: cleaned, message: `${cleaned}${rest}` };
|
|
143
|
+
}
|
package/dist/core/diff.js
CHANGED
|
@@ -6,6 +6,22 @@
|
|
|
6
6
|
* (表示が粗くなるだけで内容は欠けない)。
|
|
7
7
|
*/
|
|
8
8
|
const DEFAULT_MAX_D = 2000;
|
|
9
|
+
/**
|
|
10
|
+
* 行配列 a → b で足した行と消した行の数 (適用の結果の表示用)。
|
|
11
|
+
* 差が大きく diffLines が全削除 + 全挿入に打ち切ったときは null (全行の入れ替えと見せない。行の内容ごとの数の差でも
|
|
12
|
+
* 並べ替えを 0 と数えてしまうため、数えない)
|
|
13
|
+
*/
|
|
14
|
+
export function countLineChanges(a, b) {
|
|
15
|
+
let added = 0;
|
|
16
|
+
let removed = 0;
|
|
17
|
+
for (const op of diffLines(a, b)) {
|
|
18
|
+
if (op.kind === "ins")
|
|
19
|
+
added++;
|
|
20
|
+
else if (op.kind === "del")
|
|
21
|
+
removed++;
|
|
22
|
+
}
|
|
23
|
+
return added + removed <= DEFAULT_MAX_D ? { added, removed } : null;
|
|
24
|
+
}
|
|
9
25
|
/** 行配列 a → b の差分を返す。インデックスはともに 0-based */
|
|
10
26
|
export function diffLines(a, b, maxD = DEFAULT_MAX_D) {
|
|
11
27
|
// 共通の前置き・後置きを先に確定する (パッチ適用前後の比較では大半が共通)
|
package/dist/infra/config.js
CHANGED
|
@@ -10,6 +10,7 @@ export const DEFAULT_CONFIG = {
|
|
|
10
10
|
vscodeCommand: "code",
|
|
11
11
|
clipReportOnFailure: true,
|
|
12
12
|
vbproj: { register: true },
|
|
13
|
+
git: { commitEachApply: false },
|
|
13
14
|
};
|
|
14
15
|
/** tazuna init が書く .tazuna/config.json の雛形 (PC ごとの設定。git の管理外) */
|
|
15
16
|
export const CONFIG_TEMPLATE = `{
|
|
@@ -18,7 +19,8 @@ export const CONFIG_TEMPLATE = `{
|
|
|
18
19
|
"historyLimit": null,
|
|
19
20
|
"vscodeCommand": "code",
|
|
20
21
|
"clipReportOnFailure": true,
|
|
21
|
-
"vbproj": { "register": true }
|
|
22
|
+
"vbproj": { "register": true },
|
|
23
|
+
"git": { "commitEachApply": false }
|
|
22
24
|
}
|
|
23
25
|
`;
|
|
24
26
|
function globalConfigBase() {
|
|
@@ -65,6 +67,10 @@ function validateConfig(c) {
|
|
|
65
67
|
if (typeof c.vbproj !== "object" || c.vbproj === null || typeof register !== "boolean") {
|
|
66
68
|
throw new Error('config の vbproj が不正です ({ "register": true | false } を指定)');
|
|
67
69
|
}
|
|
70
|
+
const commitEachApply = c.git?.commitEachApply;
|
|
71
|
+
if (typeof c.git !== "object" || c.git === null || typeof commitEachApply !== "boolean") {
|
|
72
|
+
throw new Error('config の git が不正です ({ "commitEachApply": true | false } を指定)');
|
|
73
|
+
}
|
|
68
74
|
const limit = c.historyLimit;
|
|
69
75
|
if (limit !== null && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1)) {
|
|
70
76
|
throw new Error(`config の historyLimit が不正です: ${String(limit)} (null または 1 以上の整数)`);
|
|
@@ -94,6 +100,11 @@ export function loadConfig(root) {
|
|
|
94
100
|
...(global.vbproj ?? {}),
|
|
95
101
|
...(project.vbproj ?? {}),
|
|
96
102
|
},
|
|
103
|
+
git: {
|
|
104
|
+
...DEFAULT_CONFIG.git,
|
|
105
|
+
...(global.git ?? {}),
|
|
106
|
+
...(project.git ?? {}),
|
|
107
|
+
},
|
|
97
108
|
});
|
|
98
109
|
}
|
|
99
110
|
/**
|
package/dist/infra/git.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { execFile, spawnSync } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, posix } from "node:path";
|
|
2
5
|
import { promisify } from "node:util";
|
|
6
|
+
import { TOOL_NAME } from "../brand.js";
|
|
3
7
|
const execFileP = promisify(execFile);
|
|
4
8
|
/**
|
|
5
9
|
* git を読み取りだけで呼ぶための共通の指定。
|
|
@@ -55,3 +59,153 @@ export function listGitFiles(rootDir) {
|
|
|
55
59
|
const files = [...new Set(result.stdout.toString("utf8").split("\0").filter((p) => p !== ""))];
|
|
56
60
|
return { ok: true, files };
|
|
57
61
|
}
|
|
62
|
+
/** git を同期で実行する (読み取りと同じ指定に加えて、パスを文字どおりに扱い、フックを動かさない) */
|
|
63
|
+
function runGit(cwd, args, noHooksDir, input) {
|
|
64
|
+
const result = spawnSync("git", [...GIT_READ_ONLY_ARGS, "-c", `core.hooksPath=${noHooksDir}`, ...args], {
|
|
65
|
+
cwd,
|
|
66
|
+
// パスの * や :(glob) をパターンとして読ませない (ファイル名どおりのものだけを対象にする)
|
|
67
|
+
env: { ...gitEnv(), GIT_LITERAL_PATHSPECS: "1" },
|
|
68
|
+
input,
|
|
69
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
70
|
+
windowsHide: true,
|
|
71
|
+
timeout: 120_000,
|
|
72
|
+
});
|
|
73
|
+
return {
|
|
74
|
+
status: result.status,
|
|
75
|
+
stdout: result.stdout ?? Buffer.alloc(0),
|
|
76
|
+
stderr: (result.stderr ?? Buffer.alloc(0)).toString("utf8"),
|
|
77
|
+
...(result.error !== undefined ? { error: result.error } : {}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const nulList = (out) => out.toString("utf8").split("\0").filter((p) => p !== "");
|
|
81
|
+
/** 存在しないディレクトリ (乱数入り)。フックの置き場に指定して、どのフックも見つからないようにする */
|
|
82
|
+
const noHooksDirectory = () => join(tmpdir(), `${TOOL_NAME}-no-hooks-${randomBytes(8).toString("hex")}`);
|
|
83
|
+
/**
|
|
84
|
+
* manifest のパスを git が返す形にそろえる (changes.md に `./a.txt`・`sub//a.txt` と書かれていても、git は `a.txt`・
|
|
85
|
+
* `sub/a.txt` と返す)
|
|
86
|
+
*/
|
|
87
|
+
const gitPathName = (path) => posix.normalize(path);
|
|
88
|
+
/**
|
|
89
|
+
* git が返した一覧のうち、指定したファイルそのものだけ。manifest は非信頼入力で、`.` やディレクトリの名前を
|
|
90
|
+
* 書けば git はその下のファイルすべてに当てはめる (未追跡のものまで git add してしまう) ため、名前の一致で絞る。
|
|
91
|
+
* 大文字小文字は、リポジトリが区別しない (core.ignorecase。Windows・macOS の既定) ときだけ同一視する
|
|
92
|
+
*/
|
|
93
|
+
function onlyNamed(listed, paths, ignoreCase) {
|
|
94
|
+
const key = (p) => (ignoreCase ? p.toLowerCase() : p);
|
|
95
|
+
const wanted = new Set(paths.map((p) => key(gitPathName(p))));
|
|
96
|
+
return listed.filter((p) => wanted.has(key(p)));
|
|
97
|
+
}
|
|
98
|
+
/** git の出力の先頭の数行 (失敗の理由として見せる) */
|
|
99
|
+
const firstLines = (text, n = 8) => text
|
|
100
|
+
.split(/\r?\n/)
|
|
101
|
+
.map((l) => l.trimEnd())
|
|
102
|
+
.filter((l) => l !== "")
|
|
103
|
+
.slice(0, n)
|
|
104
|
+
.join("\n");
|
|
105
|
+
/**
|
|
106
|
+
* 指定したファイル (ルート相対・`/` 区切り) だけをコミットする (1 回の適用 = 1 コミット)。
|
|
107
|
+
* - 未追跡のものは `git add` してから (.gitignore に一致するものは入れない)
|
|
108
|
+
* - `git commit --only` なので、ほかのファイルの手元の変更・ステージ済みの変更はコミットに入らない
|
|
109
|
+
* - メッセージは標準入力から渡す (AI の書いた概要を引数にしない。長さの制限も受けない)
|
|
110
|
+
* - フックは動かさない (core.hooksPath を存在しない場所に向ける)。フックの置き場が作業ツリーにある
|
|
111
|
+
* リポジトリ (husky など) では、確かめる前の changes.md が書き換えたフックを動かしてしまうため
|
|
112
|
+
*/
|
|
113
|
+
export function commitPaths(rootDir, paths, message) {
|
|
114
|
+
if (paths.length === 0)
|
|
115
|
+
return { kind: "nothing" };
|
|
116
|
+
const noHooksDir = noHooksDirectory();
|
|
117
|
+
const git = (args, input) => runGit(rootDir, args, noHooksDir, input);
|
|
118
|
+
const inside = git(["rev-parse", "--is-inside-work-tree"]);
|
|
119
|
+
if (inside.error !== undefined) {
|
|
120
|
+
return {
|
|
121
|
+
kind: "not-repo",
|
|
122
|
+
message: inside.error.code === "ENOENT" ? "git が見つかりません" : inside.error.message,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
if (inside.status !== 0 || inside.stdout.toString("utf8").trim() !== "true") {
|
|
126
|
+
return { kind: "not-repo", message: firstLines(inside.stderr, 1) || "git のリポジトリではありません" };
|
|
127
|
+
}
|
|
128
|
+
const tracked = git(["ls-files", "-z", "--cached", "--", ...paths]);
|
|
129
|
+
const untracked = git(["ls-files", "-z", "--others", "--exclude-standard", "--", ...paths]);
|
|
130
|
+
if (tracked.status !== 0 || untracked.status !== 0) {
|
|
131
|
+
return { kind: "failed", message: firstLines(tracked.stderr || untracked.stderr) || "git ls-files に失敗しました" };
|
|
132
|
+
}
|
|
133
|
+
const ignoreCase = git(["config", "--bool", "core.ignorecase"]).stdout.toString("utf8").trim() === "true";
|
|
134
|
+
const added = onlyNamed(nulList(untracked.stdout), paths, ignoreCase);
|
|
135
|
+
const targets = [...new Set([...onlyNamed(nulList(tracked.stdout), paths, ignoreCase), ...added])];
|
|
136
|
+
if (targets.length === 0)
|
|
137
|
+
return { kind: "nothing" };
|
|
138
|
+
if (added.length > 0) {
|
|
139
|
+
const add = git(["add", "--", ...added]);
|
|
140
|
+
if (add.status !== 0)
|
|
141
|
+
return { kind: "failed", message: firstLines(add.stderr) || "git add に失敗しました" };
|
|
142
|
+
}
|
|
143
|
+
const status = git(["status", "--porcelain", "-z", "--", ...targets]);
|
|
144
|
+
if (status.status !== 0)
|
|
145
|
+
return { kind: "failed", message: firstLines(status.stderr) || "git status に失敗しました" };
|
|
146
|
+
if (nulList(status.stdout).length === 0)
|
|
147
|
+
return { kind: "nothing" };
|
|
148
|
+
const commit = git(["commit", "--only", "--no-verify", "--cleanup=whitespace", "-F", "-", "--", ...targets], message);
|
|
149
|
+
if (commit.error !== undefined)
|
|
150
|
+
return { kind: "failed", message: commit.error.message };
|
|
151
|
+
if (commit.status !== 0) {
|
|
152
|
+
return {
|
|
153
|
+
kind: "failed",
|
|
154
|
+
message: firstLines(commit.stderr) || firstLines(commit.stdout.toString("utf8")) || "git commit に失敗しました",
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const head = git(["rev-parse", "HEAD"]);
|
|
158
|
+
return { kind: "committed", sha: head.stdout.toString("utf8").trim(), files: targets };
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 指定したファイルのうち、HEAD と内容の違うもの (未追跡で .gitignore に一致しないものを含む) を見分ける関数。
|
|
162
|
+
* まとめてコミットするときに、git で元に戻した回を見分ける。git が無い・リポジトリでなければ null。
|
|
163
|
+
* 大文字小文字は区別しない (違うと見る側に倒れるだけ = 回を外さない)
|
|
164
|
+
*/
|
|
165
|
+
export function changedPaths(rootDir, paths) {
|
|
166
|
+
const key = (p) => gitPathName(p).toLowerCase();
|
|
167
|
+
if (paths.length === 0)
|
|
168
|
+
return () => false;
|
|
169
|
+
const noHooksDir = noHooksDirectory();
|
|
170
|
+
// git status はリポジトリの最上位からのパスで返すので、ルートがその下のフォルダならその分を外す
|
|
171
|
+
const prefix = runGit(rootDir, ["rev-parse", "--show-prefix"], noHooksDir);
|
|
172
|
+
if (prefix.error !== undefined || prefix.status !== 0)
|
|
173
|
+
return null;
|
|
174
|
+
const base = prefix.stdout.toString("utf8").trim();
|
|
175
|
+
// --untracked-files=all: 利用者の設定 (status.showUntrackedFiles=no など) によらず、作ったファイルも見る
|
|
176
|
+
const status = runGit(rootDir, ["status", "--porcelain", "-z", "--untracked-files=all", "--", ...paths], noHooksDir);
|
|
177
|
+
if (status.error !== undefined || status.status !== 0)
|
|
178
|
+
return null;
|
|
179
|
+
const changed = new Set();
|
|
180
|
+
const add = (fromTop) => {
|
|
181
|
+
if (fromTop.startsWith(base))
|
|
182
|
+
changed.add(key(fromTop.slice(base.length)));
|
|
183
|
+
};
|
|
184
|
+
const entries = nulList(status.stdout);
|
|
185
|
+
for (let i = 0; i < entries.length; i++) {
|
|
186
|
+
const entry = entries[i];
|
|
187
|
+
add(entry.slice(3));
|
|
188
|
+
// 名前の変更 (R) と写し (C) は、次の項目が元の名前 (索引側・作業ツリー側のどちらの欄でも)
|
|
189
|
+
if (/[RC]/.test(entry.slice(0, 2))) {
|
|
190
|
+
const from = entries[i + 1];
|
|
191
|
+
if (from !== undefined)
|
|
192
|
+
add(from);
|
|
193
|
+
i++;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return (path) => changed.has(key(path));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* 今の HEAD のコミット。コミットがまだ無いリポジトリでは null、git が無い・リポジトリでなければ undefined。
|
|
200
|
+
* 適用のときに manifest に残し、次の適用の前のコミットで「その間に利用者がコミットしたか」を見分ける
|
|
201
|
+
*/
|
|
202
|
+
export function gitHeadCommit(rootDir) {
|
|
203
|
+
const run = (args) => spawnSync("git", [...GIT_READ_ONLY_ARGS, ...args], { cwd: rootDir, env: gitEnv(), windowsHide: true, timeout: 60_000 });
|
|
204
|
+
const inside = run(["rev-parse", "--is-inside-work-tree"]);
|
|
205
|
+
if (inside.error !== undefined || inside.status !== 0 || inside.stdout.toString("utf8").trim() !== "true")
|
|
206
|
+
return undefined;
|
|
207
|
+
const head = run(["rev-parse", "--verify", "-q", "HEAD"]);
|
|
208
|
+
if (head.error !== undefined)
|
|
209
|
+
return undefined;
|
|
210
|
+
return head.status === 0 ? head.stdout.toString("utf8").trim() : null;
|
|
211
|
+
}
|
package/dist/infra/history.js
CHANGED
|
@@ -66,12 +66,17 @@ export function listHistoryIds(root) {
|
|
|
66
66
|
.map((e) => e.name)
|
|
67
67
|
.sort();
|
|
68
68
|
}
|
|
69
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* historyLimit を超えた古い履歴を削除する (§10)。null = 無制限。
|
|
71
|
+
* まだコミットしていない適用 (tazuna commit がまとめる分。findUncommittedApplies) は、上限を超えてもコミットするまで
|
|
72
|
+
* 残す (消すと、その回で書いたファイルが tazuna commit から黙って漏れる)
|
|
73
|
+
*/
|
|
70
74
|
export function pruneHistory(root, limit) {
|
|
71
75
|
if (limit === null || limit < 1)
|
|
72
76
|
return [];
|
|
73
77
|
const ids = listHistoryIds(root);
|
|
74
|
-
const
|
|
78
|
+
const keep = new Set(findUncommittedApplies(root).map((f) => f.id));
|
|
79
|
+
const excess = ids.slice(0, Math.max(0, ids.length - limit)).filter((id) => !keep.has(id));
|
|
75
80
|
for (const id of excess) {
|
|
76
81
|
rmSync(join(historyRoot(root), id), { recursive: true, force: true });
|
|
77
82
|
}
|
|
@@ -90,6 +95,48 @@ export function markUndone(root, id, at) {
|
|
|
90
95
|
manifest.undoneAt = at.toISOString();
|
|
91
96
|
writeFileSync(p, JSON.stringify(manifest, null, 2) + "\n", "utf8");
|
|
92
97
|
}
|
|
98
|
+
/** tazuna がこの適用の分をコミットしたことを manifest に記録する (undo と次のコミットの対象から外すため) */
|
|
99
|
+
export function markCommitted(root, id, sha, at) {
|
|
100
|
+
const p = join(historyRoot(root), id, "manifest.json");
|
|
101
|
+
const manifest = JSON.parse(readFileSync(p, "utf8"));
|
|
102
|
+
manifest.committed = { sha, at: at.toISOString() };
|
|
103
|
+
writeFileSync(p, JSON.stringify(manifest, null, 2) + "\n", "utf8");
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* まだコミットしていない適用 (古い順)。巻き戻していない直近の履歴から遡り、同じコミットの上で当てたもの
|
|
107
|
+
* (適用したときの HEAD が直近の適用と同じ) を集める。コミット済みの履歴・HEAD が違う履歴 (その間に利用者が
|
|
108
|
+
* コミットした・ブランチを変えた)・HEAD の記録がない履歴 (0.23.0 より前の版で当てた・git の外) の手前で止める
|
|
109
|
+
* (直近の 1 件は HEAD の記録がなくても含める)。manifest は非信頼入力なので、読めない・形が違う履歴に当たったら
|
|
110
|
+
* そこで止める (推測で含めない)
|
|
111
|
+
*/
|
|
112
|
+
export function findUncommittedApplies(root) {
|
|
113
|
+
const found = [];
|
|
114
|
+
for (const id of listHistoryIds(root).reverse()) {
|
|
115
|
+
let manifest;
|
|
116
|
+
try {
|
|
117
|
+
manifest = readManifest(root, id);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
if (manifest === null || typeof manifest !== "object" || !Array.isArray(manifest.files))
|
|
123
|
+
break;
|
|
124
|
+
if (manifest.undoneAt !== undefined)
|
|
125
|
+
continue;
|
|
126
|
+
if (manifest.committed !== undefined)
|
|
127
|
+
break;
|
|
128
|
+
if (!manifest.files.some((f) => f?.applied === true))
|
|
129
|
+
continue;
|
|
130
|
+
const newest = found[0];
|
|
131
|
+
if (newest !== undefined) {
|
|
132
|
+
const base = newest.manifest.gitHead;
|
|
133
|
+
if (base === undefined || manifest.gitHead !== base)
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
found.push({ id, manifest });
|
|
137
|
+
}
|
|
138
|
+
return found.reverse();
|
|
139
|
+
}
|
|
93
140
|
/**
|
|
94
141
|
* 同じ指紋の changes.md を適用した履歴 (巻き戻し済み・書き込みなしを除く) を新しい順に
|
|
95
142
|
* 探し、最初に見つかった履歴 ID を返す。指紋を持たない旧形式の manifest は、保存済みの
|