internal/control/refsupdated.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/control/refsupdated.go

315 lines · 11388 bytes

7 symbols in this file
  1package control
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"log/slog"
  8	"net/url"
  9	"path"
 10	"strings"
 11	"time"
 12
 13	"gitbay.org/gitbay/internal/ci"
 14	"gitbay.org/gitbay/internal/config"
 15	"gitbay.org/gitbay/internal/gitutil"
 16	"gitbay.org/gitbay/internal/policy"
 17	"gitbay.org/gitbay/internal/store"
 18)
 19
 20// RefsUpdated is the work that follows a ref update in repoID by userID,
 21// with a key or token of scope: post-receive runs it for every push, and
 22// a server-side write to a branch (an applied suggestion) runs it after
 23// its own ref update, so nothing a push triggers is skipped. A push to a
 24// source branch refreshes refs/merge-requests/N/head in every target
 25// repo, by fetching — the target owns the objects, so the MR outlives the
 26// fork. This is the only place a push writes outside its own repository.
 27func RefsUpdated(st *store.Store, cfg config.Config, repoID, userID int64, scope string, updates []policy.RefUpdate) {
 28	pushedRepo, pushedRepoErr := st.RepoByID(repoID)
 29	if pushedRepoErr == nil {
 30		adoptDefaultBranch(st, cfg, &pushedRepo, updates)
 31	}
 32	for _, u := range updates {
 33		// Every ref update is an event webhooks can subscribe to.
 34		st.RecordEvent(repoID, userID, "push", fmt.Sprintf(
 35			`{"ref":%q,"old":%q,"new":%q,"forced":%v,"deleted":%v}`,
 36			u.Ref, u.Old, u.New, u.IsForce, u.IsDelete))
 37
 38		// Any ref update — branch or tag — schedules the push mirrors.
 39		st.MarkMirrorsDirty(repoID, "push")
 40
 41		// Tag pushes run the tag-triggered CI jobs.
 42		if tag, ok := strings.CutPrefix(u.Ref, "refs/tags/"); ok && !u.IsDelete && pushedRepoErr == nil {
 43			QueueTagBuilds(st, cfg, pushedRepo, userID, tag, u.New)
 44		}
 45
 46		branch, ok := cutHeads(u.Ref)
 47		if !ok {
 48			continue
 49		}
 50		// Commits landing on the default branch act on issue references
 51		// in their messages (closes #N, plain #N).
 52		if pushedRepoErr == nil && branch == pushedRepo.DefaultBranch && !u.IsDelete {
 53			dir := RepoDir(cfg.Server.Root, pushedRepo.OwnerName, pushedRepo.Name)
 54			ProcessCommitMessages(st, dir, pushedRepo, userID, scope, u.Old, u.New)
 55			RecordLandedCommits(st, dir, pushedRepo, u.Old, u.New)
 56			// The symbol index is rebuilt by its worker, never here.
 57			st.RequestSymbolIndex(pushedRepo.ID, false)
 58		}
 59		// A branch push with a .gitbay/ci.yml queues one build per job.
 60		if pushedRepoErr == nil && !u.IsDelete {
 61			QueueBranchBuilds(st, cfg.Server.Root, cfg.Server.SiteURL,
 62				pushedRepo, userID, branch, u.Old, u.New, time.Now())
 63		}
 64		if u.IsForce {
 65			st.Audit(userID, "push.forced", map[string]any{
 66				"repo": repoID, "ref": u.Ref, "old": u.Old, "new": u.New})
 67		}
 68		mrs, err := st.OpenMRsBySource(repoID, branch)
 69		if err != nil {
 70			slog.Error("post-receive: listing MRs", "err", err)
 71			continue
 72		}
 73		srcRepo, err := st.RepoByID(repoID)
 74		if err != nil {
 75			continue
 76		}
 77		srcDir := RepoDir(cfg.Server.Root, srcRepo.OwnerName, srcRepo.Name)
 78		for _, mr := range mrs {
 79			target, err := st.RepoByID(mr.RepoID)
 80			if err != nil {
 81				continue
 82			}
 83			if u.IsDelete {
 84				if mr.State == "open" {
 85					st.SetMRState(mr.ID, "source_gone")
 86				}
 87				if mr.QueuedAt != "" {
 88					TryQueuedMerge(st, cfg, mr.ID) // dequeues: the source is gone
 89				}
 90				continue // head ref retained: the diff stays viewable
 91			}
 92			dstDir := RepoDir(cfg.Server.Root, target.OwnerName, target.Name)
 93			headRef := fmt.Sprintf("refs/merge-requests/%d/head", mr.Number)
 94			if err := gitutil.FetchInto(dstDir, srcDir, u.New, headRef); err != nil {
 95				slog.Error("post-receive: refreshing MR head", "mr", mr.Number, "err", err)
 96				continue
 97			}
 98			// The merge base as it stands now, so a later range-diff
 99			// compares each revision against the target it was written
100			// on rather than against today's. Best-effort: a base that
101			// cannot be worked out costs precision, not the record.
102			base, err := gitutil.MergeBase(dstDir, "refs/heads/"+mr.TargetRef, headRef)
103			if err != nil {
104				base = ""
105			}
106			if err := st.UpdateMRHead(mr.ID, u.New, base, sameChange(dstDir, mr, base, u.New)); err != nil {
107				slog.Error("post-receive: recording MR head", "mr", mr.Number, "err", err)
108			}
109			if srcRepo.ID != target.ID {
110				QueueMRBuilds(st, cfg.Server.Root, cfg.Server.SiteURL,
111					target, userID, mr.Number, u.New)
112			}
113			if mr.State == "source_gone" {
114				st.SetMRState(mr.ID, "open") // branch came back
115			}
116			// A queued merge stays queued across a push by someone who can
117			// merge it, and the new head has to pass the gates on its own.
118			if mr.QueuedAt != "" {
119				QueuedMergePushed(st, cfg, mr.ID, userID, scope)
120			}
121		}
122	}
123	// After every MR head above is refreshed, so a push carrying both a
124	// source branch and its target compares against the new head.
125	if pushedRepoErr == nil {
126		for _, u := range updates {
127			if branch, ok := cutHeads(u.Ref); ok && !u.IsDelete {
128				MarkLandedMRs(st, cfg, pushedRepo, userID, branch, u.Old, u.New)
129			}
130		}
131	}
132}
133
134// MarkLandedMRs records as merged each open or source_gone merge request
135// into branch whose head the move from old to new brought onto it: a
136// direct push, or the head riding in with another merge request (#330).
137// A head already on old is left alone.
138func MarkLandedMRs(st *store.Store, cfg config.Config, repo store.Repo, userID int64, branch, old, new string) {
139	mrs, err := st.UnmergedMRsByTarget(repo.ID, branch)
140	if err != nil {
141		slog.Error("post-receive: listing MRs by target", "err", err)
142		return
143	}
144	dir := RepoDir(cfg.Server.Root, repo.OwnerName, repo.Name)
145	var c *Ctx
146	for _, mr := range mrs {
147		head, err := gitutil.ResolveRef(dir, mrHeadRef(mr.Number))
148		if err != nil {
149			continue
150		}
151		if landed, err := gitutil.IsAncestor(dir, head, new); err != nil || !landed {
152			continue
153		}
154		base := ""
155		if !gitutil.ZeroSHA(old) {
156			if was, err := gitutil.IsAncestor(dir, head, old); err != nil || was {
157				continue
158			}
159			base, _ = gitutil.MergeBase(dir, old, head)
160		}
161		if err := st.MarkMerged(mr.ID, base, head, userID, ""); err != nil {
162			slog.Error("post-receive: recording landed MR", "mr", mr.Number, "err", err)
163			continue
164		}
165		st.DequeueMerge(mr.ID)
166		st.RecordEvent(repo.ID, userID, "mr.merged", fmt.Sprintf(`{"number":%d,"sha":%q}`, mr.Number, head))
167		if c == nil {
168			u, err := st.UserByID(userID)
169			if err != nil {
170				continue
171			}
172			c = &Ctx{User: u, Store: st, Cfg: cfg, Stdin: emptyReader{}, Stdout: io.Discard, Stderr: io.Discard}
173		}
174		if parts, err := st.MRParticipants(mr.ID); err == nil {
175			notify(c, parts, notice{repo: repo, kind: "mr", number: mr.Number,
176				subject: mrSubject(repo, mr.Number, mr.Title),
177				action:  fmt.Sprintf("merged !%d into %s (pushed)", mr.Number, branch),
178				path:    fmt.Sprintf("%s/mrs/%d", repo.Path(), mr.Number)})
179		}
180	}
181}
182
183// adoptDefaultBranch moves an unborn HEAD to the first branch a push
184// creates. A repository is initialised with HEAD at the stored default,
185// and a first push of master or trunk left HEAD naming a branch that did
186// not exist: clones checked out nothing and every surface asked git for
187// a branch that was not there (#189). A push that includes the default
188// branch itself needs nothing.
189func adoptDefaultBranch(st *store.Store, cfg config.Config, repo *store.Repo, updates []policy.RefUpdate) {
190	dir := RepoDir(cfg.Server.Root, repo.OwnerName, repo.Name)
191	if _, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch); err == nil {
192		return
193	}
194	for _, u := range updates {
195		branch, ok := cutHeads(u.Ref)
196		if !ok || u.IsDelete || !gitutil.ZeroSHA(u.Old) {
197			continue
198		}
199		if err := gitutil.SetHead(dir, branch); err != nil {
200			slog.Error("post-receive: moving HEAD", "repo", repo.Path(), "err", err)
201			return
202		}
203		if err := st.UpdateDefaultBranch(repo.ID, branch); err != nil {
204			slog.Error("post-receive: recording default branch", "repo", repo.Path(), "err", err)
205			return
206		}
207		repo.DefaultBranch = branch
208		return
209	}
210}
211
212// sameChange reports whether the new head proposes the diff the old one
213// did: the patch-id of each revision against its own merge base. A
214// rebase onto a moved target changes every sha and nothing about the
215// change, and the reviews of it should not go stale for that (#198).
216// Any doubt answers false, which is the old behaviour.
217func sameChange(dir string, mr store.MR, newBase, newHead string) bool {
218	if mr.HeadSHA == "" || newBase == "" || mr.HeadSHA == newHead {
219		return false
220	}
221	oldBase, err := gitutil.MergeBase(dir, "refs/heads/"+mr.TargetRef, mr.HeadSHA)
222	if err != nil {
223		return false
224	}
225	oldID, err := gitutil.PatchID(dir, oldBase, mr.HeadSHA)
226	if err != nil || oldID == "" {
227		return false
228	}
229	newID, err := gitutil.PatchID(dir, newBase, newHead)
230	return err == nil && newID == oldID
231}
232
233// QueueTagBuilds runs the jobs whose tag pattern matches a pushed tag.
234// The build records the tag as its ref and the peeled commit as its sha,
235// so statuses land on the commit, not an annotated tag object.
236func QueueTagBuilds(st *store.Store, cfg config.Config, repo store.Repo, userID int64, tag, pushed string) {
237	dir := RepoDir(cfg.Server.Root, repo.OwnerName, repo.Name)
238	sha, err := gitutil.PeelToCommit(dir, pushed)
239	if err != nil {
240		return
241	}
242	raw, err := gitutil.ReadBlob(dir, sha, ci.ConfigPath, 1<<16)
243	if err != nil {
244		return
245	}
246	jobs, err := ci.Parse(raw)
247	if err != nil {
248		return // the branch push already reported ci/config
249	}
250	for _, j := range jobs {
251		if j.Tags == "" {
252			continue
253		}
254		if ok, _ := path.Match(j.Tags, tag); !ok {
255			continue
256		}
257		steps, _ := json.Marshal(j.Steps)
258		n, err := st.CreateBuild(repo.ID, j.Name, sha, tag, string(steps), j.Image, "", true)
259		if err != nil {
260			slog.Error("queueing tag build", "repo", repo.Path(), "job", j.Name, "err", err)
261			continue
262		}
263		url := fmt.Sprintf("%s/%s/builds/%d", cfg.Server.SiteURL, repo.Path(), n)
264		st.SetCommitStatus(repo.ID, sha, "ci/"+j.Name, "pending", "tag "+tag, url, userID)
265	}
266}
267
268func cutHeads(ref string) (string, bool) {
269	const p = "refs/heads/"
270	if len(ref) > len(p) && ref[:len(p)] == p {
271		return ref[len(p):], true
272	}
273	return "", false
274}
275
276// PushHints formats post-receive hints for non-default branches in updates:
277// a link to any open merge request for that branch, or the CLI command and
278// web URL to open one.
279func PushHints(st *store.Store, cfg config.Config, repoID int64, updates []policy.RefUpdate) string {
280	repo, err := st.RepoByID(repoID)
281	if err != nil {
282		return ""
283	}
284	site := strings.TrimRight(cfg.Server.SiteURL, "/")
285	var lines []string
286	for _, u := range updates {
287		branch, ok := cutHeads(u.Ref)
288		if !ok || u.IsDelete || branch == repo.DefaultBranch {
289			continue
290		}
291		mrs, err := st.OpenMRsBySource(repoID, branch)
292		if err == nil && len(mrs) > 0 {
293			for _, mr := range mrs {
294				target := repo
295				if mr.RepoID != repo.ID {
296					if r, err := st.RepoByID(mr.RepoID); err == nil {
297						target = r
298					}
299				}
300				if site != "" {
301					lines = append(lines, fmt.Sprintf("open merge request !%d: %s/%s/mrs/%d", mr.Number, site, target.Path(), mr.Number))
302				} else {
303					lines = append(lines, fmt.Sprintf("open merge request !%d (%s)", mr.Number, target.Path()))
304				}
305			}
306			continue
307		}
308		lines = append(lines, fmt.Sprintf("create a merge request for %s:", branch))
309		lines = append(lines, fmt.Sprintf("  gitbay mr create --source %s", shellWord(branch)))
310		if site != "" {
311			lines = append(lines, fmt.Sprintf("  %s/%s/mrs/new?source=%s", site, repo.Path(), url.QueryEscape(branch)))
312		}
313	}
314	return strings.Join(lines, "\n")
315}