This repository has been archived by the owner on Feb 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fabfile.py
374 lines (315 loc) · 8.87 KB
/
fabfile.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env python
import binascii
import datetime
import os
import os.path
import platform
import urllib2
import urlparse
from pprint import pprint
import cssmin
from jinja2 import Environment, FileSystemLoader
from fabric.colors import *
from fabric.api import *
from fabric.contrib.console import *
from fabric.contrib.files import *
from fabric.utils import *
from flaskext.bcrypt import Bcrypt
bcrypt = Bcrypt()
"""
fabfile
Heavily inspired by: https://github.com/samuelclay/NewsBlur/blob/master/fabfile.py
"""
# ==============
# Color Printing
# ==============
def pblue(s, bold=False):
puts(blue(s,bold))
def pcyan(s, bold=False):
puts(cyan(s,bold))
def pgreen(s, bold=False):
puts(green(s, bold))
def pmage(s, bold=False):
puts(magenta(s,bold))
def pred(s, bold=False):
puts(red(s, bold))
def pwhite(s, bold=False):
puts(white(s, bold))
def pyellow(s, bold=False):
puts(yellow(s, bold))
@task
def penv():
pblue("Current Environment:")
pprint(env)
# ====================
# Environment Settings
# ====================
# Default
env.PROJECT_ROOT = os.path.dirname(__file__)
env.PROJECT_VENV = 'blog'
env.user = "mark"
env.roledefs = {
'local': ['localhost'],
'web': ['vivid-fire-8342.herokuapp.com']
#'app': ['app.uwplatt.edu',
#'dev': ['dev.uwplatt.edu'],
#'ldap': ['ldap.uwplatt.ed'],
}
def server():
env.PROJECT_ROOT = '/app/'
@task
def web():
server()
env.roles = ['web']
@task
def app():
server()
env.roles = ['app']
@task
def dev():
server()
env.roles = ['dev']
# ========
# Settings
# ========
def get_settings():
settings = dict()
# Prompt User for Settings
pblue("Enter your environment settings.")
settings['PRODUCTION'] = False
if confirm(blue("Are these settings for a production server?")):
settings['PRODUCTION'] = True
puts('')
pblue('##### ADMIN SETUP #####')
settings['ADMIN_USERNAME'] = prompt(magenta('ADMIN_USERNAME:'))
admin_password = prompt(magenta('ADMIN_PASSWORD:'))
admin_password_hashed = bcrypt.generate_password_hash(admin_password)
settings['ADMIN_PASSWORD_HASH'] = admin_password_hashed
puts('')
pblue('##### DATABASE SETUP #####')
settings['MONGODB_HOST'] = prompt(magenta('MONGODB_HOST:'))
settings['MONGODB_PORT'] = prompt(magenta('MONGODB_PORT:'))
settings['MONGODB_DATABASE'] = prompt(magenta('MONGODB_DATABASE:'))
settings['MONGODB_USERNAME'] = prompt(magenta('MONGODB_USERNAME:'))
settings['MONGODB_PASSWORD'] = prompt(magenta('MONGODB_PASSWORD:'))
puts('')
pblue('##### MAIL SETUP #####')
settings['MAIL_SERVER'] = prompt(magenta('MAIL_SERVER:'))
settings['MAIL_PORT'] = prompt(magenta('MAIL_PORT:'))
settings['MAIL_USERNAME'] = prompt(magenta('MAIL_USERNAME:'))
settings['MAIL_PASSWORD'] = prompt(magenta('MAIL_PASSWORD:'))
settings['MAILGUN_API_KEY'] = prompt(magenta('MAIL_API_KEY:'))
puts('')
pblue('##### MEMCACHE SETUP #####')
settings['MEMCACHE_SERVER'] = prompt(magenta('MEMCACHE_SERVER:'))
settings['MEMCACHE_USERNAME'] = prompt(magenta('MEMCACHE_USERNAME:'))
settings['MEMCACHE_PASSWORD'] = prompt(magenta('MEMCACHE_PASSWORD:'))
secret_key = binascii.b2a_hqx(os.urandom(42))
pred('\nSECRET KEY: %s' % secret_key)
if confirm(yellow("Verify everything looks correct?")):
settings['SECRET_KEY'] = secret_key
return settings
return None
@task
def make_local_settings():
""" Creates a new settings.py (locally) """
settings = get_settings()
if settings:
jenv = Environment(loader=FileSystemLoader('.'))
text = jenv.get_template('settings.template.py').render(**settings or {})
outputfile_name = 'settings.dev.py'
with open(outputfile_name, 'w') as outputfile:
outputfile.write(text)
@task
def make_settings():
""" Creates a new settings.dev.py """
settings = get_settings()
if settings:
outputfile_name = 'settings.dev.py'
with cd(env.PROJECT_ROOT):
with prefix('workon %s' % env.PROJECT_VENV):
upload_template('settings.template.py',
os.path.join(env.PROJECT_ROOT, outputfile_name),
context=settings, use_jinja=True, backup=False)
# ======================
# Environment Operations
# ======================
@task
def set_env():
settings = get_settings()
if settings:
for key in settings:
item = settings.get(key)
if isinstance(item, bool):
item = str(item)
os.environ[key] = item
local("export %s='%s'" % (key, item))
print os.getenv(key)
@task
def make_venv():
if run('python3 --version', True):
run('mkproject -p python2.7 %s' % env.PROJECT_VENV)
else:
run('mkproject -p python2.7 %s' % env.PROJECT_VENV)
# ===================
# Development / Debug
# ===================
@task
def console():
local('ipython -i play.py')
@task
def less():
with lcd('apps/static/less'):
local('lessc style.less ../css/style.css')
@task
def coffee():
with lcd('apps/static/coffee'):
local('coffee -b --compile --output ../js/ *.coffee')
@task
def uglify():
with lcd('apps/static/js'):
local('uglifyjs script.js >> script.min.js')
local('uglifyjs plugins.js >> plugins.min.js')
@task
def cssmin():
with lcd('apps/static/css'):
local('cat *.css | cssmin > style.min.css')
@task
def watch_coffee():
with lcd('apps/static/coffee'):
local('coffee -o ../js/ --watch --compile ./*coffee')
@task
def build_assets():
less()
coffee()
uglify()
cssmin()
@task
def test():
local('nosetest tests')
# ============
# Requirements
# ============
@task
def install_deps():
""" Install dependencies depending on server type. """
with prefix('source virtualenvwrapper.sh'):
with prefix('workon %s' % env.PROJECT_VENV):
if confirm(magenta("Is this a production server?")):
run('pip install -U -r requirements/prod.txt --use-mirrors')
else:
run('pip install -U -r requirements/dev.txt --use-mirrors')
@task
def freeze():
pass
# ===============
# Version Control
# ==============
@task
def clone():
pass
run('git clone git@github.com:feltnerm/blog.git %s' % env.PROJECT_ROOT)
@task
def commit():
clean()
build_assets()
print "Commit message: "
commit_message = raw_input()
local("git commit -am \"%s\"" % commit_message)
@task
def pull():
with cd(env.PROJECT_ROOT):
run('git pull')
@task
@serial
def push():
''' Pushes local changes to master, and pulls them down to each server'''
local('git push')
with cd(env.PROJECT_ROOT):
run('git pull')
@task
def status():
s = local('git status --porcelain', True)
if s:
pyellow('Detected Changes to Branch', bold=True)
puts(s)
# =====================
# Server Administration
# ====================
# ==========
# Migrations
# ==========
# ======
# Backups
# =======
# ===========
# Boilerplate
# ===========
@task
def boilerplate():
""" Create a new project based on the boilerplate. """
pgreen("Forging boilerplate.", bold=True)
bp = dict()
bp['SITE_NAME'] = prompt(magenta("Project Name: "))
bp['PROJECT_ROOT'] = os.path.expanduser(os.path.join('~/Projects',bp['SITE_NAME']))
if not confirm(green("%s okay for project root?" % bp['PROJECT_ROOT'])):
bp['PROJECT_ROOT'] = prompt(magenta("Project Root: "))
if not os.path.exists(bp['PROJECT_ROOT']):
local('mkdir %s' % bp['PROJECT_ROOT'])
local('cp -r %s/* %s' % (env.PROJECT_ROOT, bp['PROJECT_ROOT']))
#upload_template('settings.py.template',
# bp['PROJECT_ROOT'],
# context=bp,
# use_jinja=True,
# backup=False
# )
else:
pred('Project already exists!')
# =========
# Deployment
# =========
@task
def bootstrap():
pgreen("Bootstrappin' yer server!", bold=True)
#make_venv()
#install_deps()
#pull()
#init_postgres()
#init_mongo()
#make_settings()
#init_migrate()
#with cd(env.PROJECT_ROOT):
#run('mkdir log/')
@task
def deploy():
clean()
build_assets()
local('git push origin master')
local('git push heroku master')
# ===============
# Setup :: Common
# ===============
# =========
# Utilities
# =========
@task
def clean():
rmpyc()
with lcd('apps/static/'):
local('rm -rf js/*.js')
local('rm -rf css/*.css')
local('rm -rf gen/*')
@task
def pychecker():
local('pychecker .')
@task
def pep8():
""" Run PEP8 on my code. """
puts("Checking python style")
with cd(env.PROJECT_ROOT):
local('pep8 .')
@task
def rmpyc():
''' Delete compiled python (.pyc) files. '''
pwhite('Removing .pyc files.')
local("find . -iname '*.pyc' -exec rm -v {} \;", capture=False)