gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3373f7c33373f7c3gitoria#38: push API contract v1.2.1, reviews, worker briefs and logmre3373f7c3/lib/pullsync.hl

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

Branches

Latest commits

  • 3373f7c3gitoria#38: push API contract v1.2.1, reviews, worker briefs and logmre
  • 34143d2cgitoria#46: closing brace of appComments lost in the mergemre
  • 54927c9cgitoria#46: PR statuses and required checks before merge (merge w46-status)mre
  • 187e1871gitoria#46: badges without decorative bordersmre
  • 6b022798gitoria#46: tests/status.mjs in GATESmre
  • c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmre
  • e5a0b64egitoria#46: PUT statuses/<sha>, required contexts block the merge on the servermre
  • 26a140e3gitoria#44: reviews, inline threads, replies, conversation for apps (merge w44-reviews)mre
  • 888dbf87gitoria#44: unknown API paths answer the contract's JSON 404 and sit above the page routesmre
  • ea587d90gitoria#44: reviews with inline threads, replies, resolve and the PR conversation for apps (lib/reviews.hl, tests/reviews.mjs)mre
  • 49533a50gitoria#43: signed events to connected apps (merge w43-events)mre
  • 1a1e87d5gitoria#43: the sender never writes the apps row; Settings shows the newest deliverymre
  • cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
  • 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
  • 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
  • 15e01e94gitoria#43: tests/events.mjs and its probemre
  • 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)mre
  • b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre