kunibert
All repositories: gitoria
8.8 KB
$mode = 'static'import { run } from 'hl:proc'import { readFile } from 'hl:fs'import { fetch } from 'hl:fetch'import { sha256 } from 'hl:crypto'import { require } from './review-output.hl'// Linked tickets as the spec source (kunibert#8). gitoria lists the ids (`pull.tickets`, `project#n`); we read the content from// the tickets service ourselves with our own read token. GET only. The token lives only in this process (never in an argv, a file// we write, a log or an error text).maxTickets = 10requestTimeoutMs = 15000 // the ONE timeout: per requestmaxSpecBytes = 60000 // cap of .kunibert/spec.mdnameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'digits = '0123456789'// strict `project#n`: project of [A-Za-z0-9._-] (1..100, not starting with '.', no '..'), n a positive integer without leading zero (max 9 digits)validId = (String id) => {parts = id.split('#')if (parts.length != 2) { return false }project = parts[0]n = parts[1]if (project.length < 1 || project.length > 100 || project.startsWith('.') || project.includes('..')) { return false }if (n.length < 1 || n.length > 9 || n.startsWith('0')) { return false }for (ch of project.split('')) { if (!nameChars.includes(ch)) { return false } }for (ch of n.split('')) { if (!digits.includes(ch)) { return false } }return true}// The token from its file (mode 600 required, first line); null when no file is configured. A configured but unusable file is an error.readToken = (String file) => {if (file == null || file == '') { return null }mode = run(['stat', '-c', '%a', file], { timeout = 10 })require(mode.exit == 0, 'tickets token file not readable')require(mode.lines.join('').trim().endsWith('00'), 'tickets token file must have mode 600 (no group/other access)')token = readFile(file).split('\n')[0].trim()require(token != '', 'tickets token file is empty')return token}// One GET. { id, ok, status, text } ; 404/403/other failures are { ok = false, status } (the caller says "not readable"), never an error.fetchTicket = (String base, String token, String id) => {parts = id.split('#')url = base + '/api/projects/' + encodeURIComponent(parts[0]) + '/tickets/' + parts[1]r = fetch(url, { method = 'GET', headers = { authorization = 'Bearer ' + token, accept = 'text/markdown', 'user-agent' = 'kunibert-review' }, timeoutMs = requestTimeoutMs, maxRedirects = 0 })if (!r.ok) { return { =id, ok = false, status = r.status, text = '' } }return { =id, ok = true, status = r.status, text = r.text() }}NL = ''// "# project #n: Title" is the first line of the served markdown.titleOf = (String md) => {first = md.split(NL)[0]i = first.indexOf(': ')if (first.startsWith('# ') && i > 0) { return first.slice(i + 2).trim() }return '(no title)'}// One fetched ticket as { id, link, title, head, entries[] } : `head` is title..description (everything before "## History"),// entries are the history items ("### n · date · ..." with their text), oldest first as the service sends them.parseTicket = (String base, String id, String md) => {parts = id.split('#')let top = mdlet hist = ''k = md.indexOf(NL + '## History' + NL)if (k >= 0) { top = md.slice(0, k) hist = md.slice(k + (NL + '## History' + NL).length) }let entries = []let cur = nullfor (line of hist.split(NL)) {if (line.startsWith('### ')) {if (cur != null) { entries.push(cur) }cur = { heading = line, body = [] }} else if (cur != null) { cur.body.push(line) }}if (cur != null) { entries.push(cur) }let rest = top.split(NL)rest.shift()let items = []for (e of entries) { items.push({ heading = e.heading, body = e.body.join(NL).trim(), cut = false }) }return { =id, link = base + '/' + parts[0] + '/' + parts[1], title = titleOf(md), head = rest.join(NL).trim(), entries = items }}section = (Hybrid t) => {let lines = ['## ' + t.id + ': ' + t.title, 'link: ' + t.link, '', t.head, '', '### History (oldest first)']for (e of t.entries) {lines.push('')lines.push(e.heading)if (e.cut) { lines.push('[comment text cut to keep this file under the size limit]') }else if (e.body != '') { lines.push(e.body) }}return lines.join(NL)}header = 'Spec file of Kunibert (kunibert#8): the tickets this pull request links to, read from the tickets service just now, each with its description and its history (comments and state changes) OLDEST FIRST.A later comment overrules the description and every earlier comment: where they disagree, the newest comment is the requirement.'total = (Hybrid tickets, Hybrid notReadable, Hybrid notes) => {return toBytes(render(tickets, notReadable, notes)).length}render = (Hybrid tickets, Hybrid notReadable, Hybrid notes) => {// keep the order of the PR's list: readable ones carry their indexlet blocks = []for (let a = 1; a <= 200; a = a + 1) {for (t of tickets) { if (t.at == a) { blocks.push({ text = section(t) }) } }for (n of notReadable) { if (n.at == a) { blocks.push({ text = '## ' + n.id + ': not readable (' + n.why + ')' }) } }}let lines = [header]for (n of notes) { lines.push('') lines.push(n) }for (b of blocks) { lines.push('') lines.push('---') lines.push('') lines.push(b.text) }return lines.join(NL) + NL}// Cut to the cap: the oldest history entries first (round robin over the tickets: every ticket's oldest, then the next oldest), their text only, the// heading stays; then, only if still over, the description of the biggest ticket. Says what was cut.fit = (Hybrid tickets, Hybrid notReadable, Hybrid notes) => {limit = maxSpecBytes - 400 // room for the NOTE line added at the endlet cutEntries = 0let cutDesc = 0let more = truelet i = 0while (total(tickets, notReadable, notes) > limit && more) {more = falsefor (t of tickets) {if (i < t.entries.length) {more = trueif (!t.entries[i].cut && total(tickets, notReadable, notes) > limit) { t.entries[i].cut = true cutEntries = cutEntries + 1 }}}i = i + 1}let guard = 0while (total(tickets, notReadable, notes) > limit && guard < 20) {guard = guard + 1let big = tickets[0]for (t of tickets) { if (t.head.length > big.head.length) { big = t } }excess = total(tickets, notReadable, notes) - limitlet keep = big.head.length - excess - 200if (keep < 0) { keep = 0 }cutDesc = cutDesc + 1big.head = big.head.slice(0, keep) + NL + '[description cut to keep this file under the size limit]'}let parts = []if (cutEntries > 0) { parts.push('the text of the ' + cutEntries + ' oldest history entries') }if (cutDesc > 0) { parts.push('part of a description') }if (parts.length > 0) { notes.push('NOTE: this file was cut to stay under ' + maxSpecBytes + ' bytes: ' + parts.join(' and ') + ' (the newest comments and the descriptions are kept first). Read the full tickets at the links if a cut matters.') }return render(tickets, notReadable, notes)}// ids -> { text, hash, ids, readable, notReadable } ; text == null when there is nothing to show (no ids, or no token configured).// base/tokenFile null: no tickets are read at all (today's "no ticket linked").buildSpec = (String base, String tokenFile, Hybrid ids) => {if (base == null || tokenFile == null || ids == null || ids.length == 0) { return { text = null, hash = null, readable = 0, notReadable = 0 } }token = readToken(tokenFile)let root = base.endsWith('/') ? base.slice(0, base.length - 1) : baselet tickets = []let bad = []let notes = []let seen = []let at = 0for (id of ids.slice(0, 100)) {if (seen.includes(id)) { continue }seen.push(id)at = at + 1if (at > 200) { break }if (!validId(id)) { bad.push({ id = id.slice(0, 60), why = 'not a valid project#n id, ignored', =at }) continue }if (seen.length > maxTickets) { notes.push('NOTE: the PR links more than ' + maxTickets + ' tickets; only the first ' + maxTickets + ' are read.') break }r = fetchTicket(root, token, id)if (!r.ok) {why = r.status == 404 ? 'HTTP 404, no such ticket' : (r.status == 403 || r.status == 401 ? 'HTTP ' + r.status + ', no access' : 'HTTP ' + r.status)bad.push({ =id, =why, =at })} else {t = parseTicket(root, id, r.text)t.at = attickets.push(t)}}if (tickets.length == 0 && bad.length == 0) { return { text = null, hash = null, readable = 0, notReadable = 0 } }text = fit(tickets, bad, notes)return { =text, hash = sha256(text), readable = tickets.length, notReadable = bad.length }}