make_readme.py 2.2 KB

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