~ev/uci-engine/guard-against-breaking-virtualenvs

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
#!/usr/bin/env python
# Ubuntu CI Engine
# Copyright 2014 Canonical Ltd.

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3, as
# published by the Free Software Foundation.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys


HERE = os.path.abspath(os.path.dirname(__file__))


def _usage():
    print('Usage: %s script [arg [arg...]]' % sys.argv[0])
    print('Sets up a PYTHONPATH with our ci-utils so that python scripts '
          'can be launched properly')
    sys.exit(0)


def _parse_args(args):
    if not args or args[0] in ['-h', '--help', '-help']:
        _usage()
    return args[0], args


def _component_path(basedir, script):
    '''return the path to the component of the script'''
    script = os.path.abspath(script)
    if basedir not in script:
        sys.exit('ERROR: scripts must reside in source tree')
    script = script[len(basedir) + 1:]
    return script.split('/')[0]


def main(args):
    script, args = _parse_args(args)

    ci_utils = os.path.join(HERE, 'ci-utils')
    comp = _component_path(HERE, script)

    python_path = os.environ.get('PYTHONPATH')
    if python_path:
        python_path = '{}:{}:{}'.format(ci_utils, comp, python_path)
    else:
        python_path = '{}:{}'.format(ci_utils, comp)
    os.environ['PYTHONPATH'] = python_path

    os.execv(script, args)


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))