From d86c38434cb8e46d85e5a9f067c40211695b1d69 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Fri, 13 Nov 2026 12:15:48 -0800 Subject: [PATCH 1/2] add external link check --- .github/workflows/check_external_links.yml | 89 +++++++++++++++ utils/report_broken_links.py | 125 +++++++++++++++++++++ 2 files changed, 214 insertions(+) create mode 100644 .github/workflows/check_external_links.yml create mode 100644 utils/report_broken_links.py diff --git a/.github/workflows/check_external_links.yml b/.github/workflows/check_external_links.yml new file mode 100644 index 000000000000..800518fa1c96 --- /dev/null +++ b/.github/workflows/check_external_links.yml @@ -0,0 +1,89 @@ +name: Check external links + +# This workflow checks external links weekly instead of in +# build_pr_documentation.yml. Only links that return 404 or 410 fail the run. + +on: + schedule: + - cron: "0 10 * * 1" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + check-external-links: + name: Check external documentation links + if: github.repository == 'huggingface/diffusers' + runs-on: ubuntu-latest + permissions: + contents: read + actions: read + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 + with: + python-version: '3.10' + + - name: Install doc-builder + run: | + pip install git+https://github.com/huggingface/doc-builder.git@main + + - name: Check external links + id: check + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -o pipefail + doc-builder check-links docs/source/en --check-external --format list | tee link-report.txt + + - name: Write job summary + if: always() && hashFiles('link-report.txt') != '' + run: | + { + echo '## External link check' + echo '```' + cat link-report.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Download the links posted by the last run + id: previous + if: always() && (steps.check.outcome == 'success' || steps.check.outcome == 'failure') + env: + GH_TOKEN: ${{ github.token }} + run: | + mkdir -p previous + run_id=$(gh api "repos/${{ github.repository }}/actions/artifacts?name=external-links-state&per_page=20" \ + --jq '[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == "main")][0].workflow_run.id // empty') + if [ -n "$run_id" ]; then + gh run download "$run_id" --repo "${{ github.repository }}" --name external-links-state --dir previous + else + echo "No earlier list found. Every broken link counts as new." + fi + + - name: Post newly broken links to Slack + id: post + if: always() && steps.previous.outcome == 'success' + env: + SLACK_WEBHOOK_URL: ${{ github.ref == 'refs/heads/main' && secrets.SLACK_WEBHOOK_URL_EXTERNAL_LINKS || '' }} + OUTCOME: ${{ steps.check.outcome }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + python utils/report_broken_links.py link-report.txt previous/reported-links.txt reported-links.txt + + - name: Save the posted links for the next run + if: always() && steps.post.outcome == 'success' && github.ref == 'refs/heads/main' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a + with: + name: external-links-state + path: reported-links.txt + retention-days: 90 + if-no-files-found: error diff --git a/utils/report_broken_links.py b/utils/report_broken_links.py new file mode 100644 index 000000000000..370ddba60317 --- /dev/null +++ b/utils/report_broken_links.py @@ -0,0 +1,125 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Tell Slack when a link in the docs to another website stops working. + +The script takes three file paths: + +1. The link check report from `doc-builder check-links --check-external --format list`. +2. The list of broken links from last week. This file is missing the first time. +3. Where to save this week's list of broken links for next week. + +The script only posts about a broken link once. It stays quiet while the same +links are still broken. It posts once when all the links work again. It also +posts once if the check fails without naming a broken link, so someone can look +at the run log. + +A link is matched by its file and URL, not its line number. Moving a broken link +to another line doesn't make it count as new. +""" + +import json +import os +import re +import sys +import urllib.request + + +REPORT_LINE = re.compile(r"^(\S+?):\d+ - (https?://\S+)") +MAX_LISTED = 20 +CHECK_FAILED = ("-", "check-failed") + + +def broken_links(report: str) -> set[tuple[str, str]]: + """Return the file and URL of each broken link in the report. + + Links listed under "Could not verify" are left out. The check couldn't tell + whether they work, so they don't fail it. + """ + broken_section = report.split("Could not verify", 1)[0] + return {(m.group(1), m.group(2)) for line in broken_section.splitlines() if (m := REPORT_LINE.match(line))} + + +def read_state(path: str) -> set[tuple[str, str]]: + if not os.path.exists(path): + return set() + with open(path, encoding="utf-8") as f: + return {tuple(line.split(" ", 1)) for line in f.read().splitlines() if " " in line} + + +def write_state(path: str, links: set[tuple[str, str]]) -> None: + with open(path, "w", encoding="utf-8") as f: + f.writelines(f"{file} {url}\n" for file, url in sorted(links)) + + +def escape(text: str) -> str: + """Replace &, < and > so Slack shows them as plain text instead of formatting.""" + return text.replace("&", "&").replace("<", "<").replace(">", ">") + + +def format_links(links: set[tuple[str, str]]) -> str: + lines = [f"• `{escape(file)}` {escape(url)}" for file, url in sorted(links)[:MAX_LISTED]] + if len(links) > MAX_LISTED: + lines.append(f"…and {len(links) - MAX_LISTED} more. The run summary lists all of them.") + return "\n".join(lines) + + +def post_to_slack(webhook_url: str, text: str) -> None: + request = urllib.request.Request( + webhook_url, data=json.dumps({"text": text}).encode(), headers={"Content-Type": "application/json"} + ) + with urllib.request.urlopen(request, timeout=30) as response: + response.read() + + +def main() -> None: + report_path, previous_path, new_path = sys.argv[1:4] + outcome = os.environ["OUTCOME"] + run_url = os.environ["RUN_URL"] + webhook_url = os.environ.get("SLACK_WEBHOOK_URL") + + with open(report_path, encoding="utf-8") as f: + broken = broken_links(f.read()) + previous = read_state(previous_path) + + if outcome == "failure" and not broken: + broken = previous | {CHECK_FAILED} + text = f"The docs link check failed without listing a broken external link. <{run_url}|Run log>" + if CHECK_FAILED in previous: + print("The check failed again without listing a broken external link. Posting nothing.") + write_state(new_path, broken) + return + elif outcome == "success" and previous: + text = f"Every external link in the docs passes again. <{run_url}|Run>" + elif new := broken - previous: + text = ( + f"{len(new)} external link(s) in the docs broke since the last check. <{run_url}|Run>\n{format_links(new)}" + ) + else: + print(f"No newly broken links ({len(broken)} still broken). Posting nothing.") + write_state(new_path, broken) + return + + if not webhook_url: + print(f"SLACK_WEBHOOK_URL is empty. Would have posted:\n{text}") + write_state(new_path, previous) + return + + post_to_slack(webhook_url, text) + print(f"Posted to Slack:\n{text}") + write_state(new_path, broken) + + +if __name__ == "__main__": + main() From 4ab2dcf8edfa8e17b604998a890fc264f9f6a2c1 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Fri, 4 Dec 2026 14:35:18 -0800 Subject: [PATCH 2/2] run check on PRs --- .github/workflows/check_external_links.yml | 75 +++++-------- utils/report_broken_links.py | 125 --------------------- 2 files changed, 26 insertions(+), 174 deletions(-) delete mode 100644 utils/report_broken_links.py diff --git a/.github/workflows/check_external_links.yml b/.github/workflows/check_external_links.yml index 800518fa1c96..924e37edbf54 100644 --- a/.github/workflows/check_external_links.yml +++ b/.github/workflows/check_external_links.yml @@ -1,28 +1,26 @@ name: Check external links -# This workflow checks external links weekly instead of in -# build_pr_documentation.yml. Only links that return 404 or 410 fail the run. +# Checks every external link in the docs on PRs that change the docs. A broken +# link shows up as a warning and never fails the PR, because an external site +# can break a link that the PR didn't touch. on: - schedule: - - cron: "0 10 * * 1" + pull_request: + paths: + - "docs/**" workflow_dispatch: concurrency: - group: ${{ github.workflow }} - cancel-in-progress: false + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true permissions: contents: read jobs: check-external-links: - name: Check external documentation links - if: github.repository == 'huggingface/diffusers' + name: External links (warnings only, not caused by this PR) runs-on: ubuntu-latest - permissions: - contents: read - actions: read steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 @@ -37,16 +35,24 @@ jobs: pip install git+https://github.com/huggingface/doc-builder.git@main - name: Check external links - id: check env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - set -o pipefail - doc-builder check-links docs/source/en --check-external --format list | tee link-report.txt + status=0 + doc-builder check-links docs/source/en --check-external --format list > link-report.txt || status=$? + cat link-report.txt + + # Turn each broken external link into a warning on its file and line. + broken=0 + while IFS= read -r line; do + file=${line%%:*} + rest=${line#*:} + message=${rest#* - } + message=${message//%/%25} + echo "::warning file=$file,line=${rest%% - *},title=Broken external link::$message" + broken=$((broken + 1)) + done < <(sed '/Could not verify/q' link-report.txt | grep -E '^[^ ]+:[0-9]+ - https?://' || true) - - name: Write job summary - if: always() && hashFiles('link-report.txt') != '' - run: | { echo '## External link check' echo '```' @@ -54,36 +60,7 @@ jobs: echo '```' } >> "$GITHUB_STEP_SUMMARY" - - name: Download the links posted by the last run - id: previous - if: always() && (steps.check.outcome == 'success' || steps.check.outcome == 'failure') - env: - GH_TOKEN: ${{ github.token }} - run: | - mkdir -p previous - run_id=$(gh api "repos/${{ github.repository }}/actions/artifacts?name=external-links-state&per_page=20" \ - --jq '[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == "main")][0].workflow_run.id // empty') - if [ -n "$run_id" ]; then - gh run download "$run_id" --repo "${{ github.repository }}" --name external-links-state --dir previous - else - echo "No earlier list found. Every broken link counts as new." + if [ "$status" -ne 0 ] && [ "$broken" -eq 0 ]; then + echo "::error::check-links failed without listing a broken external link. See the log above." + exit 1 fi - - - name: Post newly broken links to Slack - id: post - if: always() && steps.previous.outcome == 'success' - env: - SLACK_WEBHOOK_URL: ${{ github.ref == 'refs/heads/main' && secrets.SLACK_WEBHOOK_URL_EXTERNAL_LINKS || '' }} - OUTCOME: ${{ steps.check.outcome }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - python utils/report_broken_links.py link-report.txt previous/reported-links.txt reported-links.txt - - - name: Save the posted links for the next run - if: always() && steps.post.outcome == 'success' && github.ref == 'refs/heads/main' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a - with: - name: external-links-state - path: reported-links.txt - retention-days: 90 - if-no-files-found: error diff --git a/utils/report_broken_links.py b/utils/report_broken_links.py deleted file mode 100644 index 370ddba60317..000000000000 --- a/utils/report_broken_links.py +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright 2026 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -Tell Slack when a link in the docs to another website stops working. - -The script takes three file paths: - -1. The link check report from `doc-builder check-links --check-external --format list`. -2. The list of broken links from last week. This file is missing the first time. -3. Where to save this week's list of broken links for next week. - -The script only posts about a broken link once. It stays quiet while the same -links are still broken. It posts once when all the links work again. It also -posts once if the check fails without naming a broken link, so someone can look -at the run log. - -A link is matched by its file and URL, not its line number. Moving a broken link -to another line doesn't make it count as new. -""" - -import json -import os -import re -import sys -import urllib.request - - -REPORT_LINE = re.compile(r"^(\S+?):\d+ - (https?://\S+)") -MAX_LISTED = 20 -CHECK_FAILED = ("-", "check-failed") - - -def broken_links(report: str) -> set[tuple[str, str]]: - """Return the file and URL of each broken link in the report. - - Links listed under "Could not verify" are left out. The check couldn't tell - whether they work, so they don't fail it. - """ - broken_section = report.split("Could not verify", 1)[0] - return {(m.group(1), m.group(2)) for line in broken_section.splitlines() if (m := REPORT_LINE.match(line))} - - -def read_state(path: str) -> set[tuple[str, str]]: - if not os.path.exists(path): - return set() - with open(path, encoding="utf-8") as f: - return {tuple(line.split(" ", 1)) for line in f.read().splitlines() if " " in line} - - -def write_state(path: str, links: set[tuple[str, str]]) -> None: - with open(path, "w", encoding="utf-8") as f: - f.writelines(f"{file} {url}\n" for file, url in sorted(links)) - - -def escape(text: str) -> str: - """Replace &, < and > so Slack shows them as plain text instead of formatting.""" - return text.replace("&", "&").replace("<", "<").replace(">", ">") - - -def format_links(links: set[tuple[str, str]]) -> str: - lines = [f"• `{escape(file)}` {escape(url)}" for file, url in sorted(links)[:MAX_LISTED]] - if len(links) > MAX_LISTED: - lines.append(f"…and {len(links) - MAX_LISTED} more. The run summary lists all of them.") - return "\n".join(lines) - - -def post_to_slack(webhook_url: str, text: str) -> None: - request = urllib.request.Request( - webhook_url, data=json.dumps({"text": text}).encode(), headers={"Content-Type": "application/json"} - ) - with urllib.request.urlopen(request, timeout=30) as response: - response.read() - - -def main() -> None: - report_path, previous_path, new_path = sys.argv[1:4] - outcome = os.environ["OUTCOME"] - run_url = os.environ["RUN_URL"] - webhook_url = os.environ.get("SLACK_WEBHOOK_URL") - - with open(report_path, encoding="utf-8") as f: - broken = broken_links(f.read()) - previous = read_state(previous_path) - - if outcome == "failure" and not broken: - broken = previous | {CHECK_FAILED} - text = f"The docs link check failed without listing a broken external link. <{run_url}|Run log>" - if CHECK_FAILED in previous: - print("The check failed again without listing a broken external link. Posting nothing.") - write_state(new_path, broken) - return - elif outcome == "success" and previous: - text = f"Every external link in the docs passes again. <{run_url}|Run>" - elif new := broken - previous: - text = ( - f"{len(new)} external link(s) in the docs broke since the last check. <{run_url}|Run>\n{format_links(new)}" - ) - else: - print(f"No newly broken links ({len(broken)} still broken). Posting nothing.") - write_state(new_path, broken) - return - - if not webhook_url: - print(f"SLACK_WEBHOOK_URL is empty. Would have posted:\n{text}") - write_state(new_path, previous) - return - - post_to_slack(webhook_url, text) - print(f"Posted to Slack:\n{text}") - write_state(new_path, broken) - - -if __name__ == "__main__": - main()