go-git icon indicating copy to clipboard operation
go-git copied to clipboard

Checkout doesn't function like `git checkout <branch-name>` when switching to a remote branch

Open Ileriayo opened this issue 2 years ago • 4 comments

When you clone a repository with say master branch - git clone <https://some-repo-url> and then you try to checkout to a different branch that exists on remote - git checkout <remote-branch>, this switches to a new branch and the effect is like in the following example message Branch 'remote-branch' set up to track remote branch 'remote-branch' from 'origin'. Switched to a new branch 'remote-branch'

I tried this:

repo.Checkout(repoWorktree, &git.CheckoutOptions{
	Branch: some-branch-name,
	Keep:  true,
})

and

  1. It moves folders from one branch to the other, howbeit empty. This is not exactly the same effect as git checkout <branch-name> which just switches to a branch and sets it to track from origin (no extra folders).
  2. Setting keep: true on checkout shows un-committed changes (i.e., on checkout to another branch, it shows the files from the other branch as deleted when you do a git status). This is also not the same effect as traditional git checkout Is there a way to keep ONLY changes made on local files?

I also tried this approach https://github.com/go-git/go-git/issues/241, where I created a symbolic reference between local and remote branch to no avail

newReference := plumbing.NewSymbolicReference(localRefName, remoteRefName)
err = repo.Storer.SetReference(newReference)

Ileriayo avatar Sep 12 '22 07:09 Ileriayo

I am experiencing something similar where files that are present in <branch-name> that are not present in master are being removed when Checkout is called to switch into <branch-name>. The only recourse is to then call Reset after Checkout to undo the removal. I suspect the issue is actually coming from the Reset call that is happening within Checkout as I tried calling Reset directly and found the same behavior.

ttsapakos avatar Nov 28 '22 15:11 ttsapakos

Just curious if you've ended up making any progress on this? I am running into something similar myself.

	w, err := m.repo.Worktree()
	if err != nil {
		log.Print(err)
	}
	refName := plumbing.NewBranchReferenceName(m.choice)
	opts := git.CheckoutOptions{
		Branch: refName,
		Create: false,
		Force:  false,
	}

	e := w.Checkout(&opts)
	if e != nil {
		log.Print(e)
	}

What I notice is that if I checkout the branch associated with refName I will just maintain the unstaged commits and bring them along from branch-to-branch. What I would normally anticipate is that git checkout branch, with uncommited changes, will raise an error telling me to stash or commit those changes.

DennisTheMenace780 avatar Sep 27 '23 02:09 DennisTheMenace780

Any updates on this seems like its still an issue

aryan29 avatar Mar 20 '24 10:03 aryan29