gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdb443456db443456log: vinzenz note retry 2mredb443456/lib/pullsync.hl

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

Branches

Latest commits

  • db443456log: vinzenz note retry 2mre
  • 802f229alog: kunibert repo ping provenmre
  • 2d2eaa92log: Kunibert connected to kunibert repomre
  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre
  • 166c775fW48 report, logmre
  • 1b4623f0Members merge pull requests: API route, button on /pulls and /pulls/N, one shared merge pathmre
  • 1075c38cW48 mission, logmre
  • 17bdd0d6V37/V39 missions, logmre
  • 146de5f8Re-vendor gitoria to Hybriel set-day39 (51e921d7)mre
  • e874e44dtests/status-keyed: app token lives 60 s so it outlives the gate's two restartsmre
  • 270b8d61deploy.sh: DEPLOY_STOP_START=1 stops, waits for the old pid, then starts (mpackdb freeze, replaces the standby swap)mre
  • 3f9235b8project.hl: drop the dummy /pulls/:n component route (hybriel#294 is fixed in day37)mre
  • c90daf19Re-vendor gitoria to Hybriel set-day37 (f6b3d45b)mre