import re
import sys
import pathlib
URL = re.compile(r"(?<![<(])(https?://[^\s<>\"'`)]+)")
def wrap_file(path: pathlib.Path) -> int:
text = path.read_text(encoding='utf-8')
lines = text.splitlines(keepends=True)
changed = 0
for i, line in enumerate(lines):
s = line.lstrip()
if s.startswith('//!') or s.startswith('///'):
new_line, n = URL.subn(r'<\1>', line)
if n:
lines[i] = new_line
changed += n
if changed:
path.write_text(''.join(lines), encoding='utf-8')
return changed
def main(root: str = 'crates') -> int:
total = 0
files = 0
for f in pathlib.Path(root).rglob('*.rs'):
n = wrap_file(f)
if n:
files += 1
total += n
print(f'wrapped {total} bare URLs across {files} files')
return 0
if __name__ == '__main__':
root = sys.argv[1] if len(sys.argv) > 1 else 'crates'
sys.exit(main(root))