summaryrefslogtreecommitdiff
path: root/scripts/sandbox_command.sh
blob: 03163458cb1b840b57f8a3663a98b7d9b13ac1c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# usage: scripts/sandbox_command.sh [-q]
#    -q: quiet mode (do not print command, just exit w/ code 0 or 1)

set -euo pipefail

# parse flags
QUIET=false
while getopts ":q" opt; do
    case ${opt} in
        q ) QUIET=true ;;
        \? ) echo "Usage: $0 [-q]"
            exit 1
            ;;
    esac
done
shift $((OPTIND - 1))


# if GEMINI_CODE_SANDBOX is not set, try to source .env in case set there
# allow .env to be in any ancestor directory (same as findEnvFile in config.ts)
if [ -z "${GEMINI_CODE_SANDBOX:-}" ]; then
    current_dir=$(pwd)
    while [ "$current_dir" != "/" ]; do
        if [ -f "$current_dir/.env" ]; then
            source "$current_dir/.env"
            break
        fi
        current_dir=$(dirname "$current_dir")
    done
fi

# if GEMINI_CODE_SANDBOX is still not set, then exit immediately w/ code 1
if [ -z "${GEMINI_CODE_SANDBOX:-}" ]; then exit 1; fi

# lowercase GEMINI_CODE_SANDBOX
GEMINI_CODE_SANDBOX=$(echo "${GEMINI_CODE_SANDBOX:-}" | tr '[:upper:]' '[:lower:]')

# if GEMINI_CODE_SANDBOX is set to 0 or false, then exit immediately w/ code 1
if [[ "${GEMINI_CODE_SANDBOX:-}" =~ ^(0|false)$ ]]; then
    exit 1
fi

# if GEMINI_CODE_SANDBOX is set to 1 or true, then try to use docker or podman
if [[ "${GEMINI_CODE_SANDBOX:-}" =~ ^(1|true)$ ]]; then
    if command -v docker &> /dev/null; then
        if [ "$QUIET" = false ]; then echo "docker"; fi
        exit 0
    elif command -v podman &> /dev/null; then
        if [ "$QUIET" = false ]; then echo "podman"; fi
        exit 0
    else
        echo "ERROR: install docker or podman or specify command in GEMINI_CODE_SANDBOX" >&2
        exit 1
    fi
fi

if ! command -v "$GEMINI_CODE_SANDBOX" &> /dev/null; then
    echo "ERROR: missing sandbox command '$GEMINI_CODE_SANDBOX' (from GEMINI_CODE_SANDBOX)" >&2
    exit 1
fi

if [ "$QUIET" = false ]; then echo "$GEMINI_CODE_SANDBOX"; fi
exit 0