Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ flowchart TD

git-fi supports two commit-message formats for the fi branch: the **preferred** terse format (`STORAGE-01`) and a **legacy** git-merge format (`STORAGE-03`). git-fi reads and round-trips either one (`STORAGE-02`, `STORAGE-03`); which one it *writes* is governed by `STORAGE-04`. In the terse format, `shorthash` is the short hash of the default branch tip.

**CI mode** — see [CI Integration](#ci-integration) for the commit message format when running in a pipeline.
**Message shape**: see [Message Shape](#message-shape) (`STORAGE-05`) for the paragraphs every fi commit message carries, and [CI Integration](#ci-integration) for the build line it opens with in a pipeline.

### Success Output

Expand Down Expand Up @@ -591,6 +591,22 @@ When parsing the fi branch's commit message, if this legacy format is detected

> **Rollout note.** git-fi writes `legacy` for now so downstream consumers that parse the fi commit message keep working unchanged. The switch to writing the preferred terse format (`STORAGE-01`) is scheduled for after the rollout window (~2026-09) — a one-line change to the default write format. Reading is unaffected by the switch; both formats are always accepted.

### Message Shape

`STORAGE-05` The fi commit message shall be up to three paragraphs separated by blank lines, in this order:

1. The pipeline line, in CI only (`MERGE-13`).
2. What the operation changed, compared with the branch list read from `origin/fi` before it: `Added <names>.`, `Removed <names>.`, or `Added <names>; removed <names>.`, with names comma-separated in the order fi lists them. A removal covers every branch that leaves fi, whether by `--remove`, `--force`, or pruning (`MERGE-06`, `MERGE-07`). When the list is unchanged, as on a plain rebuild, the paragraph is omitted.
3. The signature in the current write format (`STORAGE-04`).

```text
Added cool-feature-branch-2; removed old-branch.

Merge remote-tracking branches 'origin/feature-a' and 'origin/cool-feature-branch-2' into fi
```

The signature is always the final paragraph, and it is the only one git-fi parses (`STORAGE-02`, `STORAGE-03`). The change paragraph names branches bare, never as `'origin/<name>'`, so a reader that scans the whole message for that form (as the Ruby gem's `latest_merged_branches` did) cannot take a removed branch as still in fi. No text from the previous fi commit is carried forward, so the message's size depends only on the operation.

## Default Branch Detection

`BRANCH-05` git-fi shall determine the mainline branch for the repository (typically `main` or `master`) via `git symbolic-ref refs/remotes/origin/HEAD`, extracting the last path component. If the symbolic ref is not set, then git-fi shall fall back to probing `origin/main` and `origin/master`.
Expand Down Expand Up @@ -677,15 +693,17 @@ Where the emoji will not be drawn as a glyph, the word is shown instead (`TERM-1

## CI Integration

`MERGE-13` When git-fi runs inside a GitLab CI pipeline (detected via the `CI` environment variable), git-fi shall include pipeline context in the commit message for traceability:
`MERGE-13` When git-fi runs inside a GitLab CI pipeline (detected via the `CI` environment variable), git-fi shall open the commit message with a pipeline line for traceability, ahead of the paragraphs `STORAGE-05` defines:

```text
Re-merge fi branch triggered by build <CI_PIPELINE_ID> due to commit on <CI_COMMIT_REF_NAME>. Was originally: --- <previous_fi_commit_message>
Re-merge fi branch triggered by build <CI_PIPELINE_ID> due to commit on <CI_COMMIT_REF_NAME>.

Removed branch-b.

(branch-a, branch-b)@[shorthash]
(branch-a)@[shorthash]
```

The trailing signature line — written in the current write format (`STORAGE-04`; the example above shows the preferred terse format) — ensures round-tripping works (`STORAGE-02`, `STORAGE-03`) even when the previous commit message is embedded in the `Was originally:` preamble.
The pipeline ID is the trace back to the build that wrote the commit (the example shows the preferred terse signature; the write format is `STORAGE-04`'s). A `fi` commit written by an earlier version embeds every previous message in its preamble; since git-fi parses only the final paragraph, it still yields its current branch list, and the next re-merge replaces it with the `STORAGE-05` shape.

| Variable | Purpose |
|----------------------|----------------------------------------------------------------|
Expand Down
5 changes: 3 additions & 2 deletions STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,11 @@ Merge Process

| ID | Description | Status | Location |
|-------|-----------------------|---------|-------------------------|
| STORAGE-01 | Preferred (terse) format | Covered | `src/merge.ts` (`buildTerseSignature`) |
| STORAGE-01 | Preferred (terse) format | Covered | `src/merge.ts` (`buildSignature`) |
| STORAGE-02 | Parsing (reads both) | Covered | `src/git.ts` (`parseBranchList`) |
| STORAGE-03 | Legacy format + read detection | Covered | `src/git.ts` (`detectCommitFormat`, `parseBranchList`), `src/merge.ts` (`buildLegacyMessage`) |
| STORAGE-03 | Legacy format + read detection | Covered | `src/git.ts` (`detectCommitFormat`, `parseBranchList`), `src/merge.ts` (`buildSignature`) |
| STORAGE-04 | Write format pinned to legacy for rollout | Covered | `src/merge.ts` (`DEFAULT_WRITE_FORMAT`, `mergeProcess`) |
| STORAGE-05 | Message shape and change paragraph | Covered | `src/merge.ts` (`buildCommitMessage`, `describeChange`) |

## `FORMAT`

Expand Down
10 changes: 7 additions & 3 deletions docs/ci-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,18 @@ One caveat for CI specifically: in a shallow clone git counts only within the fe

## Pipeline context in CI

When git-fi runs inside a CI pipeline (`CI=true`), commit messages include pipeline context:
When git-fi runs inside a CI pipeline (`CI=true`), commit messages open with pipeline context:

```text
Re-merge fi branch triggered by build 12345 due to commit on feature-auth. Was originally: --- ...
Re-merge fi branch triggered by build 12345 due to commit on main.

(feature-auth, feature-search)@[a1b2c3d]
Removed feature-search.

(feature-auth)@[a1b2c3d]
```

The first line names the pipeline that wrote the commit, whose job log has the rebuild's outcome. The rest is what every fi commit carries ([Commit and push](merge-process.md#_7-commit-and-push)): what the run changed, then the branch list git-fi reads back. The [typical CI job](#typical-ci-workflow) runs `git fi -g`, which adds nothing, so in CI the change line names the branches it pruned, as here after `feature-search` merged to `main`. A rebuild that prunes nothing leaves it out.

The variables below are GitLab CI's predefined names; a future forge integration would read that forge's equivalents.

| Variable | Purpose |
Expand Down
4 changes: 3 additions & 1 deletion docs/merge-process.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,11 @@ Because each step names the branch it was merging, a failure already knows who i

### 7. Commit and push

The resulting tree is committed with `git commit-tree`, taking `origin/main` and each merged branch as its parents (the same shape a merge commit has), and a message that records the branches included in `fi`, so the list round-trips on the next run. git-fi currently writes the **legacy** standard git merge message:
The resulting tree is committed with `git commit-tree`, taking `origin/main` and each merged branch as its parents (the same shape a merge commit has), and a message that records the branches included in `fi`, so the list round-trips on the next run. Above the branch list, a line says which branches the run that wrote the commit added and removed; a rebuild that changed neither leaves it out. git-fi currently writes the branch list as the **legacy** standard git merge message:

```text
Added bugfix-nav; removed old-search.

Merge remote-tracking branches 'origin/feature-auth', 'origin/feature-search' and 'origin/bugfix-nav' into fi
```

Expand Down
8 changes: 2 additions & 6 deletions src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,8 @@ export function detectCommitFormat(commitMsg: string): CommitFormat {
}

export function parseBranchList(commitMsg: string, defBranch: string): string[] {
// The CI commit message (MERGE-13) is `<preamble>\n\n<signature>`, where the
// preamble embeds the previous fi message ("Was originally: ---") — which can
// itself quote branch names or carry an old signature line. git-fi always
// appends the signature it just wrote as the final paragraph, so parse only
// that paragraph; otherwise branches removed in this operation resurface from
// the embedded history and accumulate across CI re-merges.
// The signature is the final paragraph (STORAGE-05); text above it can name
// branches no longer in fi, so parse only that paragraph.
const sep = commitMsg.lastIndexOf("\n\n");
const sig = sep === -1 ? commitMsg : commitMsg.slice(sep + 2);

Expand Down
69 changes: 44 additions & 25 deletions src/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,46 +41,60 @@ import { branchJson, writeJson } from "./json.js";
// keep working; scheduled to switch to "terse" after the rollout (~2026-09).
const DEFAULT_WRITE_FORMAT: CommitFormat = "legacy";

function buildLegacyMessage(branches: string[]): string {
function buildSignature(
branches: string[],
defBranch: string,
format: CommitFormat
): string {
const shortNames = branches.map(localBranchName);
if (shortNames.length === 0) {
return "Merge remote-tracking branch into fi";
}
const quoted = shortNames.map((b) => `'origin/${b}'`);
if (quoted.length === 1) {
return `Merge remote-tracking branch ${quoted[0]} into fi`;
if (format === "legacy") {
if (shortNames.length === 0) {
return "Merge remote-tracking branch into fi";
}
const quoted = shortNames.map((b) => `'origin/${b}'`);
if (quoted.length === 1) {
return `Merge remote-tracking branch ${quoted[0]} into fi`;
}
const last = quoted.pop()!;
return `Merge remote-tracking branches ${quoted.join(", ")} and ${last} into fi`;
}
const last = quoted.pop()!;
return `Merge remote-tracking branches ${quoted.join(", ")} and ${last} into fi`;
}

function buildTerseSignature(branches: string[], defBranch: string): string {
const baseHash = git(["rev-parse", "--short", `origin/${defBranch}`])!;
const shortNames = branches.map(localBranchName);
if (shortNames.length === 0) return `@[${baseHash}]`;
return `(${shortNames.join(", ")})@[${baseHash}]`;
}

// Names are written bare, never as 'origin/<name>': a reader that scans the
// whole message for that form (the Ruby gem's did) would take a removed branch
// as still in fi.
function describeChange(prior: string[], branches: string[]): string | null {
const before = prior.map(localBranchName);
const after = branches.map(localBranchName);
const added = after.filter((b) => !before.includes(b));
const removed = before.filter((b) => !after.includes(b));
const clauses: string[] = [];
if (added.length > 0) clauses.push(`added ${added.join(", ")}`);
if (removed.length > 0) clauses.push(`removed ${removed.join(", ")}`);
if (clauses.length === 0) return null;
const sentence = clauses.join("; ");
return `${sentence[0].toUpperCase()}${sentence.slice(1)}.`;
}

function buildCommitMessage(
prior: string[],
branches: string[],
defBranch: string,
format: CommitFormat
): string {
const paragraphs: string[] = [];
if (process.env.CI) {
const pipelineId = process.env.CI_PIPELINE_ID || "unknown";
const refName = process.env.CI_COMMIT_REF_NAME || "unknown";
const previousMsg =
git(["log", "-1", "--format=%B", "origin/fi"], { allowFailure: true }) ||
"";
const signature = format === "legacy"
? buildLegacyMessage(branches)
: buildTerseSignature(branches, defBranch);
const preamble = `Re-merge fi branch triggered by build ${pipelineId} due to commit on ${refName}. Was originally: --- ${previousMsg.trim()}`;
return `${preamble}\n\n${signature}`;
paragraphs.push(`Re-merge fi branch triggered by build ${pipelineId} due to commit on ${refName}.`);
}

if (format === "legacy") return buildLegacyMessage(branches);
return buildTerseSignature(branches, defBranch);
const change = describeChange(prior, branches);
if (change !== null) paragraphs.push(change);
paragraphs.push(buildSignature(branches, defBranch, format));
return paragraphs.join("\n\n");
}

const ACTION_INITIAL: Record<string, string> = {
Expand Down Expand Up @@ -365,7 +379,12 @@ export async function mergeProcess(

if (outcome.outcome === "merged") {
updateProgress("committing");
const commitMsg = buildCommitMessage(mergeable, defBranch, commitFormat);
const commitMsg = buildCommitMessage(
currentFiBranches(defBranch),
mergeable,
defBranch,
commitFormat
);
// The parents a merge commit carries: the default branch fi is rebuilt
// from, then each branch in the order it was merged.
const parents = [defBranch, ...mergeable].flatMap((p) => [
Expand Down
125 changes: 125 additions & 0 deletions test/fi-message.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { test, beforeEach, afterEach, describe } from "node:test";
import assert from "node:assert/strict";
import { runFi, makeSandbox, type Sandbox } from "./helpers.ts";
import { parseBranchList } from "../src/git.ts";

const BOTH_SIGNATURE =
"Merge remote-tracking branches 'origin/feature-a' and 'origin/feature-b' into fi";

function ciEnv(pipelineId: number): Record<string, string> {
return {
CI: "true",
CI_PIPELINE_ID: String(pipelineId),
CI_COMMIT_REF_NAME: "feature-a",
};
}

function buildLine(pipelineId: number): string {
return `Re-merge fi branch triggered by build ${pipelineId} due to commit on feature-a.`;
}

function fiMessage(sb: Sandbox): string {
sb.git(["fetch", "--quiet", "origin"]);
return sb.git(["log", "-1", "--format=%B", "origin/fi"]);
}

describe("fi commit message (MERGE-13, STORAGE-05)", () => {
let sb: Sandbox;
beforeEach(() => {
sb = makeSandbox();
sb.pushBranch("feature-a", "a.txt", "a\n");
sb.pushBranch("feature-b", "b.txt", "b\n");
sb.bootstrapFi();
});
afterEach(() => sb.cleanup());

test("stays the same size across consecutive CI re-merges", () => {
let r = runFi(["--add", "feature-a", "feature-b"], sb.work, ciEnv(100));
assert.equal(r.status, 0, r.stderr);

let length: number | undefined;
for (let build = 101; build <= 106; build++) {
r = runFi(["--again"], sb.work, ciEnv(build));
assert.equal(r.status, 0, r.stderr);
const msg = fiMessage(sb);
assert.equal(msg, `${buildLine(build)}\n\n${BOTH_SIGNATURE}`);
length ??= msg.length;
assert.equal(msg.length, length);
assert.deepEqual(parseBranchList(msg, "main"), [
"origin/feature-a",
"origin/feature-b",
]);
}
});

test("one re-merge replaces an already-bloated message", () => {
let bloated = BOTH_SIGNATURE;
for (let build = 1; build <= 50; build++) {
bloated =
`Re-merge fi branch triggered by build ${build} due to commit on feature-a. ` +
`Was originally: --- ${bloated}\n\n${BOTH_SIGNATURE}`;
}
const tree = sb.git(["rev-parse", "origin/main^{tree}"]);
const sha = sb.git(["commit-tree", tree, "-p", "origin/main", "-m", bloated]);
sb.git(["push", "--quiet", "--force", "origin", `${sha}:refs/heads/fi`]);
sb.git(["fetch", "--quiet", "origin"]);

const r = runFi(["--again"], sb.work, ciEnv(51));
assert.equal(r.status, 0, r.stderr);
assert.equal(fiMessage(sb), `${buildLine(51)}\n\n${BOTH_SIGNATURE}`);
});

test("names what the operation changed, between the build line and the signature", () => {
let r = runFi(["--add", "feature-a"], sb.work, ciEnv(300));
assert.equal(r.status, 0, r.stderr);
assert.equal(
fiMessage(sb),
`${buildLine(300)}\n\nAdded feature-a.\n\n` +
"Merge remote-tracking branch 'origin/feature-a' into fi"
);

sb.pushBranch("feature-c", "c.txt", "c\n");
r = runFi(["--force", "feature-b", "feature-c"], sb.work, ciEnv(301));
assert.equal(r.status, 0, r.stderr);
const msg = fiMessage(sb);
assert.equal(
msg,
`${buildLine(301)}\n\nAdded feature-b, feature-c; removed feature-a.\n\n` +
"Merge remote-tracking branches 'origin/feature-b' and 'origin/feature-c' into fi"
);
assert.deepEqual(parseBranchList(msg, "main"), [
"origin/feature-b",
"origin/feature-c",
]);
});

test("a removed branch is named bare, so a whole-message scan cannot read it back", () => {
let r = runFi(["--add", "feature-a", "feature-b"], sb.work, ciEnv(200));
assert.equal(r.status, 0, r.stderr);
r = runFi(["--remove", "feature-b"], sb.work, ciEnv(201));
assert.equal(r.status, 0, r.stderr);

let msg = fiMessage(sb);
assert.match(msg, /^Removed feature-b\.$/m);
assert.deepEqual(
[...msg.matchAll(/'origin\/([^']+)'/g)].map((m) => m[1]),
["feature-a"]
);

r = runFi(["--again"], sb.work, ciEnv(202));
assert.equal(r.status, 0, r.stderr);
msg = fiMessage(sb);
assert.doesNotMatch(msg, /feature-b/);
assert.deepEqual(parseBranchList(msg, "main"), ["origin/feature-a"]);
});

test("outside CI, the change paragraph comes without a build line", () => {
let r = runFi(["--add", "feature-a", "feature-b"], sb.work);
assert.equal(r.status, 0, r.stderr);
assert.equal(fiMessage(sb), `Added feature-a, feature-b.\n\n${BOTH_SIGNATURE}`);

r = runFi(["--again"], sb.work);
assert.equal(r.status, 0, r.stderr);
assert.equal(fiMessage(sb), BOTH_SIGNATURE);
});
});
Loading