2 from __future__
import unicode_literals
9 ROOT_DIR
= os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
)))
10 README_FILE
= os
.path
.join(ROOT_DIR
, 'README.md')
12 PREFIX
= r
'''%yt-dlp(1)
16 yt\-dlp \- A youtube-dl fork with additional features and patches
20 **yt-dlp** \[OPTIONS\] URL [URL...]
28 parser
= optparse
.OptionParser(usage
='%prog OUTFILE.md')
29 options
, args
= parser
.parse_args()
31 parser
.error('Expected an output filename')
35 with io
.open(README_FILE
, encoding
='utf-8') as f
:
38 readme
= filter_excluded_sections(readme
)
39 readme
= move_sections(readme
)
40 readme
= filter_options(readme
)
42 with io
.open(outfile
, 'w', encoding
='utf-8') as outf
:
43 outf
.write(PREFIX
+ readme
)
46 def filter_excluded_sections(readme
):
47 EXCLUDED_SECTION_BEGIN_STRING
= re
.escape('<!-- MANPAGE: BEGIN EXCLUDED SECTION -->')
48 EXCLUDED_SECTION_END_STRING
= re
.escape('<!-- MANPAGE: END EXCLUDED SECTION -->')
50 rf
'(?s){EXCLUDED_SECTION_BEGIN_STRING}.+?{EXCLUDED_SECTION_END_STRING}\n',
54 def move_sections(readme
):
55 MOVE_TAG_TEMPLATE
= '<!-- MANPAGE: MOVE "%s" SECTION HERE -->'
56 sections
= re
.findall(rf
'(?m)^{re.escape(MOVE_TAG_TEMPLATE) % "(.+)"}$', readme
)
58 for section_name
in sections
:
59 move_tag
= MOVE_TAG_TEMPLATE
% section_name
60 if readme
.count(move_tag
) > 1:
61 raise Exception(f
'There is more than one occurrence of "{move_tag}". This is unexpected')
63 sections
= re
.findall(rf
'(?sm)(^# {re.escape(section_name)}.+?)(?=^# )', readme
)
65 raise Exception(f
'The section {section_name} does not exist')
66 elif len(sections
) > 1:
67 raise Exception(f
'There are multiple occurrences of section {section_name}, this is unhandled')
69 readme
= readme
.replace(sections
[0], '', 1).replace(move_tag
, sections
[0], 1)
73 def filter_options(readme
):
74 section
= re
.search(r
'(?sm)^# USAGE AND OPTIONS\n.+?(?=^# )', readme
).group(0)
75 options
= '# OPTIONS\n'
76 for line
in section
.split('\n')[1:]:
77 if line
.lstrip().startswith('-'):
78 split
= re
.split(r
'\s{2,}', line
.lstrip())
79 # Description string may start with `-` as well. If there is
80 # only one piece then it's a description bit not an option.
82 option
, description
= split
83 split_option
= option
.split(' ')
85 if not split_option
[-1].startswith('-'): # metavar
86 option
= ' '.join(split_option
[:-1] + [f
'*{split_option[-1]}*'])
88 # Pandoc's definition_lists. See http://pandoc.org/README.html
89 options
+= f
'\n{option}\n: {description}\n'
91 options
+= line
.lstrip() + '\n'
93 return readme
.replace(section
, options
, 1)
96 if __name__
== '__main__':