build_manpage.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. """
  21. import datetime
  22. from distutils.core import Command
  23. from distutils.errors import DistutilsOptionError
  24. import argparse
  25. class BuildManPage(Command):
  26. description = 'Generate man page from an ArgumentParser instance.'
  27. user_options = [
  28. ('output=', 'O', 'output file'),
  29. ('parser=', None, 'module path to an ArgumentParser instance'
  30. '(e.g. mymod:func, where func is a method or function which return'
  31. 'an arparse.ArgumentParser instance.'),
  32. ]
  33. def initialize_options(self):
  34. self.output = None
  35. self.parser = None
  36. def finalize_options(self):
  37. if self.output is None:
  38. raise DistutilsOptionError('\'output\' option is required')
  39. if self.parser is None:
  40. raise DistutilsOptionError('\'parser\' option is required')
  41. mod_name, func_name = self.parser.split(':')
  42. fromlist = mod_name.split('.')
  43. try:
  44. mod = __import__(mod_name, fromlist=fromlist)
  45. self._parser = getattr(mod, func_name)(formatter_class=ManPageFormatter)
  46. except ImportError as err:
  47. raise err
  48. self._parser.formatter_class = ManPageFormatter
  49. self.announce('Writing man page %s' % self.output)
  50. self._today = datetime.date.today()
  51. def _markup(self, txt):
  52. return txt.replace('-', '\\-')
  53. def _write_header(self):
  54. appname = self.distribution.get_name()
  55. ret = []
  56. ret.append(self._parser.formatter_class._mk_title(self._parser._get_formatter(),
  57. appname))
  58. description = self.distribution.get_description()
  59. if description:
  60. name = self._markup('%s - %s' % (self._markup(appname),
  61. description.splitlines()[0]))
  62. else:
  63. name = self._markup(appname)
  64. ret.append('.SH NAME\n%s\n' % name)
  65. self._parser._prog = appname
  66. ret.append(self._parser.formatter_class._mk_synopsis(self._parser._get_formatter(),
  67. self._parser))
  68. ret.append(self._parser.formatter_class._mk_description(self._parser._get_formatter(),
  69. self.distribution))
  70. return ''.join(ret)
  71. def _write_options(self):
  72. ret = ['.SH OPTIONS\n']
  73. ret.extend(self._parser.formatter_class.format_options(self._parser))
  74. return ''.join(ret)
  75. def _write_footer(self):
  76. ret = []
  77. appname = self.distribution.get_name()
  78. author = '%s <%s>' % (self.distribution.get_author(),
  79. self.distribution.get_author_email())
  80. ret.append(('.SH AUTHORS\n.B %s\nwas written by %s.\n'
  81. % (self._markup(appname), self._markup(author))))
  82. homepage = self.distribution.get_url()
  83. ret.append(('.SH DISTRIBUTION\nThe latest version of %s may '
  84. 'be downloaded from\n'
  85. '%s\n\n'
  86. % (self._markup(appname), self._markup(homepage),)))
  87. return ''.join(ret)
  88. def run(self):
  89. manpage = []
  90. manpage.append(self._write_header())
  91. manpage.append(self._write_options())
  92. manpage.append(self._write_footer())
  93. stream = open(self.output, 'w')
  94. stream.write(''.join(manpage))
  95. stream.close()
  96. class ManPageFormatter(argparse.HelpFormatter):
  97. def __init__(self,
  98. prog,
  99. indent_increment=2,
  100. max_help_position=24,
  101. width=None,
  102. section=1):
  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. def _markup(self, txt):
  108. return txt.replace('-', '\\-')
  109. def _underline(self, string):
  110. return "\\fI\\s-1" + string + "\\s0\\fR"
  111. def _bold(self, string):
  112. if not string.strip().startswith('\\fB'):
  113. string = '\\fB' + string
  114. if not string.strip().endswith('\\fR'):
  115. string = string + '\\fR'
  116. return string
  117. def _mk_synopsis(self, parser):
  118. self.add_usage(parser.usage, parser._actions,
  119. parser._mutually_exclusive_groups, prefix='')
  120. # TODO: Override _fromat_usage, work in progress
  121. usage = self._format_usage(parser._prog, parser._actions,
  122. parser._mutually_exclusive_groups, '')
  123. usage = usage.replace('%s ' % parser._prog, '')
  124. usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(parser._prog),
  125. usage)
  126. return usage
  127. def _mk_title(self, prog):
  128. return '.TH {0} {1} {2}\n'.format(prog, self._section,
  129. self._today)
  130. def _mk_description(self, distribution):
  131. long_desc = distribution.get_long_description()
  132. if long_desc:
  133. long_desc = long_desc.replace('\n', '\n.br\n')
  134. return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
  135. else:
  136. return ''
  137. @staticmethod
  138. def format_options(parser):
  139. formatter = parser._get_formatter()
  140. # positionals, optionals and user-defined groups
  141. for action_group in parser._action_groups:
  142. formatter.start_section(None)
  143. formatter.add_text(None)
  144. formatter.add_arguments(action_group._group_actions)
  145. formatter.end_section()
  146. # epilog
  147. formatter.add_text(parser.epilog)
  148. # determine help from format above
  149. return formatter.format_help()
  150. def _format_action_invocation(self, action):
  151. if not action.option_strings:
  152. metavar, = self._metavar_formatter(action, action.dest)(1)
  153. return metavar
  154. else:
  155. parts = []
  156. # if the Optional doesn't take a value, format is:
  157. # -s, --long
  158. if action.nargs == 0:
  159. parts.extend([self._bold(action_str) for action_str in action.option_strings])
  160. # if the Optional takes a value, format is:
  161. # -s ARGS, --long ARGS
  162. else:
  163. default = self._underline(action.dest.upper())
  164. args_string = self._format_args(action, default)
  165. for option_string in action.option_strings:
  166. parts.append('%s %s' % (self._bold(option_string), args_string))
  167. return ', '.join(parts)
  168. def _format_usage(self, prog, actions, groups, prefix):
  169. # if usage is specified, use that
  170. # if usage is not None:
  171. # usage = usage % dict(prog=self._prog)
  172. # if no optionals or positionals are available, usage is just prog
  173. #elif usage is None and not actions:
  174. # usage = '%(prog)s' % dict(prog=self._prog)
  175. # if optionals and positionals are available, calculate usage
  176. #elif usage is None:
  177. if True:
  178. prog = '%(prog)s' % dict(prog=prog)
  179. # split optionals from positionals
  180. optionals = []
  181. positionals = []
  182. for action in actions:
  183. if action.option_strings:
  184. optionals.append(action)
  185. else:
  186. positionals.append(action)
  187. # build full usage string
  188. format = self._format_actions_usage
  189. action_usage = format(optionals + positionals, groups)
  190. usage = ' '.join([s for s in [prog, action_usage] if s])
  191. # wrap the usage parts if it's too long
  192. text_width = self._width - self._current_indent
  193. if len(prefix) + len(usage) > text_width:
  194. # break usage into wrappable parts
  195. part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
  196. opt_usage = format(optionals, groups)
  197. pos_usage = format(positionals, groups)
  198. opt_parts = _re.findall(part_regexp, opt_usage)
  199. pos_parts = _re.findall(part_regexp, pos_usage)
  200. assert ' '.join(opt_parts) == opt_usage
  201. assert ' '.join(pos_parts) == pos_usage
  202. # helper for wrapping lines
  203. def get_lines(parts, indent, prefix=None):
  204. lines = []
  205. line = []
  206. if prefix is not None:
  207. line_len = len(prefix) - 1
  208. else:
  209. line_len = len(indent) - 1
  210. for part in parts:
  211. if line_len + 1 + len(part) > text_width:
  212. lines.append(indent + ' '.join(line))
  213. line = []
  214. line_len = len(indent) - 1
  215. line.append(part)
  216. line_len += len(part) + 1
  217. if line:
  218. lines.append(indent + ' '.join(line))
  219. if prefix is not None:
  220. lines[0] = lines[0][len(indent):]
  221. return lines
  222. # if prog is short, follow it with optionals or positionals
  223. if len(prefix) + len(prog) <= 0.75 * text_width:
  224. indent = ' ' * (len(prefix) + len(prog) + 1)
  225. if opt_parts:
  226. lines = get_lines([prog] + opt_parts, indent, prefix)
  227. lines.extend(get_lines(pos_parts, indent))
  228. elif pos_parts:
  229. lines = get_lines([prog] + pos_parts, indent, prefix)
  230. else:
  231. lines = [prog]
  232. # if prog is long, put it on its own line
  233. else:
  234. indent = ' ' * len(prefix)
  235. parts = opt_parts + pos_parts
  236. lines = get_lines(parts, indent)
  237. if len(lines) > 1:
  238. lines = []
  239. lines.extend(get_lines(opt_parts, indent))
  240. lines.extend(get_lines(pos_parts, indent))
  241. lines = [prog] + lines
  242. # join lines into usage
  243. usage = '\n'.join(lines)
  244. # prefix with 'usage:'
  245. return '%s%s\n\n' % (prefix, usage)
  246. # build.sub_commands.append(('build_manpage', None))