setup.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #!/usr/bin/env python
  2. import argparse
  3. import datetime
  4. from distutils.core import Command
  5. from distutils.command.build import build
  6. from setuptools import setup
  7. from setuptools import find_packages
  8. build.sub_commands.append(('build_manpage', None))
  9. class BuildManPage(Command):
  10. """
  11. Add a `build_manpage` command to your setup.py.
  12. To use this Command class import the class to your setup.py,
  13. and add a command to call this class::
  14. from build_manpage import BuildManPage
  15. ...
  16. ...
  17. setup(
  18. ...
  19. ...
  20. cmdclass={
  21. 'build_manpage': BuildManPage,
  22. )
  23. You can then use the following setup command to produce a man page::
  24. $ python setup.py build_manpage --output=prog.1
  25. --parser=yourmodule:argparser
  26. Alternatively, set the variable AUTO_BUILD to True, and just invoke::
  27. $ python setup.py build
  28. If automatically want to build the man page every time you invoke your build,
  29. add to your ```setup.cfg``` the following::
  30. [build_manpage]
  31. output = <appname>.1
  32. parser = <path_to_your_parser>
  33. # The BuildManPage code is distributed
  34. # under the same License of Python
  35. # Copyright (c) 2014 Oz Nahum Tiram <nahumoz@gmail.com>
  36. """
  37. description = 'Generate man page from an ArgumentParser instance.'
  38. user_options = [
  39. ('output=', 'O', 'output file'),
  40. ('parser=', None, 'module path to an ArgumentParser instance'
  41. '(e.g. mymod:func, where func is a method or function which return'
  42. 'an arparse.ArgumentParser instance.')]
  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)(
  56. formatter_class=ManPageFormatter)
  57. except ImportError as err:
  58. raise err
  59. self.announce('Writing man page %s' % self.output)
  60. self._today = datetime.date.today()
  61. def run(self):
  62. dist = self.distribution
  63. homepage = dist.get_url()
  64. appname = self._parser.prog
  65. sections = {'authors': ("Blogit is written and maintained "
  66. "by Oz N Tiram <nahumoz@gmail.com>."),
  67. 'distribution': ("The latest version of {} may be "
  68. "downloaded from {}".format(appname,
  69. homepage))
  70. }
  71. dist = self.distribution
  72. mpf = ManPageFormatter(appname,
  73. desc=dist.get_description(),
  74. long_desc=dist.get_long_description(),
  75. ext_sections=sections)
  76. m = mpf.format_man_page(self._parser)
  77. with open(self.output, 'w') as f:
  78. f.write(m)
  79. class ManPageFormatter(argparse.HelpFormatter):
  80. """
  81. Formatter class to create man pages.
  82. This class relies only on the parser, and not distutils.
  83. The following shows a scenario for usage::
  84. from pwman import parser_options
  85. from build_manpage import ManPageFormatter
  86. # example usage ...
  87. dist = distribution
  88. mpf = ManPageFormatter(appname,
  89. desc=dist.get_description(),
  90. long_desc=dist.get_long_description(),
  91. ext_sections=sections)
  92. # parser is an ArgumentParser instance
  93. m = mpf.format_man_page(parsr)
  94. with open(self.output, 'w') as f:
  95. f.write(m)
  96. The last line would print all the options and help infomation wrapped with
  97. man page macros where needed.
  98. """
  99. def __init__(self,
  100. prog,
  101. indent_increment=2,
  102. max_help_position=24,
  103. width=None,
  104. section=1,
  105. desc=None,
  106. long_desc=None,
  107. ext_sections=None,
  108. authors=None,
  109. ):
  110. super(ManPageFormatter, self).__init__(prog)
  111. self._prog = prog
  112. self._section = 1
  113. self._today = datetime.date.today().strftime('%Y\\-%m\\-%d')
  114. self._desc = desc
  115. self._long_desc = long_desc
  116. self._ext_sections = ext_sections
  117. def _get_formatter(self, **kwargs):
  118. return self.formatter_class(prog=self.prog, **kwargs)
  119. def _markup(self, txt):
  120. return txt.replace('-', '\\-')
  121. def _underline(self, string):
  122. return "\\fI\\s-1" + string + "\\s0\\fR"
  123. def _bold(self, string):
  124. if not string.strip().startswith('\\fB'):
  125. string = '\\fB' + string
  126. if not string.strip().endswith('\\fR'):
  127. string = string + '\\fR'
  128. return string
  129. def _mk_synopsis(self, parser):
  130. self.add_usage(parser.usage, parser._actions,
  131. parser._mutually_exclusive_groups, prefix='')
  132. usage = self._format_usage(None, parser._actions,
  133. parser._mutually_exclusive_groups, '')
  134. usage = usage.replace('%s ' % self._prog, '')
  135. usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
  136. usage)
  137. return usage
  138. def _mk_title(self, prog):
  139. return '.TH {0} {1} {2}\n'.format(prog, self._section,
  140. self._today)
  141. def _make_name(self, parser):
  142. """
  143. this method is in consitent with others ... it relies on
  144. distribution
  145. """
  146. return '.SH NAME\n%s \\- %s\n' % (parser.prog,
  147. parser.description)
  148. def _mk_description(self):
  149. if self._long_desc:
  150. long_desc = self._long_desc.replace('\n', '\n.br\n')
  151. return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
  152. else:
  153. return ''
  154. def _mk_footer(self, sections):
  155. if not hasattr(sections, '__iter__'):
  156. return ''
  157. footer = []
  158. for section, value in sections.items():
  159. part = ".SH {}\n {}".format(section.upper(), value)
  160. footer.append(part)
  161. return '\n'.join(footer)
  162. def format_man_page(self, parser):
  163. page = []
  164. page.append(self._mk_title(self._prog))
  165. page.append(self._mk_synopsis(parser))
  166. page.append(self._mk_description())
  167. page.append(self._mk_options(parser))
  168. page.append(self._mk_footer(self._ext_sections))
  169. return ''.join(page)
  170. def _mk_options(self, parser):
  171. formatter = parser._get_formatter()
  172. # positionals, optionals and user-defined groups
  173. for action_group in parser._action_groups:
  174. formatter.start_section(None)
  175. formatter.add_text(None)
  176. formatter.add_arguments(action_group._group_actions)
  177. formatter.end_section()
  178. # epilog
  179. formatter.add_text(parser.epilog)
  180. # determine help from format above
  181. return '.SH OPTIONS\n' + formatter.format_help()
  182. def _format_action_invocation(self, action):
  183. if not action.option_strings:
  184. metavar, = self._metavar_formatter(action, action.dest)(1)
  185. return metavar
  186. else:
  187. parts = []
  188. # if the Optional doesn't take a value, format is:
  189. # -s, --long
  190. if action.nargs == 0:
  191. parts.extend([self._bold(action_str) for action_str in
  192. action.option_strings])
  193. # if the Optional takes a value, format is:
  194. # -s ARGS, --long ARGS
  195. else:
  196. default = self._underline(action.dest.upper())
  197. args_string = self._format_args(action, default)
  198. for option_string in action.option_strings:
  199. parts.append('%s %s' % (self._bold(option_string),
  200. args_string))
  201. return ', '.join(parts)
  202. class ManPageCreator(object):
  203. """
  204. This class takes a little different approach. Instead of relying on
  205. information from ArgumentParser, it relies on information retrieved
  206. from distutils.
  207. This class makes it easy for package maintainer to create man pages in
  208. cases, that there is no ArgumentParser.
  209. """
  210. def _mk_name(self, distribution):
  211. """
  212. """
  213. return '.SH NAME\n%s \\- %s\n' % (distribution.get_name(),
  214. distribution.get_description())
  215. setup(name='blogit',
  216. version='0.1.1',
  217. description='A quick and simple static site generator based on markdown and jinja2',
  218. license="GNU GPL",
  219. url='http://github.com/oz123/blogit',
  220. packages=find_packages(exclude=['tests']),
  221. install_requires=['Jinja2', 'markdown2', 'tinydb', 'pygments'],
  222. include_package_data=True,
  223. tests_require=['pytest', 'beautifulsoup4'],
  224. entry_points={
  225. 'console_scripts': ['blogit = blogit.blogit:main']
  226. },
  227. cmdclass={
  228. 'build_manpage': BuildManPage
  229. },
  230. classifiers=['Environment :: Console',
  231. 'Intended Audience :: End Users/Desktop',
  232. 'Intended Audience :: Developers',
  233. ('License :: OSI Approved :: GNU General Public License'
  234. ' v3 or later (GPLv3+)'),
  235. 'Operating System :: OS Independent',
  236. 'Programming Language :: Python',
  237. 'Programming Language :: Python :: 3',
  238. 'Programming Language :: Python :: 3.3',
  239. 'Programming Language :: Python :: 3.4',
  240. 'Programming Language :: Python :: 3.5',
  241. ],
  242. )