gitoria
All repositories: gitoria
15.9 KB
// lib/pullsync.hl — PULL REQUEST RECORDS (gitoria#40, part of the push API #38; contract docs/apps-api.md §3, §4).// A pull request is still a commit whose subject starts `|||PR` (git-helpers.hl parsePull), but now it is also STORED, so it has// a number that never changes and is never reused. Two tables, both keyed by the repo's ID (never the slug: a repo can be renamed):// pullRecs pk @id index !key, !shaKey, repo { rid (the repo's @id), number, key "<repo>#<n>", shaKey "<repo> <sha>", sha (the |||PR commit), source,// target, implicit (the target is the repo's main branch), state open|closed|merged, head, authorId, authorName,// heads (every head the PR has had, oldest first: an app may review an earlier one), createdMs, updatedMs } storage/mpackdb/pullrecs.db// pullInit pk @id index !repo { rid } a repo whose PRs were numbered once (the numbers of the old ones, oldest first)// ensurePulls(slug) numbers the PRs a repo already has, once, without changes (before the first push / page view)// syncPulls(slug, userId) compares git with the records → the CHANGES (opened|reopened|synchronize|closed|merged), each with the// ref refs/pull/<n>/head already pointing at the new head; logChange writes them (until gitoria#43 sends events)// pullObject(slug, n) the contract's `pull` JSON; withNumbers(list, slug) puts "#N" on the rows of /pulls.// A record is found again by the sha of its |||PR commit (that is what identifies a PR to git); its source branch may be renamed.// Merged is final. Nothing here throws: a failed git call skips that PR until the next sync.import { MPackDB } from 'hl:mpackdb'import { now, timestamp } from 'hl:time'import { appendFile } from 'hl:fs'import { NL, storageDir, countOfList, firstOf, repoOrigin, px } from './util.hl'import { repoBySlug } from './repos.hl'import { nameOfUser } from './users.hl'import { gitRaw, pickDefault } from './git.hl'import { tabs, isHexId, safeName, parsePull } from './git-helpers.hl'import { bodyOfLines, ticketNames } from './pullsync-helpers.hl'import { approvalsOf } from './approvals.hl'import { approvalsJson } from './approvals-helpers.hl'import { statusesOf, statusJson, requiredOf, approversOf } from './statuses.hl'static pullRecs = new MPackDB(file = storageDir + '/pullrecs.db', primaryKey = '@id', indexes = ['!key', '!shaKey', 'rid'])static pullInit = new MPackDB(file = storageDir + '/pullinit.db', primaryKey = '@id', indexes = ['!rid'])static changeLog = storageDir + '/pull-changes.log'static maxNew = 50static scan = 500static zeroId = '0000000000000000000000000000000000000000'// ---- small git answers -------------------------------------------------------------------------------------// the first line of a git call's output, or '' (failed, nothing, or not a plain id when `hexOnly`)static firstLine = (slug, args) => {r = gitRaw(slug, args)if (r == null || r.exit != 0 || r.lines.length == 0) { return '' }return r.lines[0]}static isAncestor = (slug, a, b) => {if (a == null || b == null || a == '' || b == '') { return false }r = gitRaw(slug, ['merge-base', '--is-ancestor', a, b])return r != null && r.exit == 0}// { name: tip sha } of every branch, and the names in orderstatic branchTips = (slug) => {tips = {}names = []r = gitRaw(slug, ['for-each-ref', '--format=%(refname:short)%09%(objectname)', 'refs/heads'])if (r != null && r.exit == 0) {for (l of r.lines) {f = tabs(l)if (f.length == 2 && safeName(f[0]) && isHexId(f[1])) {tips[f[0]] = f[1]names.push(f[0])}}}return { tips = tips names = names }}// The recorded source wins while it contains the marker. Without one, prefer the known head's// branch before another branch that merely contains the marker (for example a later PR).static sourceOf = (String slug, String sha, String target, String preferred, String head) => {return sourceResult(slug, sha, target, preferred, head).source}// The list cache also needs to know whether EVERY git read succeeded. Keep sourceOf's string contract.static sourceResult = (String slug, String sha, String target, String preferred, String head) => {r = gitRaw(slug, ['for-each-ref', '--contains', sha, '--format=%(refname:short)%09%(objectname)', 'refs/heads'])if (r == null || r.exit != 0) { return { source = '' ok = false } }candidates = []for (l of r.lines) {f = tabs(l)if (f.length == 2 && safeName(f[0]) && f[0] != target && isHexId(f[1])) {if (f[0] == preferred) { return { source = f[0] ok = true } }candidates.push({ name = f[0] tip = f[1] })}}knownHead = head == null || head == '' ? sha : headfor (c of candidates) { if (c.tip == knownHead) { return { source = c.name ok = true } } }let complete = truefor (c of candidates) {ancestor = gitRaw(slug, ['merge-base', '--is-ancestor', knownHead, c.tip])if (ancestor == null || (ancestor.exit != 0 && ancestor.exit != 1)) { complete = false }if (ancestor != null && ancestor.exit == 0) { return { source = c.name ok = complete } }}return { source = candidates.length > 0 ? candidates[0].name : '' ok = complete }}// the commit that put the PR into the target: the first one on the target's first-parent line that has the PR commit as an ancestor// (the merge commit of the Merge button; a fast-forward's commit itself); the target's tip when git cannot saystatic mergeCommitOf = (slug, sha, targetTip) => {r = gitRaw(slug, ['rev-list', '--first-parent', '--ancestry-path', '--reverse', sha + '..' + targetTip])if (r != null && r.exit == 0 && r.lines.length > 0 && isHexId(r.lines[0])) { return r.lines[0] }return targetTip}// ---- the refs/pull/N/head ref (and refs/pull/N/heads/<sha> for every head it ever had) ----------------------------------------------------------------------------// point it at `head`, with the old value given (a ref that is not there must not be there). → true when it points there afterwardsstatic setPullRef = (slug, n, head) => {ref = 'refs/pull/' + n + '/head'cur = firstLine(slug, ['rev-parse', '--verify', '-q', ref])if (cur == head) { return true }r = gitRaw(slug, ['update-ref', '-m', 'pull request ' + n, ref, head, cur == '' ? zeroId : cur])if (r == null || r.exit != 0) { return false }// every head stays referenced (refs/pull/N/heads/<sha>, hidden like the rest of refs/pull): an app may review an earlier head, git gc must not drop itgitRaw(slug, ['update-ref', '-m', 'pull request ' + n + ' head', 'refs/pull/' + n + '/heads/' + head, head])return true}// ---- the records -------------------------------------------------------------------------------------------static recordsOf = (repoId) => {all = pullRecs.find('rid', repoId)return countOfList(all) == 0 ? [] : all}static recordBySha = (repoId, sha) => { return firstOf(pullRecs.find('shaKey', repoId + ' ' + sha)) }static recordByNumber = (repoId, n) => { return firstOf(pullRecs.find('key', repoId + '#' + n)) }// the next number: one more than the highest (records are never removed, so a number is never used twice)static nextNumber = (repoId) => {let top = 0for (r of recordsOf(repoId)) { if (r.number > top) { top = r.number } }return top + 1}// every head the record has had (a list of shas); the current one is always in itstatic headsOf = (rec) => {out = []if (rec.heads != null && countOfList(rec.heads) > 0) { for (h of rec.heads) { out.push(h) } }if (rec.head != null && !out.includes(rec.head)) { out.push(rec.head) }return out}static withHead = (rec, head) => {out = headsOf(rec)if (!out.includes(head)) { out.push(head) }return out}// was this sha ever a head of pull request N of the repo? (gitoria#44: a review of an earlier head is fine, only a sha that never was one is stale)static wasHeadOf = (slug, n, sha) => {repo = repoBySlug(slug)if (repo == null || n == null || sha == null || hlTypeName(sha) != 'String') { return false }rec = recordByNumber(repo.id, n)return rec != null && headsOf(rec).includes(sha)}static isInitialized = (repoId) => { return firstOf(pullInit.find('rid', repoId)) != null }static changeOf = (rec, action, before, after, forced, mergeCommit, pusherId) => {let sender = nullif (pusherId != null) { sender = { id = pusherId name = nameOfUser(pusherId) } }return { number = rec.number action = action before = before after = after forced = forced mergeCommit = mergeCommit sender = sender }}// the commits of the repo that start a pull request, oldest first, not yet stored: [{ sha, ct, author, parsed }]static newCandidates = (slug, repoId) => {out = []lg = gitRaw(slug, ['log', '-' + scan, '--branches', '--format=%H%x09%ct%x09%an%x09%s'])if (lg == null || lg.exit != 0) { return out }for (l of lg.lines) {f = tabs(l)if (f.length >= 4 && isHexId(f[0]) && f[0].length == 40) {pr = parsePull(f.slice(3).join(' '))if (pr != null && out.length < maxNew && recordBySha(repoId, f[0]) == null) {out.push({ sha = f[0] ct = toNumber(f[1]) * 1000 author = f[2] parsed = pr })}}}// commit time, oldest first (an insertion sort: no sort(), hybriel #1)let i = 1while (i < out.length) {cur = out[i]let j = i - 1while (j >= 0 && out[j].ct > cur.ct) {out[j + 1] = out[j]j = j - 1}out[j + 1] = curi = i + 1}return out}// the whole comparison. quiet = number the existing PRs and return no changes (ensurePulls). → the changes (a list)static syncNow = (slug, pusherId, quiet) => {changes = []repo = repoBySlug(slug)if (repo == null) { return changes }bt = branchTips(slug)if (bt.names.length == 0) { return changes }dflt = pickDefault(bt.names, repo.branch)stamp = now()// 1. the PRs we knowfor (rec of recordsOf(repo.id)) {if (rec.state != 'merged') {target = rec.implicit == true ? dflt : rec.targettargetTip = bt.tips[target]let source = rec.sourcelet tip = source != '' ? bt.tips[source] : nulllet onBranch = tip != null && isAncestor(slug, rec.sha, tip)if (!onBranch) {// the commit may sit on another branch now (the branch was renamed)other = sourceOf(slug, rec.sha, target, rec.source, rec.head)if (other != '' && bt.tips[other] != null) {source = othertip = bt.tips[other]onBranch = true}}u = recu.target = targetu.source = sourcelet action = ''let before = rec.headlet after = rec.headlet forced = falselet mergeCommit = nullif (targetTip != null && isAncestor(slug, rec.sha, targetTip)) {action = 'merged'u.state = 'merged'if (onBranch) { after = tip }mergeCommit = mergeCommitOf(slug, rec.sha, targetTip)} else if (onBranch && rec.state == 'closed') {action = 'reopened'u.state = 'open'after = tip} else if (onBranch && tip != rec.head) {action = 'synchronize'after = tipforced = !isAncestor(slug, rec.head, tip)} else if (!onBranch && rec.state == 'open') {action = 'closed'u.state = 'closed'}u.head = afteru.heads = withHead(rec, after)if (action != '' || source != rec.source || target != rec.target) {// the ref first: an event is only sent for a head that can be fetchedif (action == '' || setPullRef(slug, rec.number, after)) {u.updatedMs = stamppullRecs.update(rec.id, u)if (action != '' && !quiet) { changes.push(changeOf(u, action, before, after, forced, mergeCommit, pusherId)) }}}}}// 2. the PRs we have not seen, oldest first (numbers follow the commit time)for (c of newCandidates(slug, repo.id)) {target = c.parsed.target == '' ? dflt : c.parsed.targettargetTip = bt.tips[target]source = sourceOf(slug, c.sha, target)merged = targetTip != null && isAncestor(slug, c.sha, targetTip)if (merged || (source != '' && bt.tips[source] != null)) {head = !merged && source != '' ? bt.tips[source] : c.shan = nextNumber(repo.id)author = quiet || pusherId == null ? null : pusherIdrec = { rid = repo.id number = n key = repo.id + '#' + n shaKey = repo.id + ' ' + c.sha sha = c.sha source = source target = target implicit = c.parsed.target == '' state = merged ? 'merged' : 'open' head = head heads = [head] authorId = author authorName = author != null ? nameOfUser(author) : c.author createdMs = quiet ? c.ct : stamp updatedMs = quiet ? c.ct : stamp }if (setPullRef(slug, n, head)) {id = pullRecs.put(rec)if (id != null && !quiet) {saved = pullRecs.fetch(id)changes.push(changeOf(saved, merged ? 'merged' : 'opened', null, head, false, merged ? mergeCommitOf(slug, c.sha, targetTip) : null, pusherId))}}}}return changes}// number the PRs a repo already has, ONCE (quiet); call it before a push is taken and when /pulls is builtstatic ensurePulls = (slug) => {repo = repoBySlug(slug)if (repo == null || isInitialized(repo.id)) { return null }syncNow(slug, null, true)// an empty repo (no branch yet) has nothing to number and is initialized too: its first PR is a live onepullInit.put({ rid = repo.id })return null}// THE ENTRY: compare git with the records. Never fails the caller: whatever goes wrong yields the changes found so far (none).// userId = the gitoria user who pushed or merged (null when unknown). Every change is logged (logChange) and returned.static syncPulls = (slug, userId) => {ensurePulls(slug)changes = syncNow(slug, userId, false)for (c of changes) { logChange(slug, c) }return changes}// the change log until gitoria#43 sends events: one JSON line in storage/pull-changes.log (and the console)static logChange = (slug, c) => {repo = repoBySlug(slug)line = JSON.stringify({ time = timestamp(now()) repoId = repo != null ? repo.id : null slug = slug number = c.number action = c.action before = c.before after = c.after forced = c.forced mergeCommit = c.mergeCommit sender = c.sender })appendFile(changeLog, line + NL, 384)console.log('pull-change ' + line)return null}// ---- the contract's `pull` object (§4) --------------------------------------------------------------------static pullObject = (String slug, Number n, Hybrid approvalRows = null) => {repo = repoBySlug(slug)if (repo == null || n == null) { return null }rec = recordByNumber(repo.id, n)if (rec == null) { return null }msg = gitRaw(slug, ['log', '-1', '--format=%B', rec.sha])lines = msg != null && msg.exit == 0 ? msg.lines : []pr = lines.length > 0 ? parsePull(lines[0]) : nulltitle = pr != null && pr.title != '' ? pr.title : (rec.source != '' ? rec.source : rec.sha.slice(0, 8))body = bodyOfLines(lines)baseTip = firstLine(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + rec.target])mergeBase = baseTip != '' ? firstLine(slug, ['merge-base', baseTip, rec.head]) : ''project = repo.tktProject != null ? repo.tktProject : ''statuses = []for (r of statusesOf(repo.id, rec.head)) { statuses.push(statusJson(r)) }return {number = rec.numbertitle = titlebody = bodydraft = falsestate = rec.stateauthor = { id = rec.authorId name = rec.authorName }source = rec.sourcetarget = rec.targethead = rec.headref = 'refs/pull/' + rec.number + '/head'baseRef = 'refs/heads/' + rec.targetbase = baseTip != '' ? baseTip : nullmergeBase = mergeBase != '' ? mergeBase : nulltickets = ticketNames(title + NL + body, project)url = repoOrigin(slug) + '/pulls/' + rec.numbercreated = timestamp(rec.createdMs)updated = timestamp(rec.updatedMs)statuses = statusesrequired = requiredOf(repo.id)approvers = approversOf(repo.id)approvals = approvalsJson(approvalRows == null ? approvalsOf(repo.id, rec.number) : approvalRows, rec.head)}}// the rows of /pulls with their number: `number` (0 = not stored) and `numberText` ("#3")static withNumbers = (list, slug) => {out = []repo = repoBySlug(slug)for (p of list) {q = prec = repo != null ? recordBySha(repo.id, p.sha) : nullq.number = rec != null ? rec.number : 0q.numberText = rec != null ? '#' + rec.number : ''q.pageHref = rec != null ? px(slug) + '/pulls/' + rec.number : p.hrefout.push(q)}return out}
Branches
Latest commits
- fe209ffeMerge branch 'w56-owner-members' into mainGitoria
- fa0754c8|||PR repository owner transfer and members API (#55)mre
- 8862e537Merge branch 'w55-rename-org' into mainGitoria
- 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
- 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
- 499f25f2Review fixes for the Settings organization move (#53)mre
- ed3b922b|||PR move a repository into an organization in Settings (#53)mre
- 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
- 9f7ce8d8Preserve rename compatibility and live page titlesmre
- c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
- ce08920dMerge branch 'w52c-header-phone' into mainGitoria
- 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
- e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
- c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
- 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
- 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
- 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
- 155861f6Merge branch 'w52-person-approval' into mainGitoria
- b5435de8|||PR person approvals: second Kunibert round (#52)mre
- 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre