link-checker.yml 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. name: Link Checker
  2. on:
  3. push:
  4. branches: [ edge ]
  5. pull_request:
  6. branches: [ edge ]
  7. schedule:
  8. - cron: '30 12 1 * *'
  9. workflow_dispatch:
  10. permissions:
  11. contents: read
  12. concurrency:
  13. group: link-checker-${{ github.ref }}
  14. cancel-in-progress: false
  15. jobs:
  16. linkChecker:
  17. name: linkChecker
  18. runs-on: ubuntu-26.04
  19. steps:
  20. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
  21. with:
  22. persist-credentials: false
  23. fetch-depth: 0
  24. # Check local links across the repository first to catch broken links in
  25. # files that are not part of the PR's changed files.
  26. - name: Check local links (offline run)
  27. if: github.event_name == 'pull_request'
  28. uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
  29. with:
  30. fail: true
  31. failIfEmpty: false
  32. args: >
  33. --offline
  34. .
  35. - name: Get changed files
  36. if: github.event_name == 'pull_request'
  37. env:
  38. BASE_SHA: ${{ github.event.pull_request.base.sha }}
  39. HEAD_SHA: ${{ github.event.pull_request.head.sha }}
  40. run: |
  41. git -c core.quotePath=false diff --name-only --diff-filter=ACMR \
  42. "$BASE_SHA" \
  43. "$HEAD_SHA" \
  44. > changed-files.txt
  45. # Lychee does not apply `extensions` from the config to files passed via `--files-from`.
  46. # Filter the changed files so only allowed file types are checked.
  47. python3 <<'PY'
  48. import pathlib
  49. import tomllib
  50. with open("lychee.toml", "rb") as fp:
  51. config = tomllib.load(fp)
  52. extensions = {e.lstrip(".").lower() for e in config["extensions"]}
  53. files = pathlib.Path("changed-files.txt").read_text().splitlines()
  54. files = [
  55. f for f in files
  56. if (
  57. pathlib.PurePath(f).suffix.lstrip(".").lower() in extensions
  58. or (
  59. not pathlib.PurePath(f).suffix
  60. and pathlib.PurePath(f).name.startswith(".")
  61. and pathlib.PurePath(f).name.lstrip(".").lower() in extensions
  62. )
  63. or (
  64. not pathlib.PurePath(f).suffix
  65. and not pathlib.PurePath(f).name.startswith(".")
  66. and config.get("default_extension") in extensions
  67. )
  68. )
  69. ]
  70. pathlib.Path("changed-files.txt").write_text(
  71. "\n".join(files) + ("\n" if files else "")
  72. )
  73. PY
  74. echo "Changed files:"
  75. cat changed-files.txt
  76. # Lychee doesn't have an option for checking only the changed links, so neutralize all the other URLs of the changed files (`http` -> `hxxp`).
  77. # Nothing else is modified, so that lychee parses the files as usual and reports the correct filenames and line numbers.
  78. # Local links are left alone, as they are already checked by the offline run.
  79. - name: Keep only changed links
  80. if: github.event_name == 'pull_request'
  81. env:
  82. BASE_SHA: ${{ github.event.pull_request.base.sha }}
  83. run: |
  84. git diff --unified=0 --diff-filter=ACMR "$BASE_SHA" HEAD > changes.diff
  85. git diff --name-only -z --diff-filter=ACMR "$BASE_SHA" HEAD > changes.names
  86. python3 <<'PY'
  87. import itertools
  88. import pathlib
  89. import re
  90. url = re.compile(r"""(?ix)
  91. https?://
  92. (?:
  93. (?![)\]}|][^ \t\r\n\f\v"'`<>]*?https?://) # Stop before a closing bracket or `|` followed by another URL
  94. [^ \t\r\n\f\v"'`<>] # Stop at ASCII whitespace (like lychee, so not `\s`), quote, backtick or angle bracket
  95. | '(?=\w) # But an apostrophe followed by a letter is part of the URL
  96. )+
  97. """)
  98. # File names in the same order as the `diff --git` headers, which are not reliable (quoting, tabs)
  99. names = iter(pathlib.Path("changes.names").read_text().split("\0"))
  100. # Hunks as (file, first added line number, removed lines, added lines).
  101. # Hunk headers look like `@@ -12,3 +14,2 @@`, meaning 2 lines from line 14 (the count is omitted if 1).
  102. hunks = []
  103. in_hunk = False
  104. for line in pathlib.Path("changes.diff").read_text(errors="replace").split("\n"):
  105. if line.startswith("diff --git"):
  106. in_hunk = False
  107. file = next(names)
  108. elif line.startswith("@@"):
  109. in_hunk = True
  110. first = int(line.split()[2].removeprefix("+").partition(",")[0])
  111. hunks.append((file, first, [], []))
  112. elif in_hunk and line.startswith("-"):
  113. hunks[-1][2].append(line[1:])
  114. elif in_hunk and line.startswith("+"):
  115. hunks[-1][3].append(line[1:])
  116. # Changed URLs of each file as (line number, URL): those on added lines that are not on a removed line of the same hunk
  117. changed_urls = {}
  118. shown = lambda urls: [(number, u.rstrip(").,>")) for number, u in urls]
  119. print("Changed URLs (old -> new):")
  120. for file, first, removed, added in hunks:
  121. old_urls = url.findall("\n".join(removed))
  122. new_urls = [(number, u) for number, line in enumerate(added, start=first) for u in url.findall(line)]
  123. added_urls = [(number, u) for number, u in new_urls if u not in old_urls]
  124. removed_urls = [(first, u) for u in old_urls if u not in [u for _, u in new_urls]]
  125. changed_urls.setdefault(file, set()).update(added_urls)
  126. # Pair them in order, with the line of the new URL (or the first line of the hunk when there is none)
  127. for (_, old), (number, new) in itertools.zip_longest(shown(removed_urls), shown(added_urls), fillvalue=(first, "(none)")):
  128. print(f"{file}:{number}: {old} -> {new}")
  129. for number, changed_url in added_urls:
  130. if url.search(re.split("[?#]", changed_url, maxsplit=1)[0][1:]): # Another URL, but not in a query or fragment
  131. print(f"Warning: {file}:{number}: several URLs may be glued together, so unchanged ones may be checked too: {changed_url}")
  132. # Neutralize the other URLs (`http` -> `hxxp`, also inside the URL in case several are glued together)
  133. for file in pathlib.Path("changed-files.txt").read_text().splitlines():
  134. path = pathlib.Path(file)
  135. kept_urls = changed_urls.get(file, set())
  136. lines = path.read_text(errors="surrogateescape").split("\n")
  137. path.write_text("\n".join(
  138. url.sub(lambda match: match[0] if (number, match[0]) in kept_urls else re.sub("(?i)http", "hxxp", match[0]), line)
  139. for number, line in enumerate(lines, start=1)
  140. ), errors="surrogateescape")
  141. PY
  142. - name: Restore lychee cache
  143. id: restore-cache
  144. uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
  145. with:
  146. path: .lycheecache
  147. key: cache-lychee-${{ github.sha }}
  148. restore-keys: cache-lychee-
  149. - name: Run lychee
  150. uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
  151. with:
  152. # PAT with read-only permissions used to avoid GitHub rate limits (allows 5,000 requests per hour)
  153. # Won't be available to forks in pull requests due to restrictions, so falls back to default
  154. # GITHUB_TOKEN with 1,000 requests per hour instead.
  155. token: ${{ secrets.LYCHEE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
  156. fail: ${{ github.event_name != 'push' }} # Never fail the workflow on push events to reduce noise
  157. failIfEmpty: false # Avoid failing in PRs with no links in changed files (`true` is the default)
  158. # Config is loaded from lychee.toml
  159. args: >
  160. ${{ github.event_name == 'pull_request' && '--files-from changed-files.txt' || '.' }}
  161. - name: Save lychee cache
  162. uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
  163. if: always()
  164. with:
  165. path: .lycheecache
  166. key: ${{ steps.restore-cache.outputs.cache-primary-key }}