-
Notifications
You must be signed in to change notification settings - Fork 4
/
make-flaskext.py
349 lines (301 loc) · 12 KB
/
make-flaskext.py
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
"""
make-flaskext
~~~~~~~~~~~~~
Little helper script that helps creating new flask extensions.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import re
import os
import sys
import getpass
from datetime import datetime
from subprocess import Popen
from jinja2 import Template
from werkzeug import url_quote
_sep_re = re.compile(r'[\s.,;_-]+')
SPHINX_THEME_REPO = 'git://github.com/mitsuhiko/flask-sphinx-themes.git'
FILE_HEADER_TEMPLATE = Template(u'''\
# -*- coding: utf-8 -*-
"""
{{ module }}
{{ '~' * module|length }}
Description of the module goes here...
:copyright: (c) {{ year }} by {{ name }}.
:license: {{ license }}, see LICENSE for more details.
"""
''')
MIT_LICENSE_TEMPLATE = Template(u'''\
Copyright (c) {{ year }} {{ name }}
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
''')
BSD_LICENSE_TEMPLATE = Template(u'''\
Copyright (c) {{ year }} by {{ name }}.
Some rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* The names of the contributors may not be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''')
SETUP_PY_TEMPLATE = Template(u'''\
"""
{{ name }}
{{ '-' * name|length }}
Description goes here...
Links
`````
* `documentation <http://packages.python.org/{{ urlname }}>`_
{% if vcs_host in ('github', 'gitorious', 'bitbucket') -%}
* `development version
{%- if vcs_host == 'github' %}
<http://github.com/USERNAME/REPOSITORY/zipball/master#egg={{ urlname }}-dev>`_
{%- elif vcs_host == 'gitorious' %}
<http://gitorious.org/PROJECT/REPOSITORY/archive-tarball/master#egg={{ urlname }}-dev>`_
{%- elif vcs_host == 'bitbucket' %}
<http://bitbucket.org/USERNAME/REPOSITORY/get/tip.gz#egg={{ urlname }}-dev>`_
{% endif %}
{% endif %}
"""
from setuptools import setup
setup(
name={{ name|pprint }},
version='0.1',
url='<enter URL here>',
license={{ license|pprint }},
author={{ author|pprint }},
author_email='[email protected]',
description='<enter short description here>',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
{%- if license %}
'License :: OSI Approved :: {{ license }} License',
{%- endif %}
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
''')
def prompt(name, default=None):
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = raw_input(prompt)
if rv:
return rv
if default is not None:
return default
def prompt_bool(name, default=False):
while True:
rv = prompt(name + '?', default and 'Y' or 'N')
if not rv:
return default
if rv.lower() in ('y', 'yes', '1', 'on', 'true', 't'):
return True
elif rv.lower() in ('n', 'no', '0', 'off', 'false', 'f'):
return False
def prompt_choices(name, choices):
while True:
rv = prompt(name + '? - (%s)' % ', '.join(choices), choices[0])
rv = rv.lower()
if not rv:
return choices[0]
if rv in choices:
if rv == 'none':
return None
else:
return rv
def guess_package(name):
"""Guess the package name"""
words = [x.lower() for x in _sep_re.split(name)]
words = [x for x in words if x != 'flask']
return '_'.join(words) or None
class Extension(object):
def __init__(self, name, shortname, author, output_folder, vcs, vcs_host,
license, with_sphinx, sphinx_theme):
self.name = name
self.shortname = shortname
self.author = author
self.output_folder = output_folder
self.vcs = vcs
self.vcs_host = vcs_host
self.license = license
self.with_sphinx = with_sphinx
self.sphinx_theme = sphinx_theme
def make_folder(self):
os.makedirs(os.path.join(self.output_folder, 'flaskext'))
def create_files(self):
with open(os.path.join(self.output_folder, 'flaskext',
'__init__.py'), 'w') as f:
f.write("__import__('pkg_resources')."
"declare_namespace(__name__)\n")
with open(os.path.join(self.output_folder, 'flaskext',
self.shortname + '.py'), 'w') as f:
f.write(FILE_HEADER_TEMPLATE.render(
module='flaskext.' + self.shortname,
year=datetime.utcnow().year,
name=self.author,
license=self.license
).encode('utf-8') + '\n')
with open(os.path.join(self.output_folder, 'LICENSE'), 'w') as f:
if self.license == 'BSD':
f.write(BSD_LICENSE_TEMPLATE.render(
year=datetime.utcnow().year,
name=self.author
).encode('utf-8') + '\n')
elif self.license == 'MIT':
f.write(MIT_LICENSE_TEMPLATE.render(
year=datetime.utcnow().year,
name=self.author
).encode('utf-8') + '\n')
with open(os.path.join(self.output_folder, 'README'), 'w') as f:
f.write(self.name + '\n\nDescription goes here\n')
with open(os.path.join(self.output_folder, 'setup.py'), 'w') as f:
f.write(SETUP_PY_TEMPLATE.render(
name=self.name,
urlname=url_quote(self.name),
package='flaskext.' + self.shortname,
author=self.author,
vcs_host=self.vcs_host,
license=self.license
).encode('utf-8') + '\n')
def init_vcs(self):
if self.vcs == 'hg':
self.init_hg()
elif self.vcs == 'git':
self.init_git()
def init_hg(self):
Popen(['hg', 'init'], cwd=self.output_folder).wait()
def init_git(self):
Popen(['git', 'init'], cwd=self.output_folder).wait()
if self.with_sphinx:
Popen(['git', 'submodule', 'add', SPHINX_THEME_REPO,
'docs/_themes'], cwd=self.output_folder).wait()
def init_sphinx(self):
if not self.with_sphinx:
return
docdir = os.path.join(self.output_folder, 'docs')
os.makedirs(docdir)
Popen(['sphinx-quickstart'], cwd=docdir).wait()
if os.path.isfile(os.path.join(docdir, 'source', 'conf.py')):
sphinx_conf_py = os.path.join(docdir, 'source', 'conf.py')
else:
sphinx_conf_py = os.path.join(docdir, 'conf.py')
with open(sphinx_conf_py, 'r') as f:
config = f.read().splitlines()
for idx, line in enumerate(config):
if line.startswith('#sys.path.append'):
config[idx] = "sys.path.append(os.path.abspath('_themes'))"
elif line.startswith('html_theme ='):
config[idx] = 'html_theme = %r' % self.sphinx_theme
elif line == '#html_theme_path = []':
config[idx] = "html_theme_path = ['_themes']"
elif line.startswith('pygments_style ='):
config[idx] = "#pygments_style = 'sphinx'"
with open(sphinx_conf_py, 'w') as f:
f.write('\n'.join(config))
if not self.vcs == 'git':
print 'Don\'t forget to put the sphinx themes into docs/_themes!'
def main():
if len(sys.argv) not in (1, 2):
print 'usage: make-flaskext.py [output-folder]'
return
print 'Welcome to the Flask Extension Creator Wizard'
print
while 1:
name = prompt('Extension Name (human readable)')
if 'flask' in name.lower():
break
if prompt_bool('Warning: It\'s recommended that the extension name '
'contains the word "Flask". Continue'):
break
shortname = prompt('Shortname (without flaskext.)', default=guess_package(name))
author = prompt('Author', default=getpass.getuser())
license_rv = prompt_choices('License', ('bsd', 'mit', 'none'))
if license_rv == 'bsd':
license = 'BSD'
elif license_rv == 'mit':
license = 'MIT'
else:
license = None
use_sphinx = prompt_bool('Create sphinx documentation', default=True)
sphinx_theme = None
if use_sphinx:
sphinx_theme = prompt('Sphinx theme to use', default='flask_small')
vcs = prompt_choices('Which VCS to use', ('none', 'git', 'hg'))
if vcs is None:
vcs_host = None
elif vcs == 'git':
vcs_host = prompt_choices('Which git host to use',
('none', 'github', 'gitorious'))
elif vcs == 'hg':
vcs_host = prompt_choices('Which Mercurial host to use',
('none', 'bitbucket'))
output_folder = len(sys.argv) == 2 and sys.argv[1] or ('flask-%s' % shortname)
while 1:
folder = prompt('Output folder', default=output_folder)
if os.path.isfile(folder):
print 'Error: output folder is a file'
elif os.path.isdir(folder) and os.listdir(folder):
if prompt_bool('Warning: output folder is not empty. Continue'):
break
else:
break
output_folder = os.path.abspath(folder)
ext = Extension(name, shortname, author, output_folder, vcs, vcs_host,
license, use_sphinx, sphinx_theme)
ext.make_folder()
ext.create_files()
ext.init_sphinx()
ext.init_vcs()
if __name__ == '__main__':
main()