Debian Codegraph @

tools/urls-check

raw symbols SCIP
1 #!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/../test/common/pywrap", sys.argv)
2
3 #
4 # Copyright (C) 2020 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 import argparse
9 import fnmatch
10 import os
11 import subprocess
12 import sys
13 import time
14 import urllib
15 from urllib.request import Request, urlopen
16
17 from lib.github import GitHub
18
19 BASE_DIR = os.path.realpath(f'{__file__}/../..')
20
21 DAYS = 7
22 TASK_NAME = "Validate all URLs"
23
24 github = GitHub()
25
26 USER_AGENT = "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0"
27
28 IGNORE = [
29 "https://www.gnome.org", # keeps causing 403 from GitHub; DNS or user-agent ban?
30 "*example.com*", # some tests use demo urls
31 ]
32
33 KNOWN_REDIRECTS = [
34 # fnmatch-like
35 "https://access.redhat.com/security/updates/classification/#",
36 "https://firefox.com/",
37 "https://www.microsoft.com/",
38 "https://github.com/patternfly/*",
39 # SVG/XML processing in *.jsx
40 "http://www.w3.org/2000/svg",
41 "http://www.w3.org/XML/1998/namespace",
42 ]
43
44
45 def main():
46 parser = argparse.ArgumentParser(description=TASK_NAME)
47 parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
48 parser.add_argument('-n', '--dry-run', action="store_true",
49 help="Only show urls")
50 opts = parser.parse_args()
51
52 if opts.dry_run:
53 (success, err) = check_urls(opts.verbose)
54 print(err)
55 print(success)
56 sys.exit(1 if err else 0)
57
58 since = time.time() - (DAYS * 86400)
59
60 # When there is an open issue, don't do anything
61 issues = github.issues(state="open")
62 issues = [i for i in issues if i["title"] == TASK_NAME]
63 if issues:
64 return
65
66 issues = github.issues(state="closed", since=since)
67 issues = [i for i in issues if i["title"] == TASK_NAME]
68
69 # If related issue was not modified in last n-DAYS, then do your thing
70 if not issues:
71 (success, err) = check_urls(opts.verbose)
72 if err:
73 # Create a new issue
74 data = {
75 "title": TASK_NAME,
76 "body": err,
77 "labels": ["bot"]
78 }
79 github.post("issues", data)
80 else:
81 # Try to comment on the last issue (look in the last 4*DAYS)
82 # If there is not issue to be found, then just open a new one and close it
83 success = success or "Task hasn't produced any output"
84 since = time.time() - (DAYS * 4 * 86400)
85 issues = github.issues(state="closed", since=since)
86 issues = [i for i in issues if i["title"] == TASK_NAME]
87 if issues:
88 github.comment(issues[0]["number"], success)
89 else:
90 data = {
91 "title": TASK_NAME,
92 "body": success,
93 "labels": ["bot"]
94 }
95 new_issue = github.post("issues", data)
96 github.patch(f"issues/{new_issue['number']}", {"state": "closed"})
97
98
99 def check_urls(verbose):
100 command = r'git grep -IEho "(https?)://[-a-zA-Z0-9@:%_\+.~#?&=/]+" -- pkg ":!*.svg" | sort -u'
101 urls = subprocess.check_output(command, shell=True, universal_newlines=True, cwd=BASE_DIR).split("\n")
102 redirects = []
103 failed = []
104 for url in urls:
105 if not url:
106 continue
107
108 if any(fnmatch.fnmatch(url, pattern) for pattern in IGNORE):
109 if verbose:
110 print(f"Ignoring: {url}")
111 continue
112
113 if verbose:
114 print(f"Checking: {url}")
115
116 try:
117 # Specify agent as some websites otherwise block requests
118 req = Request(url=url, headers={"User-Agent": USER_AGENT})
119 resp = urlopen(req)
120 if resp.geturl() != url and not any(fnmatch.fnmatch(url, pattern) for pattern in KNOWN_REDIRECTS):
121 redirects.append(url)
122 if resp.getcode() >= 400:
123 failed.append(f"{url} : {resp.getcode()} {resp.reason}")
124 except urllib.error.URLError as e:
125 failed.append(f"{url} : {e.reason}")
126
127 err = ""
128 success = ""
129 if failed:
130 err = f"Checked {len(urls)} URLs out of which {len(failed)} is/are invalid:\n"
131 err += ''.join(f' {url}\n' for url in failed)
132 else:
133 success = f"Checked {len(urls)} URLs and all are valid."
134 if redirects:
135 success += "\nFollowing URLs are redirected:\n"
136 success += ''.join(f' {url}\n' for url in redirects)
137 return success, err
138
139
140 if __name__ == '__main__':
141 sys.exit(main())