gitoria
All repositories: gitoria
11.2 KB
// lib/pulls.hl — PULL REQUESTS (ticket gitoria#11): /pulls of a repo address.// A pull request is a COMMIT whose subject starts `|||PR ` (target = the repo's main branch) or// `|||PR|<branch>] ` (target = <branch>). The list reads git markers and prefers their recorded source branches.// Title = the text after the marker (else the source branch's name). Source = the branch holding the// commit that is not the target. State: `merged` when the commit is in the target branch, else `open`.// Each marker identifies one request, even when several requests share a containing branch. Merging happens with git itself.import { missingMessage } from './statuses-helpers.hl'import { sha256 } from 'hl:crypto'import { localStamp, px } from './util.hl'import { git, gitRaw, pickDefault } from './git.hl'import { enc, isHexId, tabs, parsePull, safeName } from './git-helpers.hl'import { repoBySlug } from './repos.hl'import { recordBySha, sourceResult } from './pullsync.hl'import { withPullParts } from './tickets-helpers.hl'import { missingText, missingOf, missingDetails, missingApproval, withStatuses } from './statuses.hl'static maxPulls = 50static pullScan = 500// One git-derived list per repository, at most 64 repositories. Every read checks all branch tips;// HTTPS/SSH pushes, force pushes, branch deletion and either merge path therefore change the key.// Hybrids copy on return: the live statuses, permissions, ticket links and numbers cannot enter this cache.static pullCache = {}static pullOrder = []static maxPullRepos = 64static keepPulls = (String slug, String key, Hybrid result) => {order = []for (k of pullOrder) { if (k != slug) { order.push(k) } }if (order.length >= maxPullRepos) {delete pullCache[order[0]]pullOrder = order.slice(1)} else { pullOrder = order }pullCache[slug] = { key = key result = result }pullOrder.push(slug)return null}// Database numbers must be read after the cache: notifyPush can scan a new marker before syncPulls numbers it.// Every caller, including status/approval checks and mergePullNow, receives the current number.static livePullNumbers = (Hybrid result, Hybrid repo) => {if (result == null || result.isMessage) { return result }rows = []for (p of result.pulls) {q = prec = repo == null ? null : recordBySha(repo.id, p.sha)q.number = rec == null ? null : rec.numberrows.push(q)}result.pulls = rowsreturn result}// The list, synchronously, as before. A failed fingerprint or scan is never retained.static pullsNow = (String slug, String setting) => {refs = gitRaw(slug, ['for-each-ref', '--format=%(refname)%09%(objectname)', 'refs/heads'])record = repoBySlug(slug)key = refs != null && refs.exit == 0 ? sha256(JSON.stringify([record == null ? null : record.id, setting, refs.lines])) : ''hit = pullCache[slug]if (key != '' && hit != null && hit.key == key) { return livePullNumbers(hit.result, record) }let out = nulllet scanned = falsepulls(slug, setting, (Hybrid result, Boolean ok) => {out = resultscanned = ok == truereturn null})if (key != '' && scanned) { keepPulls(slug, key, out) }return livePullNumbers(out, record)}static pullShape = (state, message) => {return { state = state isMessage = message != '' message = message pulls = [] hasPulls = false noPulls = false defaultName = '' openCount = 0 mergedCount = 0 }}// every pull request of a repo → done(result). setting = the repo's saved main branch ('' = none)static pulls = (slug, setting, done) => {repo = repoBySlug(slug)git(slug, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'], 500, (Hybrid branches) => {names = []if (branches.ok) { for (name of branches.lines) { if (safeName(name)) { names.push(name) } } }if (names.length == 0) {done(pullShape('empty', 'This repository has no commits yet.'), branches.ok)return null}dflt = pickDefault(names, setting)git(slug, ['log', '-' + pullScan, '--branches', '--format=%H%x09%ct%x09%an%x09%s'], pullScan, (Hybrid lg) => {let complete = branches.ok && lg.okfound = []for (l of lg.ok ? lg.lines : []) {f = tabs(l)if (f.length >= 4) {sub = f.slice(3).join(' ')pr = parsePull(sub)if (pr != null && isHexId(f[0]) && found.length < maxPulls) {found.push({ sha = f[0] short = f[0].slice(0, 8) date = localStamp(toNumber(f[1]) * 1000) author = f[2] target = pr.target == '' ? dflt : pr.target title = pr.title })}}}out = pullShape('ok', '')out.defaultName = dfltnext = (Number i) => {if (i >= found.length) {out.hasPulls = out.pulls.length > 0out.noPulls = out.pulls.length == 0done(out, complete)return null}c = found[i]rec = repo == null ? null : recordBySha(repo.id, c.sha)sourceRead = sourceResult(slug, c.sha, c.target, rec == null ? '' : rec.source, rec == null ? c.sha : rec.head)if (sourceRead == null || !sourceRead.ok) { complete = false }source = sourceRead == null ? '' : sourceRead.sourcefinish = (Boolean merged, Boolean targetMissing) => {title = c.title != '' ? c.title : (source != '' ? source : c.short)out.pulls.push({ sha = c.sha short = c.short href = px(slug) + '/commit/' + c.sha title = title source = source hasSource = source != '' noSource = source == '' sourceHref = source != '' ? px(slug) + '/branch/' + enc(source) : '' target = c.target targetHref = targetMissing ? '' : px(slug) + '/branch/' + enc(c.target) targetLinked = !targetMissing state = merged ? 'merged' : 'open' isMerged = merged isOpen = !merged mergeable = !merged && source != '' && !targetMissing targetMissing = targetMissing author = c.author date = c.date })if (merged) { out.mergedCount = out.mergedCount + 1 } else { out.openCount = out.openCount + 1 }next(i + 1)return null}if (!names.includes(c.target)) { return finish(false, true) }mb = gitRaw(slug, ['merge-base', '--is-ancestor', c.sha, c.target])if (mb == null || (mb.exit != 0 && mb.exit != 1)) { complete = false }return finish(mb != null && mb.exit == 0, false)}next(0)return null})})}// the rows with `canMerge` (`owner` = may merge: the owner or a member with push rights, lib/repos.hl mayPush; an open request whose branches exist) and the button's class: an `if` inside a// `for` row is not re-evaluated when the list is reassigned (the old button stayed), an attribute is — so the button// is always there and `.nomerge` hides it (styles.hl)static withMerge = (list, owner) => {out = []for (p of list) {q = pq.canMerge = owner && p.mergeableq.mergeClass = q.canMerge ? 'quiet mergepr' : 'nomerge'out.push(q)}return out}// ---- MERGE a pull request (ticket gitoria#17): only when the owner clicks the button ---------------------------// The repo is BARE (no work tree), so the merge is made with plumbing: `merge-tree --write-tree` merges the two// branches into a tree (exit 1 = conflict: nothing is written to any branch), `commit-tree` makes the merge commit// (parents: target, source), `update-ref` moves the target — with the old value given, so a push that arrived meanwhile// makes it fail instead of being overwritten. Always a merge commit (like GitHub's "Create a merge commit").// The pull request is found again on the SERVER by the sha of its `|||PR` commit (the client only names that).// → { ok } | { error, reason, details? }. who = the user's name (author of the merge commit).// expectHead (optional, '' = none): the head the caller looked at; another head now → { error } and nothing merged.static mergePullNow = (slug, setting, sha, who, expectHead) => {let found = nullif (sha == null || hlTypeName(sha) != 'String' || !isHexId(sha) || sha.length != 40) { return { error = 'no such pull request' } }got = pullsNow(slug, setting)if (got == null || got.isMessage) { return { error = 'no such pull request' } }for (p of got.pulls) { if (p.sha == sha) { found = p } }if (found == null) { return { error = 'no such pull request' } }if (found.isMerged) { return { error = 'this pull request is already merged' reason = 'already_merged' } }if (found.noSource) { return { error = 'the branch of this pull request is gone' reason = 'branch_gone' } }if (found.targetMissing) { return { error = 'the target branch ' + found.target + ' does not exist' reason = 'target_missing' } }target = 'refs/heads/' + found.targetold = gitRaw(slug, ['rev-parse', '--verify', '-q', target])tip = gitRaw(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + found.source])if (old == null || old.exit != 0 || old.lines.length == 0 || tip == null || tip.exit != 0 || tip.lines.length == 0) { return { error = 'could not read the branches' reason = 'git_error' } }oldSha = old.lines[0]tipSha = tip.lines[0]if (!isHexId(oldSha) || !isHexId(tipSha)) { return { error = 'could not read the branches' reason = 'git_error' } }if (expectHead != null && expectHead != '' && expectHead != tipSha) { return { error = 'the head of this pull request changed (now ' + tipSha + ') — nothing merged' reason = 'head_mismatch' } }// REQUIRED BEFORE MERGE (#46, #52): the centralized app-or-person rule on the exact head that would be mergedmissing = missingOf(repoBySlug(slug).id, tipSha, found.number)blocked = missingMessage(tipSha, missing)if (blocked != '') { return { error = blocked reason = 'checks_failed' details = missingDetails(missing) approval = missingApproval(missing) } }m = gitRaw(slug, ['merge-tree', '--write-tree', '--name-only', '--no-messages', oldSha, tipSha])if (m == null) { return { error = 'could not merge (git did not answer)' reason = 'git_error' } }if (m.exit == 1) {files = []let i = 1while (i < m.lines.length && m.lines[i] != '') {if (files.length < 5) { files.push(m.lines[i]) }i = i + 1}return { error = 'Not merged: ' + found.source + ' conflicts with ' + found.target + (files.length > 0 ? ' in ' + files.join(', ') : '') + '. Resolve it with git, then push.' reason = 'merge_conflict' }}if (m.exit != 0 || m.lines.length == 0 || !isHexId(m.lines[0])) { return { error = 'could not merge' reason = 'git_error' } }name = who != null && who != '' ? who : 'gitoria'msg = "Merge branch '" + found.source + "' into " + found.targetc = gitRaw(slug, ['-c', 'user.name=' + name, '-c', 'user.email=noreply@gitoria', 'commit-tree', m.lines[0], '-p', oldSha, '-p', tipSha, '-m', msg])if (c == null || c.exit != 0 || c.lines.length == 0 || !isHexId(c.lines[0])) { return { error = 'could not write the merge commit' reason = 'git_error' } }u = gitRaw(slug, ['update-ref', '-m', msg, target, c.lines[0], oldSha])if (u == null || u.exit != 0) {current = gitRaw(slug, ['rev-parse', '--verify', '-q', target])reason = current != null && current.exit == 0 && current.lines.length > 0 && current.lines[0] != oldSha ? 'target_moved' : 'git_error'return { error = 'The branch ' + found.target + ' changed meanwhile — nothing merged, try again.' reason = reason }}return { ok = true mergeCommit = c.lines[0] }}// the list read again, with the Merge buttons and the ticket links: the answer of the Merge face (components/pulls.hl)static pullsView = (slug, setting, owner, project) => {got = pullsNow(slug, setting)return { result = got list = withStatuses(withPullParts(withMerge(got.pulls, owner), project), slug) }}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 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
- 2a89d8d0|||PR person approvals: Approve button for people; merge needs the required checks or a listed person's approval (#52)mre
- 83f0c953Report person approval verificationmre
- 3ae94b86Record browser failures and verify owned tab cleanupmre