Aviv Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 1 | #!/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 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | import os |
Allen Li | 465a0d6 | 2016-11-30 14:55:08 -0800 | [diff] [blame] | 11 | import subprocess |
Aviv Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 12 | import sys |
Allen Li | 465a0d6 | 2016-11-30 14:55:08 -0800 | [diff] [blame] | 13 | |
Aviv Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 14 | import wrapper |
| 15 | |
Allen Li | 465a0d6 | 2016-11-30 14:55:08 -0800 | [diff] [blame] | 16 | def _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 Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 21 | |
Aviv Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 22 | |
Allen Li | 465a0d6 | 2016-11-30 14:55:08 -0800 | [diff] [blame] | 23 | _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 | |
| 31 | def main(): |
| 32 | if _IsInsideVenv(): |
| 33 | wrapper.DoMain() |
| 34 | else: |
| 35 | _CreateVenv() |
| 36 | _ExecInVenv(sys.argv) |
| 37 | |
| 38 | |
| 39 | def _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 | |
| 48 | def _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 | |
| 58 | def _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 Keshet | 39853bd | 2016-09-22 15:12:05 -0700 | [diff] [blame] | 63 | |
| 64 | |
| 65 | if __name__ == '__main__': |
Allen Li | 465a0d6 | 2016-11-30 14:55:08 -0800 | [diff] [blame] | 66 | main() |