diff --git a/apps/mobile/src/app/bot-new.tsx b/apps/mobile/src/app/bot-new.tsx index a6d6b85..a7380ca 100644 --- a/apps/mobile/src/app/bot-new.tsx +++ b/apps/mobile/src/app/bot-new.tsx @@ -7,9 +7,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import { useEffect, useMemo, useState } from "react"; import { View } from "react-native"; import type { PermissionMode } from "@hermit/core"; -import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots"; import type { BotProposalView } from "@hermit/runtime"; -import { BOT_TEMPLATES, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view"; +import { BOT_TEMPLATES, capBotName, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, toNewBot, type BotForm, type BotTemplateId } from "../bot-form-view"; import { BLANK_LOOK, TEMPLATE_LOOKS } from "../bot-templates"; import { BotAvatar } from "../components/BotAvatar"; import { ModeSheet } from "../components/ModeSheet"; @@ -136,10 +135,10 @@ export default function BotNew() { edit({ name })} + onChange={(name) => edit({ name: capBotName(name) })} invalid={problems.includes("name_too_long")} style={{ flex: 1 }} - field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }} + field={{ autoCapitalize: "words" }} /> {problems.includes("name_too_long") ? : null} diff --git a/apps/mobile/src/app/bot-settings.tsx b/apps/mobile/src/app/bot-settings.tsx index 88b45c0..063fe8a 100644 --- a/apps/mobile/src/app/bot-settings.tsx +++ b/apps/mobile/src/app/bot-settings.tsx @@ -6,9 +6,8 @@ import { useLocalSearchParams, useRouter } from "expo-router"; import { useCallback, useEffect, useState } from "react"; import { AccessibilityInfo, View } from "react-native"; -import { MAX_BOT_NAME_CHARS } from "@hermit/core/bots"; import { HERMIT_BOT_ID, type Bot, type MemoryCursor, type Note as Fact, type PermissionMode } from "@hermit/core"; -import { formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view"; +import { capBotName, formNeedsFingerprint, formPatch, formProblems, fromBot, noteActions, settingsResult, type BotForm } from "../bot-form-view"; import { forgetBotCaches } from "../adapters"; import { BotAvatar } from "../components/BotAvatar"; import { ConfirmSheet, ConnectorsList, GroupsList, LookPicker, Refusal, modeLine, useSourceChoices } from "../components/BotFormParts"; @@ -230,7 +229,7 @@ export default function BotSettings() { {hermitBot ? ( {t("HM-BOT-04.hermitRole")} ) : ( - edit({ name })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words", maxLength: MAX_BOT_NAME_CHARS }} /> + edit({ name: capBotName(name) })} invalid={problems.includes("name_too_long") || problems.includes("name_empty")} style={{ flex: 1 }} field={{ autoCapitalize: "words" }} /> )} {problems.includes("name_empty") ? : null} diff --git a/apps/mobile/src/bot-form-view.test.ts b/apps/mobile/src/bot-form-view.test.ts index d10db20..7c06f71 100644 --- a/apps/mobile/src/bot-form-view.test.ts +++ b/apps/mobile/src/bot-form-view.test.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import { RESERVED_GROUPS, SKILL_GROUPS, type BotLook } from "@hermit/core/bots"; import type { BotProposalView } from "../../../packages/runtime/src/bot-api.ts"; import { BOT_REFUSALS } from "../../../packages/runtime/src/bot-api.ts"; -import { BOT_TEMPLATES, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts"; +import { BOT_TEMPLATES, capBotName, formPatch, fromBot, fromProposal, fromTemplate, formNeedsFingerprint, formProblems, noteActions, proposalCard, refusalLine, settingsResult, shownGroups, toNewBot, type BotForm } from "./bot-form-view.ts"; const LOOK: BotLook = { shape: "whelk", color: "sand" }; const form = (over: Partial = {}): BotForm => ({ name: "Viajes", role: "Planeas los viajes de la familia Prueba.", look: LOOK, grants: ["web_read", "notes"], sites: "wikivoyage.org", connectors: [], mode: null, ...over }); @@ -18,6 +18,18 @@ test("HM-BOT-03: the form's problems match the runtime's limits", () => { assert.deepEqual(formProblems(form({ name: "n".repeat(41), role: "r".repeat(801), sites: "wikivoyage.org, 192.168.0.1" })), ["name_too_long", "role_too_long", "bad_site"]); assert.deepEqual(formProblems(form()), []); }); +test("HM-BOT-03: a bot name is capped at 40 code points, keeping emoji whole", () => { + assert.equal(capBotName("😀".repeat(40)), "😀".repeat(40)); + assert.equal(capBotName("😀".repeat(41)), "😀".repeat(40)); + assert.equal(capBotName("n".repeat(41)), "n".repeat(40)); + assert.equal(capBotName("Viajes"), "Viajes"); +}); + +test("HM-BOT-03: a role of 800 emoji passes, 801 does not", () => { + assert.deepEqual(formProblems(form({ role: "😀".repeat(800) })), []); + assert.deepEqual(formProblems(form({ role: "😀".repeat(801) })), ["role_too_long"]); +}); + test("HM-BOT-03: the fingerprint for mail send, logins, pay or Don't ask, and only when newly granted", () => { assert.equal(formNeedsFingerprint(form({ grants: ["mail_read"] })), false); assert.equal(formNeedsFingerprint(form({ grants: ["mail_send"] })), true); diff --git a/apps/mobile/src/bot-form-view.ts b/apps/mobile/src/bot-form-view.ts index 6ef009e..3d381b2 100644 --- a/apps/mobile/src/bot-form-view.ts +++ b/apps/mobile/src/bot-form-view.ts @@ -16,11 +16,16 @@ export function formProblems(f: BotForm): Array<"name_empty" | "name_too_long" | const name = f.name.trim(); if (!name) out.push("name_empty"); else if ([...name].length > MAX_BOT_NAME_CHARS) out.push("name_too_long"); - if (f.role.trim().length > MAX_ROLE_CHARS) out.push("role_too_long"); + if ([...f.role.trim()].length > MAX_ROLE_CHARS) out.push("role_too_long"); if (siteWords(f.sites).some((w) => normalizeSite(w) === undefined)) out.push("bad_site"); return out; } +/** Cap a typed bot name at MAX_BOT_NAME_CHARS code points, keeping emoji whole. React Native's `maxLength` counts UTF-16 units, so it stops a name of 40 emoji at 20; this caps by code point instead, like the store does. */ +export function capBotName(text: string): string { + return [...text].slice(0, MAX_BOT_NAME_CHARS).join(""); +} + /** * Task 1's one rule as the runtime applies it: on the bot's own mode only. A null mode ("Como el resto") brings no Don't * ask of its own, whatever the global mode is (the global took the word and the fingerprint when it was set), so diff --git a/apps/site/locales/es-419.json b/apps/site/locales/es-419.json index 703fadc..905e6c9 100644 --- a/apps/site/locales/es-419.json +++ b/apps/site/locales/es-419.json @@ -140,13 +140,13 @@ "HM-SITE-01.sourceBody": "Hermit es de código abierto bajo Apache 2.0. La jaula que revisa cada acción, los controles de privacidad que hacen fallar la compilación, las evaluaciones y este sitio viven en un solo repositorio público.", "HM-SITE-01.sourceContribute": "Contribuir", "HM-SITE-01.sourceCodeLabel": "Descarga el código y corre los controles de privacidad", - "HM-SITE-01.labKicker": "Laboratorio de dispositivos", + "HM-SITE-01.labKicker": "Laboratorio del teléfono", "HM-SITE-01.labTitle": "Ayúdanos a que Hermit sea rápido en cada teléfono.", - "HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el reporte. Cada uno muestra dónde le falta trabajo a Hermit.", + "HM-SITE-01.labBody": "Hermit corre un modelo pequeño en el propio teléfono, y cada teléfono es distinto. Corre la prueba de rendimiento en el tuyo y comparte el informe. Cada uno muestra dónde le falta trabajo a Hermit.", "HM-SITE-01.labStep1Title": "Corre la prueba", "HM-SITE-01.labStep1Body": "Mide al modelo en tu teléfono y revisa sus respuestas.", - "HM-SITE-01.labStep2Title": "Lee el reporte", - "HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el reporte antes que nadie.", + "HM-SITE-01.labStep2Title": "Lee el informe", + "HM-SITE-01.labStep2Body": "Nada sale de tu teléfono por su cuenta. Tú ves el informe antes que nadie.", "HM-SITE-01.labStep3Title": "Compártelo", "HM-SITE-01.labStep3Body": "Súbelo al repositorio, como explica la guía.", "HM-SITE-01.labCta": "Leer la guía de dispositivos", @@ -155,7 +155,7 @@ "HM-SITE-01.getKicker": "Consigue Hermit", "HM-SITE-01.getTitleA": "Hecho a la vista de todos.", "HM-SITE-01.getTitleB": "Rumbo a las tiendas.", - "HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su reporte. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.", + "HM-SITE-01.getBody": "Hermit está en pre-alfa y todavía no está en las tiendas. Los APK de vista previa para Android están en GitHub Releases: instala uno, corre el Laboratorio del teléfono y envía su informe. Dale una estrella al repositorio para seguirlo, o compílalo desde el código.", "HM-SITE-01.getSource": "Compilarlo desde el código", "HM-SITE-01.getApk": "Descargar el APK de vista previa", "HM-SITE-01.peekAlt": "Hermit asomándose desde adentro de su concha", diff --git a/apps/site/test/locales.test.ts b/apps/site/test/locales.test.ts index 8851d8a..4db9acf 100644 --- a/apps/site/test/locales.test.ts +++ b/apps/site/test/locales.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from "vitest"; import en from "../locales/en.json"; import es from "../locales/es-419.json"; +import appEn from "../../../packages/copy/locales/en.json"; +import appEs from "../../../packages/copy/locales/es-419.json"; import { translator } from "../lib/i18n"; const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/; @@ -53,6 +55,17 @@ describe("site copy", () => { } }); + test("the lab's kicker is the name the app gives the Device lab, in both languages", () => { + expect(en["HM-SITE-01.labKicker"]).toBe(appEn["HM-SET-10.title"]); + expect(es["HM-SITE-01.labKicker"]).toBe(appEs["HM-SET-10.title"]); + }); + + test("in Spanish the lab's report is an informe, as in the app, and the lab is never a laboratorio de dispositivos", () => { + for (const k of ["HM-SITE-01.labBody", "HM-SITE-01.labStep2Title", "HM-SITE-01.labStep2Body", "HM-SITE-01.getBody"] as const) { + expect(es[k], k).not.toMatch(/reporte|laboratorio de dispositivos/i); + } + }); + test("USD₮ is the only money the copy names", () => { for (const [k, v] of all) expect(v, k).not.toMatch(/\bUSDC\b|\bUSDT\b|stablecoin|\bETH\b|bitcoin/i); }); diff --git a/packages/copy/test/copy.test.ts b/packages/copy/test/copy.test.ts index 4bbffef..bb7a940 100644 --- a/packages/copy/test/copy.test.ts +++ b/packages/copy/test/copy.test.ts @@ -32,6 +32,45 @@ describe("locale files (CT-10)", () => { }); }); +// AGENTS.md rule 9: the app's Spanish uses tú. Only voseo forms that can't be read another way are listed, so +// "elegí" or "escribí" (also the first person past tense) stay out. \b doesn't count accented letters as letters, +// so the edges are (? { + test("the matcher flags voseo", () => { + for (const s of [ + "Tocá el botón", "Si querés, te aviso", "¿Podés esperar?", "Ya tenés todo.", "Si sabés la hora, dime.", "¿Qué hacés?", + "Decís que sí.", "Si necesitás algo, escribe.", "Si preferís, después.", "Mirá esto.", "Probá de nuevo.", "Activá las notificaciones.", + "Revisá el correo.", "Volvé a la lista.", "Poné tu huella.", "Usá la otra cuenta.", "Agregá un recordatorio.", "Cambiá la hora.", + "Guardá el cambio.", "Confirmá el pago.", "Dejá un mensaje.", "Buscá el archivo.", "Esperá un momento.", "Fijate en la fecha.", + "Acordate del lunes.", "Decime cuándo.", "Avisame mañana.", "Mandale un saludo a Ana.", "Contame más.", + ]) expect(s, s).toMatch(VOSEO); + }); + + test("the matcher ignores case, accented capitals included", () => { + expect("TOCÁ EL BOTÓN").toMatch(VOSEO); + expect("Querés").toMatch(VOSEO); + }); + + test("the matcher leaves tú and other words alone", () => { + for (const s of ["Toca el botón", "Si quieres, te aviso", "No abrí nada", "Elegí la primera.", "Le escribí a Luis."]) expect(s, s).not.toMatch(VOSEO); + }); + + test("the matcher counts accented letters as letters at both edges", () => { + for (const s of ["Antes tocábamos el timbre.", "Siempre dejábamos la llave.", "ñtocá", "étocá"]) expect(s, s).not.toMatch(VOSEO); + }); + + test("no value in es-419 uses voseo", () => { + for (const [k, v] of Object.entries(es)) expect(v, k).not.toMatch(VOSEO); + }); +}); + describe("translator", () => { test("fills placeholders", () => { expect(createTranslator(es)("HM-ACT-03.title", { index: 7 })).toBe("Cadena rota en la entrada 7"); diff --git a/packages/mail/src/text.ts b/packages/mail/src/text.ts index e006905..1270d7a 100644 --- a/packages/mail/src/text.ts +++ b/packages/mail/src/text.ts @@ -20,6 +20,9 @@ export function base64ToBytes(text: string): Uint8Array { return out.slice(0, o); } +/** The smallest code point each sequence length may carry, by the number of continuation bytes. */ +const MIN_CODE_POINT = [0, 0x80, 0x800, 0x10000]; + /** UTF-8 bytes to text; a malformed sequence becomes U+FFFD instead of throwing. */ export function utf8Decode(bytes: Uint8Array): string { let out = ""; @@ -46,7 +49,8 @@ export function utf8Decode(bytes: Uint8Array): string { } cp = (cp << 6) | (c & 0x3f); } - if (!ok || cp > 0x10ffff) { + // Only the shortest form is UTF-8, and it never encodes the surrogates U+D800 to U+DFFF (RFC 3629). + if (!ok || cp < MIN_CODE_POINT[need]! || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) { out += "�"; i++; continue; diff --git a/packages/mail/test/text.test.ts b/packages/mail/test/text.test.ts new file mode 100644 index 0000000..bcfe4a7 --- /dev/null +++ b/packages/mail/test/text.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "vitest"; +import { base64ToBytes, clip, decodeBase64Text, decodeEntities, htmlToText, plainText, splitAddresses, utf8Decode } from "../src/text.ts"; + +// FR-MAIL-02: the helpers that turn Gmail, Outlook and IMAP bodies into plain text. Made-up people and example.com only. +const bytes = (...b: number[]) => new Uint8Array(b); + +describe("base64ToBytes", () => { + it("reads plain base64", () => { + expect(base64ToBytes("SG9sYQ==")).toEqual(bytes(0x48, 0x6f, 0x6c, 0x61)); + }); + + it("reads base64url, with - and _ in place of + and /", () => { + expect(base64ToBytes("-_8")).toEqual(bytes(0xfb, 0xff)); + expect(base64ToBytes("-_8")).toEqual(base64ToBytes("+/8=")); + }); + + it("skips padding and line breaks", () => { + expect(base64ToBytes("SG9s\r\nYSBB\nbmE=\n")).toEqual(base64ToBytes("SG9sYSBBbmE")); + expect(new TextDecoder().decode(base64ToBytes("SG9s\r\nYSBB\nbmE=\n"))).toBe("Hola Ana"); + }); +}); + +describe("utf8Decode and decodeBase64Text", () => { + it("decodes Spanish accents and ñ", () => { + expect(utf8Decode(bytes(0x61, 0xc3, 0xb1, 0x6f, 0x20, 0x63, 0x61, 0x6d, 0x69, 0xc3, 0xb3, 0x6e))).toBe("año camión"); + expect(decodeBase64Text("TWHDsWFuYSB2ZW5nbyBhIGxhIHJldW5pw7NuLg==")).toBe("Mañana vengo a la reunión."); + }); + + it("decodes a four-byte character", () => { + expect(utf8Decode(bytes(0xf0, 0x9f, 0xa6, 0x80))).toBe("🦀"); + expect(decodeBase64Text("8J+mgA")).toBe("🦀"); + }); + + it("turns a broken sequence into U+FFFD instead of throwing", () => { + expect(utf8Decode(bytes(0x61, 0xc3, 0x28))).toBe("a�("); + expect(utf8Decode(bytes(0xff, 0x62))).toBe("�b"); + }); +}); + +describe("decodeEntities", () => { + it("decodes named references", () => { + expect(decodeEntities("María & José: mañana a las 3")).toBe("María & José: mañana a las 3"); + expect(decodeEntities("árbol")).toBe("árbol"); + }); + + it("decodes decimal and hex references", () => { + expect(decodeEntities("señor")).toBe("señor"); + expect(decodeEntities("señor y señora")).toBe("señor y señora"); + }); + + it("leaves an unknown name as it is", () => { + expect(decodeEntities("¬aname; y &")).toBe("¬aname; y &"); + }); +}); + +describe("htmlToText", () => { + it("drops script, style, head and title with their contents", () => { + const html = + "Asunto" + + "

Hola Ana

"; + expect(htmlToText(html)).toBe("Hola Ana"); + }); + + it("drops comments", () => { + expect(htmlToText("

Hola Luis

")).toBe("Hola Luis"); + }); + + it("breaks lines at br, p, div, li and headings", () => { + const html = "

Agenda

Uno
Dos
Tres

Cuatro
  • Cinco
  • Seis

Fin

"; + expect(htmlToText(html)).toBe("Agenda\nUno\nDos\nTres\nCuatro\nCinco\nSeis\nFin"); + }); + + it("leaves no blank lines", () => { + const text = htmlToText("

Hola

\n\n

 

\r\n

Chao

"); + expect(text).toBe("Hola\nChao"); + expect(text.split("\n").every((l) => l.trim())).toBe(true); + }); +}); + +describe("plainText", () => { + it("turns CRLF into LF", () => { + expect(plainText("Hola\r\nAna\r\n")).toBe("Hola\nAna"); + }); + + it("collapses runs of spaces", () => { + expect(plainText("Hola Ana,\t\tnos vemos")).toBe("Hola Ana, nos vemos"); + }); + + it("keeps at most one blank line in a row", () => { + expect(plainText("Hola\n\n\n\nAna\n\n\nChao")).toBe("Hola\n\nAna\n\nChao"); + expect(plainText("Hola\r\n\r\n\r\n\r\nAna")).toBe("Hola\n\nAna"); + }); +}); + +describe("clip", () => { + it("leaves text at or under the limit unchanged", () => { + expect(clip("Hola Ana", 8)).toBe("Hola Ana"); + expect(clip("Hola", 8)).toBe("Hola"); + }); + + it("cuts longer text and ends it with ...", () => { + const cut = clip("Nos vemos el lunes en la oficina", 12); + expect(cut).toBe("Nos vemos..."); + expect(cut.length).toBeLessThanOrEqual(12); + }); + + it("leaves no space before the ...", () => { + expect(clip("uno dos tres", 7)).toBe("uno..."); + expect(clip("uno dos tres", 7)).not.toMatch(/\s\.\.\.$/); + }); +}); + +describe("splitAddresses", () => { + it("splits at commas between addresses", () => { + expect(splitAddresses("Ana Torres , luis@example.com")).toEqual(["Ana Torres ", "luis@example.com"]); + }); + + it("doesn't split at a comma inside quotes", () => { + expect(splitAddresses("\"Pérez, Luis\" , Ana ")).toEqual([ + "\"Pérez, Luis\" ", + "Ana ", + ]); + }); + + it("doesn't split at a comma inside angle brackets", () => { + expect(splitAddresses("Ana , Luis ")).toEqual([ + "Ana ", + "Luis ", + ]); + }); + + it("gives an empty list for an empty or missing header", () => { + expect(splitAddresses("")).toEqual([]); + expect(splitAddresses(undefined)).toEqual([]); + expect(splitAddresses(" , ")).toEqual([]); + }); +}); diff --git a/packages/mail/test/utf8-decode.test.ts b/packages/mail/test/utf8-decode.test.ts new file mode 100644 index 0000000..51b32d6 --- /dev/null +++ b/packages/mail/test/utf8-decode.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { utf8Decode } from "../src/text.ts"; + +// #142: only the shortest form is UTF-8 (RFC 3629), and it never encodes U+D800 to U+DFFF. Each byte of such a +// sequence becomes U+FFFD, the same answer a standard decoder gives. +const decode = (...b: number[]) => utf8Decode(new Uint8Array(b)); +const standard = (...b: number[]) => new TextDecoder().decode(new Uint8Array(b)); + +describe("utf8Decode refuses what isn't UTF-8", () => { + it("turns overlong encodings into U+FFFD", () => { + expect(decode(0xc0, 0x80)).toBe("��"); + expect(decode(0xc1, 0x81)).toBe("��"); + expect(decode(0xe0, 0x80, 0x80)).toBe("���"); + expect(decode(0xe0, 0x9f, 0xbf)).toBe("���"); + expect(decode(0xf0, 0x80, 0x80, 0x80)).toBe("����"); + expect(decode(0xf0, 0x8f, 0xbf, 0xbf)).toBe("����"); + }); + + it("turns encoded surrogates into U+FFFD", () => { + expect(decode(0xed, 0xa0, 0x80)).toBe("���"); + expect(decode(0xed, 0xbf, 0xbf)).toBe("���"); + }); + + it("gives the same answer as a standard decoder for these sequences", () => { + for (const seq of [[0xc0, 0x80], [0xc1, 0x81], [0xe0, 0x80, 0x80], [0xf0, 0x80, 0x80, 0x80], [0xed, 0xa0, 0x80], [0x61, 0xc0, 0xaf, 0x62]]) { + expect(decode(...seq), seq.join(" ")).toBe(standard(...seq)); + } + }); + + it("still decodes the shortest form at each length's edges", () => { + expect(decode(0xc2, 0x80)).toBe("\u0080"); + expect(decode(0xe0, 0xa0, 0x80)).toBe("ࠀ"); + expect(decode(0xed, 0x9f, 0xbf)).toBe("퟿"); + expect(decode(0xee, 0x80, 0x80)).toBe(""); + expect(decode(0xf0, 0x90, 0x80, 0x80)).toBe("\u{10000}"); + expect(decode(0xf4, 0x8f, 0xbf, 0xbf)).toBe("\u{10FFFF}"); + }); +}); diff --git a/scripts/devices/table.mjs b/scripts/devices/table.mjs index 7bed2d1..c4dc570 100644 --- a/scripts/devices/table.mjs +++ b/scripts/devices/table.mjs @@ -7,6 +7,7 @@ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; import { loadSchema, reportFileName, validateReport } from "./validate.mjs"; export const START = ""; @@ -84,16 +85,43 @@ export function updateDoc(doc, table) { return `${doc.slice(0, start + START.length)}\n${table}\n${doc.slice(end)}`; } +export const USAGE = [ + "usage:", + " node scripts/devices/table.mjs [--data DIR] [--doc FILE] rewrites the table", + " node scripts/devices/table.mjs --check exits 1 when the doc's table is out of date", +].join("\n"); + +/** The command line, or a usage error: an unknown flag or argument, or --data / --doc with no value, is refused. */ +export function parseCli(argv) { + if (argv.includes("--help") || argv.includes("-h")) return { help: true }; + try { + const { values } = parseArgs({ + args: argv, + strict: true, + allowPositionals: false, + options: { data: { type: "string" }, doc: { type: "string" }, check: { type: "boolean" } }, + }); + return { values }; + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } +} + function main(argv) { - const flag = (name, fallback) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : fallback; - }; - const data = flag("--data", join(ROOT, "data", "devices")); - const docPath = flag("--doc", join(ROOT, "docs", "devices.md")); + const cli = parseCli(argv); + if (cli.help) { + console.log(USAGE); + return 0; + } + if (cli.error) { + console.error(`${cli.error}\n${USAGE}`); + return 1; + } + const data = cli.values.data ?? join(ROOT, "data", "devices"); + const docPath = cli.values.doc ?? join(ROOT, "docs", "devices.md"); const doc = readFileSync(docPath, "utf8"); const next = updateDoc(doc, renderTable(readEntries(data))); - if (argv.includes("--check")) { + if (cli.values.check) { if (next === doc) return 0; console.error(`${docPath}: the device table is out of date. Run node scripts/devices/table.mjs`); return 1; diff --git a/scripts/devices/table.test.mjs b/scripts/devices/table.test.mjs index a69b01a..ffce5b2 100644 --- a/scripts/devices/table.test.mjs +++ b/scripts/devices/table.test.mjs @@ -105,6 +105,37 @@ test("the CLI writes the doc, and --check fails when the doc is out of date", () } }); +for (const flag of ["--help", "-h"]) { + test(`the CLI prints the usage for ${flag} and exits 0 without touching the doc`, () => { + const out = execFileSync(process.execPath, [SCRIPT, flag], { cwd: ROOT, encoding: "utf8" }); + assert.match(out, /node scripts\/devices\/table\.mjs \[--data DIR\] \[--doc FILE\]/); + assert.match(out, /node scripts\/devices\/table\.mjs --check/); + }); +} + +for (const args of [["--chek"], ["--help-me"], ["extra"], ["--data"], ["--doc"], ["--data", "--check"]]) { + test(`the CLI refuses ${args.join(" ")}: usage, exit 1, doc unchanged`, () => { + const dir = mkdtempSync(join(tmpdir(), "hermit-table-args-")); + try { + const data = join(dir, "data"); + mkdirSync(data); + writeReport(data, 9, GOOD); + const doc = join(dir, "devices.md"); + const before = `# Devices\n\n${START}\n${END}\n`; + writeFileSync(doc, before); + // --doc and --data point at the temporary files unless the case is about them, so a wrong run can't touch the repo. + const rest = args.includes("--doc") ? ["--data", data] : args.includes("--data") ? ["--doc", doc] : ["--data", data, "--doc", doc]; + assert.throws( + () => execFileSync(process.execPath, [SCRIPT, ...rest, ...args], { cwd: dir, stdio: "pipe", encoding: "utf8" }), + (err) => err.status === 1 && /usage:/.test(err.stderr), + ); + assert.equal(readFileSync(doc, "utf8"), before); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +} + test("docs/devices.md holds the table the repository's data gives", () => { execFileSync(process.execPath, [SCRIPT, "--check"], { cwd: ROOT, stdio: "pipe" }); }); diff --git a/scripts/devices/validate.mjs b/scripts/devices/validate.mjs index d0c6676..67ee726 100644 --- a/scripts/devices/validate.mjs +++ b/scripts/devices/validate.mjs @@ -14,6 +14,7 @@ import { createHash } from "node:crypto"; import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; /** The newest report format. Version 1 reports, Android only and from before the platform was named, stay valid. */ export const REPORT_SCHEMA = "hermit-device-report/2"; @@ -290,15 +291,49 @@ export function issueComment(errors) { ].join("\n"); } +export const USAGE = [ + "usage:", + " node scripts/devices/validate.mjs report.json", + ' node scripts/devices/validate.mjs --event "$GITHUB_EVENT_PATH" [--github-output FILE] [--comment FILE] [--write DIR]', +].join("\n"); + +/** + * The command line, or a usage error. Unknown flags, a flag with no value and a wrong number of report files are + * refused, so a typo can't turn into a file name. Errors only repeat the command line, never a report's contents. + */ +export function parseCli(argv) { + if (argv.includes("--help") || argv.includes("-h")) return { help: true }; + let parsed; + try { + parsed = parseArgs({ + args: argv, + strict: true, + allowPositionals: true, + options: { event: { type: "string" }, "github-output": { type: "string" }, comment: { type: "string" }, write: { type: "string" } }, + }); + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } + const { values, positionals } = parsed; + if (values.event === undefined && positionals.length !== 1) return { error: "give one report file, or --event FILE" }; + if (values.event !== undefined && positionals.length > 0) return { error: "--event takes no report file" }; + return { values, file: positionals[0] }; +} + function main(argv) { - const flag = (name) => { - const i = argv.indexOf(name); - return i >= 0 ? argv[i + 1] : undefined; - }; + const cli = parseCli(argv); + if (cli.help) { + console.log(USAGE); + return 0; + } + if (cli.error) { + console.error(`${cli.error}\n${USAGE}`); + return 1; + } + const flag = (name) => cli.values[name.slice(2)]; const eventPath = flag("--event"); if (!eventPath) { - const file = argv[0]; - if (!file) throw new Error("usage: validate.mjs report.json | --event FILE [--github-output FILE] [--comment FILE] [--write DIR]"); + const file = cli.file; const v = validateReport(JSON.parse(readFileSync(file, "utf8"))); if (v.ok) console.log(`valid: ${file}`); else console.error(v.errors.join("\n")); diff --git a/scripts/devices/validate.test.mjs b/scripts/devices/validate.test.mjs index fb30643..6d7eec3 100644 --- a/scripts/devices/validate.test.mjs +++ b/scripts/devices/validate.test.mjs @@ -355,6 +355,23 @@ test("the CLI validates a report file given by path", () => { } }); +for (const flag of ["--help", "-h"]) { + test(`the CLI prints the usage for ${flag} and exits 0`, () => { + const out = execFileSync(process.execPath, [SCRIPT, flag], { encoding: "utf8" }); + assert.match(out, /node scripts\/devices\/validate\.mjs report\.json/); + assert.match(out, /--event "\$GITHUB_EVENT_PATH" \[--github-output FILE\] \[--comment FILE\] \[--write DIR\]/); + }); +} + +for (const args of [["--chek"], ["--event"], ["a.json", "b.json"], [], ["--event", "e.json", "extra.json"]]) { + test(`the CLI refuses ${args.join(" ") || "no arguments"}: usage and exit 1`, () => { + assert.throws( + () => execFileSync(process.execPath, [SCRIPT, ...args], { stdio: "pipe", encoding: "utf8" }), + (err) => err.status === 1 && /usage:/.test(err.stderr) && !/ENOENT/.test(err.stderr), + ); + }); +} + test("an issue that wasn't filed with the report form (the device-lab label marks other issues too) is skipped without a comment", () => { const r = runEvent({ issue: { number: 44, body: "The chat freezes on my phone.\n\n### Steps\n\n1. Open it." } }); try {