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