gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit54eec68754eec687Gate person approvals and merge alternativesmre54eec687/lib/pullsync.hl

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

Branches

Latest commits

  • 54eec687Gate person approvals and merge alternativesmre
  • 12b08829Add person approvals for pull request headsmre
  • 55c84779Merge branch 'gp-gate-ports' into mainGitoria
  • 57af42bbREADME: point to deploy.sh for the port listmre
  • d63375d2README: gate commands with explicit portsmre
  • feeaa701|||PR gates: explicit ports only, deploy.sh passes themmre
  • 6cc1f943Merge branch 'records-1112' into mainGitoria
  • 9448c438|||PR records: LOG, missions and reports since 11-09mre
  • 6dc08a8eMerge branch 'p51-public-pr-reads' into mainGitoria
  • 7b88cfe0Type publicReaderOfRequest parameters (L10)Gitoria
  • 2a4b3dc1|||PR Anonymous reads of public repos' pulls and statusesmre
  • 21b2c141Merge branch 's25-no-session-on-login-error' into mainGitoria
  • 698458e2|||PR No session for cookieless login errors: READMEmre
  • cce7b785|||PR No session for cookieless login errorsmre
  • 678d6303Merge branch 'v59' into mainGitoria
  • 5803cf4f|||PR vendor: Hybriel set-day59 and GC budget 32 MiBmre
  • 9eff6627Merge branch 'f2-api-bugs' into mainGitoria
  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre