3 # Allow direct execution
7 sys
.path
.insert(0, os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
))))
13 from devscripts
.utils
import (
20 ROOT_DIR
= os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
)))
21 README_FILE
= os
.path
.join(ROOT_DIR
, 'README.md')
23 PREFIX
= r
'''%yt-dlp(1)
27 yt\-dlp \- A feature\-rich command\-line audio/video downloader
31 **yt-dlp** \[OPTIONS\] URL [URL...]
38 def filter_excluded_sections(readme
):
39 EXCLUDED_SECTION_BEGIN_STRING
= re
.escape('<!-- MANPAGE: BEGIN EXCLUDED SECTION -->')
40 EXCLUDED_SECTION_END_STRING
= re
.escape('<!-- MANPAGE: END EXCLUDED SECTION -->')
42 rf
'(?s){EXCLUDED_SECTION_BEGIN_STRING}.+?{EXCLUDED_SECTION_END_STRING}\n',
46 def _convert_code_blocks(readme
):
47 current_code_block
= None
49 for line
in readme
.splitlines(True):
50 if current_code_block
:
51 if line
== current_code_block
:
52 current_code_block
= None
56 elif line
.startswith('```'):
57 current_code_block
= line
.count('`') * '`' + '\n'
63 def convert_code_blocks(readme
):
64 return ''.join(_convert_code_blocks(readme
))
67 def move_sections(readme
):
68 MOVE_TAG_TEMPLATE
= '<!-- MANPAGE: MOVE "%s" SECTION HERE -->'
69 sections
= re
.findall(r
'(?m)^%s$' % (
70 re
.escape(MOVE_TAG_TEMPLATE
).replace(r
'\%', '%') % '(.+)'), readme
)
72 for section_name
in sections
:
73 move_tag
= MOVE_TAG_TEMPLATE
% section_name
74 if readme
.count(move_tag
) > 1:
75 raise Exception(f
'There is more than one occurrence of "{move_tag}". This is unexpected')
77 sections
= re
.findall(rf
'(?sm)(^# {re.escape(section_name)}.+?)(?=^# )', readme
)
79 raise Exception(f
'The section {section_name} does not exist')
80 elif len(sections
) > 1:
81 raise Exception(f
'There are multiple occurrences of section {section_name}, this is unhandled')
83 readme
= readme
.replace(sections
[0], '', 1).replace(move_tag
, sections
[0], 1)
87 def filter_options(readme
):
88 section
= re
.search(r
'(?sm)^# USAGE AND OPTIONS\n.+?(?=^# )', readme
).group(0)
89 section_new
= section
.replace('*', R
'\*')
91 options
= '# OPTIONS\n'
92 for line
in section_new
.split('\n')[1:]:
93 mobj
= re
.fullmatch(r
'''(?x)
94 \s{4}(?P<opt>-(?:,\s|[^\s])+)
95 (?:\s(?P<meta>(?:[^\s]|\s(?!\s))+))?
99 options
+= f
'{line.lstrip()}\n'
101 option
, metavar
, description
= mobj
.group('opt', 'meta', 'desc')
103 # Pandoc's definition_lists. See http://pandoc.org/README.html
104 option
= f
'{option} *{metavar}*' if metavar
else option
105 description
= f
'{description}\n' if description
else ''
106 options
+= f
'\n{option}\n: {description}'
109 return readme
.replace(section
, options
, 1)
112 TRANSFORM
= compose_functions(filter_excluded_sections
, convert_code_blocks
, move_sections
, filter_options
)
116 write_file(get_filename_args(), PREFIX
+ TRANSFORM(read_file(README_FILE
)))
119 if __name__
== '__main__':