setup.py 12 KB

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