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
86 changes: 84 additions & 2 deletions packages/host-service/src/runtime/git/refs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@ import { asLocalRef, asRemoteRef, resolveRef } from "./refs";

/**
* Mock git that knows about a fixed set of FULL refnames. Mirrors how
* `resolveRef` probes (always with `refs/heads/...` / `refs/remotes/.../...`
* / `refs/tags/...`).
* `resolveRef` looks refs up: branch enumeration via `for-each-ref`
* (which reports refnames exactly as stored, case-sensitively) and tag
* probes via `rev-parse --verify`.
*/
function createMockGit(existingFullRefs: Set<string>) {
return {
raw: mock(async (args: string[]) => {
if (args[0] === "for-each-ref") {
const prefixes = args.filter((arg) => arg.startsWith("refs/"));
const lines = [...existingFullRefs].filter((ref) =>
prefixes.some((prefix) => ref.startsWith(prefix)),
);
return lines.length > 0 ? `${lines.join("\n")}\n` : "";
}
if (args[0] === "rev-parse" && args[1] === "--verify") {
const ref = args[2]?.replace("^{commit}", "") ?? "";
if (existingFullRefs.has(ref)) {
Expand Down Expand Up @@ -121,6 +129,80 @@ describe("resolveRef — input shape contract", () => {
expect(r?.kind).toBe("head");
});

// Case drift: on case-insensitive filesystems a differently-cased branch
// name shares the existing branch's loose-ref file, so creating a
// "new" case-twin silently corrupts the existing branch. resolveRef must
// adopt the canonical casing instead of reporting a miss.
test("adopts canonical casing of an existing local branch", async () => {
const git = createMockGit(new Set(["refs/heads/Roshvan/fix-thing"]));
const r = await resolveRef(git, "roshvan/fix-thing");
expect(r?.kind).toBe("local");
if (r?.kind === "local") {
expect(r.shortName).toBe("Roshvan/fix-thing");
expect(r.fullRef).toBe("refs/heads/Roshvan/fix-thing");
}
});

test("adopts canonical casing of an existing remote branch", async () => {
const git = createMockGit(
new Set(["refs/remotes/origin/Roshvan/fix-thing"]),
);
const r = await resolveRef(git, "roshvan/fix-thing");
expect(r?.kind).toBe("remote-tracking");
if (r?.kind === "remote-tracking") {
expect(r.shortName).toBe("Roshvan/fix-thing");
expect(r.remoteShortName).toBe("origin/Roshvan/fix-thing");
expect(r.fullRef).toBe("refs/remotes/origin/Roshvan/fix-thing");
}
});

test("exact remote match beats a case-twin local branch", async () => {
const git = createMockGit(
new Set(["refs/heads/Foo", "refs/remotes/origin/foo"]),
);
const r = await resolveRef(git, "foo");
expect(r?.kind).toBe("remote-tracking");
if (r?.kind === "remote-tracking") {
expect(r.shortName).toBe("foo");
}
});

test("exact tag match beats a case-twin branch", async () => {
const git = createMockGit(new Set(["refs/heads/Foo", "refs/tags/foo"]));
const r = await resolveRef(git, "foo");
expect(r?.kind).toBe("tag");
});

test("`head` does not case-insensitively match refs/remotes/origin/HEAD", async () => {
const git = createMockGit(
new Set(["refs/remotes/origin/HEAD", "refs/heads/main"]),
);
expect(await resolveRef(git, "head")).toBeNull();
});

// A genuine for-each-ref failure must propagate, not degrade to "no
// branches" — masking it would make an existing branch look absent and let
// a case-twin be created (the bug this module exists to prevent).
test("propagates a for-each-ref failure instead of returning null", async () => {
const git = {
raw: mock(async (args: string[]) => {
if (args[0] === "for-each-ref") {
throw new Error("fatal: not a git repository");
}
throw new Error(`Unexpected raw args: ${args.join(" ")}`);
}),
} as never;
const originalWarn = console.warn;
console.warn = () => {};
try {
await expect(resolveRef(git, "foo")).rejects.toThrow(
"not a git repository",
);
} finally {
console.warn = originalWarn;
}
});

test("custom remote name probes that remote, not origin", async () => {
const git = createMockGit(new Set(["refs/remotes/upstream/foo"]));
const r = await resolveRef(git, "foo", { remote: "upstream" });
Expand Down
107 changes: 89 additions & 18 deletions packages/host-service/src/runtime/git/refs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,55 @@ async function refExists(git: SimpleGit, fullRef: string): Promise<boolean> {
}
}

/**
* Enumerate branch refnames as git stores them. Used instead of `rev-parse`
* probes because on a case-insensitive filesystem (macOS default) probing
* `refs/heads/foo` resolves the `refs/heads/Foo` file, hiding case drift.
*/
async function listBranchShortNames(
git: SimpleGit,
remote: string,
): Promise<{ local: string[]; remoteTracking: string[] }> {
const local: string[] = [];
const remoteTracking: string[] = [];
let raw: string;
try {
// A real git failure must not be masked as "no branches" — that hides an
// existing branch and lets a case-twin be created. (An empty repo isn't
// a failure: for-each-ref exits 0 with no output.)
raw = await git.raw([
"for-each-ref",
"--format=%(refname)",
"refs/heads/",
`refs/remotes/${remote}/`,
]);
} catch (error) {
console.warn("[host-service:git] for-each-ref failed in resolveRef", {
remote,
error,
});
throw error;
}
const remotePrefix = `refs/remotes/${remote}/`;
for (const refname of raw.trim().split("\n").filter(Boolean)) {
if (refname.startsWith("refs/heads/")) {
local.push(refname.slice("refs/heads/".length));
} else if (refname.startsWith(remotePrefix)) {
const name = refname.slice(remotePrefix.length);
if (name !== "HEAD") remoteTracking.push(name);
}
}
return { local, remoteTracking };
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function findCaseInsensitiveMatch(
names: string[],
input: string,
): string | null {
const lower = input.toLowerCase();
return names.find((name) => name.toLowerCase() === lower) ?? null;
}

export interface ResolveRefOptions {
/**
* Remote name to probe for remote-tracking refs. Defaults to "origin".
Expand Down Expand Up @@ -94,38 +143,60 @@ export async function resolveRef(
return options.headFallback ? { kind: "head" } : null;
}

// Local always wins: if a local branch literally named `<input>` exists
// (including names like `origin/foo`), it takes precedence. Probes against
// the full refname so the structural prefix removes any ambiguity.
const localRef = asLocalRef(trimmed);
if (await refExists(git, localRef)) {
return { kind: "local", fullRef: localRef, shortName: trimmed };
}
// Match against enumerated refnames so casing is authoritative. Exact
// matches keep precedence (local > remote-tracking); a case-insensitive
// match is a fallback tier that adopts the existing branch's canonical
// casing rather than minting a case-twin sharing its loose-ref file.
const branches = await listBranchShortNames(git, remote);

// For the remote probe, accept both bare names (`foo`) and the natural
// For the remote form, accept both bare names (`foo`) and the natural
// short form (`origin/foo`). Strip the `<remote>/` prefix only if it's
// present in the input — without this, `origin/foo` would probe
// present in the input — without this, `origin/foo` would look up
// `refs/remotes/origin/origin/foo` and miss.
const remotePrefix = `${remote}/`;
const remoteShortName = trimmed.startsWith(remotePrefix)
? trimmed.slice(remotePrefix.length)
: trimmed;
const remoteRef = asRemoteRef(remote, remoteShortName);
if (await refExists(git, remoteRef)) {
return {
kind: "remote-tracking",
fullRef: remoteRef,
shortName: remoteShortName,
remote,
remoteShortName: `${remote}/${remoteShortName}`,
};

const asLocal = (name: string): ResolvedRef => ({
kind: "local",
fullRef: asLocalRef(name),
shortName: name,
});
const asRemoteTracking = (name: string): ResolvedRef => ({
kind: "remote-tracking",
fullRef: asRemoteRef(remote, name),
shortName: name,
remote,
remoteShortName: `${remote}/${name}`,
});

if (branches.local.includes(trimmed)) {
return asLocal(trimmed);
}

if (branches.remoteTracking.includes(remoteShortName)) {
return asRemoteTracking(remoteShortName);
}

const tagRef: `refs/tags/${string}` = `refs/tags/${trimmed}`;
if (await refExists(git, tagRef)) {
return { kind: "tag", fullRef: tagRef, shortName: trimmed };
}
Comment on lines 182 to 185

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does git rev-parse --verify on a loose tag ref resolve case-insensitively on a case-insensitive filesystem (e.g. macOS APFS)?

💡 Result:

Yes, git rev-parse --verify can resolve loose refs (such as tags) case-insensitively when running on a case-insensitive filesystem like macOS APFS [1][2][3]. This occurs because Git's ref resolution mechanism relies on the underlying filesystem to locate loose ref files [1][2][3]. On case-insensitive filesystems, the operating system treats files with different casing as the same file, allowing Git to inadvertently "find" a ref even if the provided name does not match the actual casing of the file on disk [1][2][3]. This behavior is not a deliberate feature of Git's revision parsing logic, but rather an artifact of the interaction between Git's storage architecture and the filesystem [1][2]. Key technical consequences include: 1. Ambiguity and Misresolution: In complex scenarios—most notably with linked worktrees—this can lead to critical errors [2][4]. For example, if a user attempts to resolve a ref like "head" (lowercase) on a case-insensitive system, it may inadvertently resolve to the wrong ref (such as the main worktree's HEAD instead of a linked worktree's specific HEAD) because the OS successfully opens the file path for the main HEAD [2][4]. 2. Inconsistency: While Git generally treats refs as case-sensitive internally, the reliance on the filesystem for loose refs means that operations may behave differently depending on whether the ref is loose (on disk) or packed (in the packed-refs file) [1][2]. Packed-refs typically require exact, case-sensitive matching because Git performs the search against the contents of the packed-refs file rather than the filesystem [1][2]. 3. Recommended Practice: Because of these risks, it is widely recommended to avoid creating refs that differ only by case and to always use the exact casing (e.g., "HEAD" rather than "head") when referencing them [1][5][3]. Note that while some specific commands like git tag --list allow for explicit case-insensitive sorting or filtering [6][7], this is an application-level feature and distinct from the filesystem-induced behavior observed during general ref resolution [1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the relevant symbols and surrounding code.
rg -n "refExists|listBranchShortNames|planBranchSource|refs/tags|refs/heads" packages/host-service/src/runtime/git/refs.ts packages/host-service/src/runtime/git/workspaces.ts

echo
echo "---- refs.ts outline ----"
ast-grep outline packages/host-service/src/runtime/git/refs.ts --view expanded

echo
echo "---- workspaces.ts outline ----"
ast-grep outline packages/host-service/src/runtime/git/workspaces.ts --view expanded

Repository: superset-sh/superset

Length of output: 1820


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the specific implementations around the tag/branch probes.
sed -n '1,260p' packages/host-service/src/runtime/git/refs.ts
echo
sed -n '280,360p' packages/host-service/src/runtime/git/workspaces.ts

Repository: superset-sh/superset

Length of output: 7671


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the call site and tag handling paths in the current tree.
rg -n "BAD_REQUEST|kind: \"tag\"|resolveRef\\(|resolveBranch|resolve.*Ref|checkout" packages -g '*.ts' -g '*.tsx'

echo
echo "---- files mentioning resolveRef ----"
rg -n "resolveRef\\(" packages -g '*.ts' -g '*.tsx'

Repository: superset-sh/superset

Length of output: 27650


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the workspace call site and the ref tests for tag/branch edge cases.
sed -n '290,345p' packages/host-service/src/trpc/router/workspaces/workspaces.ts
echo
sed -n '1,240p' packages/host-service/src/runtime/git/refs.test.ts

Repository: superset-sh/superset

Length of output: 9015


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check whether tag enumeration is already used anywhere else and whether refs.md documents tags.
rg -n "for-each-ref|refs/tags/|tag" packages/host-service/src/runtime/git packages/host-service/src/trpc/router/workspaces -g '*.ts' -g '*.md'

Repository: superset-sh/superset

Length of output: 2484


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '290,345p' packages/host-service/src/trpc/router/workspaces/workspaces.ts
echo
sed -n '1,240p' packages/host-service/src/runtime/git/refs.test.ts

Repository: superset-sh/superset

Length of output: 9015


Tag lookup should avoid loose-ref probing

refExists(git, tagRef) can still resolve a differently-cased loose tag on case-insensitive filesystems, so resolveRef may classify a branch as kind: "tag" and hit the BAD_REQUEST path in planBranchSource before the branch fallback runs. Enumerate tags too, or document that tag lookup is intentionally exact-only.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/runtime/git/refs.ts` around lines 179 - 182, Tag
detection in resolveRef is still relying on refExists for refs/tags/${trimmed},
which can match a differently-cased loose ref on case-insensitive filesystems
and misclassify branches as tags. Update the tag lookup in resolveRef to
enumerate actual tags (or otherwise perform an exact-only tag match) before
returning kind: "tag", and ensure the branch fallback in planBranchSource is
still reachable when no exact tag exists.


const localTwin = findCaseInsensitiveMatch(branches.local, trimmed);
if (localTwin) {
return asLocal(localTwin);
}

const remoteTwin = findCaseInsensitiveMatch(
branches.remoteTracking,
remoteShortName,
);
if (remoteTwin) {
return asRemoteTracking(remoteTwin);
}

return options.headFallback ? { kind: "head" } : null;
}

Expand Down
Loading
Loading