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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ wt update --cleanup
3. Detects parent branches via merge-base
4. Rebases feature branches in correct order — parents before children

**Fork workflow** — when `upstream` is set in config (see `wt init --upstream`), the default branch is fast-forwarded from `<upstream>/<default>` instead of `origin/<default>`. After a successful upstream sync, `post-update` hooks also run for the default branch (so you can, for example, push the synced default branch back to your fork).
**Fork workflow** — when `upstream` is set in config (see `wt init --upstream`), the default branch is synced from `<upstream>/<default>` instead of `origin/<default>`, whether it is fast-forwarded in its own worktree or updated by ref because no worktree has it checked out. After a successful upstream sync, `post-update` hooks also run for the default branch (so you can, for example, push the synced default branch back to your fork); with no worktree for the default branch they run in the repository root.

When `upstream` is **not** configured, an interactive `wt update` auto-detects candidate remotes (every remote except `origin`) the same way `wt init` does, and offers to save your choice:

Expand Down
86 changes: 86 additions & 0 deletions src/application/use-cases/update-worktrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1079,3 +1079,89 @@ describe("updateWorktrees — upstream sync", () => {
expect(shell.calls.find((c) => c.options.cwd === "/repo")).toBeUndefined();
});
});

// Whether the default branch happens to be checked out decides how it is updated
// (fast-forward vs. ref fetch) — it must not decide which remote it is updated
// from, nor whether post-update hooks run for it.
describe("updateWorktrees — upstream sync without a default-branch worktree", () => {
test("upstream set — updates the default branch ref from the upstream remote", async () => {
const updateBranchRefCalls: { branch: string; remote: string }[] = [];
const git = createFakeGit({
worktrees: [featureA],
updateBranchRefCalls,
...flatBranchesConfig([featureA]),
});

const result = await updateWorktrees({ dryRun: false, upstream: "upstream" }, { git });

const output = expectOk(result);
expect(output.defaultBranchUpdate).toBe("ref-updated");
expect(output.syncedFromUpstream).toBe("upstream");
expect(updateBranchRefCalls).toEqual([{ branch: "main", remote: "upstream" }]);
});

test("upstream unset — updates the default branch ref from the primary remote", async () => {
const updateBranchRefCalls: { branch: string; remote: string }[] = [];
const git = createFakeGit({
worktrees: [featureA],
updateBranchRefCalls,
...flatBranchesConfig([featureA]),
});

const result = await updateWorktrees({ dryRun: false }, { git });

const output = expectOk(result);
expect(output.syncedFromUpstream).toBeUndefined();
expect(updateBranchRefCalls).toEqual([{ branch: "main", remote: "origin" }]);
});

test("upstream set with post-update hook — runs the hook for the default branch in the repo root", async () => {
const git = createFakeGit({ worktrees: [featureA], ...flatBranchesConfig([featureA]) });
const shell = createFakeShell();

const result = await updateWorktrees(
{ dryRun: false, upstream: "upstream", postUpdateHooks: ["git push origin main"], repoRoot: "/repo" },
{ git, shell },
);

const output = expectOk(result);
const mainReport = output.reports.find((r) => r.branch === "main");
expect(mainReport?.result).toMatchObject({ status: "is-default-branch" });
expect(mainReport?.hookNotifications).toHaveLength(1);

// The default branch has no worktree, so the hook runs in the repo root.
const mainHookCall = shell.calls.find((c) => c.options.env?.WORKTREE_BRANCH === "main");
expect(mainHookCall?.options.cwd).toBe("/repo");
expect(mainHookCall?.options.env).toMatchObject({
WORKTREE_PATH: "/repo",
BASE_BRANCH: "upstream/main",
});
});

test("upstream unset — no hook runs for the default branch and it is not reported", async () => {
const git = createFakeGit({ worktrees: [featureA], ...flatBranchesConfig([featureA]) });
const shell = createFakeShell();

const result = await updateWorktrees(
{ dryRun: false, postUpdateHooks: ["git push"], repoRoot: "/repo" },
{ git, shell },
);

const output = expectOk(result);
expect(output.reports.find((r) => r.branch === "main")).toBeUndefined();
expect(shell.calls.find((c) => c.options.env?.WORKTREE_BRANCH === "main")).toBeUndefined();
});

test("dry run with upstream — no hook runs for the default branch", async () => {
const git = createFakeGit({ worktrees: [featureA], ...flatBranchesConfig([featureA]) });
const shell = createFakeShell();

const result = await updateWorktrees(
{ dryRun: true, upstream: "upstream", postUpdateHooks: ["git push origin main"], repoRoot: "/repo" },
{ git, shell },
);

expectOk(result);
expect(shell.calls).toEqual([]);
});
});
56 changes: 28 additions & 28 deletions src/application/use-cases/update-worktrees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ function buildRebaseOrder(worktrees: Worktree[], parentMap: Record<string, strin
}

