@yourfam/yf-merge-check 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 YourFam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,2 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # yf-merge-check
2
+ Check whether git branch merges would conflict—individually or in a stacked sequence—using isolated temp worktrees without touching your working tree or current branch. Prints a one-line console summary and writes detailed conflict reports to Markdown.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../src/index.js";
3
+ run(process.argv);
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@yourfam/yf-merge-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Check whether a git merge would conflict, without touching the current branch.",
5
+ "type": "module",
6
+ "bin": {
7
+ "yf-merge-check": "bin/yf-merge-check.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "LICENSE",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test test/*.test.js"
17
+ },
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "author": {
22
+ "name": "YourFam",
23
+ "email": "kamal@yourfam.co",
24
+ "url": "https://github.com/YourFam"
25
+ },
26
+ "license": "MIT",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "repository": "git+https://github.com/YourFam/yf-merge-check.git"
31
+ }
package/src/args.js ADDED
@@ -0,0 +1,132 @@
1
+ import { createRequire } from "node:module";
2
+ import { CliError } from "./errors.js";
3
+
4
+ const require = createRequire(import.meta.url);
5
+ export const packageVersion = require("../package.json").version;
6
+
7
+ export const helpText = `Check whether a merge would conflict. The current branch is not changed.
8
+
9
+ Usage:
10
+ yf-merge-check --base <branch> <target>...
11
+ yf-merge-check --base <branch> --branches <target>...
12
+ yf-merge-check --stack --base <branch> <target>...
13
+
14
+ Options:
15
+ --base <branch> Branch the targets merge into. Required.
16
+ --branches <name...> Target branches. Names after the flags count too.
17
+ --stack Merge targets in order onto each other, starting from the base.
18
+ --fetch git fetch --all --prune before resolving names.
19
+ --gitignore Add yf-merge/ to the repository root .gitignore.
20
+ --version Print the version and exit.
21
+ -h, --help Show this help.
22
+
23
+ There is no default base and no default target.
24
+ `;
25
+
26
+ export function parseArgs(argv) {
27
+ const tokens = argv.slice(2);
28
+ if (tokens.includes("--help") || tokens.includes("-h")) {
29
+ return { help: true };
30
+ }
31
+ if (tokens.includes("--version")) {
32
+ return { version: true };
33
+ }
34
+
35
+ let base;
36
+ let baseSet = false;
37
+ let stack = false;
38
+ let fetch = false;
39
+ let gitignore = false;
40
+ const targets = [];
41
+
42
+ for (let i = 0; i < tokens.length; i += 1) {
43
+ const token = tokens[i];
44
+ if (token === "--stack") {
45
+ stack = true;
46
+ continue;
47
+ }
48
+ if (token === "--fetch") {
49
+ fetch = true;
50
+ continue;
51
+ }
52
+ if (token === "--gitignore") {
53
+ gitignore = true;
54
+ continue;
55
+ }
56
+ if (token === "--base" || token.startsWith("--base=")) {
57
+ if (baseSet) {
58
+ throw new CliError("Error: --base was given more than once.", 2);
59
+ }
60
+ const value = token === "--base" ? tokens[i + 1] : token.slice("--base=".length);
61
+ if (token === "--base") i += 1;
62
+ if (value === undefined || value === "" || value.startsWith("-")) {
63
+ throw new CliError("Error: Missing value for --base.", 2);
64
+ }
65
+ base = value;
66
+ baseSet = true;
67
+ continue;
68
+ }
69
+ if (token === "--branches" || token.startsWith("--branches=")) {
70
+ if (token.startsWith("--branches=")) {
71
+ const value = token.slice("--branches=".length);
72
+ if (value === "" || value.startsWith("-")) {
73
+ throw new CliError("Error: Missing value for --branches.", 2);
74
+ }
75
+ targets.push(value);
76
+ continue;
77
+ }
78
+ const next = tokens[i + 1];
79
+ if (next === undefined || next.startsWith("-")) {
80
+ throw new CliError("Error: Missing value for --branches.", 2);
81
+ }
82
+ while (i + 1 < tokens.length && !tokens[i + 1].startsWith("--")) {
83
+ i += 1;
84
+ if (tokens[i].startsWith("-")) {
85
+ throw new CliError("Error: Missing value for --branches.", 2);
86
+ }
87
+ targets.push(tokens[i]);
88
+ }
89
+ continue;
90
+ }
91
+ if (token.startsWith("--")) {
92
+ throw new CliError(`Error: Unknown option: ${token}.`, 2);
93
+ }
94
+ targets.push(token);
95
+ }
96
+
97
+ if (!baseSet) {
98
+ throw new CliError("Error: --base <branch> is required.", 2);
99
+ }
100
+ if (targets.length === 0) {
101
+ throw new CliError("Error: at least one target branch is required.", 2);
102
+ }
103
+ if (stack) {
104
+ const seen = new Set();
105
+ for (const target of targets) {
106
+ if (seen.has(target)) {
107
+ throw new CliError(`Error: duplicate target branch: ${target}`, 2);
108
+ }
109
+ seen.add(target);
110
+ }
111
+ }
112
+
113
+ return {
114
+ help: false,
115
+ base,
116
+ targets: stack ? targets : dedupe(targets),
117
+ stack,
118
+ fetch,
119
+ gitignore,
120
+ };
121
+ }
122
+
123
+ function dedupe(targets) {
124
+ const seen = new Set();
125
+ const kept = [];
126
+ for (const target of targets) {
127
+ if (seen.has(target)) continue;
128
+ seen.add(target);
129
+ kept.push(target);
130
+ }
131
+ return kept;
132
+ }
package/src/errors.js ADDED
@@ -0,0 +1,7 @@
1
+ export class CliError extends Error {
2
+ constructor(message, exitCode = 2) {
3
+ super(message);
4
+ this.name = "CliError";
5
+ this.exitCode = exitCode;
6
+ }
7
+ }
package/src/git.js ADDED
@@ -0,0 +1,227 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { CliError } from "./errors.js";
6
+ import { conflictRegions } from "./report.js";
7
+
8
+ const AUTHOR_ENV = {
9
+ GIT_AUTHOR_NAME: "yf-merge-check",
10
+ GIT_COMMITTER_NAME: "yf-merge-check",
11
+ GIT_AUTHOR_EMAIL: "yf-merge-check@localhost",
12
+ GIT_COMMITTER_EMAIL: "yf-merge-check@localhost",
13
+ };
14
+
15
+ export function spawnGit(args, options = {}) {
16
+ return new Promise((resolve, reject) => {
17
+ const child = spawn("git", args, {
18
+ cwd: options.cwd,
19
+ windowsHide: true,
20
+ env: {
21
+ ...process.env,
22
+ GIT_MERGE_AUTOEDIT: "no",
23
+ GIT_EDITOR: "true",
24
+ ...options.env,
25
+ },
26
+ stdio: ["ignore", "pipe", "pipe"],
27
+ });
28
+ const stdout = [];
29
+ const stderr = [];
30
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
31
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
32
+ child.on("error", (err) => reject(err));
33
+ child.on("close", (code) => {
34
+ resolve({
35
+ code: code ?? 1,
36
+ stdout: Buffer.concat(stdout).toString("utf8"),
37
+ stderr: Buffer.concat(stderr).toString("utf8"),
38
+ });
39
+ });
40
+ });
41
+ }
42
+
43
+ export async function runGit(spawnImpl, args, options = {}) {
44
+ let result;
45
+ try {
46
+ result = await spawnImpl(args, options);
47
+ } catch (err) {
48
+ if (err && err.code === "ENOENT") {
49
+ throw new CliError("Error: git is not available.", 2);
50
+ }
51
+ throw err;
52
+ }
53
+ return result;
54
+ }
55
+
56
+ export async function repoTop(spawnImpl, cwd) {
57
+ const result = await runGit(spawnImpl, ["rev-parse", "--show-toplevel"], { cwd });
58
+ if (result.code !== 0) {
59
+ throw new CliError("Error: Not a git repository.", 2);
60
+ }
61
+ return result.stdout.trim();
62
+ }
63
+
64
+ export async function fetchAll(spawnImpl, toplevel) {
65
+ const result = await runGit(spawnImpl, ["fetch", "--all", "--prune"], { cwd: toplevel });
66
+ if (result.code !== 0) {
67
+ const detail = result.stderr.trim() || result.stdout.trim();
68
+ const error = new CliError("Error: git fetch failed.", 2);
69
+ error.detail = detail;
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ export async function resolveName(spawnImpl, name, toplevel) {
75
+ const candidates = [`refs/heads/${name}`, `refs/remotes/origin/${name}`, name];
76
+ for (let index = 0; index < candidates.length; index += 1) {
77
+ const candidate = candidates[index];
78
+ const verified = await runGit(spawnImpl, ["rev-parse", "--verify", "--quiet", candidate], { cwd: toplevel });
79
+ if (verified.code !== 0) continue;
80
+ const short = await runGit(spawnImpl, ["rev-parse", "--short=7", candidate], { cwd: toplevel });
81
+ if (short.code !== 0 || !short.stdout.trim()) continue;
82
+ return {
83
+ name,
84
+ ref: index === 2 ? name : candidate,
85
+ sha: short.stdout.trim(),
86
+ };
87
+ }
88
+ throw new CliError(`Error: Branch not found: ${name}.`, 2);
89
+ }
90
+
91
+ export async function mergeTargets({ spawnImpl, toplevel, base, targets, stack }) {
92
+ if (!stack) {
93
+ const results = [];
94
+ for (const target of targets) {
95
+ results.push(await mergeOne(spawnImpl, toplevel, base.ref, target));
96
+ }
97
+ return results;
98
+ }
99
+ return mergeStack(spawnImpl, toplevel, base.ref, targets);
100
+ }
101
+
102
+ async function mergeOne(spawnImpl, toplevel, baseRef, target) {
103
+ const dir = await mkdtemp(path.join(os.tmpdir(), "yf-merge-check-"));
104
+ try {
105
+ await addWorktree(spawnImpl, toplevel, dir, baseRef);
106
+ const merged = await runGit(
107
+ spawnImpl,
108
+ ["-C", dir, "merge", "--no-commit", "--no-ff", target.ref],
109
+ { cwd: toplevel },
110
+ );
111
+ return { name: target.name, ...(await describeMerge(spawnImpl, toplevel, dir, merged)) };
112
+ } finally {
113
+ await removeWorktree(spawnImpl, toplevel, dir);
114
+ }
115
+ }
116
+
117
+ async function mergeStack(spawnImpl, toplevel, baseRef, targets) {
118
+ const dir = await mkdtemp(path.join(os.tmpdir(), "yf-merge-check-"));
119
+ const results = [];
120
+ let stoppedAt = null;
121
+ try {
122
+ await addWorktree(spawnImpl, toplevel, dir, baseRef);
123
+ for (const target of targets) {
124
+ if (stoppedAt) {
125
+ results.push({ name: target.name, status: "not-run", lines: 0, stoppedAt });
126
+ continue;
127
+ }
128
+ const merged = await runGit(
129
+ spawnImpl,
130
+ ["-C", dir, "merge", "--no-commit", "--no-ff", target.ref],
131
+ { cwd: toplevel },
132
+ );
133
+ const described = await describeMerge(spawnImpl, toplevel, dir, merged);
134
+ results.push({ name: target.name, ...described });
135
+ if (described.status !== "clean") {
136
+ stoppedAt = target.name;
137
+ continue;
138
+ }
139
+ if (!isAlreadyUpToDate(merged)) {
140
+ const committed = await runGit(
141
+ spawnImpl,
142
+ ["-C", dir, "-c", "commit.gpgsign=false", "commit", "--no-edit", "-m", `yf-merge-check: ${target.name}`],
143
+ { cwd: toplevel, env: AUTHOR_ENV },
144
+ );
145
+ if (committed.code !== 0) {
146
+ const message = (committed.stderr.trim() || committed.stdout.trim());
147
+ results[results.length - 1] = {
148
+ name: target.name,
149
+ status: "failed",
150
+ lines: 0,
151
+ message,
152
+ };
153
+ stoppedAt = target.name;
154
+ }
155
+ }
156
+ }
157
+ } finally {
158
+ await removeWorktree(spawnImpl, toplevel, dir);
159
+ }
160
+ return results;
161
+ }
162
+
163
+ async function addWorktree(spawnImpl, toplevel, dir, baseRef) {
164
+ const added = await runGit(spawnImpl, ["worktree", "add", "--detach", dir, baseRef], { cwd: toplevel });
165
+ if (added.code !== 0) {
166
+ const text = added.stderr.trim() || added.stdout.trim() || "git worktree add failed";
167
+ const sentence = text.endsWith(".") ? text : `${text}.`;
168
+ throw new CliError(`Error: ${sentence}`, 2);
169
+ }
170
+ }
171
+
172
+ async function removeWorktree(spawnImpl, toplevel, dir) {
173
+ try {
174
+ await runGit(spawnImpl, ["worktree", "remove", "--force", dir], { cwd: toplevel });
175
+ } catch {
176
+ // The directory removal below still runs.
177
+ }
178
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
179
+ }
180
+
181
+ async function describeMerge(spawnImpl, toplevel, dir, merged) {
182
+ if (merged.code === 0) {
183
+ return { status: "clean", lines: 0, files: [] };
184
+ }
185
+ const listed = await runGit(
186
+ spawnImpl,
187
+ ["-C", dir, "diff", "--name-only", "--diff-filter=U"],
188
+ { cwd: toplevel },
189
+ );
190
+ const names = listed.stdout.split(/\r?\n/).map((name) => name.trim()).filter(Boolean);
191
+ if (names.length === 0) {
192
+ return {
193
+ status: "failed",
194
+ lines: 0,
195
+ files: [],
196
+ message: merged.stderr.trim() || merged.stdout.trim(),
197
+ };
198
+ }
199
+ const files = [];
200
+ for (const name of names) {
201
+ files.push({ path: name, ...(await readConflict(path.join(dir, name))) });
202
+ }
203
+ const lines = files.reduce((sum, file) => sum + (file.binary ? 1 : file.regions.length), 0);
204
+ return { status: "conflict", lines, files };
205
+ }
206
+
207
+ async function readConflict(filePath) {
208
+ let bytes;
209
+ try {
210
+ bytes = await readFile(filePath);
211
+ } catch {
212
+ return { binary: true, regions: [] };
213
+ }
214
+ let text;
215
+ try {
216
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
217
+ } catch {
218
+ return { binary: true, regions: [] };
219
+ }
220
+ const regions = conflictRegions(text);
221
+ if (regions.length === 0) return { binary: true, regions: [] };
222
+ return { binary: false, regions };
223
+ }
224
+
225
+ function isAlreadyUpToDate(result) {
226
+ return `${result.stdout}\n${result.stderr}`.includes("Already up to date");
227
+ }
@@ -0,0 +1,34 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const PRESENT = new Set(["yf-merge/", "/yf-merge/", "yf-merge", "/yf-merge"]);
5
+
6
+ export async function updateGitignore(toplevel) {
7
+ const file = path.join(toplevel, ".gitignore");
8
+ try {
9
+ let text;
10
+ try {
11
+ text = await readFile(file, "utf8");
12
+ } catch (err) {
13
+ if (err.code !== "ENOENT") throw err;
14
+ text = null;
15
+ }
16
+ if (text === null || text.length === 0) {
17
+ await writeFile(file, "yf-merge/\n", "utf8");
18
+ return "added yf-merge/ to .gitignore";
19
+ }
20
+ const lines = text.split(/\r?\n/);
21
+ if (lines.some((line) => PRESENT.has(line.trim()))) {
22
+ return "yf-merge/ already in .gitignore";
23
+ }
24
+ const newline = text.includes("\r\n") ? "\r\n" : "\n";
25
+ let next = text;
26
+ if (!text.endsWith("\n") && !text.endsWith("\r")) next += newline;
27
+ next += `yf-merge/${newline}`;
28
+ await writeFile(file, next, "utf8");
29
+ return "added yf-merge/ to .gitignore";
30
+ } catch (err) {
31
+ err.gitignorePath = file;
32
+ throw err;
33
+ }
34
+ }
package/src/index.js ADDED
@@ -0,0 +1,81 @@
1
+ import { packageVersion, parseArgs, helpText } from "./args.js";
2
+ import { CliError } from "./errors.js";
3
+ import { fetchAll, mergeTargets, repoTop, resolveName, spawnGit } from "./git.js";
4
+ import { updateGitignore } from "./gitignore.js";
5
+ import { renderReport, writeReport } from "./report.js";
6
+
7
+ export async function run(argv, options = {}) {
8
+ const stdout = options.stdout ?? process.stdout;
9
+ const stderr = options.stderr ?? process.stderr;
10
+ const cwd = options.cwd ?? process.cwd();
11
+ const spawnImpl = options.spawnGit ?? spawnGit;
12
+ const now = options.now ?? (() => new Date());
13
+ const shouldExit = options.exit !== false;
14
+ let code = 2;
15
+ try {
16
+ code = await execute({ argv, stdout, stderr, cwd, spawnImpl, now });
17
+ } catch (err) {
18
+ if (err instanceof CliError && err.detail !== undefined) {
19
+ stderr.write("Error: git fetch failed.\n");
20
+ if (err.detail) stderr.write(`${err.detail}\n`);
21
+ code = 2;
22
+ } else {
23
+ const line = err instanceof CliError ? err.message : `Error: ${err.message}`;
24
+ stderr.write(line.endsWith("\n") ? line : `${line}\n`);
25
+ code = err instanceof CliError ? err.exitCode : 2;
26
+ }
27
+ }
28
+ if (shouldExit) process.exit(code);
29
+ return code;
30
+ }
31
+
32
+ async function execute({ argv, stdout, stderr, cwd, spawnImpl, now }) {
33
+ const args = parseArgs(argv);
34
+ if (args.help) {
35
+ stdout.write(helpText);
36
+ return 0;
37
+ }
38
+ if (args.version) {
39
+ stdout.write(`${packageVersion}\n`);
40
+ return 0;
41
+ }
42
+
43
+ const toplevel = await repoTop(spawnImpl, cwd);
44
+ if (args.fetch) await fetchAll(spawnImpl, toplevel);
45
+
46
+ const base = await resolveName(spawnImpl, args.base, toplevel);
47
+ const targets = [];
48
+ for (const name of args.targets) {
49
+ targets.push(await resolveName(spawnImpl, name, toplevel));
50
+ }
51
+
52
+ const results = await mergeTargets({
53
+ spawnImpl,
54
+ toplevel,
55
+ base,
56
+ targets,
57
+ stack: args.stack,
58
+ });
59
+ const when = now();
60
+ const mode = args.stack ? "stack" : "each target against the base";
61
+ await writeReport(cwd, when, renderReport({ when, mode, base, targets, results }));
62
+
63
+ const conflicted = results.reduce((sum, result) => {
64
+ if (result.status === "not-run") return sum;
65
+ return sum + result.lines;
66
+ }, 0);
67
+ const pass = results.every((result) => result.status === "clean");
68
+ stdout.write(`${pass ? "PASS" : "FAIL"} ${conflicted} conflicted lines\n`);
69
+
70
+ if (args.gitignore) {
71
+ try {
72
+ const note = await updateGitignore(toplevel);
73
+ stdout.write(`${note}\n`);
74
+ } catch (err) {
75
+ const file = err.gitignorePath ?? `${toplevel}/.gitignore`;
76
+ stderr.write(`Error: Cannot write ${file}: ${err.message}.\n`);
77
+ return 2;
78
+ }
79
+ }
80
+ return pass ? 0 : 1;
81
+ }
package/src/report.js ADDED
@@ -0,0 +1,126 @@
1
+ import { mkdir, readdir, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
5
+
6
+ export function formatStamp(date, utc) {
7
+ const day = utc ? date.getUTCDate() : date.getDate();
8
+ const month = MONTHS[utc ? date.getUTCMonth() : date.getMonth()];
9
+ const year = utc ? date.getUTCFullYear() : date.getFullYear();
10
+ const hour = utc ? date.getUTCHours() : date.getHours();
11
+ const minute = utc ? date.getUTCMinutes() : date.getMinutes();
12
+ const second = utc ? date.getUTCSeconds() : date.getSeconds();
13
+ return `${pad(day)}-${month}-${year}-${pad(hour)}-${pad(minute)}-${pad(second)}`;
14
+ }
15
+
16
+ export function fileDatePart(date) {
17
+ return `${pad(date.getDate())}${pad(date.getMonth() + 1)}${pad(date.getFullYear() % 100)}`;
18
+ }
19
+
20
+ export function backtickFence(text) {
21
+ let longest = 2;
22
+ for (const run of text.matchAll(/`+/g)) {
23
+ if (run[0].length > longest) longest = run[0].length;
24
+ }
25
+ return "`".repeat(longest + 1);
26
+ }
27
+
28
+ export function conflictRegions(text) {
29
+ const lines = text.split(/\r?\n/);
30
+ if (lines.length > 0 && lines[lines.length - 1] === "" && /\r?\n$/.test(text)) {
31
+ lines.pop();
32
+ }
33
+ const regions = [];
34
+ for (let i = 0; i < lines.length; i += 1) {
35
+ if (!lines[i].startsWith("<<<<<<<")) continue;
36
+ let end = i;
37
+ for (let j = i + 1; j < lines.length; j += 1) {
38
+ if (lines[j].startsWith("<<<<<<<")) {
39
+ end = j - 1;
40
+ break;
41
+ }
42
+ end = j;
43
+ if (lines[j].startsWith(">>>>>>>")) break;
44
+ }
45
+ regions.push({ line: i + 1, text: lines.slice(i, end + 1).join("\n") });
46
+ i = end;
47
+ }
48
+ return regions;
49
+ }
50
+
51
+ export function renderReport({ when, mode, base, targets, results }) {
52
+ const lines = [
53
+ "# yf-merge-check",
54
+ "",
55
+ `UTC: ${formatStamp(when, true)}`,
56
+ `System OS: ${formatStamp(when, false)}`,
57
+ "",
58
+ `Mode: ${mode}`,
59
+ "",
60
+ `Base: ${base.name} (${base.ref} @ ${base.sha})`,
61
+ "",
62
+ "Targets:",
63
+ "",
64
+ ];
65
+ for (const target of targets) {
66
+ lines.push(`- ${target.name} (${target.ref} @ ${target.sha})`);
67
+ }
68
+ lines.push("");
69
+ for (const result of results) {
70
+ lines.push(`## ${result.name}`, "");
71
+ if (result.status === "clean") {
72
+ lines.push("Result: clean", "Conflicted lines: 0", "");
73
+ } else if (result.status === "not-run") {
74
+ lines.push("Result: not run", `The chain stopped at ${result.stoppedAt}.`, "");
75
+ } else if (result.status === "failed") {
76
+ lines.push("Result: failed", "Conflicted lines: 0", "");
77
+ lines.push(...gitLines(result.message), "");
78
+ } else {
79
+ lines.push("Result: conflict", `Conflicted lines: ${result.lines}`, "");
80
+ for (const file of result.files) {
81
+ if (file.binary) lines.push(`- \`${file.path}\` — binary/tree conflict`);
82
+ else lines.push(`- \`${file.path}\` — ${file.regions.length}`);
83
+ }
84
+ lines.push("");
85
+ for (const file of result.files) {
86
+ if (file.binary) continue;
87
+ lines.push(`### ${file.path}`, "");
88
+ file.regions.forEach((region, index) => {
89
+ const fence = backtickFence(region.text);
90
+ lines.push(`#### Conflict ${index + 1}, line ${region.line}`, "", fence, region.text, fence, "");
91
+ });
92
+ }
93
+ }
94
+ }
95
+ return `${lines.join("\n").replace(/\n+$/, "")}\n`;
96
+ }
97
+
98
+ export async function writeReport(cwd, when, body) {
99
+ const dir = path.join(cwd, "yf-merge");
100
+ await mkdir(dir, { recursive: true });
101
+ const datePart = fileDatePart(when);
102
+ const pattern = new RegExp(`^report_${datePart}_(\\d+)\\.md$`);
103
+ let highest = 0;
104
+ for (const name of await readdir(dir)) {
105
+ const match = pattern.exec(name);
106
+ if (!match) continue;
107
+ const info = await stat(path.join(dir, name));
108
+ if (!info.isFile()) continue;
109
+ const value = Number(match[1]);
110
+ if (Number.isInteger(value) && value > highest) highest = value;
111
+ }
112
+ const filePath = path.join(dir, `report_${datePart}_${highest + 1}.md`);
113
+ await writeFile(filePath, body, "utf8");
114
+ return filePath;
115
+ }
116
+
117
+ function gitLines(message) {
118
+ const trimmed = message.trim();
119
+ if (!trimmed.includes("\n")) return [`git: ${trimmed}`];
120
+ const fence = backtickFence(trimmed);
121
+ return ["git:", "", fence, trimmed, fence];
122
+ }
123
+
124
+ function pad(value) {
125
+ return String(value).padStart(2, "0");
126
+ }