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
27 changes: 24 additions & 3 deletions .github/workflows/pr-autofix-apply.yml
Original file line number Diff line number Diff line change
Expand Up @@ -153,17 +153,38 @@ jobs:
- name: Apply and constrain validated patch
if: steps.pr.outputs.run == 'true' && steps.artifact.outputs.has_changes == 'true'
working-directory: work
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ steps.pr.outputs.pr_number }}
run: |
set -euo pipefail
patch="$RUNNER_TEMP/pr-autofix/autofix.patch"

# Privileged apply must not trust redirect changes from PR artifacts.
# Recompute them using trusted default-branch code and compare patches.
if git apply --numstat "$patch" | awk '$3 == "nginx/includes/redirects.conf" {found=1} END {exit !found}'; then
base_sha="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '.base.sha')"
trusted="$RUNNER_TEMP/trusted-check-doc-redirects.py"
gh api "repos/${GITHUB_REPOSITORY}/contents/scripts/check_doc_redirects.py?ref=${GITHUB_SHA}" --jq '.content' | base64 -d > "$trusted"
test -s "$trusted"
git fetch --depth=1 "https://github.com/${GITHUB_REPOSITORY}.git" "$base_sha"
python3 "$trusted" --base "$base_sha" --head HEAD --mode fix \
--pr-url "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/${PR_NUMBER}"
git diff --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/expected-redirect.patch"
git checkout -- nginx/includes/redirects.conf
fi
git apply --check "$patch"
git apply --index "$patch"
if [[ -f "$RUNNER_TEMP/expected-redirect.patch" ]]; then
git diff --cached --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/applied-redirect.patch"
diff -u "$RUNNER_TEMP/expected-redirect.patch" "$RUNNER_TEMP/applied-redirect.patch"
fi

count=0
while IFS= read -r -d '' path; do
count=$((count + 1))
case "$path" in
routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx)
nginx/includes/redirects.conf|routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx)
;;
*)
echo "::error::Artifact attempted to change disallowed path: $path"
Expand Down Expand Up @@ -191,7 +212,7 @@ jobs:
set -euo pipefail
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git commit -m '🤖 Apply automated PR fixes'
git commit -m '🔩 Apply validated PR autofixes' -m 'Apply validated formatting, generated routes, and documentation redirects.' -m 'Co-authored-by: ChatGPT 6 <noreply@openai.com>'
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"

