Skip to content
Draft
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
16 changes: 16 additions & 0 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,22 @@ and reference builds too. Cleanup shares the assembly lock and refuses to
run during an assembly. It preserves source, dependencies and `output/`
review evidence. Custom output and cache locations need their own cleanup.

### Lua declaration source links

The Lua reference links a declaration to its line in Git when the exported
file’s SHA-256 matches the file at that revision. Older exports still
supply descriptions, signatures and examples.

To rebuild the links for `v0.1.1`, check out the tag in
`../libtmux-lua-v0.1.1`. From a Lua tooling checkout with declaration
hashes and support for the release’s example launcher, run the native exporter.

```console
$ luajit scripts/docs/docs.lua export \
--source ../libtmux-lua-v0.1.1 \
--output ../libtmux-lua-v0.1.1/docs/_build
```

## Auditing page heads

`site/scripts/audit-head.mjs` reads the head of every page and reports what
Expand Down
1 change: 1 addition & 0 deletions packages/api-model/src/doc/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ const SYNTAX: Record<string, ReadonlySet<string>> = {
// Swift doc comment ``Server`` is a symbol link, not code.
swift: new Set(['docc']),
ruby: new Set(['yard']),
lua: new Set(['markdown-link']),
cxx: new Set([]),
kotlin: new Set(['kdoc', 'jsdoc']),
scala: new Set(['scaladoc', 'jsdoc']),
Expand Down
72 changes: 56 additions & 16 deletions packages/api-model/src/languages/lua-examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@ export interface LuaExampleManifest {
schema: number
/** `launcher` is a shell script that starts the tmux daemon; programs that start their own omit it. */
setup: { lua: string; luv: string; launcher?: string }
examples: { id: string; symbols: string[]; file: string; description: string; stdout: string }[]
examples: { id: string; symbols: string[]; file: string; description: string; stdout: string; min_tmux?: string }[]
}

export interface LuaExampleOptions {
releaseRock?: string
localCheckout?: boolean
matchesExample?: (path: string, content: string) => boolean
}

/** Preserve complete source files exported by Lua's native documentation tool. */
export function attachCompleteLuaExamples(
symbols: ApiSymbol[],
manifest: LuaExampleManifest | undefined,
files: { path: string; content: string }[] | undefined,
source: { repository: string; revision: string },
source: { repository: string; revision: string } & LuaExampleOptions,
): void {
if (manifest === undefined) return
const require = (condition: unknown, message: string): void => {
Expand All @@ -32,10 +38,33 @@ export function attachCompleteLuaExamples(
const code = matches[0].content
require(typeof code === 'string' && code.trim() && code.endsWith('\n') && !code.includes('\r'),
`source file must retain complete LF bytes: ${path}`)
require(!source.matchesExample || source.matchesExample(path, code),
`${path} differs from the selected checkout; regenerate the native Lua docs artifact with scripts/docs/docs.lua export`)
return code
}
const launcher = launcherPath === undefined ? undefined : { path: launcherPath, code: read(launcherPath) }
const rock = source.releaseRock
require(rock === undefined || /^[0-9][0-9a-z.-]*-[1-9]\d*$/.test(rock), 'invalid numbered rock argument')
const url = (path: string) => `https://github.com/${source.repository}/blob/${source.revision}/${path}`
const installLuv = `$ luarocks --tree ./rocks install luv ${manifest.setup.luv} &&\n`
let install: string
let setup: string
if (source.localCheckout) {
install = installLuv + ' luarocks --tree ./rocks make rockspecs/libtmux-scm-1.rockspec\n'
setup = 'From the root of the local Lua checkout that produced this preview, build the SCM rock.'
} else if (rock) {
install = installLuv + ` luarocks --tree ./rocks install libtmux ${rock} &&\n` +
' eval "$(luarocks --tree ./rocks path)"\n'
setup = 'Install the numbered rock in a new directory.'
} else {
install = installLuv + ' rocks="$PWD/rocks" &&\n' +
' (cd ../libtmux-lua && luarocks --tree "$rocks" make rockspecs/libtmux-scm-1.rockspec)\n'
const sourceTree = `https://github.com/${source.repository}/tree/${source.revision}`
setup = `Put an empty example directory next to a copy of the [Lua source revision](${sourceTree}) named \`libtmux-lua\`. Build the SCM rock from the example directory.`
}
const launcherGuide = source.localCheckout ? '`examples/api/README.md` for launcher prerequisites'
: `the [launcher prerequisites](${url('examples/api/README.md')})`
const launcherSetup = launcher ? [`See ${launcherGuide}.`] : []
const seen = new Set<string>()
const ids = new Set<string>()
for (const example of manifest.examples) {
Expand All @@ -45,42 +74,53 @@ export function attachCompleteLuaExamples(
require(typeof example.description === 'string' && example.description.trim(), 'task description is missing')
require(typeof example.stdout === 'string' && example.stdout.trim() && example.stdout.endsWith('\n'),
'expected output is missing')
require(example.min_tmux === undefined || (typeof example.min_tmux === 'string' && /^\d+\.\d+$/.test(example.min_tmux)),
'invalid tmux floor')
require(Array.isArray(example.symbols) && example.symbols.length, 'API targets are missing')
const code = read(example.file)
const name = `${example.id}.lua`
const name = source.localCheckout ? example.file : `${example.id}.lua`
const shell = source.localCheckout ? launcherPath : 'run.sh'
const blocks: NonNullable<DocBlock['examples']> = [
{
lang: 'console',
intro: `${example.description} Use Lua 5.1 or newer with LuaRocks, tmux 3.3a or newer, and a C compiler and CMake for luv on Linux. In a new directory, install the library and its standalone runtime dependency from LuaRocks:`,
code: '$ luarocks --tree ./rocks install luv &&\n' +
' luarocks --tree ./rocks install libtmux &&\n' +
' eval "$(luarocks --tree ./rocks path)"\n',
intro: [
example.description,
`Use Lua 5.1 to 5.5 or LuaJIT with LuaRocks, tmux ${example.min_tmux ?? '3.3a'} or newer, and a C compiler and CMake for luv on Linux.`,
...launcherSetup,
setup,
].join(' '),
code: install,
},
...(launcher === undefined ? [] : [{
lang: 'sh',
intro: 'Save this complete launcher as `run.sh`. It starts a private tmux daemon and cleans up after success or failure. A failed daemon shutdown reports and retains its socket directory.',
sourceUrl: url(launcher.path),
intro: source.localCheckout ? `Use \`${launcher.path}\` from the same checkout.`
: 'Save the complete launcher as `run.sh`. It starts and stops a private tmux daemon. A failed shutdown reports and retains its socket directory.',
sourceUrl: source.localCheckout ? undefined : url(launcher.path),
code: launcher.code,
}]),
{
lang: 'lua',
intro: launcher === undefined
? `Save the complete program as \`${name}\`. It starts its own private tmux server, uses it and stops it, so no existing session is needed.`
: `Save the complete program as \`${name}\`. Closing the library connection leaves the daemon running; the launcher owns its lifetime.`,
sourceUrl: url(example.file),
intro: source.localCheckout ? `Use \`${name}\` from the same checkout.`
: launcher === undefined
? `Save the complete program as \`${name}\`. It starts its own private tmux server and stops it before exiting, including after a failure.`
: `Save the complete program as \`${name}\` beside \`run.sh\`. Closing the connection leaves the daemon running. The launcher owns its lifetime.`,
sourceUrl: source.localCheckout ? undefined : url(example.file),
code,
},
launcher === undefined
? {
lang: 'console',
intro: 'Run the saved program. It runs `/usr/bin/tmux`; set `TMUX_BIN` to another absolute path to use a different binary. Assertions and operation errors produce a failing exit status:',
intro: (source.localCheckout ? 'Run the program from that checkout.' : 'Run the saved program.') +
' Set `TMUX_BIN` to use an absolute path other than `/usr/bin/tmux`.',
code: `$ eval "$(luarocks --tree ./rocks path)" &&\n lua ${name}\n`,
}
: {
lang: 'console',
intro: 'Run the saved files. Assertions and operation errors produce a failing exit status:',
code: `$ eval "$(luarocks --tree ./rocks path)" &&\n sh run.sh ${name}\n`,
intro: (source.localCheckout ? 'Run the files from that checkout.' : 'Run the saved files together.') +
' The launcher uses tmux on `PATH` unless `TMUX_BIN` selects another binary.',
code: `$ eval "$(luarocks --tree ./rocks path)" &&\n sh ${shell} "${name}"\n`,
},
{ lang: 'text', intro: 'Expected output.', code: example.stdout },
]
for (const id of example.symbols) {
require(!seen.has(id), `duplicate API target: ${id}`)
Expand Down
67 changes: 53 additions & 14 deletions packages/api-model/src/languages/lua.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ApiModel, ApiSymbol, DocBlock, Param, Signature } from '../model.ts'
import { attachCompleteLuaExamples, type LuaExampleManifest } from './lua-examples.ts'
import { isCanonicalPath } from '../products.ts'
import { attachCompleteLuaExamples, type LuaExampleManifest, type LuaExampleOptions } from './lua-examples.ts'

interface LuaNode {
name?: string
Expand Down Expand Up @@ -29,17 +30,28 @@ interface LuaDeclaration extends LuaNode {
interface LuaArtifact {
schema: number
port: string
source: { repository: string; revision: string }
source: { repository: string; revision: string; files?: { path: string; sha256: string }[] }
exporter: { name: string; version: number; luals: string }
package: { name: string; version: string; source_tag: string }
declarations: LuaDeclaration[]
examples?: { path: string; content: string }[]
api_examples?: LuaExampleManifest
}

interface LuaDeclarationSource {
revision: string
/** SHA-256 of the file at the citation revision. */
sha256: (path: string) => string | undefined
}

interface LuaExtractionOptions extends LuaExampleOptions {
declarationSource?: LuaDeclarationSource
}

function assertArtifact(input: unknown, expectedRevision?: string): LuaArtifact {
const artifact = input as LuaArtifact
if (artifact?.schema !== 1 || artifact.port !== 'lua' || !Array.isArray(artifact.declarations)) {
if (artifact?.schema !== 1 || artifact.port !== 'lua' || !Array.isArray(artifact.declarations) ||
artifact.source?.repository !== 'libtmux/libtmux-lua') {
throw new Error('Lua documentation artifact has an unsupported schema')
}
if (expectedRevision && artifact.source?.revision !== expectedRevision) {
Expand All @@ -57,14 +69,33 @@ function doc(text?: string): DocBlock | undefined {
return { summary, body: body.join('\n\n') || undefined }
}

function source(node: LuaNode, artifact: LuaArtifact) {
return {
file: node.file ?? '',
line: node.start?.[0],
function declarationSourceReader(artifact: LuaArtifact, citation: LuaDeclarationSource | undefined) {
const hashes = new Map<string, { sha256: string; verified?: boolean }>()
const files = artifact.source.files
if (files !== undefined && !Array.isArray(files)) {
throw new Error('Lua declaration source files must be an array')
}
for (const entry of files ?? []) {
if (!isCanonicalPath(entry?.path) || !entry.path.startsWith('lua/') || !entry.path.endsWith('.lua') ||
typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(entry.sha256) || hashes.has(entry.path)) {
throw new Error('Lua declaration source files contain an invalid or repeated entry')
}
hashes.set(entry.path, { sha256: entry.sha256 })
}

const provenance = {
repo: artifact.source.repository,
revision: artifact.source.revision,
revision: citation?.revision ?? artifact.source.revision,
extractedRevision: artifact.source.revision,
}
return ({ file, start }: LuaNode): ApiSymbol['source'] => {
const entry = file && hashes.get(file)
if (file && entry && citation) {
entry.verified ??= citation.sha256(file) === entry.sha256
if (entry.verified) return { ...provenance, file, line: start?.[0] }
}
return { ...provenance, file: '' }
}
}

const argName = (argument?: LuaArg) =>
Expand Down Expand Up @@ -145,8 +176,13 @@ function originOf(
return undefined
}

export function extractLua(input: unknown, expectedRevision?: string): ApiModel {
export function extractLua(
input: unknown,
expectedRevision?: string,
options: LuaExtractionOptions = {},
): ApiModel {
const artifact = assertArtifact(input, expectedRevision)
const declarationSource = declarationSourceReader(artifact, options.declarationSource)
const symbols: ApiSymbol[] = []
const byName = new Map(artifact.declarations.map((d) => [d.name, d]))
for (const declaration of artifact.declarations) {
Expand All @@ -165,7 +201,7 @@ export function extractLua(input: unknown, expectedRevision?: string): ApiModel
// The declaration's own text, not `defines`: an alias's define holds the
// generated listing of its values.
doc: doc(declaration.rawdesc ?? declaration.desc),
source: source(ownerSource, artifact),
source: declarationSource(ownerSource),
})
for (const field of declaration.fields) {
if (!field.name) continue
Expand Down Expand Up @@ -193,12 +229,15 @@ export function extractLua(input: unknown, expectedRevision?: string): ApiModel
product: 'core',
apiScope: 'exported',
type: callable ? undefined : field.view,
source: source(field, artifact),
source: declarationSource(field),
...(inheritedFrom ? { inheritedFrom } : {}),
})
}
}
attachCompleteLuaExamples(symbols, artifact.api_examples, artifact.examples, artifact.source)
attachCompleteLuaExamples(symbols, artifact.api_examples, artifact.examples, {
...artifact.source,
...options,
})
return {
port: 'lua',
repo: artifact.source.repository,
Expand All @@ -207,9 +246,9 @@ export function extractLua(input: unknown, expectedRevision?: string): ApiModel
sources: [{
product: 'core',
package: artifact.package.name,
version: artifact.package.version,
version: options.releaseRock ?? artifact.package.version,
repo: artifact.source.repository,
revision: artifact.source.revision,
revision: options.declarationSource?.revision ?? artifact.source.revision,
extractedRevision: artifact.source.revision,
}],
symbols,
Expand Down
5 changes: 5 additions & 0 deletions packages/api-model/src/products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ export function inheritProductFromOwners(symbols: ApiSymbol[]): void {
}
}

/** A relative path inside a repository: no escape, no query, no hidden separator. */
export const isCanonicalPath = (file: unknown): file is string => typeof file === 'string' && file !== '' && !file.startsWith('/')
&& !/[\\?#%\0\n\r]/.test(file) && !/^[a-z]:/i.test(file)
&& file.split('/').every((part) => part !== '' && part !== '.' && part !== '..')

/**
* Build a source link from the declaration's repository before the port fallback.
* A file the model embeds links to its source page, `<reference>/sources/<file>/`.
Expand Down
Loading
Loading