|
| 1 | +#!/usr/bin/env python |
| 2 | +import os |
| 3 | +from optparse import OptionParser |
| 4 | + |
| 5 | +from jinja2 import Template |
| 6 | + |
| 7 | + |
| 8 | +HEADER = '!!AUTO-GENERATED!! Edit {template}.tmpl instead.' |
| 9 | +TEMPLATE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'etc', 'cron.d')) |
| 10 | + |
| 11 | + |
| 12 | +def main(): |
| 13 | + parser = OptionParser() |
| 14 | + parser.add_option('-w', '--webapp', |
| 15 | + help='Location of web app (required)') |
| 16 | + parser.add_option('-s', '--source', |
| 17 | + help='Location of source for the web app (required)') |
| 18 | + parser.add_option('-t', '--template', |
| 19 | + help='Name of the template (e.g. bedrock-prod)') |
| 20 | + parser.add_option('-u', '--user', default='root', |
| 21 | + help=('Prefix cron with this user. ' |
| 22 | + 'Only define for cron.d style crontabs.')) |
| 23 | + parser.add_option('-p', '--python', default='python2.6', |
| 24 | + help='Python interpreter to use.') |
| 25 | + |
| 26 | + (opts, args) = parser.parse_args() |
| 27 | + |
| 28 | + if not opts.webapp: |
| 29 | + parser.error('-w must be defined') |
| 30 | + |
| 31 | + if not opts.template: |
| 32 | + parser.error('-t must be defined') |
| 33 | + |
| 34 | + django_manage = 'cd %s && %s manage.py' % (opts.webapp, opts.python) |
| 35 | + ctx = { |
| 36 | + 'django_manage': django_manage, |
| 37 | + 'django_cron': '%s cron' % django_manage, |
| 38 | + } |
| 39 | + |
| 40 | + for k, v in ctx.iteritems(): |
| 41 | + ctx[k] = '%s %s' % (opts.user, v) |
| 42 | + |
| 43 | + # Needs to stay below the opts.user injection. |
| 44 | + ctx['user'] = opts.user |
| 45 | + ctx['webapp'] = opts.webapp |
| 46 | + ctx['source'] = opts.source |
| 47 | + ctx['python'] = opts.python |
| 48 | + ctx['header'] = HEADER.format(template=opts.template) |
| 49 | + |
| 50 | + tmpl_final_name = os.path.join(TEMPLATE_DIR, opts.template) |
| 51 | + tmpl_src_name = tmpl_final_name + '.tmpl' |
| 52 | + tmpl_temp_name = tmpl_final_name + '.TEMP' |
| 53 | + try: |
| 54 | + with open(tmpl_src_name, 'r') as src_fh: |
| 55 | + with open(tmpl_temp_name, 'w') as out_fh: |
| 56 | + out_fh.write(Template(src_fh.read()).render(**ctx)) |
| 57 | + except IOError: |
| 58 | + parser.error('file must exist: ' + tmpl_src_name) |
| 59 | + |
| 60 | + # atomically move into place |
| 61 | + os.rename(tmpl_temp_name, tmpl_final_name) |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + main() |
0 commit comments