setup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #!/usr/bin/env python
  2. """
  3. script to install pwman3
  4. """
  5. import datetime
  6. from distutils.core import Command
  7. from distutils.errors import DistutilsOptionError
  8. import argparse
  9. from setuptools import setup
  10. from setuptools import find_packages
  11. import sys
  12. import os
  13. # The BuildManPage code is distributed
  14. # under the same License of Python
  15. # Copyright (c) 2014 Oz Nahum Tiram <nahumoz@gmail.com>
  16. """
  17. Add a `build_manpage` command to your setup.py.
  18. To use this Command class import the class to your setup.py,
  19. and add a command to call this class::
  20. from build_manpage import BuildManPage
  21. ...
  22. ...
  23. setup(
  24. ...
  25. ...
  26. cmdclass={
  27. 'build_manpage': BuildManPage,
  28. )
  29. You can then use the following setup command to produce a man page::
  30. $ python setup.py build_manpage --output=prog.1
  31. --parser=yourmodule:argparser
  32. Alternatively, set the variable AUTO_BUILD to True, and just invoke::
  33. $ python setup.py build
  34. If automatically want to build the man page every time you invoke your build,
  35. add to your ```setup.cfg``` the following::
  36. [build_manpage]
  37. output = <appname>.1
  38. parser = <path_to_your_parser>
  39. """
  40. # build.sub_commands.append(('build_manpage', None))
  41. class BuildManPage(Command):
  42. description = 'Generate man page from an ArgumentParser instance.'
  43. user_options = [
  44. ('output=', 'O', 'output file'),
  45. ('parser=', None, 'module path to an ArgumentParser instance'
  46. '(e.g. mymod:func, where func is a method or function which return'
  47. 'an arparse.ArgumentParser instance.'),
  48. ]
  49. def initialize_options(self):
  50. self.output = None
  51. self.parser = None
  52. def finalize_options(self):
  53. if self.output is None:
  54. raise DistutilsOptionError('\'output\' option is required')
  55. if self.parser is None:
  56. raise DistutilsOptionError('\'parser\' option is required')
  57. mod_name, func_name = self.parser.split(':')
  58. fromlist = mod_name.split('.')
  59. try:
  60. mod = __import__(mod_name, fromlist=fromlist)
  61. self._parser = getattr(mod, func_name)(
  62. formatter_class=ManPageFormatter)
  63. except ImportError as err:
  64. raise err
  65. self.announce('Writing man page %s' % self.output)
  66. self._today = datetime.date.today()
  67. def run(self):
  68. dist = self.distribution
  69. homepage = dist.get_url()
  70. appname = self._parser.prog
  71. sections = {'authors': ("pwman3 was originally written by Ivan Kelly "
  72. "<ivan@ivankelly.net>.\n pwman3 is now "
  73. "maintained "
  74. "by Oz Nahum <nahumoz@gmail.com>."),
  75. 'distribution': ("The latest version of {} may be "
  76. "downloaded from {}".format(appname,
  77. homepage))
  78. }
  79. dist = self.distribution
  80. mpf = ManPageFormatter(appname,
  81. desc=dist.get_description(),
  82. long_desc=dist.get_long_description(),
  83. ext_sections=sections)
  84. m = mpf.format_man_page(self._parser)
  85. with open(self.output, 'w') as f:
  86. f.write(m)
  87. class ManPageFormatter(argparse.HelpFormatter):
  88. """
  89. Formatter class to create man pages.
  90. This class relies only on the parser, and not distutils.
  91. The following shows a scenario for usage::
  92. from pwman import parser_options
  93. from build_manpage import ManPageFormatter
  94. # example usage ...
  95. dist = distribution
  96. mpf = ManPageFormatter(appname,
  97. desc=dist.get_description(),
  98. long_desc=dist.get_long_description(),
  99. ext_sections=sections)
  100. # parser is an ArgumentParser instance
  101. m = mpf.format_man_page(parsr)
  102. with open(self.output, 'w') as f:
  103. f.write(m)
  104. The last line would print all the options and help infomation wrapped with
  105. man page macros where needed.
  106. """
  107. def __init__(self,
  108. prog,
  109. indent_increment=2,
  110. max_help_position=24,
  111. width=None,
  112. section=1,
  113. desc=None,
  114. long_desc=None,
  115. ext_sections=None,
  116. authors=None,
  117. ):
  118. super(ManPageFormatter, self).__init__(prog)
  119. self._prog = prog
  120. self._section = 1
  121. self._today = datetime.date.today().strftime('%Y\\-%m\\-%d')
  122. self._desc = desc
  123. self._long_desc = long_desc
  124. self._ext_sections = ext_sections
  125. def _get_formatter(self, **kwargs):
  126. return self.formatter_class(prog=self.prog, **kwargs)
  127. def _markup(self, txt):
  128. return txt.replace('-', '\\-')
  129. def _underline(self, string):
  130. return "\\fI\\s-1" + string + "\\s0\\fR"
  131. def _bold(self, string):
  132. if not string.strip().startswith('\\fB'):
  133. string = '\\fB' + string
  134. if not string.strip().endswith('\\fR'):
  135. string = string + '\\fR'
  136. return string
  137. def _mk_synopsis(self, parser):
  138. self.add_usage(parser.usage, parser._actions,
  139. parser._mutually_exclusive_groups, prefix='')
  140. usage = self._format_usage(None, parser._actions,
  141. parser._mutually_exclusive_groups, '')
  142. usage = usage.replace('%s ' % self._prog, '')
  143. usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
  144. usage)
  145. return usage
  146. def _mk_title(self, prog):
  147. return '.TH {0} {1} {2}\n'.format(prog, self._section,
  148. self._today)
  149. def _make_name(self, parser):
  150. """
  151. this method is in consitent with others ... it relies on
  152. distribution
  153. """
  154. return '.SH NAME\n%s \\- %s\n' % (parser.prog,
  155. parser.description)
  156. def _mk_description(self):
  157. if self._long_desc:
  158. long_desc = self._long_desc.replace('\n', '\n.br\n')
  159. return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
  160. else:
  161. return ''
  162. def _mk_footer(self, sections):
  163. if not hasattr(sections, '__iter__'):
  164. return ''
  165. footer = []
  166. for section, value in sections.items():
  167. part = ".SH {}\n {}".format(section.upper(), value)
  168. footer.append(part)
  169. return '\n'.join(footer)
  170. def format_man_page(self, parser):
  171. page = []
  172. page.append(self._mk_title(self._prog))
  173. page.append(self._mk_synopsis(parser))
  174. page.append(self._mk_description())
  175. page.append(self._mk_options(parser))
  176. page.append(self._mk_footer(self._ext_sections))
  177. return ''.join(page)
  178. def _mk_options(self, parser):
  179. formatter = parser._get_formatter()
  180. # positionals, optionals and user-defined groups
  181. for action_group in parser._action_groups:
  182. formatter.start_section(None)
  183. formatter.add_text(None)
  184. formatter.add_arguments(action_group._group_actions)
  185. formatter.end_section()
  186. # epilog
  187. formatter.add_text(parser.epilog)
  188. # determine help from format above
  189. return '.SH OPTIONS\n' + formatter.format_help()
  190. def _format_action_invocation(self, action):
  191. if not action.option_strings:
  192. metavar, = self._metavar_formatter(action, action.dest)(1)
  193. return metavar
  194. else:
  195. parts = []
  196. # if the Optional doesn't take a value, format is:
  197. # -s, --long
  198. if action.nargs == 0:
  199. parts.extend([self._bold(action_str) for action_str in
  200. action.option_strings])
  201. # if the Optional takes a value, format is:
  202. # -s ARGS, --long ARGS
  203. else:
  204. default = self._underline(action.dest.upper())
  205. args_string = self._format_args(action, default)
  206. for option_string in action.option_strings:
  207. parts.append('%s %s' % (self._bold(option_string),
  208. args_string))
  209. return ', '.join(parts)
  210. class ManPageCreator(object):
  211. """
  212. This class takes a little different approach. Instead of relying on
  213. information from ArgumentParser, it relies on information retrieved
  214. from distutils.
  215. This class makes it easy for package maintainer to create man pages in
  216. cases, that there is no ArgumentParser.
  217. """
  218. def _mk_name(self, distribution):
  219. """
  220. """
  221. return '.SH NAME\n%s \\- %s\n' % (distribution.get_name(),
  222. distribution.get_description())
  223. sys.path.insert(0, os.getcwd())
  224. install_requires = ['colorama>=0.2.4', 'cryptography']
  225. if sys.platform.startswith('win'):
  226. install_requires.append('pyreadline')
  227. long_description = u"""\
  228. Pwman3 aims to provide a simple but powerful commandline interface for
  229. password management.
  230. It allows one to store passwords in database locked by master password which
  231. is AES encrypted.
  232. Pwman3 supports MySQL, Postgresql and SQLite and even MongoDB"""
  233. packages = find_packages(exclude=['tests', 'pwman/ui/templates'])
  234. setup(name='pwman3',
  235. version='0.9.2',
  236. description=("a command line password manager with support for multiple"
  237. " databases."),
  238. long_description=long_description,
  239. author='Oz Nahum Tiram',
  240. author_email='nahumoz@gmail.com',
  241. url='http://pwman3.github.io/pwman3/',
  242. license="GNU GPL",
  243. packages=packages,
  244. include_package_data=True,
  245. zip_safe=False,
  246. install_requires=install_requires,
  247. keywords="password-manager crypto cli",
  248. classifiers=['Environment :: Console',
  249. 'Intended Audience :: End Users/Desktop',
  250. 'Intended Audience :: Developers',
  251. 'Intended Audience :: System Administrators',
  252. ('License :: OSI Approved :: GNU General Public License'
  253. ' v3 or later (GPLv3+)'),
  254. 'Operating System :: OS Independent',
  255. 'Programming Language :: Python',
  256. 'Programming Language :: Python :: 3',
  257. 'Programming Language :: Python :: 3.2',
  258. 'Programming Language :: Python :: 3.3',
  259. 'Programming Language :: Python :: 3.4',
  260. 'Programming Language :: Python :: 3.5',
  261. ],
  262. test_suite='tests.test_pwman.suite',
  263. cmdclass={
  264. 'build_manpage': BuildManPage
  265. },
  266. entry_points={
  267. 'console_scripts': ['pwman3 = pwman.ui.cli:main']
  268. }
  269. )