prepare_manpage.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from __future__ import unicode_literals
  2. import optparse
  3. import os.path
  4. import re
  5. from utils import read_file, write_file
  6. ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7. README_FILE = os.path.join(ROOT_DIR, 'README.md')
  8. PREFIX = r'''%YOUTUBE-DL(1)
  9. # NAME
  10. youtube\-dl \- download videos from youtube.com or other video platforms
  11. # SYNOPSIS
  12. **youtube-dl** \[OPTIONS\] URL [URL...]
  13. '''
  14. def main():
  15. parser = optparse.OptionParser(usage='%prog OUTFILE.md')
  16. options, args = parser.parse_args()
  17. if len(args) != 1:
  18. parser.error('Expected an output filename')
  19. outfile, = args
  20. readme = read_file(README_FILE)
  21. readme = re.sub(r'(?s)^.*?(?=# DESCRIPTION)', '', readme)
  22. readme = re.sub(r'\s+youtube-dl \[OPTIONS\] URL \[URL\.\.\.\]', '', readme)
  23. readme = PREFIX + readme
  24. readme = filter_options(readme)
  25. write_file(outfile, readme)
  26. def filter_options(readme):
  27. ret = ''
  28. in_options = False
  29. for line in readme.split('\n'):
  30. if line.startswith('# '):
  31. if line[2:].startswith('OPTIONS'):
  32. in_options = True
  33. else:
  34. in_options = False
  35. if in_options:
  36. if line.lstrip().startswith('-'):
  37. split = re.split(r'\s{2,}', line.lstrip())
  38. # Description string may start with `-` as well. If there is
  39. # only one piece then it's a description bit not an option.
  40. if len(split) > 1:
  41. option, description = split
  42. split_option = option.split(' ')
  43. if not split_option[-1].startswith('-'): # metavar
  44. option = ' '.join(split_option[:-1] + ['*%s*' % split_option[-1]])
  45. # Pandoc's definition_lists. See http://pandoc.org/README.html
  46. # for more information.
  47. ret += '\n%s\n: %s\n' % (option, description)
  48. continue
  49. ret += line.lstrip() + '\n'
  50. else:
  51. ret += line + '\n'
  52. return ret
  53. if __name__ == '__main__':
  54. main()