setup.py 11 KB

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