build_manpage.py 11 KB

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