gitoria
All repositories: gitoria
12.6 KB
// tickets.hl — THE TICKETS OF A REPO (gitoria#10, gitoria#18; CONCEPT "/tickets"). The tickets are NOT stored in// gitoria: they live in a tickets.worldapi.org project the repo's OWNER connected in the repo's settings// (docs: antcolony-docs/docs/tickets-connect-apps.md). The connect flow:// 1. /settings/connect (project.hl) sends the owner's browser to <tickets>/connect?app=gitoria&label=<slug>&return=…&state=…// 2. tickets brings them back to /settings/connected?code=…&state=… (the state is the nonce of step 1, kept in the session)// 3. exchangeConnect(code): POST <tickets>/api/connect/exchange { code } → { key, project, title, api }, from THIS server.// The key is stored per repo (repos.hl, mpackdb) and never sent to a page.// Every write then carries `Authorization: Bearer <key>` and `X-Tickets-Identity: <ident id of the person>`: the person// (not gitoria) is the author, under the project's roles. Reads need no key.// Links both ways: "#12" in a commit subject or a pull request title links ticket 12 (refParts); a push posts// "mentioned in commit …" on that ticket, and a merged `|||PR` whose title says "fixes #12" sets ticket 12 to review (notifyPush).// Config (environment, or `.env` beside project.hl — never printed): GITORIA_TICKETS_URL, default https://tickets.worldapi.orgimport { fetch } from 'hl:fetch'import { MPackDB } from 'hl:mpackdb'import { now } from 'hl:time'import { envOr, plainError, storageDir, firstOf, countOfList, userRecord, publicUrl, repoOrigin } from './users.hl'import { repoBySlug } from './repos.hl'import { gitRaw, tabs, isHexId, pullsNow } from './git.hl'static NL = ""static ticketsRaw = envOr('GITORIA_TICKETS_URL', 'https://tickets.worldapi.org')static ticketsUrl = ticketsRaw.endsWith('/') ? ticketsRaw.slice(0, ticketsRaw.length - 1) : ticketsRawstatic maxRows = 200static agent = 'gitoria.worldapi.org (tickets)'// what was already told to tickets (a push arrives again with the same commits): one row per `<slug> <what> <sha> <n>`static seenTable = new MPackDB(file = storageDir + '/ticketlinks.db', primaryKey = '@id', indexes = ['!key'])// ---- the connect flow ------------------------------------------------------------------------------static connectHref = (slug, state) => {let back = repoOrigin(slug) + '/settings/connected'return ticketsUrl + '/connect?app=gitoria&label=' + encodeURIComponent(slug) + '&return=' + encodeURIComponent(back) + '&state=' + encodeURIComponent(state)}static isCode = (s) => {if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 200) { return false }let i = 0while (i < s.length) {let c = s.charCodeAt(i)if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || c == 45 || c == 95)) { return false }i = i + 1}return true}// the code tickets sent back → { key, project, title, api } | { error }static exchangeConnect = (code) => {if (!isCode(code)) { return { error = 'that is not a code from tickets' } }let r = fetch(ticketsUrl + '/api/connect/exchange', { method = 'POST' json = { code = code } headers = { 'user-agent' = agent } timeoutMs = 10000 })if (r == null || r.status == null || r.status == 0) { return { error = 'tickets.worldapi.org did not answer' } }let j = r.json()if (r.status != 200 || j == null || j.key == null || j.project == null || j.api == null) {return { error = 'tickets.worldapi.org refused the connection (' + r.status + (j != null && j.error != null ? ': ' + j.error : '') + ')' }}if (hlTypeName(j.key) != 'String' || !j.key.startsWith('tktc_') || hlTypeName(j.api) != 'String' || !j.api.startsWith(ticketsUrl + '/api/projects/')) { return { error = 'tickets.worldapi.org sent an answer gitoria does not understand' } }return { key = j.key project = '' + j.project title = j.title != null ? '' + j.title : '' + j.project api = j.api }}// ---- reading ---------------------------------------------------------------------------------------// the project of a connected repo (the server-side record has the key): { key, api, project } or nullstatic connectionOf = (slug) => {let r = repoBySlug(slug)if (r == null || r.tktKey == null || r.tktKey == '' || r.tktApi == null || r.tktApi == '') { return null }return { key = r.tktKey api = r.tktApi project = r.tktProject title = r.tktTitle }}static ticketHref = (project, n) => { return ticketsUrl + '/projects/' + project + '/' + n }// one row for the page (a state's words are shown as tickets writes them)static viewOf = (t) => {return { number = t.number subject = t.subject state = t.state stateSlug = t.stateSlug created = t.created updated = t.updated url = ticketsUrl + t.href }}// the repo's tickets, newest update first (tickets' order): { tickets, count, truncated, project, url } or { error }static loadTickets = (slug) => {let c = connectionOf(slug)if (c == null) { return { error = 'not connected' } }let r = fetch(c.api + '/tickets', { method = 'GET' headers = { 'user-agent' = agent } timeoutMs = 10000 })if (r == null || r.status == null || r.status == 0) { return { error = 'tickets.worldapi.org did not answer' } }let base = { project = c.project url = ticketsUrl + '/projects/' + c.project }let j = r.status == 200 ? r.json() : nullif (j == null || j.tickets == null) { return { error = 'tickets.worldapi.org answered ' + r.status } }let out = []for (t of j.tickets) { if (out.length < maxRows) { out.push(viewOf(t)) } }base.tickets = outbase.count = j.tickets.lengthbase.truncated = j.tickets.length > out.lengthreturn base}// ---- writing (as a person) ---------------------------------------------------------------------------static writeHeaders = (c, identity) => {return { 'user-agent' = agent 'authorization' = 'Bearer ' + c.key 'x-tickets-identity' = identity }}static whyOf = (r) => {let j = r.json()return j != null && j.error != null ? ': ' + j.error : ''}// open a ticket for a repo as the person with this ident id: { ticket } or { error, field }static openTicket = (slug, identity, subject, summary) => {let s = subject == null ? '' : ('' + subject).trim()if (s == '') { return { error = 'the ticket needs a subject' field = 'subject' } }let bad = plainError(s, 200, 'the subject')if (bad != null) { return { error = bad field = 'subject' } }let body = summary == null ? '' : ('' + summary).trim()if (body.length > 20000) { return { error = 'the text is too long (at most 20000 characters)' field = 'summary' } }let c = connectionOf(slug)if (c == null) { return { error = 'this repository is not connected to a tickets project (see Settings)' field = '' } }let r = fetch(c.api + '/tickets', { method = 'POST' json = { subject = s summary = body } headers = writeHeaders(c, identity) timeoutMs = 10000 })if (r == null || r.status == null || r.status == 0) { return { error = 'tickets.worldapi.org did not answer' field = '' } }let j = r.json()if ((r.status != 201 && r.status != 200) || j == null || j.ticket == null) {if (r.status == 403) { return { error = 'tickets refused: log in to tickets.worldapi.org once, choose a display name there, and check you may edit this project' + whyOf(r) field = '' } }return { error = 'tickets.worldapi.org refused the ticket (' + r.status + whyOf(r).slice(0, 200) + ')' field = '' }}return { ticket = viewOf(j.ticket) }}// a comment on ticket n as a person → true when tickets took it, or answered it with a refusal (no retry then)static commentTicket = (c, identity, n, text) => {let r = fetch(c.api + '/tickets/' + n + '/comments', { method = 'POST' json = { text = text } headers = writeHeaders(c, identity) timeoutMs = 10000 })return r != null && r.status != null && r.status > 0 && r.status < 500}static stateTicket = (c, identity, n, state, text) => {let r = fetch(c.api + '/tickets/' + n + '/state', { method = 'POST' json = { state = state text = text } headers = writeHeaders(c, identity) timeoutMs = 10000 })return r != null && r.status != null && r.status > 0 && r.status < 500}// ---- "#12" in a text ---------------------------------------------------------------------------------static isDigitCode = (c) => { return c >= 48 && c <= 57 }static isWordCode = (c) => { return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 }// every `#N` of a text (N = 1–9 digits, not glued to a word before it): [{ at, len, n }]static refsOf = (text) => {let out = []if (text == null || hlTypeName(text) != 'String') { return out }let i = 0while (i < text.length) {if (text[i] == '#' && (i == 0 || !isWordCode(text.charCodeAt(i - 1)))) {let j = i + 1while (j < text.length && j - i - 1 < 9 && isDigitCode(text.charCodeAt(j))) { j = j + 1 }let stop = j >= text.length || !isWordCode(text.charCodeAt(j))if (j > i + 1 && stop && text.slice(i + 1, i + 2) != '0') { out.push({ at = i len = j - i n = toNumber(text.slice(i + 1, j)) }) }i = j} else {i = i + 1}}return out}// a text as pieces for a View: [{ text, href, isLink, isText }] — `#N` becomes a link when the repo is connectedstatic refParts = (text, project) => {let out = []let t = text == null ? '' : '' + textlet refs = project == null || project == '' ? [] : refsOf(t)let pos = 0for (x of refs) {if (x.at > pos) { out.push({ text = t.slice(pos, x.at) href = '' isLink = false isText = true }) }out.push({ text = t.slice(x.at, x.at + x.len) href = ticketHref(project, x.n) isLink = true isText = false })pos = x.at + x.len}if (pos < t.length || out.length == 0) { out.push({ text = t.slice(pos) href = '' isLink = false isText = true }) }return out}// the numbers a text says it fixes: "fixes #3", "closes #4, #5"? — only the word directly before `#N` countsstatic fixedBy = (text) => {let out = []let t = text == null ? '' : ('' + text).toLowerCase()for (x of refsOf(t)) {let before = t.slice(0, x.at).trimEnd()let ok = falsefor (w of ['fix', 'fixes', 'fixed', 'close', 'closes', 'closed', 'resolve', 'resolves', 'resolved']) {if (before.endsWith(w) && (before.length == w.length || !isWordCode(before.charCodeAt(before.length - w.length - 1)))) { ok = true }}if (ok && !out.includes(x.n)) { out.push(x.n) }}return out}// the commit list of a code page with pieces for the subjects (the View draws links from `parts`)static withRefParts = (data, project) => {if (data == null || data.isMessage) { return data }let d = datad.subjectParts = refParts(d.subject, project)let cs = []for (c of d.commits) {let q = cq.parts = refParts(c.subject, project)cs.push(q)}d.commits = csreturn d}static withPullParts = (list, project) => {let out = []for (p of list) {let q = pq.parts = refParts(p.title, project)out.push(q)}return out}// ---- after a push or a merge: tell tickets ---------------------------------------------------------------static seen = (key) => { return countOfList(seenTable.find('key', key)) > 0 }static markSeen = (key) => { seenTable.put({ key = key created = now() }) }// The recent commits of every branch that name a ticket: "mentioned in commit …" as a comment on it, once per// commit and ticket. `quiet` only marks them (the moment of connecting: old history is not announced).// Then every MERGED pull request whose title says "fixes #N" sets ticket N to review, once. The person is the repo's// owner (pushes and merges are the owner's). Failures are silent (the push has succeeded); a refusal by tickets is not retried.static notifyPush = (slug, quiet) => {let c = connectionOf(slug)let repo = repoBySlug(slug)if (c == null || repo == null) { return null }let owner = userRecord(repo.owner)if (owner == null || owner.identity == null) { return null }let lg = gitRaw(slug, ['log', '-100', '--branches', '--format=%H%x09%s'])if (lg != null && lg.exit == 0) {for (l of lg.lines) {let f = tabs(l)if (f.length >= 2 && isHexId(f[0])) {let sub = f.slice(1).join(' ')for (x of refsOf(sub)) {let key = slug + ' commit ' + f[0] + ' ' + x.nif (!seen(key)) {if (quiet || commentTicket(c, owner.identity, x.n, 'Mentioned in commit [' + f[0].slice(0, 8) + '](' + repoOrigin(slug) + '/commit/' + f[0] + ') of ' + slug + ':' + NL + NL + '> ' + sub)) { markSeen(key) }}}}}}let got = pullsNow(slug, repo.branch != null ? repo.branch : '')if (got != null && !got.isMessage) {for (p of got.pulls) {if (p.isMerged) {for (n of fixedBy(p.title)) {let key = slug + ' pr ' + p.sha + ' ' + nif (!seen(key)) {if (quiet || stateTicket(c, owner.identity, n, 'review', 'Fixed by the merged pull request [' + p.title + '](' + repoOrigin(slug) + '/commit/' + p.sha + ') of ' + slug + '.')) { markSeen(key) }}}}}}return null}
Branches
- mainmain branch