github.com/openshift/source-to-image@v1.4.1-0.20240516041539-bf52fc02204e/hack/util.sh (about)

     1  #!/bin/bash
     2  
     3  # Provides simple utility functions
     4  
     5  # Handler for when we exit automatically on an error.
     6  # Borrowed from https://gist.github.com/ahendrix/7030300
     7  s2i::log::errexit() {
     8    local err="${PIPESTATUS[@]}"
     9  
    10    # If the shell we are in doesn't have errexit set (common in subshells) then
    11    # don't dump stacks.
    12    set +o | grep -qe "-o errexit" || return
    13  
    14    set +o xtrace
    15    local code="${1:-1}"
    16    s2i::log::error_exit "'${BASH_COMMAND}' exited with status $err" "${1:-1}" 1
    17  }
    18  
    19  s2i::log::install_errexit() {
    20    # trap ERR to provide an error handler whenever a command exits nonzero this
    21    # is a more verbose version of set -o errexit
    22    trap 's2i::log::errexit' ERR
    23  
    24    # setting errtrace allows our ERR trap handler to be propagated to functions,
    25    # expansions and subshells
    26    set -o errtrace
    27  }
    28  
    29  # Print out the stack trace
    30  #
    31  # Args:
    32  #  $1 The number of stack frames to skip when printing.
    33  s2i::log::stack() {
    34    local stack_skip=${1:-0}
    35    stack_skip=$((stack_skip + 1))
    36    if [[ ${#FUNCNAME[@]} -gt $stack_skip ]]; then
    37    echo "Call stack:" >&2
    38    local i
    39    for ((i=1 ; i <= ${#FUNCNAME[@]} - $stack_skip ; i++))
    40    do
    41      local frame_no=$((i - 1 + stack_skip))
    42      local source_file=${BASH_SOURCE[$frame_no]}
    43      local source_lineno=${BASH_LINENO[$((frame_no - 1))]}
    44      local funcname=${FUNCNAME[$frame_no]}
    45      echo "  $i: ${source_file}:${source_lineno} ${funcname}(...)" >&2
    46    done
    47    fi
    48  }
    49  
    50  # Log an error and exit.
    51  # Args:
    52  #  $1 Message to log with the error
    53  #  $2 The error code to return
    54  #  $3 The number of stack frames to skip when printing.
    55  s2i::log::error_exit() {
    56    local message="${1:-}"
    57    local code="${2:-1}"
    58    local stack_skip="${3:-0}"
    59    stack_skip=$((stack_skip + 1))
    60  
    61    local source_file=${BASH_SOURCE[$stack_skip]}
    62    local source_line=${BASH_LINENO[$((stack_skip - 1))]}
    63    echo "!!! Error in ${source_file}:${source_line}" >&2
    64    [[ -z ${1-} ]] || {
    65    echo "  ${1}" >&2
    66    }
    67  
    68    s2i::log::stack $stack_skip
    69  
    70    echo "Exiting with status ${code}" >&2
    71    exit "${code}"
    72  }
    73  
    74  s2i::util::sed() {
    75    if [[ "$(go env GOHOSTOS)" == "darwin" ]]; then
    76      sed -i '' $@
    77    else
    78      sed -i'' $@
    79    fi
    80  }
    81  
    82  s2i::util::find_files() {
    83    find . -type d -name vendor -prune -o -name '*.go' -print
    84  }