This commit is contained in:
Lunny Xiao
2026-05-12 16:45:58 -07:00
parent 09bba53aec
commit 4266720a2e
4 changed files with 195 additions and 32 deletions
+31 -19
View File
@@ -6,6 +6,8 @@ package git
import (
"encoding/base64"
"fmt"
"os"
"os/exec"
"strings"
"unicode"
@@ -17,34 +19,28 @@ import (
// TeaCreateBranch creates a new branch in the repo, tracking from another branch.
func (r TeaRepo) TeaCreateBranch(localBranchName, remoteBranchName, remoteName string) error {
// save in .git/config to assign remote for future pulls
localBranchRefName := git_plumbing.NewBranchReferenceName(localBranchName)
err := r.CreateBranch(&git_config.Branch{
Name: localBranchName,
Merge: git_plumbing.NewBranchReferenceName(remoteBranchName),
Remote: remoteName,
})
if err != nil {
if _, err := r.Reference(localBranchRefName, true); err == nil {
return git.ErrBranchExists
} else if err != nil && err != git_plumbing.ErrReferenceNotFound {
return err
}
// serialize the branch to .git/refs/heads
remoteBranchRefName := git_plumbing.NewRemoteReferenceName(remoteName, remoteBranchName)
remoteBranchRef, err := r.Storer.Reference(remoteBranchRefName)
if err != nil {
return err
}
localHashRef := git_plumbing.NewHashReference(localBranchRefName, remoteBranchRef.Hash())
return r.Storer.SetReference(localHashRef)
return runGitCommand("branch", "--track", localBranchName, fmt.Sprintf("%s/%s", remoteName, remoteBranchName))
}
// TeaCheckout checks out the given branch in the worktree.
func (r TeaRepo) TeaCheckout(ref git_plumbing.ReferenceName) error {
tree, err := r.Worktree()
if err != nil {
return err
args := []string{"checkout"}
if ref.IsRemote() {
args = append(args, "--detach", ref.String())
} else if ref.IsBranch() {
args = append(args, ref.Short())
} else {
args = append(args, ref.String())
}
return tree.Checkout(&git.CheckoutOptions{Branch: ref})
return runGitCommand(args...)
}
// TeaDeleteLocalBranch removes the given branch locally
@@ -293,3 +289,19 @@ func isASCII(s string) bool {
}
return true
}
func runGitCommand(args ...string) error {
cmd := exec.Command("git", args...)
cmd.Env = os.Environ()
output, err := cmd.CombinedOutput()
if err == nil {
return nil
}
msg := strings.TrimSpace(string(output))
if msg == "" {
return fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
}
return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, msg)
}
+61 -13
View File
@@ -4,14 +4,19 @@
package task
import (
"encoding/base64"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"code.gitea.io/sdk/gitea"
"code.gitea.io/tea/modules/config"
local_git "code.gitea.io/tea/modules/git"
"code.gitea.io/tea/modules/utils"
"github.com/go-git/go-git/v5"
git_config "github.com/go-git/go-git/v5/config"
git_plumbing "github.com/go-git/go-git/v5/plumbing"
)
@@ -78,36 +83,30 @@ func doPRFetch(
localRemote *git.Remote,
callback func(string) (string, error),
) (string, error) {
_ = callback
localRemoteName := localRemote.Config().Name
localBranchName := pr.Head.Ref
// get auth & fetch remote via its configured protocol
url, err := localRepo.TeaRemoteURL(localRemoteName)
if err != nil {
return "", err
}
auth, err := local_git.GetAuthForURL(url, login.GetAccessToken(), login.SSHKey, callback)
if err != nil {
return "", err
}
fetchOpts := &git.FetchOptions{Auth: auth}
refspecs := []string{}
if isRemoteDeleted(pr) {
// When the head branch is already deleted, pr.Head.Ref points to
// `refs/pull/<idx>/head`, where the commits stay available.
// This ref must be fetched explicitly, and does not allow pushing, so we use it
// only in this case as fallback.
localBranchName = fmt.Sprintf("pulls/%d", pr.Index)
fetchOpts.RefSpecs = []git_config.RefSpec{git_config.RefSpec(fmt.Sprintf("%s:refs/remotes/%s/%s",
refspecs = append(refspecs, fmt.Sprintf("%s:refs/remotes/%s/%s",
pr.Head.Ref,
localRemoteName,
localBranchName,
))}
))
}
fmt.Printf("Fetching PR %v (head %s:%s) from remote '%s'\n", pr.Index, url, pr.Head.Ref, localRemoteName)
err = localRemote.Fetch(fetchOpts)
if err == git.NoErrAlreadyUpToDate {
fmt.Println(err)
} else if err != nil {
err = runGitFetch(localRemoteName, url.String(), login.GetAccessToken(), login.SSHKey, refspecs...)
if err != nil {
return "", err
}
return localBranchName, nil
@@ -160,3 +159,52 @@ func doPRCheckout(
fmt.Println(info)
return localRepo.TeaCheckout(checkoutRef)
}
func runGitFetch(remoteName, remoteURL, authToken, sshKey string, refspecs ...string) error {
args := []string{}
if authToken != "" && isHTTPRemote(remoteURL) {
args = append(args, "-c", "http.extraheader="+buildGitAuthHeader(authToken))
}
args = append(args, "fetch")
args = append(args, remoteName)
args = append(args, refspecs...)
cmd := exec.Command("git", args...)
cmd.Env = os.Environ()
if sshKey != "" && isSSHRemote(remoteURL) {
absKey, err := utils.AbsPathWithExpansion(sshKey)
if err != nil {
return err
}
cmd.Env = append(cmd.Env, "GIT_SSH_COMMAND=ssh -i "+strconv.Quote(absKey)+" -o IdentitiesOnly=yes")
}
output, err := cmd.CombinedOutput()
if err == nil {
trimmed := string(output)
if trimmed != "" {
fmt.Print(trimmed)
}
return nil
}
msg := string(output)
if msg == "" {
return fmt.Errorf("git fetch %s: %w", remoteName, err)
}
return fmt.Errorf("git fetch %s: %w: %s", remoteName, err, msg)
}
func buildGitAuthHeader(authToken string) string {
encoded := base64.StdEncoding.EncodeToString([]byte(authToken + ":"))
return "Authorization: Basic " + encoded
}
func isHTTPRemote(remoteURL string) bool {
return strings.HasPrefix(remoteURL, "http://") || strings.HasPrefix(remoteURL, "https://")
}
func isSSHRemote(remoteURL string) bool {
return strings.HasPrefix(remoteURL, "ssh://")
}