Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

*Branch* functions of Repository are just manipulating .git/config so... #518

Closed
lkxed opened this issue Apr 16, 2022 · 0 comments
Closed

Comments

@lkxed
Copy link

lkxed commented Apr 16, 2022

If you want to check whether a local branch exists, you DON'T call Repository.Branch(name string) which returns a *config.Branch representing a branch in .git/config, which is a dead end.

Instead, you NEED to call Repository.Branchs() which returns a storer.ReferenceIter. Then you can call its ForEach to iterate and compare every Reference.Name() to get the result you want.

Here is an example:

func hasLocalBranch(branch string) bool {
	name := plumbing.NewBranchReferenceName(branch)
	return hasBranch(name)
}

func hasBranch(name plumbing.ReferenceName) bool {
	var exist bool
	if iter, err := repository.Branches(); err == nil {
		iterFunc := func(reference *plumbing.Reference) error {
			if name == reference.Name() {
				exist = true
				return nil
			}
			return nil
		}
		_ = iter.ForEach(iterFunc)
	}
	return exist
}

It took me a while to figure this out. Hope it helps.

@lkxed lkxed closed this as completed Apr 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant