]> jfr.im git - yt-dlp.git/blob - devscripts/make_readme.py
[devscripts/update-formulae] Do not change dependency section
[yt-dlp.git] / devscripts / make_readme.py
1 #!/usr/bin/env python3
2
3 """
4 yt-dlp --help | make_readme.py
5 This must be run in a console of correct width
6 """
7
8
9 import functools
10 import re
11 import sys
12
13 README_FILE = 'README.md'
14
15 OPTIONS_START = 'General Options:'
16 OPTIONS_END = 'CONFIGURATION'
17 EPILOG_START = 'See full documentation'
18 ALLOWED_OVERSHOOT = 2
19
20 DISABLE_PATCH = object()
21
22
23 def take_section(text, start=None, end=None, *, shift=0):
24 return text[
25 text.index(start) + shift if start else None:
26 text.index(end) + shift if end else None
27 ]
28
29
30 def apply_patch(text, patch):
31 return text if patch[0] is DISABLE_PATCH else re.sub(*patch, text)
32
33
34 options = take_section(sys.stdin.read(), f'\n {OPTIONS_START}', f'\n{EPILOG_START}', shift=1)
35
36 max_width = max(map(len, options.split('\n')))
37 switch_col_width = len(re.search(r'(?m)^\s{5,}', options).group())
38 delim = f'\n{" " * switch_col_width}'
39
40 PATCHES = (
41 ( # Headings
42 r'(?m)^ (\w.+\n)( (?=\w))?',
43 r'## \1'
44 ),
45 ( # Do not split URLs
46 rf'({delim[:-1]})? (?P<label>\[\S+\] )?(?P<url>https?({delim})?:({delim})?/({delim})?/(({delim})?\S+)+)\s',
47 lambda mobj: ''.join((delim, mobj.group('label') or '', re.sub(r'\s+', '', mobj.group('url')), '\n'))
48 ),
49 ( # Do not split "words"
50 rf'(?m)({delim}\S+)+$',
51 lambda mobj: ''.join((delim, mobj.group(0).replace(delim, '')))
52 ),
53 ( # Allow overshooting last line
54 rf'(?m)^(?P<prev>.+)${delim}(?P<current>.+)$(?!{delim})',
55 lambda mobj: (mobj.group().replace(delim, ' ')
56 if len(mobj.group()) - len(delim) + 1 <= max_width + ALLOWED_OVERSHOOT
57 else mobj.group())
58 ),
59 ( # Avoid newline when a space is available b/w switch and description
60 DISABLE_PATCH, # This creates issues with prepare_manpage
61 r'(?m)^(\s{4}-.{%d})(%s)' % (switch_col_width - 6, delim),
62 r'\1 '
63 ),
64 )
65
66 with open(README_FILE, encoding='utf-8') as f:
67 readme = f.read()
68
69 with open(README_FILE, 'w', encoding='utf-8') as f:
70 f.write(''.join((
71 take_section(readme, end=f'## {OPTIONS_START}'),
72 functools.reduce(apply_patch, PATCHES, options),
73 take_section(readme, f'# {OPTIONS_END}'),
74 )))