From 77eedd22f7dc511f48621e6fd705e937d0e2c746 Mon Sep 17 00:00:00 2001 From: bttk Date: Fri, 21 Feb 2020 07:30:29 -0800 Subject: [PATCH] Running installer with option -s makes it use sudo (#20) * Running installer with option -s makes it use sudo * Add an example of using sudo to README --- README.md | 9 +++++++++ installer/installer.bash.template | 16 +++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9f95705..72a418f 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,15 @@ Think: `make install`. Someday: `bazel run install`. bazel run //src/path/to/pkg:install_foo -c opt ~/bin ``` + If you need to use `sudo` to install a file in a system directory: + + * **Do not** run `sudo bazel`. + * Instead pass flag `-s` to the installer. + + ```shell + bazel run //src/path/to/pkg:install_foo -c opt -- -s /usr/local/bin + ``` + ## See also * [Examples](examples/README.md) diff --git a/installer/installer.bash.template b/installer/installer.bash.template index e07d873..4642273 100644 --- a/installer/installer.bash.template +++ b/installer/installer.bash.template @@ -24,6 +24,9 @@ # # If you don't want --compilation_mode=opt, run: # bazel run //path/to/your:installer_target -- -g /usr/local/bin +# +# To use sudo, run: +# bazel run //path/to/your:installer_target -- -s /usr/local/bin set -o pipefail -o errexit -o nounset @@ -48,7 +51,7 @@ function error() { } function usage() { - echo >&2 "Usage: bazel run ${INSTALLER_LABEL} [-c opt] [--] [-g] [--] /INSTALL_PREFIX" + echo >&2 "Usage: bazel run ${INSTALLER_LABEL} [-c opt] [--] [-g] [-s] [--] /INSTALL_PREFIX" } # Checks that all template variables have been substituted. @@ -78,6 +81,7 @@ function check_sources() { function install_file() { local prefix="$1" local i="$2" + local sudo="$3" local source="${SOURCE_FILES[${i}]}" local target="${TARGET_NAMES[${i}]}" local target_dir @@ -92,9 +96,9 @@ function install_file() { fi [[ -d "${target_dir}" ]] || \ - mkdir --parents -- "${target_dir}" + $sudo mkdir --parents -- "${target_dir}" - install --mode="${target_mode}" \ + $sudo install --mode="${target_mode}" \ -T -- "${source}" "${target_dir}/${target_name}" } @@ -102,9 +106,11 @@ function main() { verify_templates local g_flag='' - while getopts ':gh' flag; do + local s_flag='' + while getopts ':ghs' flag; do case "${flag}" in g) g_flag='true' ;; # Accept debug builds + s) s_flag='sudo' ;; # Run with sudo h) usage; exit 0 ;; *) error "Unexpected option '-${OPTARG}'" ;; esac @@ -125,7 +131,7 @@ function main() { check_sources local i for ((i=0; i<${N_FILES}; i++)); do - install_file "${prefix}" "${i}" + install_file "${prefix}" "${i}" "${s_flag}" done }