gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchw62-pr-close6e03be0apull state: keep the resync marker until the sync ran (#56)mrew62-pr-close/lib/pulls.hl

12.8 KB

  1. // lib/pulls.hl — PULL REQUESTS (ticket gitoria#11): /pulls of a repo address.
  2. // A pull request is a COMMIT whose subject starts `|||PR ` (target = the repo's main branch) or
  3. // `|||PR|<branch>] ` (target = <branch>). The list reads git markers and prefers their recorded source branches.
  4. // Title = the text after the marker (else the source branch's name). Source = the branch holding the
  5. // commit that is not the target. State: `merged` when the commit is in the target branch, else `open`.
  6. // Each marker identifies one request, even when several requests share a containing branch. Merging happens with git itself.
  7. import { missingMessage } from './statuses-helpers.hl'
  8. import { sha256 } from 'hl:crypto'
  9. import { localStamp, px } from './util.hl'
  10. import { git, gitRaw, pickDefault } from './git.hl'
  11. import { enc, isHexId, tabs, parsePull, safeName } from './git-helpers.hl'
  12. import { repoBySlug, mayPush } from './repos.hl'
  13. import { recordBySha, sourceResult, setManualPull } from './pullsync.hl'
  14. import { withPullParts } from './tickets-helpers.hl'
  15. import { missingText, missingOf, missingDetails, missingApproval, withStatuses } from './statuses.hl'
  16. import { raisePullChanges, syncAndRaise } from './events.hl'
  17. static maxPulls = 50
  18. static pullScan = 500
  19. // One git-derived list per repository, at most 64 repositories. Every read checks all branch tips;
  20. // HTTPS/SSH pushes, force pushes, branch deletion and either merge path therefore change the key.
  21. // Hybrids copy on return: the live statuses, permissions, ticket links and numbers cannot enter this cache.
  22. static pullCache = {}
  23. static pullOrder = []
  24. static maxPullRepos = 64
  25. static keepPulls = (String slug, String key, Hybrid result) => {
  26. order = []
  27. for (k of pullOrder) { if (k != slug) { order.push(k) } }
  28. if (order.length >= maxPullRepos) {
  29. delete pullCache[order[0]]
  30. pullOrder = order.slice(1)
  31. } else { pullOrder = order }
  32. pullCache[slug] = { key = key result = result }
  33. pullOrder.push(slug)
  34. return null
  35. }
  36. // Database numbers must be read after the cache: notifyPush can scan a new marker before syncPulls numbers it.
  37. // Every caller, including status/approval checks and mergePullNow, receives the current number.
  38. static livePullNumbers = (Hybrid result, Hybrid repo) => {
  39. if (result == null || result.isMessage) { return result }
  40. rows = []
  41. for (p of result.pulls) {
  42. q = p
  43. rec = repo == null ? null : recordBySha(repo.id, p.sha)
  44. q.number = rec == null ? null : rec.number
  45. q.state = p.isMerged ? 'merged' : (rec == null ? p.state : rec.state)
  46. q.isOpen = q.state == 'open'
  47. q.isMerged = q.state == 'merged'
  48. q.manualClosed = rec != null && rec.manualClosedBy != null && q.state == 'closed'
  49. q.mergeable = p.mergeable && q.isOpen
  50. rows.push(q)
  51. }
  52. result.pulls = rows
  53. result.openCount = 0
  54. result.mergedCount = 0
  55. for (p of rows) {
  56. if (p.isOpen) { result.openCount = result.openCount + 1 }
  57. if (p.isMerged) { result.mergedCount = result.mergedCount + 1 }
  58. }
  59. return result
  60. }
  61. // The list, synchronously, as before. A failed fingerprint or scan is never retained.
  62. static pullsNow = (String slug, String setting) => {
  63. refs = gitRaw(slug, ['for-each-ref', '--format=%(refname)%09%(objectname)', 'refs/heads'])
  64. record = repoBySlug(slug)
  65. key = refs != null && refs.exit == 0 ? sha256(JSON.stringify([record == null ? null : record.id, setting, refs.lines])) : ''
  66. hit = pullCache[slug]
  67. if (key != '' && hit != null && hit.key == key) { return livePullNumbers(hit.result, record) }
  68. let out = null
  69. let scanned = false
  70. pulls(slug, setting, (Hybrid result, Boolean ok) => {
  71. out = result
  72. scanned = ok == true
  73. return null
  74. })
  75. if (key != '' && scanned) { keepPulls(slug, key, out) }
  76. return livePullNumbers(out, record)
  77. }
  78. static pullShape = (state, message) => {
  79. return { state = state isMessage = message != '' message = message pulls = [] hasPulls = false noPulls = false defaultName = '' openCount = 0 mergedCount = 0 }
  80. }
  81. // every pull request of a repo → done(result). setting = the repo's saved main branch ('' = none)
  82. static pulls = (slug, setting, done) => {
  83. repo = repoBySlug(slug)
  84. git(slug, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'], 500, (Hybrid branches) => {
  85. names = []
  86. if (branches.ok) { for (name of branches.lines) { if (safeName(name)) { names.push(name) } } }
  87. if (names.length == 0) {
  88. done(pullShape('empty', 'This repository has no commits yet.'), branches.ok)
  89. return null
  90. }
  91. dflt = pickDefault(names, setting)
  92. git(slug, ['log', '-' + pullScan, '--branches', '--format=%H%x09%ct%x09%an%x09%s'], pullScan, (Hybrid lg) => {
  93. let complete = branches.ok && lg.ok
  94. found = []
  95. for (l of lg.ok ? lg.lines : []) {
  96. f = tabs(l)
  97. if (f.length >= 4) {
  98. sub = f.slice(3).join(' ')
  99. pr = parsePull(sub)
  100. if (pr != null && isHexId(f[0]) && found.length < maxPulls) {
  101. 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 })
  102. }
  103. }
  104. }
  105. out = pullShape('ok', '')
  106. out.defaultName = dflt
  107. next = (Number i) => {
  108. if (i >= found.length) {
  109. out.hasPulls = out.pulls.length > 0
  110. out.noPulls = out.pulls.length == 0
  111. done(out, complete)
  112. return null
  113. }
  114. c = found[i]
  115. rec = repo == null ? null : recordBySha(repo.id, c.sha)
  116. sourceRead = sourceResult(slug, c.sha, c.target, rec == null ? '' : rec.source, rec == null ? c.sha : rec.head)
  117. if (sourceRead == null || !sourceRead.ok) { complete = false }
  118. source = sourceRead == null ? '' : sourceRead.source
  119. finish = (Boolean merged, Boolean targetMissing) => {
  120. title = c.title != '' ? c.title : (source != '' ? source : c.short)
  121. 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 })
  122. if (merged) { out.mergedCount = out.mergedCount + 1 } else { out.openCount = out.openCount + 1 }
  123. next(i + 1)
  124. return null
  125. }
  126. if (!names.includes(c.target)) { return finish(false, true) }
  127. mb = gitRaw(slug, ['merge-base', '--is-ancestor', c.sha, c.target])
  128. if (mb == null || (mb.exit != 0 && mb.exit != 1)) { complete = false }
  129. return finish(mb != null && mb.exit == 0, false)
  130. }
  131. next(0)
  132. return null
  133. })
  134. })
  135. }
  136. // 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
  137. // `for` row is not re-evaluated when the list is reassigned (the old button stayed), an attribute is — so the button
  138. // is always there and `.nomerge` hides it (styles.hl)
  139. static withMerge = (list, owner) => {
  140. out = []
  141. for (p of list) {
  142. q = p
  143. q.canMerge = owner && p.mergeable
  144. q.mergeClass = q.canMerge ? 'quiet mergepr' : 'nomerge'
  145. q.closeClass = owner && p.isOpen ? 'quiet' : 'nomerge'
  146. q.reopenClass = owner && p.manualClosed ? 'quiet' : 'nomerge'
  147. out.push(q)
  148. }
  149. return out
  150. }
  151. // ---- MERGE a pull request (ticket gitoria#17): only when the owner clicks the button ---------------------------
  152. // The repo is BARE (no work tree), so the merge is made with plumbing: `merge-tree --write-tree` merges the two
  153. // branches into a tree (exit 1 = conflict: nothing is written to any branch), `commit-tree` makes the merge commit
  154. // (parents: target, source), `update-ref` moves the target — with the old value given, so a push that arrived meanwhile
  155. // makes it fail instead of being overwritten. Always a merge commit (like GitHub's "Create a merge commit").
  156. // The pull request is found again on the SERVER by the sha of its `|||PR` commit (the client only names that).
  157. // → { ok } | { error, reason, details? }. who = the user's name (author of the merge commit).
  158. // expectHead (optional, '' = none): the head the caller looked at; another head now → { error } and nothing merged.
  159. static mergePullNow = (slug, setting, sha, who, expectHead) => {
  160. let found = null
  161. if (sha == null || hlTypeName(sha) != 'String' || !isHexId(sha) || sha.length != 40) { return { error = 'no such pull request' } }
  162. got = pullsNow(slug, setting)
  163. if (got == null || got.isMessage) { return { error = 'no such pull request' } }
  164. for (p of got.pulls) { if (p.sha == sha) { found = p } }
  165. if (found == null) { return { error = 'no such pull request' } }
  166. if (found.isMerged) { return { error = 'this pull request is already merged' reason = 'already_merged' } }
  167. if (!found.isOpen) { return { error = 'this pull request is closed' reason = 'closed' } }
  168. if (found.noSource) { return { error = 'the branch of this pull request is gone' reason = 'branch_gone' } }
  169. if (found.targetMissing) { return { error = 'the target branch ' + found.target + ' does not exist' reason = 'target_missing' } }
  170. target = 'refs/heads/' + found.target
  171. old = gitRaw(slug, ['rev-parse', '--verify', '-q', target])
  172. tip = gitRaw(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + found.source])
  173. 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' } }
  174. oldSha = old.lines[0]
  175. tipSha = tip.lines[0]
  176. if (!isHexId(oldSha) || !isHexId(tipSha)) { return { error = 'could not read the branches' reason = 'git_error' } }
  177. if (expectHead != null && expectHead != '' && expectHead != tipSha) { return { error = 'the head of this pull request changed (now ' + tipSha + ') — nothing merged' reason = 'head_mismatch' } }
  178. // REQUIRED BEFORE MERGE (#46, #52): the centralized app-or-person rule on the exact head that would be merged
  179. missing = missingOf(repoBySlug(slug).id, tipSha, found.number)
  180. blocked = missingMessage(tipSha, missing)
  181. if (blocked != '') { return { error = blocked reason = 'checks_failed' details = missingDetails(missing) approval = missingApproval(missing) } }
  182. m = gitRaw(slug, ['merge-tree', '--write-tree', '--name-only', '--no-messages', oldSha, tipSha])
  183. if (m == null) { return { error = 'could not merge (git did not answer)' reason = 'git_error' } }
  184. if (m.exit == 1) {
  185. files = []
  186. let i = 1
  187. while (i < m.lines.length && m.lines[i] != '') {
  188. if (files.length < 5) { files.push(m.lines[i]) }
  189. i = i + 1
  190. }
  191. 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' }
  192. }
  193. if (m.exit != 0 || m.lines.length == 0 || !isHexId(m.lines[0])) { return { error = 'could not merge' reason = 'git_error' } }
  194. name = who != null && who != '' ? who : 'gitoria'
  195. msg = "Merge branch '" + found.source + "' into " + found.target
  196. c = gitRaw(slug, ['-c', 'user.name=' + name, '-c', 'user.email=noreply@gitoria', 'commit-tree', m.lines[0], '-p', oldSha, '-p', tipSha, '-m', msg])
  197. 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' } }
  198. u = gitRaw(slug, ['update-ref', '-m', msg, target, c.lines[0], oldSha])
  199. if (u == null || u.exit != 0) {
  200. current = gitRaw(slug, ['rev-parse', '--verify', '-q', target])
  201. reason = current != null && current.exit == 0 && current.lines.length > 0 && current.lines[0] != oldSha ? 'target_moved' : 'git_error'
  202. return { error = 'The branch ' + found.target + ' changed meanwhile — nothing merged, try again.' reason = reason }
  203. }
  204. return { ok = true mergeCommit = c.lines[0] }
  205. }
  206. // the list read again, with the Merge buttons and the ticket links: the answer of the Merge face (components/pulls.hl)
  207. static pullsView = (slug, setting, owner, project) => {
  208. got = pullsNow(slug, setting)
  209. return { result = got list = withStatuses(withPullParts(withMerge(got.pulls, owner), project), slug) }
  210. }
  211. // Permission is the existing Merge rule, checked again for every action.
  212. static changePullState = (String userId, String slug, Number number, Boolean closed) => {
  213. repo = repoBySlug(slug)
  214. if (repo == null) { return { error = 'no such pull request' code = 404 } }
  215. if (userId == null || !mayPush(userId, repo)) { return { error = 'only the owner and the members of this repository can do that' code = 403 } }
  216. r = setManualPull(userId, slug, number, closed)
  217. if (r.error != null) { return r }
  218. raisePullChanges(slug, [r.change])
  219. if (!closed) { syncAndRaise(slug, userId) }
  220. emit client gitoriaPullStateChanged(slug, number)
  221. return { ok = true }
  222. }
  223. static closePull = (String userId, String slug, Number number) => { return changePullState(userId, slug, number, true) }
  224. static reopenPull = (String userId, String slug, Number number) => { return changePullState(userId, slug, number, false) }

Branches

Latest commits

  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • 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