Skip to content
Open
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
49 changes: 49 additions & 0 deletions .github/workflows/documentation-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Test documentation builder

on:
pull_request:
push:
branches: [main]
workflow_dispatch:

permissions:
contents: read

jobs:
# These tests use Node built-ins only; installing the Docusaurus dependency tree is unnecessary.
unit-tests:
name: Test documentation tooling
runs-on: ubuntu-latest
steps:
- name: Checkout builder
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 'lts/*'
- name: Test builder
run: npm test

documentation:
name: Build branded documentation fixture
runs-on: ubuntu-latest
steps:
- name: Checkout action
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build fixture with the local action
id: docs
uses: ./
with:
source-directory: fixture
site-config: branding.json
- name: Verify published assets
shell: bash
env:
BUILD_DIRECTORY: ${{ steps.docs.outputs.build-directory }}
run: |
test -f "$BUILD_DIRECTORY/index.html"
test -f "$BUILD_DIRECTORY/img/logo.svg"
2 changes: 1 addition & 1 deletion .github/workflows/pr-title.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
run:
name: Validate PR title
if: github.event_name == 'pull_request_target' && github.event.pull_request.draft == false
runs-on: [self-hosted]
runs-on: ubuntu-latest
permissions:
pull-requests: read
statuses: write
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
build/
.docusaurus/
*.log
25 changes: 25 additions & 0 deletions .yamllint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# yamllint — https://yamllint.readthedocs.io/
# Lints GitHub Actions workflow YAML. Install locally via `pip install yamllint`.

extends: default

rules:
# GitHub Actions sometimes needs long one-line expressions — be lenient.
line-length:
max: 200
level: warning

# Allow quoted 'on:' to avoid YAML 1.1 truthy pitfalls.
truthy:
allowed-values: ['true', 'false', 'on', 'off']
check-keys: false

# Comments can start at any column.
comments:
min-spaces-from-content: 1

# Let document start (---) be optional.
document-start: disable

ignore: |
node_modules/
157 changes: 156 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,156 @@
# action-docusaurus-build
# action-docusaurus-build

Build a repository's Markdown as a Docusaurus documentation site. The composite
action owns the build and shared branding defaults; the consumer workflow decides
whether and how to upload or deploy the generated site.

## Get started

1. Add `docs/index.md` as your homepage and any additional `.md` or `.mdx` files.
2. Add `.github/workflows/documentation.yml`:

```yaml
name: Documentation
on:
push:
branches: [main]
paths: ['docs/**', '.github/workflows/documentation.yml']
pull_request:
paths: ['docs/**', '.github/workflows/documentation.yml']
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: docs
uses: rtCamp/action-docusaurus-build@v1
```

The action automatically loads the root `action.yml` at the selected tag. The built
site is available to later steps at `${{ steps.docs.outputs.build-directory }}`.
Change `main` if your default branch has another name.

To publish on GitHub Pages, set **Settings → Pages → Source** to **GitHub
Actions**, allow the publishing branch in the `github-pages` environment, and use
the complete consumer-owned workflow in
[examples/documentation.yml](examples/documentation.yml). It configures Pages,
uploads the build output, and deploys it only from the default branch.

**Availability:** `v1` must point to a commit containing the root `action.yml`. To
try an unreleased version, replace `@v1` with its branch or commit SHA. Organisation
Actions policies must allow this action and the actions selected by the consumer.

## What happens on each run

| Consumer workflow path | Result |
| --- | --- |
| Call only `rtCamp/action-docusaurus-build@v1` | Build and expose `build-directory` |
| Add `actions/upload-pages-artifact` | Build and upload the selected output |
| Add a Pages deployment job | Build, upload and deploy according to consumer conditions |
| Build fails | Later upload and deployment steps do not run |

Artifacts and logs appear in **your repository → Actions → workflow run**. The
live site belongs to your repository too, typically `https://OWNER.github.io/REPO/`
or its configured custom domain. Upload, deployment, concurrency, environments and
artifact retention are all controlled by the consumer workflow.

## Available options

Add any of these beneath the consumer job's `with:` block. All are optional.
Paths are relative to the consumer checkout or project as specified below.

| Input | Default | Use it to… |
| --- | --- | --- |
| `source-directory` | `.` | Select a project inside a monorepo |
| `docs-directory` | `docs` | Select the Markdown folder relative to `source-directory` |
| `site-title` | Repository name | Set the site and navbar title |
| `site-config` | None | Load branding JSON relative to `source-directory` |
| `site-url` | `https://OWNER.github.io` | Override the origin, without a path |
| `base-url` | `/REPO/` | Override the path, with leading/trailing `/`; use `/` for a root domain |
| `sidebar` | Autogenerated | Supply a JSON array of Docusaurus sidebar items |
| `node-version` | `lts/*` | Defaults to the latest LTS; accepts an explicit version, 22 or later |

