gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb9137ff0b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmreb9137ff0/lib/pullsync.hl

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

Branches

Latest commits

  • b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
  • 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
  • 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre
  • c4175e6dgitoria: a startup error prints its message before exit 1 (hybriel#247)mre
  • c50d17efKeep function-route not-found style in shared stylesheetmre
  • e42d78d3Preserve ticket state CSS and document function-route style gapmre
  • c6b7154eWIP gitoria#26: move styles into nested component blocksmre
  • 77a2c31cgitoria#31: plain declarations instead of needless let in lib/ and tools/ (103 let removed, 137 kept because reassigned); no other changemre
  • 4b98ab62gitoria: an ident access key (idt_) works as the git password; read key clones only, bad key 401, ident down 503 (ident#27); gate tests/ident-access-gitoria.mjs in deploy.shmre
  • 1185f686gitoria#36: a failed return from tickets shows a note on the settings page and leaves one log line per outcome; no code is exchangedmre
  • 5d2c385agitoria: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 71+5 failing → 76 passed; deploy.sh runs tests/private.mjs toomre
  • 241ef3f9deploy.sh: rebuild the sshd image before up -d (GO34c)mre
  • 821cdbb1gitoria#34b: styles, create-repo tool, docs, push/ssh gates sign in through the selector, shots scriptmre
  • a81abdc9gitoria#34: org page via function route, member-reachable orgs, selects, reportmre
  • 17f031f0gitoria#34: private repos, organizations, members, move tool, gatemre
  • 71b69343gitoria#23: the sidebar's Repositories link was a 404 after any in-page navigation (static menu re-evaluated publicUrl in the browser); the menu is an instance property now; gate taps it after a tab, folder, filemre
  • 90b4f728gitoria#25: restore the homepage cache and the parsed-blocks cache (they store data under immutable keys, no HTML); the page key, the framework readme key and the textHash key stay removedmre
  • a487248cgitoria#25: remove every cache that hid the page build (page key, Markdown render key, homepage cache, parsed-blocks cache) and the gate that only tested themmre
  • 12f2f4fegitoria: re-vendor Hybriel set-day27b, a startup fault in on Error exits 1mre
  • c21c084egitoria: write the standby service out in full so the boot gate can read the main servicemre