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
28 changes: 11 additions & 17 deletions .github/workflows/merge-build-push.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
name: Build , Push to web, Deploy Antora Docs

on:
pull_request_target:
types:
- closed
create:
push:
branches:
- master
- 'v[0-9]+.[0-9]+'
- 'v[0-9]+.[0-9]+.[0-9]+'
workflow_dispatch:
inputs:
source_branch:
Expand All @@ -14,23 +15,16 @@ on:
jobs:
build-and-deploy:
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || github.event_name == 'create' || github.event.pull_request.merged == true
permissions:
contents: write
pull-requests: write

steps:
- name: PR was merged
if: github.event.pull_request.number != ''
run: |
echo "PR #${{ github.event.pull_request.number }} was merged into ${{ github.event.pull_request.base.ref }}."
echo "Head commit was: ${{ github.event.pull_request.head.sha }}"

- name: Checkout Documentation Repository (ivorysql_doc)
uses: actions/checkout@v4
with:
path: ivorysql_doc
ref: ${{ inputs.source_branch || github.ref }}
ref: ${{ inputs.source_branch || github.sha }}

- name: Checkout Doc Builder Repository (doc_builder)
uses: actions/checkout@v4
Expand Down Expand Up @@ -107,10 +101,10 @@ jobs:
fi
done

- name: Pin PDF assembler to merged PR branch
- name: Pin PDF assembler to source branch
working-directory: ./ivory-doc-builder
env:
MERGED_BRANCH: ${{ inputs.source_branch || github.event.pull_request.base.ref || github.ref_name }}
MERGED_BRANCH: ${{ inputs.source_branch || github.ref_name }}
COMPONENT_NAME: ivorysql-doc
run: |
if [[ -z "${MERGED_BRANCH}" ]]; then
Expand All @@ -136,7 +130,7 @@ jobs:
working-directory: ./www_publish_target
env:
LATEST_VERSION: ${{ steps.latest_version_step.outputs.version }}
MERGED_PR_BASE: ${{ github.event.pull_request.base.ref || github.ref_name }}
MERGED_PR_BASE: ${{ inputs.source_branch || github.ref_name }}
run: |
set -euo pipefail

Expand Down Expand Up @@ -201,7 +195,7 @@ jobs:
- name: Copy English PDF export into web repo
working-directory: ./ivory-doc-builder
env:
MERGED_BRANCH: ${{ inputs.source_branch || github.event.pull_request.base.ref || github.ref_name }}
MERGED_BRANCH: ${{ inputs.source_branch || github.ref_name }}
COMPONENT_NAME: ivorysql-doc
run: |
set -euo pipefail
Expand Down Expand Up @@ -234,7 +228,7 @@ jobs:
- name: Copy Chinese PDF export into web repo
working-directory: ./ivory-doc-builder
env:
MERGED_BRANCH: ${{ inputs.source_branch || github.event.pull_request.base.ref || github.ref_name }}
MERGED_BRANCH: ${{ inputs.source_branch || github.ref_name }}
COMPONENT_NAME: ivorysql-doc
run: |
set -euo pipefail
Expand Down
244 changes: 244 additions & 0 deletions .github/workflows/pr-preview-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
name: Deploy PR preview

on:
workflow_run:
workflows: [Pr preview]
types: [completed]

permissions: {}

jobs:
verify:
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
runs-on: ubuntu-latest
permissions:
actions: read
pull-requests: read
outputs:
number: ${{ steps.preview.outputs.number }}
artifact_id: ${{ steps.preview.outputs.artifact_id }}
steps:
- name: Match the build artifact to an open pull request
id: preview
uses: actions/github-script@v7
with:
script: |
const run = context.payload.workflow_run;
if (run.path?.split('@')[0] !== '.github/workflows/pr-preview.yml' ||
run.repository?.id !== context.payload.repository.id || !run.head_repository) {
return;
}

// GitHub can omit pull_requests for fork runs. Use the artifact name
// to look up the PR, then verify its source against GitHub's run data.
const pattern = new RegExp(`^docs-preview-${run.run_attempt}-pr-([1-9][0-9]*)$`);
const artifacts = await github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
...context.repo,
run_id: run.id,
});
const matches = artifacts.filter(artifact => !artifact.expired && pattern.test(artifact.name));
if (matches.length !== 1) {
core.setFailed('Expected one unexpired documentation artifact. Re-run the preview build to upload a new one.');
return;
}

const artifact = matches[0];
const number = Number(artifact.name.match(pattern)[1]);
if (!Number.isSafeInteger(number) ||
(run.pull_requests?.length && !run.pull_requests.some(pr => pr.number === number))) {
return;
}

const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number: number,
});
if (pr.state !== 'open' || pr.head.sha !== run.head_sha ||
pr.head.ref !== run.head_branch || pr.head.repo?.id !== run.head_repository.id) {
core.notice('The pull request is closed or its source has changed.');
return;
}

core.setOutput('number', number);
core.setOutput('artifact_id', artifact.id);