Owner-site repositories (`OWNER.github.io`) default to `/`. URL inputs override
the inferred values. A consumer can pass outputs from `actions/configure-pages` to
validate a configured custom domain or Pages path, as the full example does.

**Brand a site:**

```yaml
with:
site-title: My Plugin
site-config: docs/branding.json
```

**Build a monorepo project:**

```yaml
with:
source-directory: packages/my-plugin
docs-directory: manual
site-title: My Plugin
```

Update the caller's branch/path filters too: for this example, use `develop` and
`packages/my-plugin/manual/**`. Include any branding files and assets in the path
filters. The consumer also owns any publishing-branch conditions.

## Branding and labels

With `site-config: docs/branding.json`, create:

```json
{
"tagline": "My Plugin handbook",
"favicon": "img/logo.svg",
"staticDirectory": "docs/assets",
"customCss": "docs/brand.css",
"navbar": {
"logo": { "alt": "My Plugin", "src": "img/logo.svg" },
"items": [
{ "type": "docSidebar", "sidebarId": "docs", "label": "Handbook", "position": "left" },
{ "href": "https://github.com/example/my-plugin", "label": "Source", "position": "right" }
]
},
"footer": { "copyright": "My Plugin contributors" }
}
```

Place the logo at `docs/assets/img/logo.svg`. Only put public assets in
`staticDirectory`: its contents are copied into the site root. CSS and asset paths
are relative to `source-directory` and cannot escape that project through symlinks.

Navbar and footer accept Docusaurus fields, merged one level over shared defaults;
arrays such as `navbar.items` replace the defaults. `navbar.title` can override only
the navbar title. The supported top-level keys are `tagline`, `favicon`, `navbar`,
`footer`, `customCss`, and `staticDirectory`.

Consumer CSS loads after the shared stylesheet. For example, in `docs/brand.css`:

```css
:root { --docs-color-primary: #6750a4; }
[data-theme='dark'] { --docs-color-primary: #c9b8ff; }
```

The `--docs-color-primary-dark`, `-darker`, `-darkest`, `-light`, `-lighter` and
`-lightest` variants are also available. See [fixture/branding.json](fixture/branding.json)
for a working example.

## Writing documentation

- Keep `index.md` in the docs root as the homepage.
- Use Markdown in `.md`; use `.mdx` when you need MDX features.
- Use `sidebar_position` and `sidebar_label` front matter to organise pages.
- Keep links between docs relative. Links to repository files outside docs become
GitHub source links; local images, including reference-style images, are bundled.
- Source links on PR builds use the head repository and branch, including forks.
- Broken internal links/anchors and missing repository-file links fail the build.

## Build output

The action exposes one output, `build-directory`, containing the absolute path to
the generated site on the current runner. It is intentionally runner-local. Pass
that path to the consumer's preferred artifact, deployment or validation step.
61 changes: 61 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: Build Docusaurus documentation
description: Build consumer Markdown with shared branding defaults.
inputs:
source-directory:
description: Project directory relative to the consumer checkout.
default: '.'
docs-directory:
description: Markdown directory relative to source-directory; index.md is the homepage.
default: docs
site-title:
description: Site title; empty uses the consumer repository name.
default: ''
site-config:
description: Optional branding JSON file relative to source-directory.
default: ''
site-url:
description: Site origin; empty uses https://OWNER.github.io.
default: ''
base-url:
description: Site path; empty uses the consumer repository path.
default: ''
sidebar:
description: Optional JSON array of Docusaurus sidebar items; empty generates it from docs.
default: ''
node-version:
description: Node.js version for the builder; defaults to the latest LTS (minimum 22).
default: 'lts/*'
outputs:
build-directory:
description: Absolute path to the built site on the current runner.
value: ${{ steps.build.outputs.build-directory }}
runs:
using: composite
steps:
- name: Setup Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: ${{ inputs.node-version }}
# Remote action lockfiles live outside the checkout, beyond setup-node's cache hashing scope.
package-manager-cache: false

- name: Install builder dependencies
shell: bash
working-directory: ${{ github.action_path }}
run: npm ci --no-fund

