Skip to content

Instantly share code, notes, and snippets.

@mik-laj
Created March 19, 2020 23:16
Show Gist options
  • Save mik-laj/4bc156242ad362edd6e641dda368649d to your computer and use it in GitHub Desktop.
Save mik-laj/4bc156242ad362edd6e641dda368649d to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
set -eu
_showed_traceback=0
function _breeze_handle_err() {
local _ec="$?"
if [[ $_ec != 0 && "${_showed_traceback}" != 0 ]]; then
traceback 1
display_code ${BASH_SOURCE[0]} ${BASH_LINENO[1]}
fi
}
function _breeze_handle_exit() {
local _ec="$?"
local _cmd="${BASH_COMMAND:-unknown}"
traceback 1
display_code ${BASH_SOURCE[0]} ${BASH_LINENO[1]}
_showed_traceback=1
echo "The command ${_cmd} exited with exit code ${_ec}." 1>&2
}
function traceback() {
# Hide the traceback() call.
local -i start=$((${1:-0} + 1))
local -i end=${#BASH_SOURCE[@]}
local -i i=0
local -i j=0
echo "Traceback (last called is first):" 1>&2
for ((i = start; i < end; i++)); do
j=$((i - 1))
local function="${FUNCNAME[$i]}"
local file="${BASH_SOURCE[$i]}"
local line="${BASH_LINENO[$j]}"
printf '%6d %s() in %s:%s\n' "$j" "${function}" "${file}" "${line}" 1>&2
done
echo "" 1>&2
}
function highlight_code {
local input=${1:-$(</dev/stdin)}
if command -v pygmentize; then
printf '%s' "${input}" | pygmentize | cat -n
else
printf '%s' "${input}" | cat -n
fi
}
function display_code() {
local -i err_line=${2}
local err_file=${1}
local -i code_start=$((err_line - 2))
local -i code_end=$((err_line + 4))
code_start=$((code_start > 0 ? code_start : 1))
echo "Last frame in code: [${err_file}:${err_line}]" 1>&2
cat $err_file | highlight_code | sed -n "${code_start},${code_end}p" 1>&2
echo "" 1>&2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment