|
| 1 | +# Modified from: |
| 2 | +# https://github.com/allenai/allennlp/blob/main/scripts/check_links.py |
| 3 | + |
| 4 | +import argparse |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import pathlib |
| 8 | +import re |
| 9 | +import sys |
| 10 | +from multiprocessing.dummy import Pool |
| 11 | +from typing import NamedTuple, Optional, Tuple |
| 12 | + |
| 13 | +import requests |
| 14 | +from mmcv.utils import get_logger |
| 15 | + |
| 16 | + |
| 17 | +def parse_args(): |
| 18 | + parser = argparse.ArgumentParser( |
| 19 | + description='Goes through all the inline-links ' |
| 20 | + 'in markdown files and reports the breakages') |
| 21 | + parser.add_argument( |
| 22 | + '--num-threads', |
| 23 | + type=int, |
| 24 | + default=100, |
| 25 | + help='Number of processes to confirm the link') |
| 26 | + parser.add_argument('--https-proxy', type=str, help='https proxy') |
| 27 | + parser.add_argument( |
| 28 | + '--out', |
| 29 | + type=str, |
| 30 | + default='link_reports.txt', |
| 31 | + help='output path of reports') |
| 32 | + args = parser.parse_args() |
| 33 | + return args |
| 34 | + |
| 35 | + |
| 36 | +OK_STATUS_CODES = ( |
| 37 | + 200, |
| 38 | + 401, # the resource exists but may require some sort of login. |
| 39 | + 403, # ^ same |
| 40 | + 405, # HEAD method not allowed. |
| 41 | + # the resource exists, but our default 'Accept-' header may not |
| 42 | + # match what the server can provide. |
| 43 | + 406, |
| 44 | +) |
| 45 | + |
| 46 | + |
| 47 | +class MatchTuple(NamedTuple): |
| 48 | + source: str |
| 49 | + name: str |
| 50 | + link: str |
| 51 | + |
| 52 | + |
| 53 | +def check_link( |
| 54 | + match_tuple: MatchTuple, |
| 55 | + http_session: requests.Session, |
| 56 | + logger: logging = None) -> Tuple[MatchTuple, bool, Optional[str]]: |
| 57 | + reason: Optional[str] = None |
| 58 | + if match_tuple.link.startswith('http'): |
| 59 | + result_ok, reason = check_url(match_tuple, http_session) |
| 60 | + else: |
| 61 | + result_ok = check_path(match_tuple) |
| 62 | + if logger is None: |
| 63 | + print(f" {'✓' if result_ok else '✗'} {match_tuple.link}") |
| 64 | + else: |
| 65 | + logger.info(f" {'✓' if result_ok else '✗'} {match_tuple.link}") |
| 66 | + return match_tuple, result_ok, reason |
| 67 | + |
| 68 | + |
| 69 | +def check_url(match_tuple: MatchTuple, |
| 70 | + http_session: requests.Session) -> Tuple[bool, str]: |
| 71 | + """Check if a URL is reachable.""" |
| 72 | + try: |
| 73 | + result = http_session.head( |
| 74 | + match_tuple.link, timeout=5, allow_redirects=True) |
| 75 | + return ( |
| 76 | + result.ok or result.status_code in OK_STATUS_CODES, |
| 77 | + f'status code = {result.status_code}', |
| 78 | + ) |
| 79 | + except (requests.ConnectionError, requests.Timeout): |
| 80 | + return False, 'connection error' |
| 81 | + |
| 82 | + |
| 83 | +def check_path(match_tuple: MatchTuple) -> bool: |
| 84 | + """Check if a file in this repository exists.""" |
| 85 | + relative_path = match_tuple.link.split('#')[0] |
| 86 | + full_path = os.path.join( |
| 87 | + os.path.dirname(str(match_tuple.source)), relative_path) |
| 88 | + return os.path.exists(full_path) |
| 89 | + |
| 90 | + |
| 91 | +def main(): |
| 92 | + args = parse_args() |
| 93 | + |
| 94 | + # setup logger |
| 95 | + logger = get_logger(name='mmdet', log_file=args.out) |
| 96 | + |
| 97 | + # setup https_proxy |
| 98 | + if args.https_proxy: |
| 99 | + os.environ['https_proxy'] = args.https_proxy |
| 100 | + |
| 101 | + # setup http_session |
| 102 | + http_session = requests.Session() |
| 103 | + for resource_prefix in ('http://', 'https://'): |
| 104 | + http_session.mount( |
| 105 | + resource_prefix, |
| 106 | + requests.adapters.HTTPAdapter( |
| 107 | + max_retries=5, |
| 108 | + pool_connections=20, |
| 109 | + pool_maxsize=args.num_threads), |
| 110 | + ) |
| 111 | + |
| 112 | + logger.info('Finding all markdown files in the current directory...') |
| 113 | + |
| 114 | + project_root = (pathlib.Path(__file__).parent / '..').resolve() |
| 115 | + markdown_files = project_root.glob('**/*.md') |
| 116 | + |
| 117 | + all_matches = set() |
| 118 | + url_regex = re.compile(r'\[([^!][^\]]+)\]\(([^)(]+)\)') |
| 119 | + for markdown_file in markdown_files: |
| 120 | + with open(markdown_file) as handle: |
| 121 | + for line in handle.readlines(): |
| 122 | + matches = url_regex.findall(line) |
| 123 | + for name, link in matches: |
| 124 | + if 'localhost' not in link: |
| 125 | + all_matches.add( |
| 126 | + MatchTuple( |
| 127 | + source=str(markdown_file), |
| 128 | + name=name, |
| 129 | + link=link)) |
| 130 | + |
| 131 | + logger.info(f' {len(all_matches)} markdown files found') |
| 132 | + logger.info('Checking to make sure we can retrieve each link...') |
| 133 | + |
| 134 | + with Pool(processes=args.num_threads) as pool: |
| 135 | + results = pool.starmap(check_link, [(match, http_session, logger) |
| 136 | + for match in list(all_matches)]) |
| 137 | + |
| 138 | + # collect unreachable results |
| 139 | + unreachable_results = [(match_tuple, reason) |
| 140 | + for match_tuple, success, reason in results |
| 141 | + if not success] |
| 142 | + |
| 143 | + if unreachable_results: |
| 144 | + logger.info('================================================') |
| 145 | + logger.info(f'Unreachable links ({len(unreachable_results)}):') |
| 146 | + for match_tuple, reason in unreachable_results: |
| 147 | + logger.info(' > Source: ' + match_tuple.source) |
| 148 | + logger.info(' Name: ' + match_tuple.name) |
| 149 | + logger.info(' Link: ' + match_tuple.link) |
| 150 | + if reason is not None: |
| 151 | + logger.info(' Reason: ' + reason) |
| 152 | + sys.exit(1) |
| 153 | + logger.info('No Unreachable link found.') |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == '__main__': |
| 157 | + main() |
0 commit comments