I am doing the following operations using the go-git/v5 golang library (keeping only the relevant err for brevity
repo, err := git.PlainOpen(pathToRepo)
wTree, err := repo.Worktree()
referenceName := plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", dstBranch))
currentBranch, err := repo.Head()
if currentBranch.Name() != referenceName {
// checkout new branch
checkoutOpts := git.CheckoutOptions{
Branch: referenceName,
Create: true,
Keep: true,
}
if err = wTree.Checkout(&checkoutOpts); err != nil {
return fmt.Errorf("failed to checkout branch %s: %w", dstBranch, err)
}
}
// add files to index
if _, err = wTree.Add("."); err != nil {
return fmt.Errorf("failed to add to worktree: %w", err)
}
commitOpts := git.CommitOptions{
All: true,
Author: signature,
}
if _, err = wTree.Commit(commitMsg, &commitOpts); err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
auth, err := GitAuth(keyPath)
if err != nil {
return fmt.Errorf("failed to authenticate to git using key %s: %w", keyPath, err)
}
// perform git push
pushOptions := git.PushOptions{
RemoteName: "origin",
Auth: auth,
}
if err = repo.Push(&pushOptions); err != nil {
return fmt.Errorf("failed git push operation: %w", err)
}
This is the one that fails
if err = repo.Push(&pushOptions); err != nil
Prior to the above commands, another function modified some files in repoPath.
If after the failure I go manually to repoPath to execute git push (the changes are pushed (!!))
It becomes more interesting by the actual error msg:
failed git push operation: non-fast-forward update: refs/heads/lalabranch
lalabranch is NOT the value of referenceName (which I am actually performing the operations on) but rather of another local (with a corresponding remote) branch.
Why is this happening and why the discrepancy with the actual git commands?