setup.py 12 KB

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