From 94f735623b8f7e325eeda7e7c27da8d2fe6e4a06 Mon Sep 17 00:00:00 2001 From: Tim Carman <15333667+tpcarman@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:21:42 +1100 Subject: [PATCH] Add a README section icon pack and brand the README badges section-icons.mjs renders 17 icons for the section headings of module READMEs (Getting Started, System Requirements, Required Privileges and so on) into assets/section-icons/, as SVG and PNG with a catalogue. They follow the feature icons on the website: an Octicons glyph in console blue on a highlighter yellow tile. The README rollout (readme-banners.mjs, renamed readme-prs.mjs) now applies the whole brand through readme-brand.mjs: the banner, icons in place of emoji on known section headings, and badges in the brand palette (link blue for versions, console blue for counts, highlighter for compatibility). It commits to an open pull request's branch rather than opening a second one, and uses a new branch name, because the earlier banner branches remain after their pull requests merge. The workflow runs the new tests and renders the icons. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/repo-banners.yml | 16 +++- generator/README.md | 31 ++++++-- generator/package-lock.json | 19 +++++ generator/package.json | 1 + generator/readme-banners.mjs | 120 ----------------------------- generator/readme-brand.mjs | 108 ++++++++++++++++++++++++++ generator/readme-brand.test.mjs | 90 ++++++++++++++++++++++ generator/readme-prs.mjs | 106 +++++++++++++++++++++++++ generator/section-icons.json | 22 ++++++ generator/section-icons.mjs | 93 ++++++++++++++++++++++ 10 files changed, 476 insertions(+), 130 deletions(-) delete mode 100644 generator/readme-banners.mjs create mode 100644 generator/readme-brand.mjs create mode 100644 generator/readme-brand.test.mjs create mode 100644 generator/readme-prs.mjs create mode 100644 generator/section-icons.json create mode 100644 generator/section-icons.mjs diff --git a/.github/workflows/repo-banners.yml b/.github/workflows/repo-banners.yml index f6adb2d..d1cef18 100644 --- a/.github/workflows/repo-banners.yml +++ b/.github/workflows/repo-banners.yml @@ -1,5 +1,6 @@ # Renders the README banner for every public AsBuiltReport.* repo into assets/repo-banners/, -# and the organisation profile tiles into profile/images/tiles/, then commits any that changed. +# the organisation profile tiles into profile/images/tiles/, and the README section icon pack +# into assets/section-icons/, then commits any that changed. # On a pull request it renders without committing, and uploads the images for review. # The generator lives in generator/. Run it by hand after creating a new repo, or wait for the daily run. name: Repo banners @@ -48,6 +49,14 @@ jobs: npm ci npx playwright install --with-deps chromium + - name: Test the README changes + working-directory: generator + run: node --test + + - name: Render section icons + working-directory: generator + run: node section-icons.mjs + - name: Render banners and tiles working-directory: generator env: @@ -67,17 +76,18 @@ jobs: name: repo-banners path: | assets/repo-banners + assets/section-icons profile/images/tiles - name: Commit changes if: github.event_name != 'pull_request' run: | - git add assets/repo-banners profile/images/tiles + git add assets/repo-banners assets/section-icons profile/images/tiles if git diff --cached --quiet; then echo "No banner changes" exit 0 fi git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git commit -m 'Update repo banners and profile tiles' + git commit -m 'Update repo banners, profile tiles and section icons' git push diff --git a/generator/README.md b/generator/README.md index c4c8bea..52ae068 100644 --- a/generator/README.md +++ b/generator/README.md @@ -1,11 +1,12 @@ -# Repo banner generator +# Brand asset generator -Renders the README banner for every public `AsBuiltReport.*` repo, and the module tiles on the organisation profile, from one HTML template. +Renders the brand images for AsBuiltReport repos: a README banner for every public `AsBuiltReport.*` repo and the module tiles on the organisation profile, from one HTML template, and the section icon pack used on README headings. | Output | Size | Path | |---|---|---| | README banner | 1760 x 480 | `assets/repo-banners/.png` | | Profile tile | 840 x 240 | `profile/images/tiles/.png` | +| README section icon | 32 x 32 SVG, 96 x 96 PNG | `assets/section-icons/.svg`, `.png` | The [Repo banners](../.github/workflows/repo-banners.yml) workflow runs daily, on pushes to `generator/`, and by hand. It commits only the images that changed. After creating a new repo, run the workflow by hand so its banner exists straight away. @@ -15,6 +16,10 @@ The [Repo banners](../.github/workflows/repo-banners.yml) workflow runs daily, o - Line 3 is `PS> Install-Module ` when the module is on the PowerShell Gallery, and the GitHub URL when it is not, so a banner never shows a command that fails. - `repos.json` sets the exceptions: repos to skip, repos without a tile, and fixed line 3 text (the website shows `www.asbuiltreport.com`). +## Section icons + +Section headings in module READMEs use icons in place of emoji, in the style of the feature icons on [www.asbuiltreport.com](https://www.asbuiltreport.com): an [Octicons](https://primer.style/octicons/) glyph in console blue on a highlighter yellow tile. `section-icons.json` lists each icon, its Octicon and the heading texts it is used for. `section-icons.mjs` renders them, with a catalogue at [`assets/section-icons`](../assets/section-icons). To add an icon, add an entry to `section-icons.json`. + ## Using a banner in a README ```html @@ -27,13 +32,23 @@ The [Repo banners](../.github/workflows/repo-banners.yml) workflow runs daily, o New modules get this from the [Plaster template](https://github.com/AsBuiltReport/AsBuiltReport.Plaster.Template). -For existing repos, `readme-banners.mjs` opens a pull request in each one that replaces the old logo at the top of the README with the banner (or adds the banner at the top when there is no logo). It skips repos that already use the banner or already have the pull request open. It is a dry run unless you pass `--apply`: +## Applying the brand to existing READMEs + +`readme-prs.mjs` opens a pull request in each repo that applies the brand to its README, using the functions in `readme-brand.mjs`: + +- the banner in place of the old logo at the top (or at the top when there is no logo) +- section icons in place of the emoji on known section headings, sized to the heading level (headings inside code blocks are left alone) +- badges in the brand palette: link blue `#1F5FD0` for versions, console blue `#012456` for counts (downloads, contributors), highlighter `#FFD02B` for compatibility (platform) + +Where the pull request is already open, it commits to that branch instead. It skips READMEs that already have every change. It is a dry run unless you pass `--apply`: ```sh -GITHUB_TOKEN=$(gh auth token) node readme-banners.mjs --out ./preview # dry run, writes the new READMEs to ./preview -GITHUB_TOKEN=$(gh auth token) node readme-banners.mjs --apply # opens the pull requests +GITHUB_TOKEN=$(gh auth token) node readme-prs.mjs --out ./preview # dry run, writes the new READMEs to ./preview +GITHUB_TOKEN=$(gh auth token) node readme-prs.mjs --apply # opens or updates the pull requests ``` +`readme-brand.test.mjs` tests these changes (`node --test`). Set `README_DIR` to a folder of downloaded READMEs to also check that nothing else in them changes. + ## Running it locally Needs Node.js 22 or later. @@ -44,10 +59,12 @@ npm ci npx playwright install chromium node render.mjs # every repo node render.mjs --repo AsBuiltReport.Microsoft.Azure # one repo +node section-icons.mjs # the section icon pack +node --test # tests ``` To preview a layout change, open `template.html` in a browser with a query string, for example `template.html?kind=banner&name=Microsoft.Azure`. Local renders on Windows or macOS differ slightly from the Linux runner, so let the workflow produce the committed images. -## Fonts +## Fonts and icons -Archivo and Cascadia Code are copied from the project website and used under the SIL Open Font License (see `fonts/`). +Archivo and Cascadia Code are copied from the project website and used under the SIL Open Font License (see `fonts/`). Octicons are by GitHub, used under the MIT License. diff --git a/generator/package-lock.json b/generator/package-lock.json index f3273c2..1b41979 100644 --- a/generator/package-lock.json +++ b/generator/package-lock.json @@ -6,12 +6,31 @@ "": { "name": "asbuiltreport-repo-banners", "dependencies": { + "@primer/octicons": "19.42.0", "playwright": "1.64.1" }, "engines": { "node": ">=22" } }, + "node_modules/@primer/octicons": { + "version": "19.42.0", + "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-19.42.0.tgz", + "integrity": "sha512-MEcHxVxNHu1I2Ndk5Mcwp7tfBiDk/EpytDJgKOfE2ldqIczWucVrZNeNU4wtEN5mnNudZ0YL5G0spax3bSMT4w==", + "license": "MIT", + "dependencies": { + "object-assign": "^4.1.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/playwright": { "version": "1.64.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", diff --git a/generator/package.json b/generator/package.json index 028d7f3..a888cfe 100644 --- a/generator/package.json +++ b/generator/package.json @@ -10,6 +10,7 @@ "node": ">=22" }, "dependencies": { + "@primer/octicons": "19.42.0", "playwright": "1.64.1" } } diff --git a/generator/readme-banners.mjs b/generator/readme-banners.mjs deleted file mode 100644 index 92a3244..0000000 --- a/generator/readme-banners.mjs +++ /dev/null @@ -1,120 +0,0 @@ -// Opens a pull request in each AsBuiltReport.* repo that puts its brand banner at the top of README.md. -// The old organisation logo block is replaced where there is one. Otherwise the banner goes at the top. -// Repos whose README already uses the banner, or that already have the pull request open, are skipped. -// -// Usage (from this folder, GITHUB_TOKEN needs repo write access, for example: GITHUB_TOKEN=$(gh auth token)): -// node readme-banners.mjs dry run: shows what would change in every repo -// node readme-banners.mjs --out ./preview dry run, also writes each new README to ./preview -// node readme-banners.mjs --apply opens the pull requests -// node readme-banners.mjs --apply --repo AsBuiltReport.Microsoft.Azure - -import { mkdir, writeFile } from "node:fs/promises"; -import { join } from "node:path"; -import { config, githubHeaders, listOrgRepos, parseRepoArgs } from "./repos.mjs"; - -const branch = "feature/readme-banner"; -const title = "Use the AsBuiltReport brand banner in the README"; -const args = process.argv.slice(2); -const apply = args.includes("--apply"); -const outIndex = args.indexOf("--out"); -const outDir = outIndex >= 0 ? args[outIndex + 1] : null; - -export function bannerBlock(repo) { - return [ - '

