gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitbef635c1bef635c1Merge branch 'w30b'mrebef635c1/lib/pullsync.hl

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

Branches

Latest commits

  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre
  • 01b71c2edocs: neutral wording in missions, reports and logmre
  • 3eeea733log: 2026-11-09 PR flow plan and membersmre
  • e7c2ff1fdocs: neutral name for the apps-api reviewmre
  • 120b7abdlog: step 3 queuedmre
  • 358474bflog: P50 livemre
  • 477d7bdcMerge branch 'p50'mre
  • 00efc06fP50 reportmre
  • e3f85afblog: commit mention slipmre
  • 4d1a4cf4log: #25 numbersmre
  • 1af0a60ddocs: H25 run() correctionmre
  • eefa2dbcRepo setting: refuse direct pushes to the main branch (pre-receive over HTTPS and ssh)mre
  • 8c8ba2f1log: PR flow announcedmre
  • fa00cd35log: Kunibert pings provenmre
  • 3a68cfaclog: components decisionmre
  • 87de8e31log: Kunibert connected to 9 app reposmre