Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 35 additions & 9 deletions scripts/stage-port-docs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,11 @@ export function stagedPortGuides(port, artifact) {
const guides = new Map((artifact.guides ?? []).map((guide) => [guide.path, guide.content]))
const files = new Map()
const descriptions = new Map()
const checkoutGuidePaths = new Set(port === 'lua' ? artifact.checkoutGuidePaths : undefined)
const sourceFor = (path) => ({
repo: artifact.source.repository, path,
...(checkoutGuidePaths.has(path) ? { workingCopy: true } : { ref: artifact.source.revision }),
})
const titles = new Map(Object.entries(routes).map(([path, entry]) => [entry.route, entry.title ?? titleAndBody(guides.get(path) ?? '', path).title]))
for (const [sourcePath, guide] of Object.entries(routes)) {
const { route, product, package: packageId, domain, aliases, equivalence, sidebar } = guide
Expand All @@ -327,7 +332,7 @@ export function stagedPortGuides(port, artifact) {
...(aliases.length ? { aliases } : {}),
...(equivalence ? { equivalence } : {}),
route,
source: { repo: artifact.source.repository, path: sourcePath, ref: artifact.source.revision },
source: sourceFor(sourcePath),
sidebar: sidebar ?? { group: product ? (product === 'mcp' ? 'MCP' : 'Workspace Manager')
: route === 'reference' ? 'API reference' : route.split('/')[0].replace(/^./, (letter) => letter.toUpperCase()) },
}
Expand All @@ -336,7 +341,7 @@ export function stagedPortGuides(port, artifact) {
files.set(`${port}/${route}/index.md`, `---\n${frontmatter}\n---\n\n${rewritten.trim()}\n`)
}
{
const source = { repo: artifact.source.repository, path: Object.keys(routes)[0], ref: artifact.source.revision }
const source = sourceFor(Object.keys(routes)[0])
const writeIndex = (route, title, body, cards = []) => {
const data = { title, description: leadSentence(body) || `${title} for ${identity.packageName}.`, port, route, source, cards,
sidebar: { group: route === 'reference' ? 'API reference' : route[0].toUpperCase() + route.slice(1), label: 'Overview', order: 1 } }
Expand Down Expand Up @@ -421,7 +426,7 @@ function linkDocumenter(content, source) {
}

/** Read the integrated commit even when a contributor's working tree has advanced. */
export function artifactFromRevision(port, checkout, revision) {
export function artifactFromRevision(port, checkout, revision, { allowMissing = false } = {}) {
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${port.slug}: invalid integrated source revision`)
const git = (...args) => execFileSync('git', ['-C', checkout, ...args], { encoding: 'utf8', stdio: 'pipe' })
try {
Expand All @@ -439,6 +444,10 @@ export function artifactFromRevision(port, checkout, revision) {
for (const path of paths) {
const end = blobs.indexOf(10, offset)
const header = blobs.subarray(offset, end).toString('ascii')
if (end >= offset && allowMissing && header === `${revision}:${path} missing`) {
offset = end + 1
continue
}
const match = /^[a-f0-9]{40} blob (\d+)$/.exec(header)
const size = match && Number(match[1])
if (end < offset || size === null || !Number.isSafeInteger(size) || size < 0 ||
Expand All @@ -452,11 +461,26 @@ export function artifactFromRevision(port, checkout, revision) {
const readSource = (file) => contents.get(file) ?? git('show', `${revision}:${file}`)
return {
source: { repository: port.repo, revision },
guides: paths.map((path) => {
const content = readSource(path)
return { path, content: port.slug === 'julia' ? expandDocumenter(content, path, readSource) : content }
}),
guides: [...contents].map(([path, content]) => ({
path, content: port.slug === 'julia' ? expandDocumenter(content, path, readSource) : content,
})),
}
}

function luaCheckoutGuides(port, checkout, artifact) {
const { revision } = artifact.source
const pinned = artifactFromRevision(port, checkout, revision, { allowMissing: true })
const contents = new Map(pinned.guides.map(({ path, content }) => [path, content]))
const checkoutGuidePaths = []
for (const { path, content } of artifact.guides ?? []) {
if (!Object.hasOwn(ROUTES.lua, path) || typeof content !== 'string' || contents.get(path) === content) continue
const file = join(checkout, path)
if (!existsSync(file) || readFileSync(file, 'utf8') !== content) {
throw new Error(`lua: exported guide ${path} differs from both ${revision} and ${file}. Regenerate docs/_build/api.json from the selected checkout.`)
}
checkoutGuidePaths.push(path)
}
return checkoutGuidePaths.length ? { ...artifact, checkoutGuidePaths } : artifact
}

export function run() {
Expand Down Expand Up @@ -495,12 +519,14 @@ export function run() {
if (expected && artifact.source?.revision !== expected) {
throw new Error(`${port.slug}: expected source ${expected}, artifact records ${artifact.source?.revision}`)
}
const stagingArtifact = port.slug === 'lua' && !cached && !integrated && !fromSource && existsSync(join(checkout, '.git'))
? luaCheckoutGuides(port, checkout, artifact) : artifact
if (!check && (refreshCache || selectedSource)) {
mkdirSync(cacheRoot, { recursive: true })
const content = `${JSON.stringify(artifact, null, 2)}\n`
const content = `${JSON.stringify(stagingArtifact, null, 2)}\n`
if (!existsSync(cachePath) || readFileSync(cachePath, 'utf8') !== content) writeFileSync(cachePath, content)
}
for (const [file, content] of stagedPortGuides(port.slug, artifact)) generated.set(file, content)
for (const [file, content] of stagedPortGuides(port.slug, stagingArtifact)) generated.set(file, content)
}

const actual = new Map()
Expand Down
5 changes: 3 additions & 2 deletions site/src/components/SiteFooter.astro
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ interface Props {

const { locale, port, version, pagePath, source, markdownHref, llmsRoot, githubUrl, flush = false, compact = false } = Astro.props
const inventories = inventoryLinks(port, version, pagePath)
const rawSource = source && rawSourceUrl(source)
---

<footer class:list={[!flush && !compact && 'mt-16', 'border-t border-edge']} data-site-footer>
Expand All @@ -52,10 +53,10 @@ const inventories = inventoryLinks(port, version, pagePath)
</>}
<div class:list={[!compact && 'mt-6', 'flex items-start justify-between gap-4', !compact && 'border-t border-edge pt-4', 'opacity-80']}>
<div class="page-source min-w-0 wrap-anywhere">
{source && <>{t(locale, 'footer.source')}: <code>{source.path}</code> &#183; </>}
{source && <>{t(locale, source.workingCopy ? 'footer.checkoutSource' : 'footer.source')}: <code data-working-copy={source.workingCopy ? 'true' : undefined}>{source.path}</code> &#183; </>}
{t(locale, 'footer.machineReadable')}:
{markdownHref && <><a class="muted-link underline" href={markdownHref}>Markdown</a>, </>}
{source && <><a class="muted-link underline" href={rawSourceUrl(source)}>{t(locale, 'footer.rawSource')}</a>, </>}
{rawSource && <><a class="muted-link underline" href={rawSource}>{t(locale, 'footer.rawSource')}</a>, </>}
<a class="muted-link underline" href={`${llmsRoot}docs.json`}>docs.json</a>,
<a class="muted-link underline" href={`${llmsRoot}llms.txt`}>llms.txt</a>,
<a class="muted-link underline" href={`${llmsRoot}llms-full.txt`}>llms-full.txt</a>,
Expand Down
3 changes: 2 additions & 1 deletion site/src/content.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { glob } from 'astro/loaders'
import { defineCollection } from 'astro:content'
import { z } from 'astro/zod'
import { workspaceDocsLoader } from './loaders/workspace-shared.ts'
import { pageSourceSchema } from './lib/markdown-twins.ts'
import { PORTS } from './lib/ports.ts'

/**
Expand Down Expand Up @@ -51,7 +52,7 @@ const docs = defineCollection({
/** Shared task identity for verified counterparts with different routes. */
equivalence: z.string().min(1).optional(),
/** Exact port source backing a staged guide. */
source: z.object({ repo: z.string(), path: z.string(), ref: z.string() }).optional(),
source: pageSourceSchema.optional(),
/** Sidebar placement. */
sidebar: z
.object({
Expand Down
2 changes: 2 additions & 0 deletions site/src/i18n/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const ui = {
'i18n.editPage': 'Edit this page on GitHub',
'i18n.coverageLink': 'See what else needs translating',
'footer.source': 'Source',
'footer.checkoutSource': 'Checkout source',
'footer.machineReadable': 'Machine-readable',
'footer.rawSource': 'raw source',
},
Expand Down Expand Up @@ -70,6 +71,7 @@ export const ui = {
'i18n.editPage': 'GitHub でこのページを編集する',
'i18n.coverageLink': '他に翻訳が必要なページを見る',
'footer.source': 'ソース',
'footer.checkoutSource': '作業ツリーのソース',
'footer.machineReadable': '機械可読',
'footer.rawSource': '生のソース',
},
Expand Down
2 changes: 1 addition & 1 deletion site/src/layouts/BaseLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ const inventoryPage: InventoryPage = {
scope: portSlug ?? (tmuxVersion ? `tmux@${tmuxVersion}` : 'site'),
product: /^(?:mcp|workspace)(?:\/|$)/.exec(pagePath)?.[0].replace(/\/$/, '') ?? 'core',
identity: inventoryId ?? (pagePath || 'index'),
title, version: portSlug ? target.version : tmuxVersion, source,
title, version: portSlug ? target.version : tmuxVersion, source: source.workingCopy ? undefined : source,
previousScopes: !portSlug && tmuxVersion && pagePath.startsWith(`tmux/${tmuxVersion}/catalog`) ? ['site'] : undefined,
aliases: inventoryAliases, exclude: inventoryExclude || bare ||
Boolean(process.env.LIBTMUX_DOCS_PORT && !inVersionTree) ||
Expand Down
20 changes: 11 additions & 9 deletions site/src/lib/markdown-twins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@
* loads, applies the same rules as the routes that write twins from source.
*/
import type { ApiModel, ApiSymbol, SourceApiModel } from '@libtmux/api-model'
import { z } from 'astro/zod'
import { CONTRIBUTE_BRANCH, CONTRIBUTE_REPO } from '../i18n/contribute.ts'

/** The file a page is rendered from: a path in a repository, at a ref. */
export interface PageSource {
repo: string
path: string
ref: string
}
const repositoryFile = z.object({ repo: z.string(), path: z.string() })

/** The file a page is rendered from, at a public ref or in the working copy. */
export const pageSourceSchema = z.union([
repositoryFile.extend({ ref: z.string(), workingCopy: z.never().optional() }),
repositoryFile.extend({ workingCopy: z.literal(true), ref: z.never().optional() }),
])
export type PageSource = z.infer<typeof pageSourceSchema>

/** The footer's raw source link. */
export function rawSourceUrl(source: PageSource): string {
return `https://github.com/${source.repo}/raw/${source.ref}/${source.path}`
export function rawSourceUrl(source: PageSource): string | undefined {
return source.workingCopy ? undefined : `https://github.com/${source.repo}/raw/${source.ref}/${source.path}`
}

/** A generated API page's source: its declaration, else the extracted model. */
Expand Down
16 changes: 13 additions & 3 deletions site/test/machine-readable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ function trackedFiles(): Set<string> {

interface Footer {
source?: string
checkoutSource: boolean
markdown?: string
raw?: string
manifest?: string
Expand All @@ -140,8 +141,10 @@ function footerOf(html: string): Footer | undefined {
const links = [...html.matchAll(/<link\b[^>]*>/g)].map((tag) => tag[0])
const alternate = links.find((tag) => value(tag, 'rel') === 'alternate' && value(tag, 'type') === 'text/markdown')
const canonical = links.find((tag) => value(tag, 'rel') === 'canonical')
const code = /<code\b[^>]*>([^<]+)<\/code>/.exec(block)
return {
source: /<code\b[^>]*>([^<]+)<\/code>/.exec(block)?.[1],
source: code?.[1],
checkoutSource: Boolean(code && value(code[0], 'data-working-copy') === 'true'),
markdown: hrefs.find((href) => href.endsWith('.md')),
raw: hrefs.find((href) => href.startsWith('https://github.com/')),
manifest: hrefs.find((href) => href.endsWith('/docs.json')),
Expand All @@ -156,7 +159,12 @@ function footerOf(html: string): Footer | undefined {
describe('machine-readable footer parsing', () => {
it.each(['', ' data-astro-cid-footer'])('reads the source path with code attributes %j', (attributes) => {
const html = `<div class="page-source">Source: <code${attributes}>README.md</code></div>`
expect(footerOf(html)?.source).toBe('README.md')
expect(footerOf(html)).toMatchObject({ source: 'README.md', checkoutSource: false })
})

it('recognizes an explicit working-copy source on the path', () => {
const html = '<div class="page-source">Checkout source: <code data-working-copy="true">README.md</code></div>'
expect(footerOf(html)).toMatchObject({ source: 'README.md', checkoutSource: true })
})
})

Expand Down Expand Up @@ -209,7 +217,9 @@ describe.skipIf(!SITE_BUILT)('machine-readable footer', () => {
}
}
const raw = footer.raw && /^https:\/\/github\.com\/([^/]+\/[^/]+)\/raw\/[^/]+\/(.+)$/.exec(footer.raw)
if (!raw) problems.push(`${page}: raw source ${footer.raw} is not a GitHub raw URL`)
if (footer.checkoutSource) {
if (!footer.source || footer.raw) problems.push(`${page}: invalid checkout source ${footer.source} with raw link ${footer.raw}`)
} else if (!raw) problems.push(`${page}: raw source ${footer.raw} is not a GitHub raw URL`)
else {
if (!REPOS.has(raw[1])) problems.push(`${page}: raw source repository ${raw[1]} is unknown`)
if (footer.source !== raw[2]) problems.push(`${page}: source ${footer.source} differs from raw path ${raw[2]}`)
Expand Down
36 changes: 36 additions & 0 deletions site/test/sidebar-demo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { afterEach, expect, it, vi } from 'vitest'
import { Window } from 'happy-dom'
import { demoConfig, demoUrl } from '../src/lib/sidebar-demo'
import { API_MODEL_PORTS } from '../src/lib/ports'
import { renderedTargets } from '../src/lib/inventory-targets'
import { pageSourceSchema } from '../src/lib/markdown-twins'
import { loadAstroTemplate, renderAstroTemplate } from './astro-templates'
import { buildLocale } from '../src/i18n/locales'
import { parseHtml, renderPage } from './header-page'
Expand Down Expand Up @@ -80,3 +82,37 @@ it('links a port inventory only from pages inside that port\'s version tree', as
vi.stubEnv('LIBTMUX_DOCS_VERSION', 'latest')
expect(await scoped('https://libtmux.org/ts/latest/guides/')).toEqual([expect.stringMatching(/\/ts\/latest\/objects\.inv$/)])
})

it('shows the Lua guide source without inventing a raw link or a Git inventory target for checkout bytes', async () => {
const layout = await loadAstroTemplate('layouts/BaseLayout.astro', { real: ['components/SiteFooter.astro'], modules: { '../i18n/resolve': { buildLocale } } })
const path = '/en/lua/latest/guides/runtime/'
const url = new URL(path, 'https://libtmux.org').href
const source = { repo: 'libtmux/libtmux-lua', path: 'docs/runtime.md' }
const render = (sourceValue: unknown) => renderAstroTemplate(layout, {
url, props: { title: 'Runtime', portSlug: 'lua', markdownIndex: true, pageSource: pageSourceSchema.parse(sourceValue) },
slots: { default: '<main>Guide</main>' },
})

const localHtml = await render({ ...source, workingCopy: true })
const local = parseHtml(localHtml, url)
const footer = local.document.querySelector('.page-source')!
expect(footer.querySelector('a[href^="https://github.com/"]')).toBeNull()
expect(footer.querySelector('code[data-working-copy]')?.textContent).toBe(source.path)
expect(footer.textContent).toContain('Checkout source')
expect(footer.querySelector('a[href$="/index.md"]')?.getAttribute('href')).toBe(`${path}index.md`)
expect(local.document.querySelector('footer a[aria-label="GitHub"]')?.getAttribute('href')).toBe('https://github.com/libtmux/libtmux-lua/')
const [localTarget] = renderedTargets(localHtml, path)
expect(localTarget?.href).toBe(path)
expect(localTarget?.source).toBeUndefined()

const ref = 'a'.repeat(40)
expect(pageSourceSchema.safeParse({ ...source, ref, workingCopy: true }).success).toBe(false)
const pinnedHtml = await render({ ...source, ref })
const pinned = parseHtml(pinnedHtml, url)
const pinnedFooter = pinned.document.querySelector('.page-source')!
expect(pinnedFooter.querySelector('code[data-working-copy]')).toBeNull()
expect(pinnedFooter.querySelector('a[href^="https://github.com/"]')?.getAttribute('href'))
.toBe(`https://github.com/${source.repo}/raw/${ref}/${source.path}`)
expect(renderedTargets(pinnedHtml, path)[0]?.source).toEqual({ ...source, ref })
await Promise.all([local.happyDOM.abort(), pinned.happyDOM.abort()])
})
42 changes: 42 additions & 0 deletions site/test/stage-port-docs.outer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,48 @@ it('leaves the preview mount to Markdown while selecting the parent API version'
})
})

it('marks native Lua guides whose bytes come from the checkout', () => {
fixture('lua', ({ directory, checkout, write, artifact }) => {
// Use this repository's existing object database without creating a commit.
const git = (...args: string[]) => execFileSync('git', ['--no-optional-locks', '-C', root, ...args], { encoding: 'utf8' })
const revision = git('rev-parse', 'HEAD').trim()
const repo = 'libtmux/libtmux-lua'
const artifactPath = join(checkout, 'docs/_build/api.json')
const input = JSON.parse(artifact('lua', revision, 'checkout'))
const readme = input.guides.find((guide: { path: string }) => guide.path === 'README.md')
readme.content = git('show', `${revision}:README.md`)
const env = { ...process.env, LIBTMUX_DOCS_PORT: 'lua', LIBTMUX_DOCS_SOURCE_SHA: revision,
LIBTMUX_DOCS_CHECKOUT_LUA: checkout }
const stagedSource = (route: string) => {
const staged = readFileSync(join(directory, 'site/src/content/docs/_staged/lua', route, 'index.md'), 'utf8')
return JSON.parse(/^source: (.*)$/m.exec(staged)![1]!)
}
const stage = () => invokeGenerator(directory, env, ['--port', 'lua'])
const writeInput = () => { write(artifactPath, JSON.stringify(input)) }
write(join(checkout, '.git'), `gitdir: ${git('rev-parse', '--absolute-git-dir').trim()}\n`)
write(join(directory, 'site/src/data/api/lua.json'), JSON.stringify({ revision, symbols: [] }))
for (const guide of input.guides) write(join(checkout, guide.path), guide.content)
writeInput()
const check = (result: ReturnType<typeof stage>) => { expect(result.status, result.stderr).toBe(0) }
check(stage())
expect(stagedSource('guides/overview')).toEqual({ repo, path: 'README.md', ref: revision })
expect(stagedSource('guides/runtime')).toEqual({ repo, path: 'docs/runtime.md', workingCopy: true })

readme.content = '# Guide with local changes\n'
write(join(checkout, readme.path), readme.content)
writeInput()
check(stage())
expect(stagedSource('guides/overview')).toEqual({ repo, path: 'README.md', workingCopy: true })

readme.content += '\nStale export\n'
writeInput()
const stale = stage()
expect(stale.status).not.toBe(0)
expect(stale.stderr).toContain('README.md differs from both')
expect(stagedSource('guides/overview')).toEqual({ repo, path: 'README.md', workingCopy: true })
})
})

it.each(['ruby', 'lua', 'kotlin', 'ocaml', 'haskell'] as const)('stages other caches before accepting only the selected %s source', (slug) => {
fixture(slug, ({ directory, checkout, revision, write, artifact, invoke }) => {
const staged = join(directory, 'site/src/content/docs/_staged')
Expand Down
Loading