', - ' ', - ` ${repo}`, - "

", - ]; -} - -// The old logo is a centred paragraph holding the organisation avatar or AsBuiltReport.png. -const logoBlock = /

\s*]*>(?:\s*<\/a>)?\s*]*>\s*(?:<\/a>)?\s*<\/p>/; - -export function addBanner(readme, repo) { - if (readme.includes("/assets/repo-banners/")) return null; - const eol = readme.includes("\r\n") ? "\r\n" : "\n"; - const block = bannerBlock(repo).join(eol); - if (logoBlock.test(readme)) return { how: "replaced logo", text: readme.replace(logoBlock, block) }; - - // No logo: put the banner first, after the "DO NOT EDIT" comment if the README has one. - const comment = readme.match(/^\r?\n/); - const head = comment ? comment[0] : ""; - return { how: "inserted at top", text: head + block + eol + readme.slice(head.length) }; -} - -async function api(path, options = {}) { - const response = await fetch(`https://api.github.com${path}`, { - ...options, - headers: { ...githubHeaders(), ...(options.body ? { "Content-Type": "application/json" } : {}) }, - }); - if (!response.ok && response.status !== 404) { - throw new Error(`${options.method || "GET"} ${path}: ${response.status} ${await response.text()}`); - } - return response.status === 404 ? null : response.json(); -} - -async function openPullRequest(repo, base, readme, text) { - const owner = config.org; - const open = await api(`/repos/${owner}/${repo}/pulls?state=open&head=${owner}:${branch}`); - if (open && open.length) return `already open: ${open[0].html_url}`; - - const baseRef = await api(`/repos/${owner}/${repo}/git/ref/heads/${base}`); - const existing = await api(`/repos/${owner}/${repo}/git/ref/heads/${encodeURIComponent(branch)}`); - if (existing) return `skipped: branch ${branch} already exists`; - await api(`/repos/${owner}/${repo}/git/refs`, { - method: "POST", - body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: baseRef.object.sha }), - }); - await api(`/repos/${owner}/${repo}/contents/README.md`, { - method: "PUT", - body: JSON.stringify({ - branch, - sha: readme.sha, - content: Buffer.from(text, "utf8").toString("base64"), - message: `${title}\n\nThe banner is rendered centrally by the generator in the .github repo.\n\nCo-Authored-By: Claude Opus 5.5 `, - }), - }); - const pr = await api(`/repos/${owner}/${repo}/pulls`, { - method: "POST", - body: JSON.stringify({ - title, - head: branch, - base, - body: [ - "## Summary", - "", - `Puts the AsBuiltReport brand banner at the top of the README, in place of the small organisation logo. The banner is rendered by the [generator in the .github repo](https://github.com/${owner}/.github/tree/main/generator), which keeps it up to date, so this repo does not store the image.`, - "", - `Line 3 of the banner shows \`PS> Install-Module ${repo}\` once the module is on the PowerShell Gallery, and the GitHub URL until then.`, - "", - "πŸ€– Generated with [Claude Code](https://claude.com/claude-code)", - ].join("\n"), - }), - }); - return pr.html_url; -} - -const requested = parseRepoArgs(args); -const repos = (await listOrgRepos()) - .filter((r) => !config.noReadmeBanner.includes(r.name)) - .filter((r) => !requested.length || requested.includes(r.name)); - -console.log(`${apply ? "Applying to" : "Dry run for"} ${repos.length} repos`); -if (outDir) await mkdir(outDir, { recursive: true }); -for (const { name, default_branch: base } of repos) { - const readme = await api(`/repos/${config.org}/${name}/contents/README.md?ref=${base}`); - if (!readme) { - console.log(`no README ${name}`); - continue; - } - const current = Buffer.from(readme.content, "base64").toString("utf8"); - const result = addBanner(current, name); - if (!result) { - console.log(`has banner ${name}`); - continue; - } - if (outDir) await writeFile(join(outDir, `${name}.md`), result.text); - const outcome = apply ? await openPullRequest(name, base, readme, result.text) : `would open a PR on ${base}`; - console.log(`${result.how.padEnd(16)} ${name}: ${outcome}`); -} diff --git a/generator/readme-brand.mjs b/generator/readme-brand.mjs new file mode 100644 index 0000000..cc5a9cd --- /dev/null +++ b/generator/readme-brand.mjs @@ -0,0 +1,108 @@ +// Pure functions that apply the AsBuiltReport brand to a module README: +// addBanner the repo banner in place of the old organisation logo +// addSectionIcons section icons in place of the emoji on known section headings +// recolourBadges shields.io badges in the brand palette +// readme-banners.mjs uses these to open pull requests. readme-brand.test.mjs tests them. + +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { config, here } from "./repos.mjs"; + +const { icons } = JSON.parse(readFileSync(join(here, "section-icons.json"), "utf8")); +const assetBase = `https://raw.githubusercontent.com/${config.org}/.github/main/assets`; + +const eolOf = (text) => (text.includes("\r\n") ? "\r\n" : "\n"); + +// ---------- Banner ---------- + +export function bannerBlock(repo, eol = "\n") { + return [ + '

', + ' ', + ` ${repo}`, + "

", + ].join(eol); +} + +// The old logo is a centred paragraph holding the organisation avatar or AsBuiltReport.png. +const logoBlock = /

\s*]*>(?:\s*<\/a>)?\s*]*>\s*(?:<\/a>)?\s*<\/p>/; + +export function addBanner(readme, repo) { + if (readme.includes("/assets/repo-banners/")) return readme; + const block = bannerBlock(repo, eolOf(readme)); + if (logoBlock.test(readme)) return readme.replace(logoBlock, block); + + // No logo: put the banner first, after the "DO NOT EDIT" comment if the README has one. + const comment = readme.match(/^\r?\n/); + const head = comment ? comment[0] : ""; + return head + block + eolOf(readme) + readme.slice(head.length); +} + +// ---------- Section icons ---------- + +// A GitHub :shortcode: or a run of Unicode emoji (with variation selectors and joiners). +const emoji = String.raw`(?::[a-z0-9_+-]+:|(?:\p{Extended_Pictographic}|\p{Regional_Indicator})(?:️|‍|\p{Extended_Pictographic})*)`; +const leadingEmoji = new RegExp(String.raw`^(?:${emoji}\s*)+`, "u"); +const trailingEmoji = new RegExp(String.raw`(?:\s*${emoji})+$`, "u"); +const iconSizes = { 1: 28, 2: 24, 3: 20, 4: 16 }; + +const normalise = (text) => text.replace(/\*\*/g, "").replace(/\s+/g, " ").trim().toLowerCase(); +const iconByHeading = new Map(icons.flatMap((icon) => icon.headings.map((h) => [normalise(h), icon]))); + +export function sectionIcon(icon, level) { + const size = iconSizes[level]; + return ``; +} + +export function addSectionIcons(readme) { + const eol = eolOf(readme); + let fence = null; + return readme.split(/\r?\n/).map((line) => { + // Skip fenced code blocks, where "# ..." lines are comments, not headings. + const fenceMatch = line.match(/^\s*(`{3,}|~{3,})/); + if (fenceMatch) { + if (!fence) fence = fenceMatch[1][0]; + else if (fenceMatch[1][0] === fence) fence = null; + return line; + } + if (fence) return line; + + const heading = line.match(/^(#{1,4})\s+(.*?)\s*$/); + if (!heading || heading[2].includes("/assets/section-icons/")) return line; + const hadEmoji = leadingEmoji.test(heading[2]); + const text = heading[2].replace(leadingEmoji, "").replace(trailingEmoji, "").trim(); + const icon = iconByHeading.get(normalise(text)); + // Headings without an emoji only get an icon down to level 3, so deep sub-headings stay plain. + if (!icon || (!hadEmoji && heading[1].length > 3)) return line; + return `${heading[1]} ${sectionIcon(icon, heading[1].length)} ${text}`; + }).join(eol); +} + +// ---------- Badges ---------- + +// Brand palette for shields.io badges: link blue for versions, console blue for counts, +// highlighter for compatibility. Shields picks dark text on the highlighter automatically. +const badgeColours = [ + { pattern: /img\.shields\.io\/powershellgallery\/v\//, colour: "1F5FD0" }, + { pattern: /img\.shields\.io\/github\/v\/release\//, colour: "1F5FD0" }, + { pattern: /img\.shields\.io\/powershellgallery\/dt\//, colour: "012456" }, + { pattern: /img\.shields\.io\/github\/contributors\//, colour: "012456" }, + { pattern: /img\.shields\.io\/github\/stars\//, colour: "012456" }, + { pattern: /img\.shields\.io\/powershellgallery\/p\//, colour: "FFD02B" }, +]; + +export function recolourBadge(url) { + const rule = badgeColours.find((r) => r.pattern.test(url)); + if (!rule) return url; + const [path, query = ""] = url.split("?"); + const params = query.split("&").filter((p) => p && !/^colou?r=/i.test(p)); + return `${path}?${[`color=${rule.colour}`, ...params].join("&")}`; +} + +export function recolourBadges(readme) { + return readme.replace(/https:\/\/img\.shields\.io\/[^\s"'()<>]+/g, recolourBadge); +} + +export function applyBrand(readme, repo) { + return recolourBadges(addSectionIcons(addBanner(readme, repo))); +} diff --git a/generator/readme-brand.test.mjs b/generator/readme-brand.test.mjs new file mode 100644 index 0000000..a687132 --- /dev/null +++ b/generator/readme-brand.test.mjs @@ -0,0 +1,90 @@ +// Tests for readme-brand.mjs: the banner, section icon and badge changes made to module READMEs. +// Nothing is stubbed: the functions are pure and read only section-icons.json and repos.json. +// Run from this folder: node --test +// To check against the live READMEs as well, set README_DIR to a folder of downloaded README files. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { addBanner, addSectionIcons, recolourBadge, recolourBadges, applyBrand } from "./readme-brand.mjs"; + +const icon = (name, size) => ``; + +test("replaces the emoji on known section headings, sized to the heading level", () => { + const input = "# :beginner: Getting Started\n## :package: Module Installation\n### :closed_lock_with_key: Required Privileges"; + const expected = `# ${icon("getting-started", 28)} Getting Started\n## ${icon("module-installation", 24)} Module Installation\n### ${icon("required-privileges", 20)} Required Privileges`; + assert.equal(addSectionIcons(input), expected); +}); + +test("handles Unicode emoji, including variation selectors", () => { + assert.equal(addSectionIcons("## πŸ—ΊοΈ Language Support"), `## ${icon("language-support", 24)} Language Support`); + assert.equal(addSectionIcons("## 🌐 Language Support"), `## ${icon("language-support", 24)} Language Support`); +}); + +test("maps every Known Issues emoji variant to the same icon", () => { + for (const e of [":x:", ":bug:", ":exclamation:", ":rotating_light:"]) { + assert.equal(addSectionIcons(`## ${e} Known Issues`), `## ${icon("known-issues", 24)} Known Issues`); + } +}); + +test("drops a trailing emoji and keeps the heading text as written", () => { + const input = "## :exclamation: THIS ASBUILTREPORT MODULE IS CURRENTLY IN DEVELOPMENT AND MIGHT NOT YET BE FUNCTIONAL ❗"; + assert.equal(addSectionIcons(input), `## ${icon("in-development", 24)} THIS ASBUILTREPORT MODULE IS CURRENTLY IN DEVELOPMENT AND MIGHT NOT YET BE FUNCTIONAL`); +}); + +test("leaves headings inside fenced code blocks alone", () => { + const input = "```powershell\n# Examples\nInstall-Module Foo\n```\n## :computer: Examples"; + assert.equal(addSectionIcons(input), `\`\`\`powershell\n# Examples\nInstall-Module Foo\n\`\`\`\n## ${icon("examples", 24)} Examples`); +}); + +test("leaves unknown headings, and deep headings without an emoji, alone", () => { + const input = "### Report\n## :tada: Something Else\n#### Configuration"; + assert.equal(addSectionIcons(input), input); +}); + +test("is idempotent and keeps CRLF line endings", () => { + const once = addSectionIcons("# :beginner: Getting Started\r\nText\r\n"); + assert.equal(addSectionIcons(once), once); + assert.ok(!once.replace(/\r\n/g, "").includes("\n")); +}); + +test("recolours badges by kind and leaves others alone", () => { + assert.equal(recolourBadge("https://img.shields.io/powershellgallery/v/AsBuiltReport.Core.svg"), "https://img.shields.io/powershellgallery/v/AsBuiltReport.Core.svg?color=1F5FD0"); + assert.equal(recolourBadge("https://img.shields.io/powershellgallery/dt/AsBuiltReport.Core.svg"), "https://img.shields.io/powershellgallery/dt/AsBuiltReport.Core.svg?color=012456"); + assert.equal(recolourBadge("https://img.shields.io/github/contributors/AsBuiltReport/AsBuiltReport.Core.svg"), "https://img.shields.io/github/contributors/AsBuiltReport/AsBuiltReport.Core.svg?color=012456"); + assert.equal(recolourBadge("https://img.shields.io/powershellgallery/p/AsBuiltReport.Core.svg"), "https://img.shields.io/powershellgallery/p/AsBuiltReport.Core.svg?color=FFD02B"); + const licence = "https://img.shields.io/github/license/AsBuiltReport/AsBuiltReport.Core.svg"; + assert.equal(recolourBadge(licence), licence); +}); + +test("replaces an existing colour and keeps other query parameters", () => { + assert.equal(recolourBadge("https://img.shields.io/powershellgallery/v/X?style=flat&color=red"), "https://img.shields.io/powershellgallery/v/X?color=1F5FD0&style=flat"); + assert.equal(recolourBadges(''), ''); +}); + +test("adds the banner once", () => { + const readme = "

\n \n \n

\nText"; + const once = addBanner(readme, "AsBuiltReport.Core"); + assert.match(once, /repo-banners\/AsBuiltReport\.Core\.png/); + assert.equal(addBanner(once, "AsBuiltReport.Core"), once); +}); + +// Runs the full change over real READMEs: every emoji section heading gets an icon, +// nothing outside headings, badge URLs and the logo block changes, and a second run changes nothing. +const readmeDir = process.env.README_DIR; +if (readmeDir) { + for (const file of readdirSync(readmeDir).filter((f) => f.endsWith(".md"))) { + test(`real README: ${file}`, () => { + const repo = file.replace(/\.md$/, ""); + const before = readFileSync(join(readmeDir, file), "utf8"); + const after = applyBrand(before, repo); + assert.equal(applyBrand(after, repo), after, "second run changes nothing"); + const lines = (t) => t.split(/\r?\n/); + const changed = lines(after).filter((l, i, all) => !lines(before).includes(l)); + for (const line of changed) { + assert.ok(/section-icons\/|img\.shields\.io|repo-banners\/|^

$|^\s*$|^<\/p>$/.test(line), `unexpected change: ${line}`); + } + }); + } +} diff --git a/generator/readme-prs.mjs b/generator/readme-prs.mjs new file mode 100644 index 0000000..326ecb5 --- /dev/null +++ b/generator/readme-prs.mjs @@ -0,0 +1,106 @@ +// Opens a pull request in each AsBuiltReport.* repo that applies the brand to README.md +// (see readme-brand.mjs): the repo banner, section icons in place of emoji, and badges in the brand palette. +// Where the pull request is already open, the changes are committed to its branch instead. +// Repos whose README already has every change are skipped. +// +// Usage (from this folder, GITHUB_TOKEN needs repo write access, for example: GITHUB_TOKEN=$(gh auth token)): +// node readme-prs.mjs dry run: shows what would change in every repo +// node readme-prs.mjs --out ./preview dry run, also writes each new README to ./preview +// node readme-prs.mjs --apply opens or updates the pull requests +// node readme-prs.mjs --apply --repo AsBuiltReport.Microsoft.Azure + +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { config, githubHeaders, listOrgRepos, parseRepoArgs } from "./repos.mjs"; +import { applyBrand } from "./readme-brand.mjs"; + +const branch = "feature/readme-brand"; +const title = "Apply the AsBuiltReport brand to the README"; +const args = process.argv.slice(2); +const apply = args.includes("--apply"); +const outIndex = args.indexOf("--out"); +const outDir = outIndex >= 0 ? args[outIndex + 1] : null; +const owner = config.org; + +const commitMessage = [ + title, + "", + "- Repo banner in place of the organisation logo", + "- Section icons in place of emoji on the section headings", + "- Badges in the brand palette: link blue for versions, console blue for counts, highlighter for compatibility", + "", + "The banner and icons are rendered centrally by the generator in the .github repo.", + "", + "Co-Authored-By: Claude Opus 5.5 ", +].join("\n"); + +const prBody = (repo) => [ + "## Summary", + "", + "Applies the AsBuiltReport brand to the README, to match [www.asbuiltreport.com](https://www.asbuiltreport.com) and the other report modules:", + "", + `- **Banner:** the repo banner in place of the small organisation logo. Its last line shows \`PS> Install-Module ${repo}\` once the module is on the PowerShell Gallery, and the GitHub address until then.`, + `- **Section icons:** the emoji on the section headings are replaced with the [section icon pack](https://github.com/${owner}/.github/tree/main/assets/section-icons), in the style of the feature icons on the website.`, + "- **Badges:** recoloured to the brand palette: link blue `#1F5FD0` for versions, console blue `#012456` for counts, highlighter `#FFD02B` for compatibility.", + "", + `The banner and icons are rendered by the [generator in the .github repo](https://github.com/${owner}/.github/tree/main/generator), which keeps them up to date, so this repo does not store the images. Only \`README.md\` changes.`, + "", + "πŸ€– Generated with [Claude Code](https://claude.com/claude-code)", +].join("\n"); + +async function api(path, options = {}) { + const response = await fetch(`https://api.github.com${path}`, { + ...options, + headers: { ...githubHeaders(), ...(options.body ? { "Content-Type": "application/json" } : {}) }, + }); + if (!response.ok && response.status !== 404) { + throw new Error(`${options.method || "GET"} ${path}: ${response.status} ${await response.text()}`); + } + return response.status === 404 ? null : response.json(); +} + +const getReadme = (repo, ref) => api(`/repos/${owner}/${repo}/contents/README.md?ref=${encodeURIComponent(ref)}`); +const putReadme = (repo, readme, text) => api(`/repos/${owner}/${repo}/contents/README.md`, { + method: "PUT", + body: JSON.stringify({ branch, sha: readme.sha, content: Buffer.from(text, "utf8").toString("base64"), message: commitMessage }), +}); +const decode = (readme) => Buffer.from(readme.content, "base64").toString("utf8"); + +const requested = parseRepoArgs(args); +const repos = (await listOrgRepos()) + .filter((r) => !config.noReadmeBanner.includes(r.name)) + .filter((r) => !requested.length || requested.includes(r.name)); + +console.log(`${apply ? "Applying to" : "Dry run for"} ${repos.length} repos`); +if (outDir) await mkdir(outDir, { recursive: true }); +for (const { name, default_branch: base } of repos) { + const open = await api(`/repos/${owner}/${name}/pulls?state=open&head=${owner}:${branch}`); + const pr = open && open.length ? open[0] : null; + const readme = await getReadme(name, pr ? branch : base); + if (!readme) { + console.log(`no README ${name}`); + continue; + } + const text = applyBrand(decode(readme), name); + if (text === decode(readme)) { + console.log(`up to date ${name}${pr ? `: ${pr.html_url}` : ""}`); + continue; + } + if (outDir) await writeFile(join(outDir, `${name}.md`), text); + + if (!apply) { + console.log(`would ${pr ? "update" : "open "} ${name}: ${pr ? pr.html_url : `PR on ${base}`}`); + } else if (pr) { + await putReadme(name, readme, text); + await api(`/repos/${owner}/${name}/pulls/${pr.number}`, { method: "PATCH", body: JSON.stringify({ title, body: prBody(name) }) }); + console.log(`updated ${name}: ${pr.html_url}`); + } else if (await api(`/repos/${owner}/${name}/git/ref/heads/${encodeURIComponent(branch)}`)) { + console.log(`skipped ${name}: branch ${branch} exists with no open PR`); + } else { + const baseRef = await api(`/repos/${owner}/${name}/git/ref/heads/${base}`); + await api(`/repos/${owner}/${name}/git/refs`, { method: "POST", body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: baseRef.object.sha }) }); + await putReadme(name, readme, text); + const created = await api(`/repos/${owner}/${name}/pulls`, { method: "POST", body: JSON.stringify({ title, head: branch, base, body: prBody(name) }) }); + console.log(`opened ${name}: ${created.html_url}`); + } +} diff --git a/generator/section-icons.json b/generator/section-icons.json new file mode 100644 index 0000000..988979e --- /dev/null +++ b/generator/section-icons.json @@ -0,0 +1,22 @@ +{ + "_comment": "Section icons for report module READMEs. octicon is the 16 px Octicons glyph. headings are the README heading texts (after any emoji, ignoring case) that the icon replaces the emoji on.", + "icons": [ + { "name": "getting-started", "octicon": "rocket", "label": "Getting Started", "headings": ["Getting Started"] }, + { "name": "supported-versions", "octicon": "versions", "label": "Supported Versions", "headings": ["Supported Versions"] }, + { "name": "unsupported-versions", "octicon": "circle-slash", "label": "Unsupported Versions", "headings": ["Unsupported Versions"] }, + { "name": "system-requirements", "octicon": "tools", "label": "System Requirements", "headings": ["System Requirements"] }, + { "name": "required-privileges", "octicon": "shield-lock", "label": "Required Privileges", "headings": ["Required Privileges"] }, + { "name": "authentication", "octicon": "key", "label": "Authentication Methods", "headings": ["Authentication Methods", "Authentication"] }, + { "name": "language-support", "octicon": "globe", "label": "Language Support", "headings": ["Language Support"] }, + { "name": "module-installation", "octicon": "download", "label": "Module Installation", "headings": ["Module Installation"] }, + { "name": "configuration", "octicon": "gear", "label": "Configuration", "headings": ["Configuration"] }, + { "name": "examples", "octicon": "terminal", "label": "Examples", "headings": ["Examples", "GUI Examples", "Pwsh 5.1/7 Console Examples", "Pwsh 7 GUI Examples"] }, + { "name": "example-index", "octicon": "list-unordered", "label": "Example Index", "headings": ["Example Index"] }, + { "name": "commands", "octicon": "code", "label": "Commands", "headings": ["Commands"] }, + { "name": "sample-reports", "octicon": "book", "label": "Sample Reports", "headings": ["Sample Reports"] }, + { "name": "export-diagrams", "octicon": "workflow", "label": "Export Diagrams", "headings": ["Export Diagrams"] }, + { "name": "log-collection", "octicon": "log", "label": "Log Collection", "headings": ["Log Collection"] }, + { "name": "known-issues", "octicon": "bug", "label": "Known Issues", "headings": ["Known Issues"] }, + { "name": "in-development", "octicon": "alert", "label": "In development notice", "headings": ["This AsBuiltReport module is currently in development and might not yet be functional"] } + ] +} diff --git a/generator/section-icons.mjs b/generator/section-icons.mjs new file mode 100644 index 0000000..8a719c7 --- /dev/null +++ b/generator/section-icons.mjs @@ -0,0 +1,93 @@ +// Renders the README section icons listed in section-icons.json into assets/section-icons/: +// .svg 32 x 32, for READMEs +// .png 96 x 96, for places that do not accept SVG +// README.md a catalogue of the pack, with the Markdown to use each icon +// +// The style matches the feature icons on www.asbuiltreport.com: an Octicons glyph in +// console blue on a highlighter yellow tile, corner radius 1/8 and glyph 55% of the tile. +// +// Usage (from this folder): node section-icons.mjs +// Only files whose bytes change are written. + +import octicons from "@primer/octicons"; +import { chromium } from "playwright"; +import { readFile, writeFile, mkdir } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { config, here } from "./repos.mjs"; + +const { icons } = JSON.parse(await readFile(join(here, "section-icons.json"), "utf8")); +const outDir = join(here, "..", "assets", "section-icons"); +const baseUrl = `https://raw.githubusercontent.com/${config.org}/.github/main/assets/section-icons`; +const tile = 32; +const glyph = tile * 0.55; +const inset = (tile - glyph) / 2; + +export function iconSvg(icon) { + const source = octicons[icon.octicon]; + if (!source || !source.heights[16]) throw new Error(`Octicon ${icon.octicon}-16 not found for ${icon.name}`); + return [ + ``, + `${icon.label}`, + ``, + `${source.heights[16].path}`, + "", + "", + ].join("\n"); +} + +async function writeIfChanged(path, data) { + const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, "utf8"); + if (existsSync(path) && (await readFile(path)).equals(buffer)) return false; + await writeFile(path, buffer); + return true; +} + +function catalogue() { + const rows = icons.map((icon) => + `| | \`${icon.name}\` | ${icon.headings.join(", ")} |`); + return [ + "# README section icons", + "", + "Icons for the section headings of AsBuiltReport module READMEs, in place of emoji. They follow the feature icons on [www.asbuiltreport.com](https://www.asbuiltreport.com): an [Octicons](https://primer.style/octicons/) glyph in console blue `#012456` on a highlighter yellow `#FFD02B` tile.", + "", + "This folder is generated by [`generator/section-icons.mjs`](../../generator/section-icons.mjs) from [`section-icons.json`](../../generator/section-icons.json). Do not edit the files here by hand.", + "", + "| Icon | Name | Used for |", + "|:---:|---|---|", + ...rows, + "", + "## Using an icon", + "", + "Put the icon before the heading text. Size it to the heading: 28 for `#`, 24 for `##` and 20 for `###`. The alt text is empty because the heading already says what the section is.", + "", + "```markdown", + `## Getting Started`, + "```", + "", + "Each icon is also available as a 96 x 96 PNG with the same name, for places that do not accept SVG.", + "", + "Octicons are by GitHub, used under the MIT License.", + "", + ].join("\n"); +} + +await mkdir(outDir, { recursive: true }); +const browser = await chromium.launch(); +const page = await browser.newPage({ deviceScaleFactor: 3 }); +let changed = 0; +try { + for (const icon of icons) { + const svg = iconSvg(icon); + if (await writeIfChanged(join(outDir, `${icon.name}.svg`), svg)) changed++; + + await page.setViewportSize({ width: tile, height: tile }); + await page.setContent(`${svg}`); + const png = await page.locator("body > svg").screenshot({ omitBackground: true }); + if (await writeIfChanged(join(outDir, `${icon.name}.png`), png)) changed++; + } +} finally { + await browser.close(); +} +if (await writeIfChanged(join(outDir, "README.md"), catalogue())) changed++; +console.log(`${icons.length} icons, ${changed} file(s) changed`);