deploy:
needs: verify
if: needs.verify.outputs.number != ''
runs-on: ubuntu-latest
concurrency:
group: docs-preview-deploy-${{ needs.verify.outputs.number }}
cancel-in-progress: false
queue: max
permissions:
actions: read
deployments: write
pull-requests: write
statuses: write
env:
PR_NUMBER: ${{ needs.verify.outputs.number }}
steps:
- name: Download the verified preview archive
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
artifact-ids: ${{ needs.verify.outputs.artifact_id }}
path: ${{ runner.temp }}/docs-preview-archive
github-token: ${{ github.token }}
run-id: ${{ github.event.workflow_run.id }}
skip-decompress: true
digest-mismatch: error

- name: Validate and extract the static site
shell: bash
run: |
python3 - <<'PY'
import os
import stat
from pathlib import Path
from zipfile import ZipFile

runner_temp = Path(os.environ['RUNNER_TEMP'])
downloads = list((runner_temp / 'docs-preview-archive').iterdir())
if len(downloads) != 1 or not downloads[0].is_file():
raise SystemExit('Expected exactly one preview archive.')

with ZipFile(downloads[0]) as archive:
paths = set()
missing_homepages = {'cn/index.html', 'en/index.html'}
for entry in archive.infolist():
name = entry.filename.removesuffix('/')
parts = name.split('/')
if (parts[0] not in {'cn', 'en'} or '\\' in name or
any(part in {'', '.', '..'} for part in parts) or name in paths or
(len(parts) == 1 and not entry.is_dir())):
raise SystemExit(f'Invalid or duplicate preview path: {entry.filename!r}')
expected_type = stat.S_IFDIR if entry.is_dir() else stat.S_IFREG
if stat.S_IFMT(entry.external_attr >> 16) not in (0, expected_type):
raise SystemExit(f'Invalid preview file type: {entry.filename!r}')
paths.add(name)
if not entry.is_dir():
missing_homepages.discard(name)

if missing_homepages:
raise SystemExit('The preview archive must include both language homepages.')
archive.extractall(runner_temp / 'docs-preview')
PY

cat > "$RUNNER_TEMP/docs-preview/index.html" <<'HTML'
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>IvorySQL Docs Preview</title>
<script>
const language = navigator.language || navigator.userLanguage || '';
window.location.replace(language.toLowerCase().startsWith('zh') ? './cn/' : './en/');
</script>
<a href="./cn/">中文预览</a>
<a href="./en/">English preview</a>
</html>
HTML

- name: Check that this is still the current PR commit
id: current
uses: actions/github-script@v7
with:
script: |
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number: Number(process.env.PR_NUMBER),
});
core.setOutput('deploy', pr.state === 'open' && pr.head.sha === context.payload.workflow_run.head_sha);

- name: Deploy to Netlify
if: steps.current.outputs.deploy == 'true'
id: netlify
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654 # v3.0
with:
publish-dir: ${{ runner.temp }}/docs-preview
deploy-message: "Deploy preview for PR #${{ env.PR_NUMBER }}"
# PR HTML and JavaScript are contributor-controlled. Keep them on a draft preview alias.
production-deploy: false
enable-pull-request-comment: false
enable-commit-comment: false
enable-commit-status: false
enable-github-deployment: false
fails-without-credentials: true
alias: pr-${{ env.PR_NUMBER }}-doc
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
timeout-minutes: 5

- name: Post preview links and report deployment on GitHub
if: steps.netlify.outputs.deploy-url != ''
uses: actions/github-script@v7
env:
DEPLOY_URL: ${{ steps.netlify.outputs.deploy-url }}
with:
script: |
const number = Number(process.env.PR_NUMBER);
const sha = context.payload.workflow_run.head_sha;
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number: number,
});
if (pr.state !== 'open' || pr.head.sha !== sha) {
return;
}

const base = new URL(process.env.DEPLOY_URL);
const chinese = new URL('/cn/', base);
const english = new URL('/en/', base);
const marker = '<!-- ivorysql-docs-preview -->';
const body = [
marker,
'🚀 **IvorySQL-Docs Preview Ready**',
'',
`- **Chinese Preview:** [${chinese}](${chinese})`,
`- **English Preview:** [${english}](${english})`,
].join('\n');
const comments = await github.paginate(github.rest.issues.listComments, {
...context.repo,
issue_number: number,
per_page: 100,
});
const previewComment = comments.find(comment =>
comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(marker)
);
if (previewComment) {
await github.rest.issues.updateComment({ ...context.repo, comment_id: previewComment.id, body });
} else {
await github.rest.issues.createComment({ ...context.repo, issue_number: number, body });
}

try {
await github.rest.repos.createCommitStatus({
...context.repo,
sha,
context: 'Netlify',
description: 'Netlify deployment',
state: 'success',
target_url: base.href,
});
} catch (error) {
core.warning(`Could not update the Netlify commit status: ${error.message}`);
}

try {
const { data: deployment } = await github.rest.repos.createDeployment({
...context.repo,
ref: sha,
environment: 'pull request',
auto_merge: false,
required_contexts: [],
production_environment: false,
});
await github.rest.repos.createDeploymentStatus({
...context.repo,
deployment_id: deployment.id,
state: 'success',
environment_url: base.href,
});
} catch (error) {
core.warning(`Could not record the GitHub deployment: ${error.message}`);
}
Loading
Loading