Skip to content

Commit 6ffec49

Browse files
committed
fix: ensure main tracks origin/main after clone
1 parent 7a15377 commit 6ffec49

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

lib/git_work/commands/clone.ex

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ defmodule GitWork.Commands.Clone do
4949
:ok <- fix_head(bare_dir, branch),
5050
:ok <- add_main_worktree(dir, branch),
5151
:ok <- configure_bare(bare_dir),
52-
:ok <- fetch_refs(bare_dir) do
52+
:ok <- fetch_refs(bare_dir),
53+
:ok <- ensure_upstream(dir, branch) do
5354
{:ok, Path.join(dir, branch)}
5455
end
5556
end
@@ -133,4 +134,33 @@ defmodule GitWork.Commands.Clone do
133134
{:error, msg} -> {:error, "worktree add failed: #{msg}"}
134135
end
135136
end
137+
138+
defp ensure_upstream(dir, branch) do
139+
worktree_dir = Path.join(dir, branch)
140+
141+
case Git.cmd(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], cd: worktree_dir) do
142+
{:ok, _} ->
143+
:ok
144+
145+
{:error, _} ->
146+
case Git.cmd(["show-ref", "--verify", "--quiet", "refs/remotes/origin/#{branch}"],
147+
cd: worktree_dir
148+
) do
149+
{:ok, _} ->
150+
case Git.cmd(["branch", "--set-upstream-to=origin/#{branch}", branch],
151+
cd: worktree_dir
152+
) do
153+
{:ok, _} ->
154+
:ok
155+
156+
{:error, msg} ->
157+
IO.write(:stderr, "warning: failed to set upstream for #{branch}: #{msg}\n")
158+
:ok
159+
end
160+
161+
{:error, _} ->
162+
:ok
163+
end
164+
end
165+
end
136166
end

test/git_work/commands/clone_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ defmodule GitWork.Commands.CloneTest do
4343
# git worktree list shows main
4444
{output, 0} = System.cmd("git", ["worktree", "list"], cd: Path.join(project, ".bare"))
4545
assert output =~ "main"
46+
47+
{upstream, 0} =
48+
System.cmd("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
49+
cd: main_path
50+
)
51+
52+
assert upstream =~ "origin/main"
4653
end
4754

4855
test "clone derives directory from URL", %{tmp: tmp} do

0 commit comments

Comments
 (0)