• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/bin/bash
2# Copyright 2017 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# Starts a python interpreter in virtualenv.
7#
8# This script will set up a virtualenv when it has not been created yet and
9# executes the Python interpreter.
10#
11# The canonical version of this script is in infra_virtualenv repository.
12# See infra_virtualenv/README.md about how to adopt virtualenv to your project.
13
14set -eu
15
16# Change this constant to the path(s) to infra_virtualenv directory when you
17# copy this script to other repos.
18# A path can be a relative path from this script, or an absolute path. If this
19# array contains multiple paths, they are searched in the listed order.
20readonly -a infra_virtualenv_paths=(
21    "../../../../../../infra_virtualenv"
22    "/opt/infra_virtualenv"
23    ~chromeos-test/chromiumos/infra_virtualenv
24)
25
26readonly bin_dir="$(readlink -e -- "$(dirname -- "$0")")"
27if [[ ! -d "${bin_dir}" ]]; then
28    echo "python_venv: Cannot locate python_env!" >&2
29    exit 1
30fi
31
32realpath() {
33    pushd "${bin_dir}" > /dev/null 2>&1
34    readlink -e -- "$1"
35    popd > /dev/null 2>&1
36}
37
38find_create_venv() {
39    local p
40    for p in "${infra_virtualenv_paths[@]}"; do
41        local create_venv=$(realpath "${p}/bin/create_venv")
42        if [[ -f "${create_venv}" ]]; then
43            echo "${create_venv}"
44            break
45        fi
46    done
47}
48
49readonly create_venv=$(find_create_venv)
50if [[ ! -f "${create_venv}" ]]; then
51    cat <<EOF >&2
52python_venv: create_venv script could not be located
53python_venv: Possible causes: python_venv configured incorrectly or
54python_venv: incomplete repo checkout
55EOF
56    exit 1
57fi
58
59readonly extra_imports_dir=$(realpath ../venv)
60if [[ ! -d "${extra_imports_dir}" ]]; then
61    cat <<EOF >&2
62python_venv: ${bin_dir}/../venv does not exist
63python_venv: See infra_virtualenv/README.md for details
64EOF
65    exit 1
66fi
67
68readonly venv_dir=$("${create_venv}" "${extra_imports_dir}/requirements.txt")
69if [[ ! -d "${venv_dir}" ]]; then
70    echo "ERROR: Failed to set up a virtualenv." >&2
71    exit 1
72fi
73
74export PYTHONPATH="${extra_imports_dir}"
75exec "${venv_dir}/bin/python" "$@"
76