build_manpage.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # -*- coding: utf-8 -*-
  2. # This file is distributed under the same License of Python
  3. # Copyright (c) 2014 Oz Nahum Tiram <nahumoz@gmail.com>
  4. """
  5. build_manpage.py
  6. Add a `build_manpage` command to your setup.py.
  7. To use this Command class import the class to your setup.py,
  8. and add a command to call this class::
  9. from build_manpage import BuildManPage
  10. ...
  11. ...
  12. setup(
  13. ...
  14. ...
  15. cmdclass={
  16. 'build_manpage': BuildManPage,
  17. )
  18. You can then use the following setup command to produce a man page::
  19. $ python setup.py build_manpage --output=prog.1 --parser=yourmodule:argparser
  20. Alternatively, set the variable AUTO_BUILD to True, and just invoke::
  21. $ python setup.py build
  22. If automatically want to build the man page every time you invoke your build,
  23. add to your ```setup.cfg``` the following::
  24. [build_manpage]
  25. output = <appname>.1
  26. parser = <path_to_your_parser>
  27. """
  28. import datetime
  29. from distutils.core import Command
  30. from distutils.errors import DistutilsOptionError
  31. from distutils.command.build import build
  32. import argparse
  33. import re as _re
  34. AUTO_BUILD = False
  35. class BuildManPage(Command):
  36. description = 'Generate man page from an ArgumentParser instance.'
  37. user_options = [
  38. ('output=', 'O', 'output file'),
  39. ('parser=', None, 'module path to an ArgumentParser instance'
  40. '(e.g. mymod:func, where func is a method or function which return'
  41. 'an arparse.ArgumentParser instance.'),
  42. ]
  43. def initialize_options(self):
  44. self.output = None
  45. self.parser = None
  46. def finalize_options(self):
  47. if self.output is None:
  48. raise DistutilsOptionError('\'output\' option is required')
  49. if self.parser is None:
  50. raise DistutilsOptionError('\'parser\' option is required')
  51. mod_name, func_name = self.parser.split(':')
  52. fromlist = mod_name.split('.')
  53. try:
  54. mod = __import__(mod_name, fromlist=fromlist)
  55. self._parser = getattr(mod, func_name)(formatter_class=ManPageFormatter)
  56. except ImportError as err:
  57. raise err
  58. self._parser.formatter_class = ManPageFormatter
  59. self.announce('Writing man page %s' % self.output)
  60. self._today = datetime.date.today()
  61. def _markup(self, txt):
  62. return txt.replace('-', '\\-')
  63. def _write_header(self):
  64. appname = self.distribution.get_name()
  65. ret = []
  66. ret.append(self._parser.formatter_class._mk_title(self._parser._get_formatter(),
  67. appname))
  68. description = self.distribution.get_description()
  69. ret.append(self._parser.formatter_class._mk_name(self._parser._get_formatter(),
  70. self.distribution))
  71. self._parser._prog = appname
  72. ret.append(self._parser.formatter_class._mk_synopsis(self._parser._get_formatter(),
  73. self._parser))
  74. ret.append(self._parser.formatter_class._mk_description(self._parser._get_formatter(),
  75. self.distribution))
  76. return ''.join(ret)
  77. def _write_options(self):
  78. return self._parser.formatter_class.format_options(self._parser)
  79. def _write_footer(self):
  80. """
  81. Writing the footer allows one to add a lot of extra information.
  82. Sections and and their content can be specified in the dictionary
  83. sections which is passed to the formater method
  84. """
  85. appname = self.distribution.get_name()
  86. homepage = self.distribution.get_url()
  87. sections = {'authors': ("pwman3 was originally written by Ivan Kelly "
  88. "<ivan@ivankelly.net>. pwman3 is now maintained "
  89. "by Oz Nahum <nahumoz@gmail.com>."),
  90. 'distribution': ("The latest version of {} may be "
  91. "downloaded from {}".format(appname,
  92. homepage))
  93. }
  94. return self._parser.formatter_class._mk_footer(self._parser._get_formatter(),
  95. sections)
  96. def run(self):
  97. manpage = []
  98. manpage.append(self._write_header())
  99. manpage.append(self._write_options())
  100. manpage.append(self._write_footer())
  101. stream = open(self.output, 'w')
  102. stream.write(''.join(manpage))
  103. stream.close()
  104. class ManPageFormatter(argparse.HelpFormatter):
  105. def __init__(self,
  106. prog,
  107. indent_increment=2,
  108. max_help_position=24,
  109. width=None,
  110. section=1,
  111. authors=None,
  112. distribution=None):
  113. super(ManPageFormatter, self).__init__(prog)
  114. self._prog = prog
  115. self._section = 1
  116. self._today = datetime.date.today().strftime('%Y\\-%m\\-%d')
  117. def _markup(self, txt):
  118. return txt.replace('-', '\\-')
  119. def _underline(self, string):
  120. return "\\fI\\s-1" + string + "\\s0\\fR"
  121. def _bold(self, string):
  122. if not string.strip().startswith('\\fB'):
  123. string = '\\fB' + string
  124. if not string.strip().endswith('\\fR'):
  125. string = string + '\\fR'
  126. return string
  127. def _mk_synopsis(self, parser):
  128. self.add_usage(parser.usage, parser._actions,
  129. parser._mutually_exclusive_groups, prefix='')
  130. usage = self._format_usage(None, parser._actions,
  131. parser._mutually_exclusive_groups, '')
  132. usage = usage.replace('%s ' % parser._prog, '')
  133. usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(parser._prog),
  134. usage)
  135. return usage
  136. def _mk_title(self, prog):
  137. return '.TH {0} {1} {2}\n'.format(prog, self._section,
  138. self._today)
  139. def _mk_name(self, distribution):
  140. """
  141. this method is in consitent with others ... it relies on
  142. distribution
  143. """
  144. return '.SH NAME\n%s \\- %s\n' % (distribution.get_name(),
  145. distribution.get_description())
  146. def _mk_description(self, distribution):
  147. long_desc = distribution.get_long_description()
  148. if long_desc:
  149. long_desc = long_desc.replace('\n', '\n.br\n')
  150. return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
  151. else:
  152. return ''
  153. def _mk_footer(self, sections):
  154. footer = []
  155. for section, value in sections.iteritems():
  156. part = ".SH {}\n {}".format(section.upper(), value)
  157. footer.append(part)
  158. return '\n'.join(footer)
  159. @staticmethod
  160. def format_options(parser):
  161. formatter = parser._get_formatter()
  162. # positionals, optionals and user-defined groups
  163. for action_group in parser._action_groups:
  164. formatter.start_section(None)
  165. formatter.add_text(None)
  166. formatter.add_arguments(action_group._group_actions)
  167. formatter.end_section()
  168. # epilog
  169. formatter.add_text(parser.epilog)
  170. # determine help from format above
  171. return '.SH OPTIONS\n' + formatter.format_help()
  172. def _format_action_invocation(self, action):
  173. if not action.option_strings:
  174. metavar, = self._metavar_formatter(action, action.dest)(1)
  175. return metavar
  176. else:
  177. parts = []
  178. # if the Optional doesn't take a value, format is:
  179. # -s, --long
  180. if action.nargs == 0:
  181. parts.extend([self._bold(action_str) for action_str in action.option_strings])
  182. # if the Optional takes a value, format is:
  183. # -s ARGS, --long ARGS
  184. else:
  185. default = self._underline(action.dest.upper())
  186. args_string = self._format_args(action, default)
  187. for option_string in action.option_strings:
  188. parts.append('%s %s' % (self._bold(option_string), args_string))
  189. return ', '.join(parts)
  190. if AUTO_BUILD:
  191. build.sub_commands.append(('build_manpage', None))