Gitlab CSE Unil

generate_config.py 2.96 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate Apache configuration based on templates found in templates/apache_config/**

"""
import os
import sys
import time
import django
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

__TARGETS = ('local', 'production', 'staging')


def generate_apache_conf(target='local', quiet=True, yes=True):
    config_tpl = get_template('apache_config/{}.conf'.format(target))

    is_robot = os.path.isfile(os.path.join(settings.STATIC_ROOT, 'robots.txt'))
    is_favicon = os.path.isfile(os.path.join(settings.STATIC_ROOT, 'favicon.ico'))
23
    wsgi_alias = getattr(settings, 'BASE_URL', '/').rstrip('/') or '/'
24
25
26
27
    rendered = config_tpl.render(Context({
        'settings': settings,
        'is_robot': is_robot,
        'is_favicon': is_favicon,
28
        'wsgi_alias': wsgi_alias,
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
        'wsgi_path': os.path.join(settings.SITE_ROOT, *settings.WSGI_APPLICATION.split('.')[:-1]) + '.py',
    }))

    # Cleanup blanklines
    rendered_lines = rendered.split("\n")
    rendered = []
    lp = None
    for i, l in enumerate(rendered_lines):
        if not lp == l.strip() == "":
            rendered.append(l)
        lp = l.strip()
    rendered = "\n".join(rendered)

    output_filename = '{}.conf'.format(target)
    output_path = os.path.join(settings.DJANGO_ROOT, 'apache', output_filename)
    if os.path.exists(output_path) and not (yes or quiet):
        r = raw_input("Config file «{}» already exists, overwrite ? [Y/n]".format(output_filename))
        if r and r[0] not in ('Y', 'y'):
            output_filename = '{0}-{1}.conf'.format(target, int(time.time()))
            output_path = os.path.join(settings.DJANGO_ROOT, 'apache', output_filename)

    with file(output_path, 'w') as output_file:
        output_file.write(rendered)

    if not quiet:
        print "Saved target {0} as {1}".format(target, output_filename)


def main(quiet=True, yes=True, targets=None):
    if not targets:
        targets = __TARGETS
    for target in targets:
        generate_apache_conf(target=target, quiet=quiet, yes=yes)

    # for tgt_conf in os.listdir(tpl_dir):
    #     if os.path.isfile(os.path.join(tpl_dir, tgt_conf)) and not tgt_conf.startswith('base'):
    #         generate_apache_conf(target=os.path.splitext(tgt_conf)[0])


if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
    sys.path.append(BASE_DIR)
    django.setup()

    args = sys.argv[:]
    args.pop(0)
    if '-h' in args:
        print """
usage generate_config.py [-y] [-q] [target, target, ]

Params:

    -y  Force 'yes' if overwrite confirmation needed (not echoed)
    -q  Quiet, no output (implies -q)

    target The name of the target to render. May have more. Must be at the end of the command line

"""
        sys.exit(0)

    main(
        quiet='-q' in args,
        yes='-y' in args,
        targets=[t for t in args if not t.startswith('-')]
    )