blob: 61bb7b07387e0c8db3c7eacf121ca7aa4a8919fc [file] [log] [blame]
Aviv Keshet39853bd2016-09-22 15:12:05 -07001#!/usr/bin/env python2
2# Copyright 2016 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Wrapper around chromite executable scripts that use virtualenv."""
7
8from __future__ import print_function
9
10import os
Allen Li465a0d62016-11-30 14:55:08 -080011import subprocess
Aviv Keshet39853bd2016-09-22 15:12:05 -070012import sys
Allen Li465a0d62016-11-30 14:55:08 -080013
Aviv Keshet39853bd2016-09-22 15:12:05 -070014import wrapper
15
Allen Li465a0d62016-11-30 14:55:08 -080016def _FindChromiteDir():
17 path = os.path.dirname(os.path.realpath(__file__))
18 while not os.path.exists(os.path.join(path, 'PRESUBMIT.cfg')):
19 path = os.path.dirname(path)
20 return path
Aviv Keshet39853bd2016-09-22 15:12:05 -070021
Aviv Keshet39853bd2016-09-22 15:12:05 -070022
Allen Li465a0d62016-11-30 14:55:08 -080023_CHROMITE_DIR = _FindChromiteDir()
24# _VIRTUALENV_DIR contains the scripts for working with venvs
25_VIRTUALENV_DIR = os.path.join(_CHROMITE_DIR, '../infra_virtualenv')
26# _VENV_DIR is the actual virtualenv that contains bin/activate.
27_VENV_DIR = os.path.join(_CHROMITE_DIR, '.venv')
28_REQUIREMENTS = os.path.join(_CHROMITE_DIR, 'venv', 'requirements.txt')
29
30
31def main():
32 if _IsInsideVenv():
33 wrapper.DoMain()
34 else:
35 _CreateVenv()
36 _ExecInVenv(sys.argv)
37
38
39def _CreateVenv():
40 """Create or update chromite venv."""
41 subprocess.check_call([
42 os.path.join(_VIRTUALENV_DIR, 'create_venv'),
43 _VENV_DIR,
44 _REQUIREMENTS,
45 ], stdout=sys.stderr)
46
47
48def _ExecInVenv(args):
49 """Exec command in chromite venv.
50
51 Args:
52 args: Sequence of arguments.
53 """
54 os.execv(os.path.join(_VIRTUALENV_DIR, 'venv_command'),
55 ['venv_command', _VENV_DIR] + list(args))
56
57
58def _IsInsideVenv():
59 """Return whether we're running inside a virtualenv."""
60 # Proper way is checking sys.prefix and sys.base_prefix in Python 3.
61 # PEP 405 isn't fully implemented in Python 2.
62 return _VENV_DIR in os.environ.get('VIRTUAL_ENV', '')
Aviv Keshet39853bd2016-09-22 15:12:05 -070063
64
65if __name__ == '__main__':
Allen Li465a0d62016-11-30 14:55:08 -080066 main()