gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/lib/pullsync.hl

15.9 KB

  1. // lib/pullsync.hl — PULL REQUEST RECORDS (gitoria#40, part of the push API #38; contract docs/apps-api.md §3, §4).
  2. // A pull request is still a commit whose subject starts `|||PR` (git-helpers.hl parsePull), but now it is also STORED, so it has
  3. // 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):
  4. // pullRecs pk @id index !key, !shaKey, repo { rid (the repo's @id), number, key "<repo>#<n>", shaKey "<repo> <sha>", sha (the |||PR commit), source,
  5. // target, implicit (the target is the repo's main branch), state open|closed|merged, head, authorId, authorName,
  6. // heads (every head the PR has had, oldest first: an app may review an earlier one), createdMs, updatedMs } storage/mpackdb/pullrecs.db
  7. // pullInit pk @id index !repo { rid } a repo whose PRs were numbered once (the numbers of the old ones, oldest first)
  8. // ensurePulls(slug) numbers the PRs a repo already has, once, without changes (before the first push / page view)
  9. // syncPulls(slug, userId) compares git with the records → the CHANGES (opened|reopened|synchronize|closed|merged), each with the
  10. // ref refs/pull/<n>/head already pointing at the new head; logChange writes them (until gitoria#43 sends events)
  11. // pullObject(slug, n) the contract's `pull` JSON; withNumbers(list, slug) puts "#N" on the rows of /pulls.
  12. // 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.
  13. // Merged is final. Nothing here throws: a failed git call skips that PR until the next sync.
  14. import { MPackDB } from 'hl:mpackdb'
  15. import { now, timestamp } from 'hl:time'
  16. import { appendFile } from 'hl:fs'
  17. import { NL, storageDir, countOfList, firstOf, repoOrigin, px } from './util.hl'
  18. import { repoBySlug } from './repos.hl'
  19. import { nameOfUser } from './users.hl'
  20. import { gitRaw, pickDefault } from './git.hl'
  21. import { tabs, isHexId, safeName, parsePull } from './git-helpers.hl'
  22. import { bodyOfLines, ticketNames } from './pullsync-helpers.hl'
  23. import { approvalsOf } from './approvals.hl'
  24. import { approvalsJson } from './approvals-helpers.hl'
  25. import { statusesOf, statusJson, requiredOf, approversOf } from './statuses.hl'
  26. static pullRecs = new MPackDB(file = storageDir + '/pullrecs.db', primaryKey = '@id', indexes = ['!key', '!shaKey', 'rid'])
  27. static pullInit = new MPackDB(file = storageDir + '/pullinit.db', primaryKey = '@id', indexes = ['!rid'])
  28. static changeLog = storageDir + '/pull-changes.log'
  29. static maxNew = 50
  30. static scan = 500
  31. static zeroId = '0000000000000000000000000000000000000000'
  32. // ---- small git answers -------------------------------------------------------------------------------------
  33. // the first line of a git call's output, or '' (failed, nothing, or not a plain id when `hexOnly`)
  34. static firstLine = (slug, args) => {
  35. r = gitRaw(slug, args)
  36. if (r == null || r.exit != 0 || r.lines.length == 0) { return '' }
  37. return r.lines[0]
  38. }
  39. static isAncestor = (slug, a, b) => {
  40. if (a == null || b == null || a == '' || b == '') { return false }
  41. r = gitRaw(slug, ['merge-base', '--is-ancestor', a, b])
  42. return r != null && r.exit == 0
  43. }
  44. // { name: tip sha } of every branch, and the names in order
  45. static branchTips = (slug) => {
  46. tips = {}
  47. names = []
  48. r = gitRaw(slug, ['for-each-ref', '--format=%(refname:short)%09%(objectname)', 'refs/heads'])
  49. if (r != null && r.exit == 0) {
  50. for (l of r.lines) {
  51. f = tabs(l)
  52. if (f.length == 2 && safeName(f[0]) && isHexId(f[1])) {
  53. tips[f[0]] = f[1]
  54. names.push(f[0])
  55. }
  56. }
  57. }
  58. return { tips = tips names = names }
  59. }
  60. // The recorded source wins while it contains the marker. Without one, prefer the known head's
  61. // branch before another branch that merely contains the marker (for example a later PR).
  62. static sourceOf = (String slug, String sha, String target, String preferred, String head) => {
  63. return sourceResult(slug, sha, target, preferred, head).source
  64. }
  65. // The list cache also needs to know whether EVERY git read succeeded. Keep sourceOf's string contract.
  66. static sourceResult = (String slug, String sha, String target, String preferred, String head) => {
  67. r = gitRaw(slug, ['for-each-ref', '--contains', sha, '--format=%(refname:short)%09%(objectname)', 'refs/heads'])
  68. if (r == null || r.exit != 0) { return { source = '' ok = false } }
  69. candidates = []
  70. for (l of r.lines) {
  71. f = tabs(l)
  72. if (f.length == 2 && safeName(f[0]) && f[0] != target && isHexId(f[1])) {
  73. if (f[0] == preferred) { return { source = f[0] ok = true } }
  74. candidates.push({ name = f[0] tip = f[1] })
  75. }
  76. }
  77. knownHead = head == null || head == '' ? sha : head
  78. for (c of candidates) { if (c.tip == knownHead) { return { source = c.name ok = true } } }
  79. let complete = true
  80. for (c of candidates) {
  81. ancestor = gitRaw(slug, ['merge-base', '--is-ancestor', knownHead, c.tip])
  82. if (ancestor == null || (ancestor.exit != 0 && ancestor.exit != 1)) { complete = false }
  83. if (ancestor != null && ancestor.exit == 0) { return { source = c.name ok = complete } }
  84. }
  85. return { source = candidates.length > 0 ? candidates[0].name : '' ok = complete }
  86. }
  87. // 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
  88. // (the merge commit of the Merge button; a fast-forward's commit itself); the target's tip when git cannot say
  89. static mergeCommitOf = (slug, sha, targetTip) => {
  90. r = gitRaw(slug, ['rev-list', '--first-parent', '--ancestry-path', '--reverse', sha + '..' + targetTip])
  91. if (r != null && r.exit == 0 && r.lines.length > 0 && isHexId(r.lines[0])) { return r.lines[0] }
  92. return targetTip
  93. }
  94. // ---- the refs/pull/N/head ref (and refs/pull/N/heads/<sha> for every head it ever had) ----------------------------------------------------------------------------
  95. // point it at `head`, with the old value given (a ref that is not there must not be there). → true when it points there afterwards
  96. static setPullRef = (slug, n, head) => {
  97. ref = 'refs/pull/' + n + '/head'
  98. cur = firstLine(slug, ['rev-parse', '--verify', '-q', ref])
  99. if (cur == head) { return true }
  100. r = gitRaw(slug, ['update-ref', '-m', 'pull request ' + n, ref, head, cur == '' ? zeroId : cur])
  101. if (r == null || r.exit != 0) { return false }
  102. // 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 it
  103. gitRaw(slug, ['update-ref', '-m', 'pull request ' + n + ' head', 'refs/pull/' + n + '/heads/' + head, head])
  104. return true
  105. }
  106. // ---- the records -------------------------------------------------------------------------------------------
  107. static recordsOf = (repoId) => {
  108. all = pullRecs.find('rid', repoId)
  109. return countOfList(all) == 0 ? [] : all
  110. }
  111. static recordBySha = (repoId, sha) => { return firstOf(pullRecs.find('shaKey', repoId + ' ' + sha)) }
  112. static recordByNumber = (repoId, n) => { return firstOf(pullRecs.find('key', repoId + '#' + n)) }
  113. // the next number: one more than the highest (records are never removed, so a number is never used twice)
  114. static nextNumber = (repoId) => {
  115. let top = 0
  116. for (r of recordsOf(repoId)) { if (r.number > top) { top = r.number } }
  117. return top + 1
  118. }
  119. // every head the record has had (a list of shas); the current one is always in it
  120. static headsOf = (rec) => {
  121. out = []
  122. if (rec.heads != null && countOfList(rec.heads) > 0) { for (h of rec.heads) { out.push(h) } }
  123. if (rec.head != null && !out.includes(rec.head)) { out.push(rec.head) }
  124. return out
  125. }
  126. static withHead = (rec, head) => {
  127. out = headsOf(rec)
  128. if (!out.includes(head)) { out.push(head) }
  129. return out
  130. }
  131. // 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)
  132. static wasHeadOf = (slug, n, sha) => {
  133. repo = repoBySlug(slug)
  134. if (repo == null || n == null || sha == null || hlTypeName(sha) != 'String') { return false }
  135. rec = recordByNumber(repo.id, n)
  136. return rec != null && headsOf(rec).includes(sha)
  137. }
  138. static isInitialized = (repoId) => { return firstOf(pullInit.find('rid', repoId)) != null }
  139. static changeOf = (rec, action, before, after, forced, mergeCommit, pusherId) => {
  140. let sender = null
  141. if (pusherId != null) { sender = { id = pusherId name = nameOfUser(pusherId) } }
  142. return { number = rec.number action = action before = before after = after forced = forced mergeCommit = mergeCommit sender = sender }
  143. }
  144. // the commits of the repo that start a pull request, oldest first, not yet stored: [{ sha, ct, author, parsed }]
  145. static newCandidates = (slug, repoId) => {
  146. out = []
  147. lg = gitRaw(slug, ['log', '-' + scan, '--branches', '--format=%H%x09%ct%x09%an%x09%s'])
  148. if (lg == null || lg.exit != 0) { return out }
  149. for (l of lg.lines) {
  150. f = tabs(l)
  151. if (f.length >= 4 && isHexId(f[0]) && f[0].length == 40) {
  152. pr = parsePull(f.slice(3).join(' '))
  153. if (pr != null && out.length < maxNew && recordBySha(repoId, f[0]) == null) {
  154. out.push({ sha = f[0] ct = toNumber(f[1]) * 1000 author = f[2] parsed = pr })
  155. }
  156. }
  157. }
  158. // commit time, oldest first (an insertion sort: no sort(), hybriel #1)
  159. let i = 1
  160. while (i < out.length) {
  161. cur = out[i]
  162. let j = i - 1
  163. while (j >= 0 && out[j].ct > cur.ct) {
  164. out[j + 1] = out[j]
  165. j = j - 1
  166. }
  167. out[j + 1] = cur
  168. i = i + 1
  169. }
  170. return out
  171. }
  172. // the whole comparison. quiet = number the existing PRs and return no changes (ensurePulls). → the changes (a list)
  173. static syncNow = (slug, pusherId, quiet) => {
  174. changes = []
  175. repo = repoBySlug(slug)
  176. if (repo == null) { return changes }
  177. bt = branchTips(slug)
  178. if (bt.names.length == 0) { return changes }
  179. dflt = pickDefault(bt.names, repo.branch)
  180. stamp = now()
  181. // 1. the PRs we know
  182. for (rec of recordsOf(repo.id)) {
  183. if (rec.state != 'merged') {
  184. target = rec.implicit == true ? dflt : rec.target
  185. targetTip = bt.tips[target]
  186. let source = rec.source
  187. let tip = source != '' ? bt.tips[source] : null
  188. let onBranch = tip != null && isAncestor(slug, rec.sha, tip)
  189. if (!onBranch) {
  190. // the commit may sit on another branch now (the branch was renamed)
  191. other = sourceOf(slug, rec.sha, target, rec.source, rec.head)
  192. if (other != '' && bt.tips[other] != null) {
  193. source = other
  194. tip = bt.tips[other]
  195. onBranch = true
  196. }
  197. }
  198. u = rec
  199. u.target = target
  200. u.source = source
  201. let action = ''
  202. let before = rec.head
  203. let after = rec.head
  204. let forced = false
  205. let mergeCommit = null
  206. if (targetTip != null && isAncestor(slug, rec.sha, targetTip)) {
  207. action = 'merged'
  208. u.state = 'merged'
  209. if (onBranch) { after = tip }
  210. mergeCommit = mergeCommitOf(slug, rec.sha, targetTip)
  211. } else if (onBranch && rec.state == 'closed') {
  212. action = 'reopened'
  213. u.state = 'open'
  214. after = tip
  215. } else if (onBranch && tip != rec.head) {
  216. action = 'synchronize'
  217. after = tip
  218. forced = !isAncestor(slug, rec.head, tip)
  219. } else if (!onBranch && rec.state == 'open') {
  220. action = 'closed'
  221. u.state = 'closed'
  222. }
  223. u.head = after
  224. u.heads = withHead(rec, after)
  225. if (action != '' || source != rec.source || target != rec.target) {
  226. // the ref first: an event is only sent for a head that can be fetched
  227. if (action == '' || setPullRef(slug, rec.number, after)) {
  228. u.updatedMs = stamp
  229. pullRecs.update(rec.id, u)
  230. if (action != '' && !quiet) { changes.push(changeOf(u, action, before, after, forced, mergeCommit, pusherId)) }
  231. }
  232. }
  233. }
  234. }
  235. // 2. the PRs we have not seen, oldest first (numbers follow the commit time)
  236. for (c of newCandidates(slug, repo.id)) {
  237. target = c.parsed.target == '' ? dflt : c.parsed.target
  238. targetTip = bt.tips[target]
  239. source = sourceOf(slug, c.sha, target)
  240. merged = targetTip != null && isAncestor(slug, c.sha, targetTip)
  241. if (merged || (source != '' && bt.tips[source] != null)) {
  242. head = !merged && source != '' ? bt.tips[source] : c.sha
  243. n = nextNumber(repo.id)
  244. author = quiet || pusherId == null ? null : pusherId
  245. rec = { 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 }
  246. if (setPullRef(slug, n, head)) {
  247. id = pullRecs.put(rec)
  248. if (id != null && !quiet) {
  249. saved = pullRecs.fetch(id)
  250. changes.push(changeOf(saved, merged ? 'merged' : 'opened', null, head, false, merged ? mergeCommitOf(slug, c.sha, targetTip) : null, pusherId))
  251. }
  252. }
  253. }
  254. }
  255. return changes
  256. }
  257. // number the PRs a repo already has, ONCE (quiet); call it before a push is taken and when /pulls is built
  258. static ensurePulls = (slug) => {
  259. repo = repoBySlug(slug)
  260. if (repo == null || isInitialized(repo.id)) { return null }
  261. syncNow(slug, null, true)
  262. // an empty repo (no branch yet) has nothing to number and is initialized too: its first PR is a live one
  263. pullInit.put({ rid = repo.id })
  264. return null
  265. }
  266. // THE ENTRY: compare git with the records. Never fails the caller: whatever goes wrong yields the changes found so far (none).
  267. // userId = the gitoria user who pushed or merged (null when unknown). Every change is logged (logChange) and returned.
  268. static syncPulls = (slug, userId) => {
  269. ensurePulls(slug)
  270. changes = syncNow(slug, userId, false)
  271. for (c of changes) { logChange(slug, c) }
  272. return changes
  273. }
  274. // the change log until gitoria#43 sends events: one JSON line in storage/pull-changes.log (and the console)
  275. static logChange = (slug, c) => {
  276. repo = repoBySlug(slug)
  277. 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 })
  278. appendFile(changeLog, line + NL, 384)
  279. console.log('pull-change ' + line)
  280. return null
  281. }
  282. // ---- the contract's `pull` object (§4) --------------------------------------------------------------------
  283. static pullObject = (String slug, Number n, Hybrid approvalRows = null) => {
  284. repo = repoBySlug(slug)
  285. if (repo == null || n == null) { return null }
  286. rec = recordByNumber(repo.id, n)
  287. if (rec == null) { return null }
  288. msg = gitRaw(slug, ['log', '-1', '--format=%B', rec.sha])
  289. lines = msg != null && msg.exit == 0 ? msg.lines : []
  290. pr = lines.length > 0 ? parsePull(lines[0]) : null
  291. title = pr != null && pr.title != '' ? pr.title : (rec.source != '' ? rec.source : rec.sha.slice(0, 8))
  292. body = bodyOfLines(lines)
  293. baseTip = firstLine(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + rec.target])
  294. mergeBase = baseTip != '' ? firstLine(slug, ['merge-base', baseTip, rec.head]) : ''
  295. project = repo.tktProject != null ? repo.tktProject : ''
  296. statuses = []
  297. for (r of statusesOf(repo.id, rec.head)) { statuses.push(statusJson(r)) }
  298. return {
  299. number = rec.number
  300. title = title
  301. body = body
  302. draft = false
  303. state = rec.state
  304. author = { id = rec.authorId name = rec.authorName }
  305. source = rec.source
  306. target = rec.target
  307. head = rec.head
  308. ref = 'refs/pull/' + rec.number + '/head'
  309. baseRef = 'refs/heads/' + rec.target
  310. base = baseTip != '' ? baseTip : null
  311. mergeBase = mergeBase != '' ? mergeBase : null
  312. tickets = ticketNames(title + NL + body, project)
  313. url = repoOrigin(slug) + '/pulls/' + rec.number
  314. created = timestamp(rec.createdMs)
  315. updated = timestamp(rec.updatedMs)
  316. statuses = statuses
  317. required = requiredOf(repo.id)
  318. approvers = approversOf(repo.id)
  319. approvals = approvalsJson(approvalRows == null ? approvalsOf(repo.id, rec.number) : approvalRows, rec.head)
  320. }
  321. }
  322. // the rows of /pulls with their number: `number` (0 = not stored) and `numberText` ("#3")
  323. static withNumbers = (list, slug) => {
  324. out = []
  325. repo = repoBySlug(slug)
  326. for (p of list) {
  327. q = p
  328. rec = repo != null ? recordBySha(repo.id, p.sha) : null
  329. q.number = rec != null ? rec.number : 0
  330. q.numberText = rec != null ? '#' + rec.number : ''
  331. q.pageHref = rec != null ? px(slug) + '/pulls/' + rec.number : p.href
  332. out.push(q)
  333. }
  334. return out
  335. }

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