Debian Codegraph @

tools/divergent_links.py

raw
1 """This script help checking inconsistent links.
2
3 That is to say, links that have the same title but go to different places.
4 This is useful for screen-reader and accessibility devices, where the user may
5 say "Go to X", but if there are 2 links named "X" this creates ambiguity.
6
7
8 Example (links that have the same name, but different URL):
9
10 We have a JavaScript <a href="javascript.html">API</a> and
11 a Python <a href="python.html">API</a>.
12
13 How to fix (give the links different names):
14
15 We have a <a href="javascript.html">JavaScript API</a> and
16 a <a href="python.html">Python API</a>.
17 """
18
19 import os
20 import sys
21
22 from collections import defaultdict
23 from urllib.parse import urljoin
24
25 from bs4 import BeautifulSoup
26 from rich import print
27
28
29 # when looking at inconsistent links across pages,
30 # a number of text is recurrent and appear on many pages.
31 # So we'll ignore these.
32
33 ignores = [
34 "#",
35 "next",
36 "previous",
37 "[source]",
38 "edit on github",
39 "[docs]",
40 "read more ...",
41 "show source",
42 "module",
43 ]
44
45
46 def find_html_files(folder_path):
47 """Find all html files in given folder."""
48 html_files = []
49 for root, dirs, files in os.walk(folder_path):
50 for file in files:
51 if file.endswith(".html"):
52 html_files.append(os.path.join(root, file))
53 return html_files
54
55
56 class Checker:
57 """Link checker."""
58
59 links: dict[str, list]
60
61 def __init__(self):
62 self.links = defaultdict(list)
63
64 def scan(self, html_content, file_path):
65 """Scan given file for html links."""
66 # Parse the HTML content using BeautifulSoup
67 soup = BeautifulSoup(html_content, "html.parser")
68
69 # Dictionary to store URLs and their corresponding titles
70
71 # Extract all anchor tags
72 for a_tag in soup.find_all("a", href=True):
73 url = a_tag["href"]
74
75 # These are usually link into the same page ("see below", or even
76 # header anchors we thus exclude those.
77 if url.startswith("#"):
78 continue
79 content = a_tag.text.strip().lower()
80 if content in ignores:
81 continue
82 # Some links are "$Title\nNext", or "$Title\nprev", so we only
83 # want to look at what is before the `\n`
84 if content.split("\n")[0] in ignores:
85 continue
86
87 fullurl = urljoin(file_path, url)
88 self.links[content].append((fullurl, file_path))
89
90 def duplicates(self):
91 """Print potential duplicates."""
92 for content, url_pages in self.links.items():
93 uniq_url = {u for u, _ in url_pages}
94 if len(uniq_url) >= 2:
95 print(
96 f"The link text [red]{content!r}[/red] appears {len(url_pages)} "
97 f"times and links to {len(uniq_url)} different URLs, "
98 f"on the following pages:"
99 )
100 dct = defaultdict(list)
101 for u, p in url_pages:
102 dct[u].append(p)
103 for u, ps in dct.items():
104 print(f" [blue]{u}[/blue] in")
105 for p in set(ps):
106 print(f" [green]{p}[/green]")
107
108
109 if len(sys.argv) == 3 and sys.argv[2] == "--all":
110 c = Checker()
111
112 for file in find_html_files(sys.argv[1]):
113 with open(file) as f:
114 data = f.read()
115 c.scan(data, file)
116
117 c.duplicates()
118 elif len(sys.argv) == 2:
119 for file in find_html_files(sys.argv[1]):
120 with open(file) as f:
121 data = f.read()
122 c = Checker()
123 c.scan(data, file)
124 c.duplicates()
125 else:
126 print(
127 """
128 Check page-wise link consistency
129 (links with the same name on the same page should go to the same URL)
130
131 python tools/divergent_links.py docs/_build/html/
132
133 Check site-wide link consistency
134 (links with the same name across all pages should go the same URL)
135
136 python tools/divergent_links.py docs/_build/html/ --all
137
138 """
139 )
140 sys.exit(1)