package main import ( "bufio" "fmt" "path" "strings" "src.opensuse.org/autogits/common" ) func prGitBranchNameForPR(req *common.PullRequestWebhookEvent) string { return fmt.Sprintf("PR_%s#%d", req.Pull_Request.Base.Repo.Name, req.Pull_Request.Number) } func updateSubmoduleInPR(req *common.PullRequestWebhookEvent, git common.Git) { common.PanicOnError(git.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--checkout", "--depth", "1", req.Repository.Name)) common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, req.Repository.Name), "fetch", "--depth", "1", "origin", req.Pull_Request.Head.Sha)) common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, req.Repository.Name), "checkout", req.Pull_Request.Head.Sha)) } func processPrjGitPullRequestSync(req *common.PullRequestWebhookEvent) error { // req := h.Data.(*common.PullRequestAction) return nil } type PullRequestSynced struct{} func (o *PullRequestSynced) Process(req *common.PullRequestWebhookEvent, git common.Git, config *common.AutogitConfig) error { prjGitOrg, prjGitRepo, _ := config.GetPrjGit() if req.Repository.Owner.Username == prjGitOrg && req.Repository.Name == prjGitRepo { return processPrjGitPullRequestSync(req) } // need to verify that submodule in the PR for prjgit // is still pointing to the HEAD of the PR pr, err := Gitea.GetPullRequest(req.Repository.Owner.Username, req.Repository.Name, req.Number) if err != nil { return fmt.Errorf("Cannot fetch PR data from gitea: %w", err) } _, prs := common.ExtractDescriptionAndPRs(bufio.NewScanner(strings.NewReader(pr.Body))) if len(prs) != 1 { return fmt.Errorf("Package update associated with invalid number of projects. Expected 1. Got %d", len(prs)) } prjPr, err := Gitea.GetPullRequest(prs[0].Org, prs[0].Repo, prs[0].Num) if err != nil { return fmt.Errorf("Cannot get PrjGit PR in processPullRequestSync. Err: %w", err) } branchName := prGitBranchNameForPR(req) remote, err := git.GitClone(common.DefaultGitPrj, branchName, prjPr.Head.Repo.SSHURL) common.PanicOnError(err) commitId, ok := git.GitSubmoduleCommitId(common.DefaultGitPrj, req.Repository.Name, prjPr.Head.Sha) if !ok { return fmt.Errorf("Cannot fetch submodule commit id in prjgit for '%s'", req.Repository.Name) } // nothing changed, still in sync if commitId == req.Pull_Request.Head.Sha { common.LogDebug("commitID already match - nothing to do") return nil } common.LogDebug("Sync repo update. Old", commitId, " New", req.Pull_Request.Head.Sha) commitMsg := fmt.Sprintf(`Sync PR Update to %s`, req.Pull_Request.Head.Sha) common.LogDebug("Creating new commit msg:", commitMsg) // we need to update prjgit PR with the new head hash updateSubmoduleInPR(req, git) common.PanicOnError(git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", commitMsg)) common.PanicOnError(git.GitExec(common.DefaultGitPrj, "push", remote)) return nil }