async function runPostUpdateHooks(
wt: Worktree,
wt: { path: string; branch: string },
parent: string,
input: UpdateWorktreesInput,
deps: UpdateWorktreesDeps,
Expand Down Expand Up @@ -197,6 +197,9 @@ export async function updateWorktrees(
const goneSet = new Set(goneResult.success ? goneResult.data.filter((b) => b !== defaultBranch) : []);

const mainWorktree = worktrees.find((w) => w.branch === defaultBranch);
// Where default-branch work happens: its own worktree when it has one, else the
// repo root — the branch is then updated by ref and is checked out nowhere.
const defaultBranchPath = mainWorktree?.path ?? input.repoRoot ?? "";
let defaultBranchUpdate: "ff-updated" | "ref-updated";
let defaultBranchHookNotifications: Notification[] = [];
let syncedFromUpstream: string | undefined;
Expand All @@ -209,38 +212,33 @@ export async function updateWorktrees(
return R.err(new Error(`Failed to fast-forward ${defaultBranch}: ${ffResult.error.message}`));
}
defaultBranchUpdate = "ff-updated";

// When syncing the default branch from an upstream remote, run post-update hooks
// for the default branch too (mirrors the feature-branch path).
if (input.upstream) {
syncedFromUpstream = input.upstream;
if (!input.dryRun && input.postUpdateHooks?.length && deps.shell) {
const baseRef = `${input.upstream}/${defaultBranch}`;
const hookResult = await runHooks(
{
commands: input.postUpdateHooks,
context: {
worktreePath: mainWorktree.path,
branch: defaultBranch,
repoRoot: input.repoRoot ?? "",
baseBranch: baseRef,
},
},
{ shell: deps.shell },
);
if (hookResult.success) {
defaultBranchHookNotifications = hookResult.data.notifications;
}
}
}
} else {
const refResult = await git.updateBranchRef(defaultBranch);
// Same remote as the fast-forward path above: which remote is authoritative for
// the default branch must not depend on whether it happens to be checked out.
const refResult = input.upstream
? await git.updateBranchRef(defaultBranch, input.upstream)
: await git.updateBranchRef(defaultBranch);
if (!refResult.success) {
return R.err(new Error(`Failed to update ${defaultBranch} ref: ${refResult.error.message}`));
}
defaultBranchUpdate = "ref-updated";
}

// When syncing the default branch from an upstream remote, run post-update hooks
// for the default branch too (mirrors the feature-branch path). The branch was
// synced either way, so this does not depend on how it was updated.
if (input.upstream) {
syncedFromUpstream = input.upstream;
if (!input.dryRun && defaultBranchPath) {
defaultBranchHookNotifications = await runPostUpdateHooks(
{ path: defaultBranchPath, branch: defaultBranch },
`${input.upstream}/${defaultBranch}`,
input,
deps,
);
}
}

const parentMap: Record<string, string> = {};
const retargetMap: Record<string, string> = {};
for (const wt of worktrees) {
Expand All @@ -266,10 +264,12 @@ export async function updateWorktrees(
const reports: WorktreeReport[] = [];
const failedBranches = new Set<string>();

if (mainWorktree) {
// The default branch is reported when it has a worktree; without one there is
// nothing to rebase, but hook results still need somewhere to surface.
if (mainWorktree || defaultBranchHookNotifications.length > 0) {
reports.push({
branch: defaultBranch,
path: mainWorktree.path,
path: defaultBranchPath,
result: { status: "is-default-branch" },
hookNotifications: defaultBranchHookNotifications,
});
Expand Down
3 changes: 2 additions & 1 deletion src/domain/ports/git-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export interface GitPort {
listRemotes(): Promise<Result<string[], GitError>>;
listGoneBranches(): Promise<Result<string[], GitError>>;
mergeFFOnly(worktreePath: string, branch: string, remote?: string): Promise<Result<void, GitError>>;
updateBranchRef(branch: string): Promise<Result<void, GitError>>;
/** Fast-forward a local branch ref that is not checked out anywhere, from `remote` (default: primary remote). */
updateBranchRef(branch: string, remote?: string): Promise<Result<void, GitError>>;
rebase(
worktreePath: string,
onto: string,
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const main = defineCommand({
},
},
async setup({ args }) {
container = createContainer({
container = await createContainer({
verbose: args.verbose || process.env.WT_VERBOSE === "1",
nonInteractive: args["non-interactive"] || process.env.WT_NON_INTERACTIVE === "1",
});
Expand Down
Loading