-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·321 lines (253 loc) · 9.88 KB
/
setup.py
File metadata and controls
executable file
·321 lines (253 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Setup file for appngizer.
This file was generated with PyScaffold 2.5.7, a tool that easily
puts up a scaffold for your new Python project. Learn more under:
http://pyscaffold.readthedocs.org/
"""
import sys
import datetime
from distutils.core import Command
from distutils.errors import DistutilsOptionError
from distutils.command.build import build
import argparse
from setuptools import setup
from setuptools import find_packages
# The BuildManPage code is distributed
# under the same License of Python
# Copyright (c) 2014 Oz Nahum Tiram <nahumoz@gmail.com>
"""
Add a `build_manpage` command to your setup.py.
To use this Command class import the class to your setup.py,
and add a command to call this class::
from build_manpage import BuildManPage
...
...
setup(
...
...
cmdclass={
'build_manpage': BuildManPage,
)
You can then use the following setup command to produce a man page::
$ python setup.py build_manpage --output=prog.1
--parser=yourmodule:argparser
Alternatively, set the variable AUTO_BUILD to True, and just invoke::
$ python setup.py build
If automatically want to build the man page every time you invoke your build,
add to your ```setup.cfg``` the following::
[build_manpage]
output = <appname>.1
parser = <path_to_your_parser>
"""
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
raise SystemExit(
subprocess.call([sys.executable,
'-m',
'tests.test_pwman']))
class BuildManPage(Command):
description = 'Generate man page from an ArgumentParser instance.'
user_options = [
('output=', 'O', 'output file'),
('parser=', None, 'module path to an ArgumentParser instance'
'(e.g. mymod:func, where func is a method or function which return'
'an arparse.ArgumentParser instance.'),
]
def initialize_options(self):
self.output = None
self.parser = None
def finalize_options(self):
if self.output is None:
raise DistutilsOptionError('\'output\' option is required')
if self.parser is None:
raise DistutilsOptionError('\'parser\' option is required')
mod_name, func_name = self.parser.split(':')
fromlist = mod_name.split('.')
try:
mod = __import__(mod_name, fromlist=fromlist)
self._parser = getattr(mod, func_name)(
formatter_class=ManPageFormatter)
except ImportError as err:
raise err
self.announce('Writing man page %s' % self.output)
self._today = datetime.date.today()
def run(self):
dist = self.distribution
homepage = dist.get_url()
appname = 'appngizer'
sections = {'authors': ("2017 aiticon GmbH. All rights reserved"),
'distribution': ("The latest version of {} may be "
"downloaded from {}".format(appname,
homepage))
}
dist = self.distribution
mpf = ManPageFormatter(appname,
desc=dist.get_description(),
long_desc=dist.get_long_description(),
ext_sections=sections)
m = mpf.format_man_page(self._parser)
with open(self.output, 'w') as f:
f.write(m)
class ManPageFormatter(argparse.HelpFormatter):
"""
Formatter class to create man pages.
This class relies only on the parser, and not distutils.
The following shows a scenario for usage::
from pwman import parser_options
from build_manpage import ManPageFormatter
# example usage ...
dist = distribution
mpf = ManPageFormatter(appname,
desc=dist.get_description(),
long_desc=dist.get_long_description(),
ext_sections=sections)
# parser is an ArgumentParser instance
m = mpf.format_man_page(parsr)
with open(self.output, 'w') as f:
f.write(m)
The last line would print all the options and help infomation wrapped with
man page macros where needed.
"""
def __init__(self,
prog,
indent_increment=2,
max_help_position=24,
width=None,
section=1,
desc=None,
long_desc=None,
ext_sections=None,
authors=None,
):
super(ManPageFormatter, self).__init__(prog)
self._prog = prog
self._section = 1
self._today = datetime.date.today().strftime('%Y\\-%m\\-%d')
self._desc = desc
self._long_desc = long_desc
self._ext_sections = ext_sections
def _get_formatter(self, **kwargs):
return self.formatter_class(prog=self.prog, **kwargs)
def _markup(self, txt):
return txt.replace('-', '\\-')
def _underline(self, string):
return "\\fI\\s-1" + string + "\\s0\\fR"
def _bold(self, string):
if not string.strip().startswith('\\fB'):
string = '\\fB' + string
if not string.strip().endswith('\\fR'):
string = string + '\\fR'
return string
def _mk_synopsis(self, parser):
self.add_usage(parser.usage, parser._actions,
parser._mutually_exclusive_groups, prefix='')
usage = self._format_usage(None, parser._actions,
parser._mutually_exclusive_groups, '')
usage = usage.replace('%s ' % self._prog, '')
usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
usage)
return usage
def _mk_title(self, prog):
return '.TH {0} {1} {2}\n'.format(prog, self._section,
self._today)
def _make_name(self, parser):
"""
this method is in consitent with others ... it relies on
distribution
"""
return '.SH NAME\n%s \\- %s\n' % (parser.prog,
parser.description)
def _mk_description(self):
if self._long_desc:
long_desc = self._long_desc.replace('\n', '\n.br\n')
return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc)
else:
return ''
def _mk_footer(self, sections):
if not hasattr(sections, '__iter__'):
return ''
footer = []
for section, value in sections.items():
part = ".SH {}\n {}".format(section.upper(), value)
footer.append(part)
return '\n'.join(footer)
def format_man_page(self, parser):
page = []
page.append(self._mk_title(self._prog))
page.append(self._mk_synopsis(parser))
page.append(self._mk_description())
page.append(self._mk_options(parser))
page.append(self._mk_footer(self._ext_sections))
return ''.join(page)
def _mk_options(self, parser):
formatter = parser._get_formatter()
# positionals, optionals and user-defined groups
for action_group in parser._action_groups:
formatter.start_section(None)
formatter.add_text(None)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(parser.epilog)
# determine help from format above
return '.SH OPTIONS\n' + formatter.format_help()
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend([self._bold(action_str) for action_str in
action.option_strings])
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = self._underline(action.dest.upper())
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append('%s %s' % (self._bold(option_string),
args_string))
return ', '.join(parts)
class ManPageCreator(object):
"""
This class takes a little different approach. Instead of relying on
information from ArgumentParser, it relies on information retrieved
from distutils.
This class makes it easy for package maintainer to create man pages in
cases, that there is no ArgumentParser.
"""
def _mk_name(self, distribution):
"""
"""
return '.SH NAME\n%s \\- %s\n' % (distribution.get_name(),
distribution.get_description())
class custom_build(build):
def run(self):
self.run_command("build_manpage")
build.run(self)
def setup_package():
cmdclass={
'build_manpage': BuildManPage,
'build': custom_build,
}
needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv)
sphinx = ['sphinx'] if needs_sphinx else []
setup(
setup_requires=['six', 'stdeb', 'setuptools>=33.1', 'setuptools_scm>=1.15',
'sphinx>=1.4.9', 'sphinx_rtd_theme>=0.1.6', 'pyscaffold>=2.5a0,<2.6a0'],
use_pyscaffold=True,
use_scm_version={ 'version_scheme':'guess-next-dev' },
cmdclass=cmdclass)
if __name__ == "__main__":
setup_package()