- name: Build static documentation
id: build
shell: bash
working-directory: ${{ github.action_path }}
env:
SOURCE_DIRECTORY: ${{ inputs.source-directory }}
DOCS_DIRECTORY: ${{ inputs.docs-directory }}
SITE_TITLE: ${{ inputs.site-title }}
SITE_CONFIG: ${{ inputs.site-config }}
SITE_URL: ${{ inputs.site-url }}
BASE_URL: ${{ inputs.base-url }}
SIDEBAR: ${{ inputs.sidebar }}
SOURCE_REF: ${{ github.head_ref || github.ref_name }}
SOURCE_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
run: node build-action.mjs
28 changes: 28 additions & 0 deletions build-action.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { appendFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
const env = process.env;
// Keep each invocation's output distinct when a job builds more than one site.
const work = mkdtempSync(path.join(env.RUNNER_TEMP, 'docusaurus-'));
const settingsPath = path.join(work, 'settings.json');
const output = path.join(work, 'build');
const settings = {
sourceDirectory: env.SOURCE_DIRECTORY,
docsDirectory: env.DOCS_DIRECTORY,
sourceRef: env.SOURCE_REF,
sourceRepository: env.SOURCE_REPOSITORY,
title: env.SITE_TITLE,
siteConfig: env.SITE_CONFIG,
url: env.SITE_URL,
baseUrl: env.BASE_URL,
...(env.SIDEBAR ? { sidebar: JSON.parse(env.SIDEBAR) } : {}),
};
writeFileSync(settingsPath, JSON.stringify(settings));
try {
const child = spawnSync(process.execPath, ['cli.mjs', 'build', '--source', env.GITHUB_WORKSPACE, '--settings', settingsPath, '--out-dir', output], { stdio: 'inherit' });
if (child.error) throw child.error;
process.exitCode = child.status ?? 1;
if (process.exitCode === 0) appendFileSync(env.GITHUB_OUTPUT, `build-directory=${output}\n`);
} finally {
rmSync(settingsPath, { force: true });
}
53 changes: 53 additions & 0 deletions cli.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { spawnSync, execFileSync } from 'node:child_process';
import { mkdtempSync, readFileSync, realpathSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { settingsFor, inside } from './settings.mjs';

const root = path.dirname(fileURLToPath(import.meta.url));
const [command, ...args] = process.argv.slice(2);
const options = {};
const forwarded = [];
// Consume only wrapper options; pass flags such as --host and --out-dir to Docusaurus.
for (let i = 0; i < args.length; i++) {
if (['--source', '--settings', '--repository'].includes(args[i])) {
const key = args[i].slice(2);
if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing --${key} value`);
options[key] = args[++i];
} else forwarded.push(args[i]);
}
if (!['start', 'build', 'serve'].includes(command) || !options.source) {
console.error('Usage: node cli.mjs <start|build|serve> --source <repository checkout> [--repository owner/name] [--settings site.json] [Docusaurus options]');
process.exit(1);
}
const source = realpathSync(options.source);
const git = (...gitArgs) => execFileSync('git', ['-C', source, ...gitArgs], { encoding: 'utf8' }).trim();
let repository = options.repository || process.env.GITHUB_REPOSITORY;
if (!repository) {
const remote = git('remote', 'get-url', 'origin');
const match = remote.match(/^(?:https:\/\/github\.com\/|git@github\.com:)([^/]+\/[^/]+?)(?:\.git)?$/);
if (!match) throw new Error('Cannot infer GitHub repository; pass --repository owner/name');
repository = match[1];
}
const overrides = options.settings ? JSON.parse(readFileSync(path.resolve(options.settings), 'utf8')) : {};
const settings = settingsFor(repository, {
// PRs use the head branch; detached local checkouts fall back to a commit SHA.
sourceRef: process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME || git('branch', '--show-current') || git('rev-parse', 'HEAD'),
...overrides,
});
inside(inside(source, settings.sourceDirectory), settings.docsDirectory);
// Share resolved settings with the config and sidebar modules without editing either checkout.
const temp = mkdtempSync(path.join(tmpdir(), 'docusaurus-settings-'));
const settingsPath = path.join(temp, 'site.json');
writeFileSync(settingsPath, JSON.stringify(settings));
try {
const child = spawnSync(process.execPath, [path.join(root, 'node_modules/@docusaurus/core/bin/docusaurus.mjs'), command, ...forwarded], {
cwd: root,
env: { ...process.env, DOCS_SOURCE: source, DOCS_SETTINGS: settingsPath, NO_UPDATE_NOTIFIER: '1' },
stdio: 'inherit',
});
if (child.error) throw child.error;
// Preserve build failures for CI; a signal-terminated child has no numeric exit status.
process.exitCode = child.status ?? 1;
} finally { rmSync(temp, { recursive: true, force: true }); }
Loading
Loading