build_manpage.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.announce('Writing man page %s' % self.output)
  59. self._today = datetime.date.today()
  60. def run(self):
  61. dist = self.distribution
  62. homepage = dist.get_url()
  63. appname = self._parser.prog
  64. self._parser._prog = appname
  65. sections = {'authors': ("pwman3 was originally written by Ivan Kelly "
  66. "<ivan@ivankelly.net>.\n pwman3 is now maintained "
  67. "by Oz Nahum <nahumoz@gmail.com>."),
  68. 'distribution': ("The latest version of {} may be "
  69. "downloaded from {}".format(appname,
  70. homepage))
  71. }
  72. dist = self.distribution
  73. mpf = ManPageFormatter(appname,
  74. desc=dist.get_description(),
  75. long_desc=dist.get_long_description(),
  76. ext_sections=sections)
  77. m = mpf.format_man_page(self._parser)
  78. with open(self.output, 'w') as f:
  79. f.write(m)
  80. class ManPageFormatter(argparse.HelpFormatter):
  81. """
  82. Formatter class to create man pages.
  83. Ideally, this class should rely only on the parser, and not distutils.
  84. The following shows a scenario for usage::
  85. from pwman import parser_options
  86. from build_manpage import ManPageFormatter
  87. p = parser_options(ManPageFormatter)
  88. p.format_help()
  89. The last line would print all the options and help infomation wrapped with
  90. man page macros where needed.
  91. """
  92. def __init__(self,
  93. prog,
  94. indent_increment=2,
  95. max_help_position=24,
  96. width=None,
  97. section=1,
  98. desc=None,
  99. long_desc=None,
  100. ext_sections=None,
  101. authors=None,
  102. ):
  103. super(ManPageFormatter, self).__init__(prog)
  104. self._prog = prog
  105. self._section = 1
  106. self._today = datetime.date.today().strftime('%Y\\-%m\\-%d')
  107. self._desc = desc
  108. self._long_desc = long_desc
  109. self._ext_sections = ext_sections
  110. def _get_formatter(self, **kwargs):
  111. return self.formatter_class(prog=self.prog, **kwargs)
  112. def _markup(self, txt):
  113. return txt.replace('-', '\\-')
  114. def _underline(self, string):
  115. return "\\fI\\s-1" + string + "\\s0\\fR"
  116. def _bold(self, string):
  117. if not string.strip().startswith('\\fB'):
  118. string = '\\fB' + string
  119. if not string.strip().endswith('\\fR'):
  120. string = string + '\\fR'
  121. return string
  122. def _mk_synopsis(self, parser):
  123. self.add_usage(parser.usage, parser._actions,
  124. parser._mutually_exclusive_groups, prefix='')
  125. usage = self._format_usage(None, parser._actions,
  126. parser._mutually_exclusive_groups, '')
  127. usage = usage.replace('%s ' % parser._prog, '')
  128. usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(parser._prog),
  129. usage)
  130. return usage
  131. def _mk_title(self, prog):
  132. return '.TH {0} {1} {2}\n'.format(prog, self._section,
  133. self._today)
  134. def _make_name(self, parser):
  135. """
  136. this method is in consitent with others ... it relies on
  137. distribution
  138. """
  139. return '.SH NAME\n%s \\- %s\n' % (parser.prog,
  140. parser.description)
  141. def _mk_description(self):
  142. if self._long_desc:
  143. long_desc = self._long_desc.replace('\n', '\n.br\n')
  144. return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
  145. else:
  146. return ''
  147. def _mk_footer(self, sections):
  148. if not hasattr(sections, '__iter__'):
  149. return ''
  150. footer = []
  151. for section, value in sections.iteritems():
  152. part = ".SH {}\n {}".format(section.upper(), value)
  153. footer.append(part)
  154. return '\n'.join(footer)
  155. def format_man_page(self, parser):
  156. page = []
  157. page.append(self._mk_title(self._prog))
  158. page.append(self._mk_synopsis(parser))
  159. page.append(self._mk_description())
  160. page.append(self.format_options(parser))
  161. page.append(self._mk_footer(self._ext_sections))
  162. return ''.join(page)
  163. @staticmethod
  164. def format_options(parser):
  165. formatter = parser._get_formatter()
  166. # positionals, optionals and user-defined groups
  167. for action_group in parser._action_groups:
  168. formatter.start_section(None)
  169. formatter.add_text(None)
  170. formatter.add_arguments(action_group._group_actions)
  171. formatter.end_section()
  172. # epilog
  173. formatter.add_text(parser.epilog)
  174. # determine help from format above
  175. return '.SH OPTIONS\n' + formatter.format_help()
  176. def _format_action_invocation(self, action):
  177. if not action.option_strings:
  178. metavar, = self._metavar_formatter(action, action.dest)(1)
  179. return metavar
  180. else:
  181. parts = []
  182. # if the Optional doesn't take a value, format is:
  183. # -s, --long
  184. if action.nargs == 0:
  185. parts.extend([self._bold(action_str) for action_str in action.option_strings])
  186. # if the Optional takes a value, format is:
  187. # -s ARGS, --long ARGS
  188. else:
  189. default = self._underline(action.dest.upper())
  190. args_string = self._format_args(action, default)
  191. for option_string in action.option_strings:
  192. parts.append('%s %s' % (self._bold(option_string), args_string))
  193. return ', '.join(parts)
  194. class ManPageCreator(object):
  195. """
  196. This class takes a little different approach. Instead of relying on
  197. information from ArgumentParser, it relies on information retrieved
  198. from distutils.
  199. This class makes it easy for package maintainer to create man pages in cases,
  200. that there is no ArgumentParser.
  201. """
  202. pass
  203. def _mk_name(self, distribution):
  204. """
  205. """
  206. return '.SH NAME\n%s \\- %s\n' % (distribution.get_name(),
  207. distribution.get_description())
  208. if AUTO_BUILD:
  209. build.sub_commands.append(('build_manpage', None))