- name: Push bot commit
Expand Down Expand Up @@ -239,7 +260,7 @@ jobs:
set -euo pipefail
marker='<!-- stellar-docs-pr-autofix -->'
body="$marker
Autofix found a validated formatting, lint, or generated-route patch, but the upstream workflow could not push to this PR branch. Download and extract the \`pr-autofix-*\` artifact from the [autofix run]($RUN_URL), then run \`git apply autofix.patch\` on the PR branch."
Autofix produced a validated formatting, lint, generated-route, or redirect patch but could not push to this PR branch. Any added redirect contains a comment explaining the move and its originating PR. Download and extract the \`pr-autofix-*\` artifact from the [autofix run]($RUN_URL), then run \`git apply autofix.patch\` on the PR branch."

comment_id="$(gh api --paginate "repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/comments" \
--jq ".[] | select(.body | contains(\"$marker\")) | .id" | head -n 1)"
Expand Down
28 changes: 25 additions & 3 deletions .github/workflows/pr-autofix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ jobs:
- name: Install dependencies
run: pnpm install --prefer-offline --frozen-lockfile

- name: Test redirect regression behavior
run: python3 -m unittest discover -s tests -p test_doc_redirects.py

- name: Generate formatting and lint fixes
run: |
set -euo pipefail
Expand All @@ -65,6 +68,18 @@ jobs:
git reset --hard "$HEAD_SHA"
git clean -fd

- name: Generate safe documentation redirects
env:
PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }}
run: |
set -euo pipefail
git remote add base "https://github.com/${GITHUB_REPOSITORY}.git"
git fetch base "refs/heads/${BASE_REF}:refs/remotes/base/${BASE_REF}"
python3 scripts/check_doc_redirects.py --base "base/${BASE_REF}" --head HEAD --mode fix --pr-url "$PR_URL"
git diff --binary -- nginx/includes/redirects.conf > "$RUNNER_TEMP/redirect.patch"
git reset --hard "$HEAD_SHA"
git clean -fd

- name: Assemble autofix patch
id: patch
run: |
Expand All @@ -77,6 +92,10 @@ jobs:
git apply "$RUNNER_TEMP/routes.patch"
fi

if [[ -s "$RUNNER_TEMP/redirect.patch" ]]; then
git apply "$RUNNER_TEMP/redirect.patch"
fi

git diff --binary > "$RUNNER_TEMP/autofix.patch"
if [[ -s "$RUNNER_TEMP/autofix.patch" ]]; then
echo "has_changes=true" >> "$GITHUB_OUTPUT"
Expand All @@ -93,7 +112,7 @@ jobs:
while IFS= read -r -d '' path; do
count=$((count + 1))
case "$path" in
routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx)
nginx/includes/redirects.conf|routes.txt|docs/*.md|docs/*.mdx|src/pages/*.md|src/pages/*.mdx|meetings/*.md|meetings/*.mdx|src/*.js|src/*.jsx|src/*.ts|src/*.tsx)
;;
*)
echo "::error::Autofix attempted to change disallowed path: $path"
Expand Down Expand Up @@ -122,6 +141,11 @@ jobs:
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git commit -m 'Autofix validation tree'

- name: Validate documentation redirect coverage
env:
PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }}
run: python3 scripts/check_doc_redirects.py --base "base/${BASE_REF}" --head HEAD --mode check --pr-url "$PR_URL"

- name: Check MDX formatting
run: git update-index -g && pnpm ci:mdx

Expand All @@ -131,8 +155,6 @@ jobs:
- name: Check new absolute internal links
run: |
set -euo pipefail
git remote add base "https://github.com/${GITHUB_REPOSITORY}.git"
git fetch base "$BASE_REF" --depth=1
scripts/check-relative-links.sh --range "base/${BASE_REF}...HEAD" \
|| { echo "::error::New absolute /docs link(s) found above."; exit 1; }

Expand Down
33 changes: 33 additions & 0 deletions .github/workflows/pr-redirect-regression.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Check documentation redirect regressions

on:
pull_request:
paths:
- "docs/**"
- "nginx/includes/redirects.conf"
- "scripts/check_doc_redirects.py"
- "tests/test_doc_redirects.py"
- ".github/workflows/pr-redirect-regression.yml"

permissions:
contents: read

jobs:
redirect-check:
name: Preserve moved documentation URLs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Run redirect regression tests
run: python3 -m unittest discover -s tests -p test_doc_redirects.py
- name: Verify moved page redirects
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
PR_URL: ${{ github.server_url }}/${{ github.repository }}/pull/${{ github.event.pull_request.number }}
run: |
set -euo pipefail
git fetch --depth=1 origin "$BASE_SHA"
python3 scripts/check_doc_redirects.py --base "$BASE_SHA" --head HEAD --mode check --pr-url "$PR_URL"
184 changes: 184 additions & 0 deletions scripts/check_doc_redirects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Detect removed docs URLs and propose safe, documented Nginx redirects.

Only moves with uniquely identified destinations receive an automatic fix.
Ambiguous deletions and invalid redirect chains must be reviewed manually.
"""

import argparse
import re
import subprocess
import sys
from pathlib import Path

REDIRECTS = Path("nginx/includes/redirects.conf")
DOC_SUFFIXES = (".md", ".mdx")
REWRITE = re.compile(r'^\s*rewrite\s+(\^\S+)\s+"([^"\n]+)"\s+permanent\s*;', re.M)
SLUG = re.compile(r'^slug:\s*["\']?([^\s"\']+)', re.M)


def git(*args):
result = subprocess.run(["git", *args], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.stdout.decode("utf-8", errors="replace")


def is_doc(path):
return path.startswith("docs/") and path.endswith(DOC_SUFFIXES)


def route(path, content=""):
"""Map ordinary docs paths and supported absolute Docusaurus slugs to URLs."""
if not is_doc(path):
return None
frontmatter = content.split("---", 2)
if content.startswith("---") and len(frontmatter) > 2:
match = SLUG.search(frontmatter[1])
if match:
slug = match.group(1)
if not slug.startswith("/"):
return None # Relative slugs require manual inspection.
return ("/docs" + slug).rstrip("/") if not slug.startswith("/docs/") else slug.rstrip("/")
raw = "/" + path.rsplit(".", 1)[0]
return raw[:-6] if raw.endswith("/index") else raw


def changed_docs(base, head):
"""Return removed or renamed pages, plus candidate newly added pages."""
changes = git("diff", "--name-status", "-M", "--diff-filter=ADR", base, head, "--", "docs/")
removed = []
added = []
for row in changes.splitlines():
fields = row.split("\t")
action = fields[0][0]
if action == "R" and len(fields) == 3:
old, new = fields[1:]
if is_doc(old):
removed.append((old, new if is_doc(new) else None))
if is_doc(new):
added.append(new)
elif action == "D" and len(fields) == 2 and is_doc(fields[1]):
removed.append((fields[1], None))
elif action == "A" and len(fields) == 2 and is_doc(fields[1]):
added.append(fields[1])
return removed, added


def current_docs(head):
paths = git("ls-tree", "-r", "--name-only", head, "--", "docs/").splitlines()
docs = {path: "" for path in paths if is_doc(path)}
# Read bodies only where an explicit slug might override a file's URL.
result = subprocess.run(
["git", "grep", "-l", "^slug:", head, "--", "docs/"],
check=False, capture_output=True, text=True,
)
if result.returncode not in (0, 1):
raise RuntimeError(result.stderr)
for row in result.stdout.splitlines():
path = row.split(":", 1)[1]
if path in docs:
docs[path] = git("show", f"{head}:{path}")
return docs


def redirects(contents):
return [(re.compile(source), target) for source, target in REWRITE.findall(contents)]


def lookup(url, rules):
"""Resolve permanent rewrite chains without accepting loops or external URLs."""
visited = set()
current = url
for _ in range(20):
if current in visited:
return None, "redirect loop"
visited.add(current)
matches = [(pattern, target) for pattern, target in rules if pattern.match(current)]
if not matches:
return current, None
pattern, target = matches[0]
match = pattern.match(current)
next_url = re.sub(
r"\$(\d+)",
lambda m: (match.group(int(m.group(1))) or "") if int(m.group(1)) <= (match.lastindex or 0) else "",
target,
)
current = next_url.split("#", 1)[0].split("?", 1)[0]
if not current.startswith("/docs"):
return None, "external or unsupported redirect destination"
return None, "redirect chain too long"


def assess(removed, added, before_docs, after_docs, conf, pr_url):
"""Return safe generated rewrite statements and unresolved problems."""
live_routes = {route(path, content) for path, content in after_docs.items()}
live_routes.discard(None)
candidates = {}
for path in added:
candidates.setdefault(Path(path).name, []).append(path)
rules = redirects(conf)
new_rules = []
problems = []
for old, moved in removed:
previous = route(old, before_docs[old])
if previous is None:
problems.append(f"{old}: unsupported slug; check redirect manually")
continue
if previous in live_routes:
continue
new = moved
if not new:
matches = candidates.get(Path(old).name, [])
if len(matches) == 1:
new = matches[0]
replacement = route(new, after_docs[new]) if new in after_docs else None
resolved, error = lookup(previous, rules)
if error:
problems.append(f"{previous}: {error}")
continue
if resolved != previous:
if resolved not in live_routes:
problems.append(f"{previous}: redirect points to missing {resolved}")
continue
if replacement is None or replacement == previous or replacement not in live_routes:
problems.append(f"{previous}: removed without a unique, live replacement; add a reviewed redirect")
continue
if any(pattern.match(previous) for pattern, _ in rules):
problems.append(f"{previous}: existing redirect must be reviewed")
continue
# A contextual comment explains *why* the rule exists, not merely its URL.
explanation = f"# Preserve links after moving {previous} to {replacement} ({pr_url})"
escaped = re.escape(previous).replace("\\-", "-")
statement = f'rewrite ^{escaped}$ "{replacement}" permanent;'
new_rules.append(explanation + "\n" + statement)
rules.append((re.compile("^" + re.escape(previous) + "$"), replacement))
return new_rules, problems


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base", required=True, help="Git base ref before the PR")
parser.add_argument("--head", default="HEAD", help="Git head ref")
parser.add_argument("--mode", choices=("check", "fix"), default="check")
parser.add_argument("--pr-url", default="https://github.com/stellar/stellar-docs/pulls")
args = parser.parse_args()
removed, added = changed_docs(args.base, args.head)
if not removed:
print("No moved or deleted documentation pages")
return 0
after = current_docs(args.head)
before = {old: git("show", f"{args.base}:{old}") for old, _ in removed}
conf = REDIRECTS.read_text(encoding="utf-8")
fixes, problems = assess(removed, added, before, after, conf, args.pr_url)
if fixes and args.mode == "fix":
with REDIRECTS.open("a", encoding="utf-8") as stream:
stream.write("\n# Automatically preserved documentation URLs\n" + "\n\n".join(fixes) + "\n")
print(f"Added {len(fixes)} documented Nginx redirects")
elif fixes:
problems.extend(f"Missing permanent redirect: {rule.splitlines()[-1]}" for rule in fixes)
for error in problems:
print(f"::error::{error}", file=sys.stderr)
return 1 if problems else 0


if __name__ == "__main__":
sys.exit(main())
Loading