• 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)
24
25readonly bin_dir="$(readlink -e -- "$(dirname -- "$0")")"
26if [[ ! -d "${bin_dir}" ]]; then
27    echo "ERROR: Can not locate the location of python_env!" >&2
28    exit 1
29fi
30
31realpath() {
32    pushd "${bin_dir}" > /dev/null 2>&1
33    readlink -e -- "$1"
34    popd > /dev/null 2>&1
35}
36
37find_create_venv() {
38    local p
39    for p in "${infra_virtualenv_paths[@]}"; do
40        local create_venv=$(realpath "${p}/bin/create_venv")
41        if [[ -f "${create_venv}" ]]; then
42            echo "${create_venv}"
43            break
44        fi
45    done
46}
47
48readonly create_venv=$(find_create_venv)
49if [[ ! -f "${create_venv}" ]]; then
50    cat <<EOF >&2
51ERROR: create_venv script could not be located.
52You need to update a constant inside python_venv, or your checkout might be
53incomplete.
54EOF
55    exit 1
56fi
57
58readonly extra_imports_dir=$(realpath ../venv)
59if [[ ! -d "${extra_imports_dir}" ]]; then
60    cat <<EOF >&2
61ERROR: ${bin_dir}/../venv does not exist
62See infra_virtualenv/README.md for details.
63EOF
64    exit 1
65fi
66
67readonly venv_dir=$("${create_venv}" "${extra_imports_dir}/requirements.txt")
68if [[ ! -d "${venv_dir}" ]]; then
69    echo "ERROR: Failed to set up a virtualenv." >&2
70    exit 1
71fi
72
73export PYTHONPATH="${extra_imports_dir}"
74exec "${venv_dir}/bin/python" "$@"
75