├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE.txt ├── README.md ├── base ├── colors.sh ├── permission.sh └── trap.bash ├── core ├── 000_core_func.sh └── 010_logging.sh ├── docker ├── bashrc └── zshrc ├── gpl-3.0.txt ├── init.sh ├── lib ├── 000_gnusafe.sh ├── 000_trap_helper.sh ├── 010_helpers.sh ├── 020_date_helpers.sh └── scripts │ └── shellcore_install.sh ├── load.sh ├── logs └── .gitignore ├── map_libs.sh ├── run.sh └── tests.bats /.gitignore: -------------------------------------------------------------------------------- 1 | .last_update 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: bash 2 | 3 | addons: 4 | apt: 5 | packages: 6 | - git 7 | - curl 8 | - shellcheck 9 | homebrew: 10 | packages: 11 | - gsed 12 | - gawk 13 | - ggrep 14 | - bash 15 | update: true 16 | 17 | jobs: 18 | include: 19 | - os: linux 20 | dist: xenial 21 | env: NAME="Ubuntu 16.04 Xenial" 22 | - os: linux 23 | dist: bionic 24 | env: NAME="Ubuntu 18.04 Bionic" 25 | - os: osx 26 | env: NAME="Mac OSX" 27 | 28 | 29 | before_script: 30 | - | 31 | if [[ "$TRAVIS_OS_NAME" = "osx" ]]; then 32 | echo "/usr/local/bin/bash" | sudo tee -a /etc/shells 33 | sudo chsh -s /usr/local/bin/bash $(whoami) 34 | echo "Real OSX bash version - $(bash --version)" 35 | fi 36 | - git clone -q https://github.com/bats-core/bats-core.git 37 | - sudo cp -R bats-core /usr/local/git-bats 38 | - pushd /usr/local/git-bats && sudo ./install.sh /usr/local/bats-core && popd 39 | 40 | script: 41 | - /usr/local/bats-core/bin/bats -t tests.bats 42 | 43 | 44 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # # 3 | # Privex's Shell Core # 4 | # Cross-platform / Cross-shell helper functions # 5 | # # 6 | # Released under the GNU GPLv3 # 7 | # # 8 | # Official Repo: github.com/Privex/shell-core # 9 | # # 10 | ############################################################# 11 | FROM ubuntu:bionic 12 | 13 | RUN apt-get update -qy && apt-get install -y zsh bash-completion curl wget git && apt-get clean -qy 14 | 15 | COPY . /root/sgshell 16 | 17 | COPY docker/bashrc /root/.bashrc 18 | COPY docker/zshrc /root/.zshrc 19 | 20 | COPY docker/bashrc /etc/skel/.bashrc 21 | COPY docker/zshrc /etc/skel/.zshrc 22 | 23 | RUN echo "Installing bats-core/bats-core (Bash unit testing)" \ 24 | && git clone -q https://github.com/bats-core/bats-core.git /tmp/bats-core \ 25 | && cd /tmp/bats-core \ 26 | && ./install.sh /usr \ 27 | && cd && rm -rf /tmp/bats-core 28 | 29 | RUN adduser --gecos "" --disabled-password testuser 30 | 31 | WORKDIR /root/sgshell 32 | ENTRYPOINT [ "bash" ] 33 | 34 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | +===================================================+ 2 | | © 2019 Privex Inc. | 3 | | https://www.privex.io | 4 | +===================================================+ 5 | | | 6 | | Privex ShellCore | 7 | | | 8 | | Core Developer(s): | 9 | | | 10 | | (+) Chris (@someguy123) [Privex] | 11 | | | 12 | +===================================================+ 13 | 14 | Copyright (C) 2019 Privex Inc. (https://www.privex.io) 15 | 16 | This program is free software: you can redistribute it and/or modify 17 | it under the terms of the GNU General Public License as published by 18 | the Free Software Foundation, either version 3 of the License, or 19 | (at your option) any later version. 20 | 21 | This program is distributed in the hope that it will be useful, 22 | but WITHOUT ANY WARRANTY; without even the implied warranty of 23 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 24 | GNU General Public License for more details. 25 | 26 | You should have received a copy of the GNU General Public License 27 | along with this program. If not, see . 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Privex's Shell Core 2 | 3 | A library of shell functions designed to ease the development of shell scripts written for both `bash` and `zsh`. 4 | 5 | # What's included 6 | 7 | - Core functions 8 | - `len` - Check the length of passed arguments, e.g. `len 'hello'` would output `5` 9 | - `has_command` - Returns 0 (true) if a requested command exists (function/alias/binary) 10 | - `has_binary` - Returns 0 (true) if a command exists as a binary (not an alias/function) 11 | - `ident_shell` - Identify the current shell (either bash, zsh or unknown) 12 | - `sudo` - Wrapper function designed to prevent issues on systems which don't have `sudo` installed 13 | - GnuSafe (`lib/000_gnusafe.sh`) - A function to ensure calls to `sed`, `awk` and `grep` are always the GNU 14 | versions, rather than BSD - preventing strange issues on non-Linux systems. 15 | It detects whether or not the running system is Linux or a BSD, if the system is a BSD, it will attempt to alias `sed` / `awk` and `grep` to gsed/gawk/ggrep. If the GNU versions are missing, it will display a warning 16 | letting the user know they need to install certain GNU utils. 17 | - Error handling helpers 18 | - `base/trap.bash` is a painless plug-n-play error handler specifically for Bash scripts, which offers 19 | pretty printed tracebacks, stderr tracking, and attempts to identify the line of code causing the issue 20 | in a readable way to assist with fixing bugs. 21 | - `lib/000_trap_helper.sh` is a set of functions designed to make handling shell script errors easier, 22 | some of which work on both bash and zsh. 23 | - `get_trap_cmd` - shows the code currently tied to a given signal (e.g. `INT` `USR1` or `EXIT`) 24 | - `trap_add` - appends to / creates a trap signal, allowing you to easily add multiple functions to 25 | bash/zsh traps, instead of just overwriting the trap. 26 | - `add_on_exit` - appends shellscript code to be ran when the script terminates. if the script is 27 | running on Bash, then it will append to the `EXIT` trap. if the script is running on ZSH, then it 28 | will append to the `zshexit` function (or create it if it doesn't exist). 29 | - Coloured / Timestamped messages 30 | - Inside of `base/colors.sh` is a set of bash+zsh compatible formatted message functions 31 | - `msg` allows you to easily output both plain and coloured messages, e.g. `msg bold red hello world` 32 | - `msgerr` works the same as `msg` but outputs your message to stderr instead of stdout 33 | - `msgts` (or `msg ts` / `msgerr ts`) adds a timestamp to the start of your message 34 | e.g. `msgts hello world` would print `[2019-11-25 22:47:38 GMT] hello world` 35 | - General helper functions (`lib/010_helpers.sh`) 36 | - `containsElement` - returns 0 (true) if `$1` exists in the array `$2` 37 | 38 | e.g. `x=(hello world); if containsElement "hello" "${x[@]}"; then echo 'hello is in x'; fi` would print 39 | `hello is in x` 40 | - `yesno` - (bash only) yes/no prompts made as simple as an `if` statement (or `||` / `&&`). 41 | 42 | `yesno "Are you sure? (y/n) > " && echo "You said yes" || echo "You said no"` 43 | - `pkg_not_found` - Check if the command `$1` is available. If not, install `$2` via apt 44 | (can override package install command via PKG_MGR_INSTALL) 45 | 46 | Example - If `lz4` doesn't exist, install package `liblz4-tool`: `pkg_not_found lz4 liblz4-tool` 47 | 48 | - `split_by` - Split a string `$1` into an array by the character `$2` 49 | 50 | `x=($(split_by "hello-world-abc" "-")); echo "${x[0]}";` would print `hello` 51 | 52 | - `split_assoc` - Split a string into an associative array (key value pairs). Due to limitations with 53 | exporting associative arrays in both zsh/bash, you must source the temporary file which the 54 | function prints to load the array. 55 | 56 | `source $(split_assoc "hello:world,lorem:ipsum" "," ":"); echo "${assoc_result[hello]}"` would print `world`. 57 | 58 | 59 | 60 | # Usage 61 | 62 | **Automatically install ShellCore if it's missing on the first run** 63 | 64 | This is the recommended method, as it means you don't have to bundle ShellCore with small scripts. 65 | 66 | Below is a short snippet that you can place at the start of your script or main shell file, which will: 67 | 68 | - Check if ShellCore is installed at all - locally or globally 69 | - If not, attempt to automatically install ShellCore if we failed to find an installation. The installation script is fully 70 | unattended - errors are sent to **stderr**. 71 | - If the installation fails, then output an error message to **stderr** and exit the script with a non-zero return code. 72 | - Attempt to load ShellCore from `~/.pv-shcore` (local) first, then fallback to `/usr/local/share/pv-shcore` (global) 73 | 74 | ```bash 75 | # Error handling function for ShellCore 76 | _sc_fail() { >&2 echo "Failed to load or install Privex ShellCore..." && exit 1; } 77 | # If `load.sh` isn't found in the user install / global install, then download and run the auto-installer 78 | # from Privex's CDN. 79 | [[ -f "${HOME}/.pv-shcore/load.sh" ]] || [[ -f "/usr/local/share/pv-shcore/load.sh" ]] || \ 80 | { curl -fsS https://cdn.privex.io/github/shell-core/install.sh | bash >/dev/null; } || _sc_fail 81 | 82 | # Attempt to load the local install of ShellCore first, then fallback to global install if it's not found. 83 | [[ -d "${HOME}/.pv-shcore" ]] && source "${HOME}/.pv-shcore/load.sh" || \ 84 | source "/usr/local/share/pv-shcore/load.sh" || _sc_fail 85 | 86 | # Optionally, you may wish to run `autoupdate_shellcore` after loading it. This will quietly update ShellCore to 87 | # the latest version. 88 | # To avoid auto-updates causing slow load times, by default they'll only be triggered at most once per week. 89 | # You can also use `update_shellcore` from within your script to force a ShellCore update. 90 | autoupdate_shellcore 91 | ``` 92 | 93 | **Bundling with your application** 94 | 95 | You can also simply `git clone https://github.com/Privex/shell-core.git` and place it within your project, or use a Git Submodule. 96 | 97 | If you're concerned about ShellCore updates potentially breaking your script, then this may be the preferred option - as any other 98 | shellscript project (or a user) on the system could trigger updates to the local/global ShellCore installation. 99 | 100 | # Features 101 | 102 | **Bash Error Handler** 103 | 104 | ![Screenshot of Error Handler](http://cdn.privex.io/github/shell-core/shellcore_errorhandler.png) 105 | 106 | Included with ShellCore's various helpers, is a bash module in `base/trap.bash` - which adds python-like error handling 107 | to any bash script, with tracebacks, the file and line number of the problematic code, etc. 108 | 109 | It's known to work on both Mac OSX as well as Ubuntu Linux Server, and may work on other OS's too. 110 | 111 | The error handling module is based on a snippet posted to Stack Overflow by Luca Borrione - Source: https://stackoverflow.com/a/13099228 112 | 113 | # Unit Tests 114 | 115 | To help with detection of accidental breakage and bugs, we try to add unit tests where possible for ShellCore. 116 | 117 | We use [BATS for unit testing](https://github.com/bats-core/bats-core), which is a unit testing system for Bash. 118 | 119 | To run the tests, you first need to [install BATS](https://github.com/bats-core/bats-core). If you're on OSX, just run `brew install bats-core` 120 | 121 | **Running tests.bats directly** 122 | 123 | The simplest way to run the tests is to just execute `tests.bats` - as it has the appropriate shebang and should be executable. 124 | 125 | ```bash 126 | $ ./tests.bats 127 | ✓ test has_binary returns zero with existant binary (ls) 128 | ✓ test has_binary returns non-zero with non-existant binary (thisbinaryshouldnotexit) 129 | ✓ test has_binary returns non-zero for existing function but non-existant binary (example_test_func) 130 | ✓ test has_command returns zero for existing function but non-existant binary (example_test_func) 131 | ✓ test has_command returns zero for non-existing function but existant binary (ls) 132 | ... 133 | 19 tests, 0 failures 134 | 135 | ``` 136 | 137 | **Running tests.bats via the bats program** 138 | 139 | You can also run the tests via the `bats` program itself. This gives you more customization, e.g. you can run it in TAPS mode 140 | with the `-t` flag (often required for compatibility with automated testing systems like Travis). 141 | 142 | ```bash 143 | $ bats -t tests.bats 144 | 1..19 145 | ok 1 test has_binary returns zero with existant binary (ls) 146 | ok 2 test has_binary returns non-zero with non-existant binary (thisbinaryshouldnotexit) 147 | ok 3 test has_binary returns non-zero for existing function but non-existant binary (example_test_func) 148 | ok 4 test has_command returns zero for existing function but non-existant binary (example_test_func) 149 | ok 5 test has_command returns zero for non-existing function but existant binary (ls) 150 | ``` 151 | 152 | 153 | # License 154 | 155 | ``` 156 | +===================================================+ 157 | | © 2019 Privex Inc. | 158 | | https://www.privex.io | 159 | +===================================================+ 160 | | | 161 | | Privex ShellCore | 162 | | | 163 | | Core Developer(s): | 164 | | | 165 | | (+) Chris (@someguy123) [Privex] | 166 | | | 167 | +===================================================+ 168 | 169 | Copyright (C) 2019 Privex Inc. (https://www.privex.io) 170 | 171 | This program is free software: you can redistribute it and/or modify 172 | it under the terms of the GNU General Public License as published by 173 | the Free Software Foundation, either version 3 of the License, or 174 | (at your option) any later version. 175 | 176 | This program is distributed in the hope that it will be useful, 177 | but WITHOUT ANY WARRANTY; without even the implied warranty of 178 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 179 | GNU General Public License for more details. 180 | 181 | You should have received a copy of the GNU General Public License 182 | along with this program. If not, see . 183 | 184 | ``` 185 | 186 | -------------------------------------------------------------------------------- /base/colors.sh: -------------------------------------------------------------------------------- 1 | # Used by dependent scripts to check if this file has been sourced or not. 2 | export SRCED_COLORS=1 3 | 4 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 5 | _XDIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 6 | 7 | # # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 8 | # # script is located, and then source map_libs.sh using a relative path from this script. 9 | # { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ] } && source "${_XDIR}/../map_libs.sh" || true 10 | # Mark this library script as loaded successfully 11 | [ -z ${SG_LIB_LOADED[@]+x} ] && source "${_XDIR}/../map_libs.sh" 12 | SG_LIB_LOADED[colors]=1 13 | 14 | # # Check whether 'core_func' has already been sourced, otherwise source it using the path stored in SG_LIBS 15 | # ((SG_LIB_LOADED[core_func]==1)) || source "${SG_LIBS[core_func]}" 16 | 17 | # [ -z ${SRCED_SG_CORE+x} ] && source "${DIR}/../core/core_func.sh" 18 | 19 | 20 | if [ -t 1 ]; then 21 | if command -v tput &>/dev/null; then 22 | BOLD="$(tput bold)" RED="$(tput setaf 1)" GREEN="$(tput setaf 2)" YELLOW="$(tput setaf 3)" BLUE="$(tput setaf 4)" 23 | PURPLE="$(tput setaf 5)" MAGENTA="$(tput setaf 5)" CYAN="$(tput setaf 6)" WHITE="$(tput setaf 7)" 24 | RESET="$(tput sgr0)" NORMAL="$(tput sgr0)" 25 | else 26 | BOLD='\033[1m' RED='\033[00;31m' GREEN='\033[00;32m' YELLOW='\033[00;33m' BLUE='\033[00;34m' 27 | PURPLE='\033[00;35m' MAGENTA='\033[00;35m' CYAN='\033[00;36m' WHITE='\033[01;37m' 28 | RESET='\033[0m' NORMAL='\033[0m' 29 | fi 30 | else 31 | BOLD="" RED="" GREEN="" YELLOW="" BLUE="" 32 | MAGENTA="" CYAN="" WHITE="" RESET="" 33 | fi 34 | 35 | ##### 36 | # Easy coloured messages function 37 | # Written by @someguy123 38 | # Usage: 39 | # # Prints "hello" and "world" across two lines in the default terminal color 40 | # msg "hello\nworld" 41 | # 42 | # # Prints " this is an example" in green text 43 | # msg green "\tthis" is an example 44 | # 45 | # # Prints "An error has occurred" in bold red text 46 | # msg bold red "An error has occurred" 47 | # 48 | ##### 49 | function msg () { 50 | local _color="" _dt="" _msg="" _bold="" 51 | if [[ "$#" -eq 0 ]]; then echo ""; return; fi; 52 | [[ "$1" == "ts" ]] && shift && _dt="[$(date +'%Y-%m-%d %H:%M:%S %Z')] " || _dt="" 53 | if [[ "$#" -gt 1 ]] && [[ "$1" == "bold" ]]; then 54 | _bold="${BOLD}" 55 | shift 56 | fi 57 | (($#==1)) || _msg="${@:2}" 58 | 59 | case "$1" in 60 | bold) _color="${BOLD}";; 61 | BLUE|blue) _color="${BLUE}";; 62 | YELLOW|yellow) _color="${YELLOW}";; 63 | RED|red) _color="${RED}";; 64 | GREEN|green) _color="${GREEN}";; 65 | CYAN|cyan) _color="${CYAN}";; 66 | MAGENTA|magenta|PURPLE|purple) _color="${MAGENTA}";; 67 | * ) _msg="$1 ${_msg}";; 68 | esac 69 | 70 | (($#==1)) && _msg="${_dt}$1" || _msg="${_color}${_bold}${_dt}${_msg}" 71 | echo -e "$_msg${RESET}" 72 | } 73 | 74 | # Alias for 'msg' function with timestamp on the left. 75 | function msgts () { 76 | msg ts "${@:1}" 77 | } 78 | 79 | function msgerr () { 80 | # Same as `msg` but outputs to stderr instead of stdout 81 | >&2 msg "$@" 82 | } 83 | 84 | 85 | if [[ $(ident_shell) == "bash" ]]; then 86 | export -f msg msgts >/dev/null 87 | elif [[ $(ident_shell) == "zsh" ]]; then 88 | export msg msgts >/dev/null 89 | else 90 | >&2 echo -e "${RED}${BOLD}WARNING: Could not identify your shell. Attempting to export msg and msgts with plain export..." 91 | export msg msgts 92 | fi 93 | 94 | export RED GREEN YELLOW BLUE BOLD NORMAL RESET 95 | 96 | -------------------------------------------------------------------------------- /base/permission.sh: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # # 3 | # Privex's Shell Core # 4 | # Cross-platform / Cross-shell helper functions # 5 | # # 6 | # Released under the GNU GPLv3 # 7 | # # 8 | # Official Repo: github.com/Privex/shell-core # 9 | # # 10 | ############################################################# 11 | 12 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 13 | _XDIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 14 | 15 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 16 | # script is located, and then source map_libs.sh using a relative path from this script. 17 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 18 | SG_LIB_LOADED[permission]=1 # Mark this library script as loaded successfully 19 | sg_load_lib colors # Check whether 'colors' has already been sourced, otherwise source it. 20 | 21 | # [ -z ${SRCED_COLORS+x} ] && source "${DIR}/colors.sh" 22 | 23 | ##### 24 | # Check if there are directory permissions issues affecting access to a file. 25 | # Based on the StackOverflow answer https://unix.stackexchange.com/a/82349 and modified by Someguy123 into a function 26 | # with return codes and zsh compatibility. 27 | # 28 | # If there's a problem, it prints a red message to stderr specifying the first directory in the path which is non-executable. 29 | # 30 | # Example: 31 | # if path_permission "/root/.ssh/authorized_keys"; then 32 | # # do something with the file, maybe further read/write checks 33 | # else 34 | # >&2 echo "Could not access /root/.ssh/authorized_keys due to a directory being non-executable" 35 | # fi 36 | # 37 | ##### 38 | path_permission() { 39 | local pm_file="$1" pm_path="" part parts 40 | [[ "$pm_file" != /* ]] && pm_path="." 41 | parts=($(dirname "$pm_file" | tr '/' $'\n')) 42 | for part in "${parts[@]}"; do 43 | pm_path="$pm_path/$part" 44 | # Check for execute permissions 45 | if ! [[ -x "$pm_path" ]] ; then 46 | msgerr red "Cannot access file/folder '$pm_file' because '$pm_path' isn't +x - please run 'sudo chmod +x \"$pm_path\"' to resolve this." 47 | return 1 48 | fi 49 | done 50 | return 0 51 | } 52 | 53 | ##### 54 | # can_read [file|folder] 55 | # Check if we have read permission to a file/folder, while also checking that each folder in the path 56 | # is executable - alerts with a red message to stderr if a folder in the path is not executable. 57 | ##### 58 | can_read() { 59 | path_permission "$1" && [ -r "$1" ] && return 0 || return 1 60 | } 61 | 62 | ##### 63 | # can_write [file|folder] 64 | # Check if we have write permission to a file/folder, while also checking that each folder in the path 65 | # is executable - alerts with a red message to stderr if a folder in the path is not executable. 66 | ##### 67 | can_write() { 68 | path_permission "$1" && [ -w "$1" ] && return 0 || return 1 69 | } 70 | 71 | -------------------------------------------------------------------------------- /base/trap.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | # 13 | # This long bash script adds automatic detailed error handling to any bash script, including: 14 | # 15 | # - A function traceback, similar to Python 16 | # - Shows the numeric error code and the file which triggered the error 17 | # - Shows the line number which caused the error (if known) 18 | # - Prints the function / line of code believed to have triggered the error (if known) 19 | # - Shows the error message related to the error (if known) 20 | # 21 | # Simply source this file in your bash script and you're done :) 22 | # You can raise custom errors using `raise_error` if needed. 23 | # 24 | # If something isn't working correctly with this error handling, set `enable_trap_debug=1` in your shell. 25 | # 26 | # export enable_trap_debug=1 27 | # 28 | # This will enable detailed debugging messages (outputted to stderr) helping you to diagnose 29 | # which part is going wrong. 30 | # 31 | # ========================================================================================================= 32 | # 33 | # Usage (from within an application already using ShellCore): 34 | # 35 | # source "${SG_DIR}/base/trap.bash" 36 | # 37 | # If you need to temporarily disable the error handling: 38 | # 39 | # somefunc() { # This is an example function which always returns 1 (a non-zero exit code to trigger errors) 40 | # return 1 41 | # } 42 | # otherfunc() { 43 | # error_control 1 # Ignore the following non-zero return, but handle any non-zero returns after this. 44 | # somefunc # This non-zero returning function would work the first time 45 | # somefunc # ...but trigger a fatal error the second time, as error handling would be re-enabled. 46 | # 47 | # # To disable error handling semi-permanently, pass 2 instead of 1, which disables error handling 48 | # # until you manually re-enable it with 'error_control 0' 49 | # error_control 2 50 | # 51 | # # We can now run somefunc 3 times, despite the non-zero return codes 52 | # somefunc; somefunc; somefunc; 53 | # 54 | # error_control 0 # Re-enable error handling 55 | # somefunc # This will trigger the error handler now, as error handling has been re-enabled. 56 | # } 57 | # 58 | # ========================================================================================================= 59 | # 60 | # This trap error handling code was originally found on StackOverflow here: 61 | # https://stackoverflow.com/a/13099228 62 | # Originally written by Luca Borrione on StackOverflow: 63 | # https://stackoverflow.com/users/1032370/luca-borrione 64 | # 65 | # Modified by Chris (@someguy123) @ Privex Inc. :: 66 | # 67 | # - Better POSIX compatibility, so it works on both Linux and OSX 68 | # - Added FIFO named pipes so that stderr can be printed at the same time as being logged 69 | # - Added _trap_debug to assist with debugging this trap error handling system 70 | # - Improved detection of the file / line which caused the error 71 | # - Prints the line of code which triggered the error, if known 72 | # - Added `raise_err` function for custom error handling 73 | # - Improved readability of error output 74 | # 75 | ############################################################# 76 | 77 | lib_name='trap' 78 | lib_version=20191008 79 | 80 | : ${enable_trap_debug=0} # 0 = disable debugging messages, 1 = enable debugging messages 81 | : ${trap_debug_stderr=1} # 0 = output debugging messages to stdout // 1 = output debugging to stderr 82 | : ${stderr_log="$(mktemp).log"} # Randomly generated file in a temp folder for logging stderr into 83 | 84 | # Set this to 1 within a function to ignore the next non-zero return code. Automatically re-set's to 0 after a non-zero. 85 | # Set to 2 to permanently ignore non-zero return codes until you manually reset IGNORE_ERR back to 0 86 | export IGNORE_ERR=0 87 | 88 | # 89 | # TO BE SOURCED ONLY ONCE: 90 | # 91 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 92 | 93 | set +u # Temporarily allow uninitialised vars so we can test for g_libs 94 | 95 | if (("${g_libs[$lib_name]+_}")); then 96 | return 0 97 | else 98 | if ((${#g_libs[@]}==0)); then 99 | declare -A g_libs 100 | fi 101 | g_libs[$lib_name]=$lib_version 102 | fi 103 | 104 | _TRAP_LAST_LINE="" 105 | _TRAP_LAST_CALLER="" 106 | _TRAP_ERR_CALL=0 107 | : ${SRCED_000LOG=""} 108 | 109 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 110 | __TRAP_DIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 111 | # __DIR="$__TRAP_DIR" 112 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 113 | # script is located, and then source map_libs.sh using a relative path from this script. 114 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${__TRAP_DIR}/../map_libs.sh" || true 115 | SG_LIB_LOADED[traplib]=1 # Mark this library script as loaded successfully 116 | # Check whether 'colors', 'trap_helper' and 'logging' have already been sourced, otherwise source em. 117 | sg_load_lib trap_helper colors logging 118 | # source "${__TRAP_DIR}/colors.sh" 119 | 120 | _trap_debug () { 121 | local dbg_msg="[DEBUG trap.bash]${RESET} $@" 122 | (($enable_trap_debug==0)) || { (($trap_debug_stderr==0)) && msg ts yellow "$dbg_msg" || msgerr ts yellow "$dbg_msg"; } 123 | } 124 | 125 | # 126 | # MAIN CODE: 127 | # 128 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 129 | 130 | set -o pipefail # trace ERR through pipes 131 | set -o errtrace # trace ERR through 'time command' and other functions 132 | set -o nounset ## set -u : exit the script if you try to use an uninitialised variable 133 | set -o errexit ## set -e : exit the script if any statement returns a non-true return value 134 | 135 | # #### 136 | # # Log stderr to '$stderr_log' using a named pipe (fifo) with tee, this allows us to log stderr 137 | # # and have it printed to the screen at the same time. 138 | # #### 139 | # _trap_log_pipe=$(mktemp -u) 140 | # mkfifo "$_trap_log_pipe" 141 | # >&2 tee <"$_trap_log_pipe" "$stderr_log" & 142 | # # Backup the stderr descriptor (2) into descriptor 4 for later restoration 143 | # exec 4>&2 2> "$_trap_log_pipe" 144 | 145 | # [ -z ${SRCED_000LOG} ] && source "$SG_DIR/lib/000_logging.sh" 146 | 147 | 148 | _handle_ignore_err () { 149 | (($IGNORE_ERR==1)) && IGNORE_ERR=0 && _trap_debug "Ignoring error (1)" && set -eE && return 1 150 | (($IGNORE_ERR==2)) && _trap_debug "Ignoring error (2)" && return 1 151 | # IGNORE_ERR 5 is set by `error_control` so that error_control returning doesn't cause IGNORE_ERRORS to be reset back to 0 152 | (($IGNORE_ERR==5)) && IGNORE_ERR=1 && _trap_debug "Resetting IGNORE_ERRORS to 1" && return 1 153 | return 0 154 | } 155 | 156 | 157 | error_control () { 158 | # Enable/Disable automatic error handling and bash exit-on-err setting. 159 | # Argument 1: 160 | # 0 = handle errors 1 = ignore the next non-zero error 2 = ignore errors until manually changed back to normal 161 | # 162 | # Example: 163 | # somefunc() { 164 | # error_control 1 # Ignore the following non-zero return, but handle any non-zero returns after this. 165 | # return 1 166 | # } 167 | # 168 | # If no ignore code was passed as the first arg, then just flip IGNORE_ERR 169 | # between 0 (handle errors) and 1 (ignore the next non-zero code), plus enable/disable the 'eE' flags. 170 | if (($#==0)); then 171 | if (($IGNORE_ERR==0)); then 172 | set +eE 173 | IGNORE_ERR=5 174 | return 175 | fi 176 | set -eE 177 | IGNORE_ERR=0 178 | return 179 | fi 180 | (($1==1)) && IGNORE_ERR=5 || IGNORE_ERR=$(($1)) 181 | _trap_debug "Set IGNORE_ERR to $IGNORE_ERR" 182 | (($1==0)) && set -eE || set +eE 183 | } 184 | 185 | function raise_error () { 186 | # Outputs an error message to stderr in bash error format, then calls `exit`. This allows the trap function 187 | # `exit_handler` to correctly display the error in a user readable format. 188 | # 189 | # All arguments are optional, but the message, script, and line number strongly recommended for accurate error details. 190 | # 191 | # Usage: 192 | # raise_error [message] [your_script] [line_num] [exit_code] 193 | # Example: 194 | # raise_error "Error while doing x" "${BASH_SOURCE[0]}" $LINENO 195 | # 196 | local _caller="$(basename $0)" _lnum="line 0" _errmsg="An unknown error occurred, but no message was given." 197 | local _excode=1 198 | 199 | (($#>0)) && _errmsg="$1"; (($#>1)) && _caller="$2"; (($#>2)) && _lnum="line $3"; (($#>3)) && _excode=$(($4)) 200 | >&2 echo "${_caller}: ${_lnum}: ${_errmsg}" 201 | exit $_excode 202 | } 203 | 204 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 205 | # 206 | # FUNCTION: EXIT_HANDLER 207 | # 208 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 209 | 210 | function exit_handler () 211 | { 212 | local error_code="$?" 213 | _handle_ignore_err || return 214 | # Restore stderr descriptor (2) from the copy we made in descriptor 4 215 | exec 2>&4 216 | 217 | 218 | # msgerr "code: $error_code arg 1: $1 arg 2: $2" 219 | _trap_debug "Logging stderr to file: $stderr_log" 220 | _trap_debug "Running exit handler" 221 | (($error_code==0)) && _trap_debug "Return code 0 - ignoring." && return; 222 | _trap_debug "Non-zero return code" 223 | 224 | # Disable exit on non-zero, and raising errors for unset variables 225 | # to ensure the error handler doesn't get disrupted 226 | set +eu 227 | 228 | # 229 | # LOCAL VARIABLES: 230 | # ------------------------------------------------------------------ 231 | # 232 | local i=0 233 | local regex='' 234 | local mem='' 235 | 236 | local error_file="$(basename $0)" 237 | local error_lineno='' 238 | local error_message='unknown' 239 | local error_func='' 240 | 241 | local lineno='' 242 | 243 | # 244 | # PRINT THE HEADER: 245 | # ------------------------------------------------------------------ 246 | # 247 | msgerr bold red "\n(!) ERROR HANDLER:\n" 248 | 249 | 250 | # 251 | # GETTING LAST ERROR OCCURRED: 252 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 253 | 254 | # 255 | # Read last file from the error log 256 | # ------------------------------------------------------------------ 257 | # 258 | if [ -f "$stderr_log" ]; then 259 | _trap_debug "Found log at $stderr_log" 260 | stderr=$( tail -n 1 "$stderr_log" ) 261 | _trap_debug "Log last line: $stderr" 262 | if (($enable_trap_debug==1)); then 263 | _trap_debug "Not deleting error log file as 'enable_trap_debug' is enabled." 264 | _trap_debug "Full stderr log can be found at: $stderr_log" 265 | else 266 | rm "$stderr_log" 267 | fi 268 | fi 269 | 270 | # 271 | # Managing the line to extract information: 272 | # ------------------------------------------------------------------ 273 | # 274 | 275 | if [ -n "$stderr" ]; then 276 | _trap_debug "\$stderr not empty." 277 | #### 278 | # This 'if' block parses the standard bash error output format from the stderr log, which looks like this: 279 | # ./run.sh: line 192: unexpected error removing comments 280 | ### 281 | # Exploding stderr on : 282 | mem="$IFS" 283 | local shrunk_stderr=$( echo "$stderr" | sed -E 's/\: /\:/g' ) 284 | IFS=':' 285 | local stderr_parts=( $shrunk_stderr ) 286 | IFS="$mem" 287 | # Storing information on the error 288 | if ((${#stderr_parts[@]}>=2)); then 289 | _trap_debug "Extracting file/line no from parts: ${stderr_parts[@]}" 290 | error_file="${stderr_parts[0]}" 291 | (($_TRAP_ERR_CALL==0)) && error_lineno="${stderr_parts[1]}" 292 | error_message="" 293 | 294 | _trap_debug "Building error_message from stderr_parts" 295 | for (( i = 3; i <= ${#stderr_parts[@]}; i++ )); do 296 | error_message="$error_message "${stderr_parts[$i-1]}": " 297 | done 298 | 299 | # Removing last ':' (colon character) 300 | error_message="${error_message%:*}" 301 | 302 | # Trim 303 | _trap_debug "Trimming error_message with sed" 304 | error_message="$( echo "$error_message" | sed -E 's/^[ \t]*//' | sed -E 's/[ \t]*$//' )" 305 | else 306 | _trap_debug "Not extracting file/line as not enough stderr_parts: ${stderr_parts[@]}" 307 | fi 308 | fi 309 | 310 | _trap_debug "Getting backtrace" 311 | # 312 | # GETTING BACKTRACE: 313 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 314 | _backtrace=$( backtrace 2 ) 315 | 316 | 317 | # 318 | # MANAGING THE OUTPUT: 319 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 320 | _trap_debug "Parsing error data with regex" 321 | local lineno="" 322 | regex='^([a-z]{1,}) ([0-9]{1,})$' 323 | 324 | if [[ $error_lineno =~ $regex ]]; then 325 | _trap_debug "error line number (error_lineno) was found" 326 | # The error line was found on the log 327 | # (e.g. type 'ff' without quotes wherever) 328 | # -------------------------------------------------------------- 329 | 330 | local row="${BASH_REMATCH[1]}" 331 | lineno="${BASH_REMATCH[2]}" 332 | 333 | msgerr white "FILE:\t\t${error_file}" 334 | msgerr white "${row^^}:\t\t${lineno}\n" 335 | 336 | msgerr white "ERROR CODE:\t${error_code}" 337 | msgerr yellow "ERROR MESSAGE:\n" 338 | msgerr white "\t$error_message\n" 339 | 340 | else 341 | regex="^${error_file}\$|^${error_file}\s+|\s+${error_file}\s+|\s+${error_file}\$" 342 | _trap_debug "error line number (error_lineno) NOT found. scanning backtrace with regex: $regex" 343 | if [[ "$_backtrace" =~ $regex ]]; then 344 | _trap_debug "_backtrace matched regex" 345 | # The file was found on the log but not the error line 346 | # (could not reproduce this case so far) 347 | # ------------------------------------------------------ 348 | 349 | msgerr white "FILE:\t\t$error_file" 350 | msgerr white "ROW:\t\tunknown\n" 351 | 352 | msgerr white "ERROR CODE:\t${error_code}" 353 | msgerr yellow "ERROR MESSAGE:\n" 354 | msgerr white "\t${stderr}\n" 355 | else 356 | _trap_debug "_backtrace did not match regex..." 357 | # Neither the error line nor the error file was found on the log 358 | # (e.g. type 'cp ffd fdf' without quotes wherever) 359 | # ------------------------------------------------------ 360 | # 361 | # The error file is the first on backtrace list: 362 | 363 | # Exploding backtrace on newlines 364 | mem=$IFS 365 | IFS=' 366 | ' 367 | # 368 | # Substring: I keep only the carriage return 369 | # (others needed only for tabbing purpose) 370 | IFS=${IFS:0:1} 371 | local lines=( $_backtrace ) 372 | 373 | IFS=$mem 374 | 375 | 376 | if [ -n "${lines[1]}" ]; then 377 | array=( ${lines[1]} ) 378 | _trap_debug "Lines are: ${lines[1]}" 379 | _trap_debug "Array is: ${array[@]}" 380 | # if ((${#array[@]})) 381 | error_file="" 382 | for (( i=2; i<${#array[@]}; i++ )) 383 | do 384 | _trap_debug "appending to error_file: $error_file --- value: ${array[$i]}" 385 | error_file="$error_file ${array[$i]}" 386 | done 387 | _trap_debug "out of loop error_file: $error_file" 388 | # Trim 389 | error_file="$( echo "$error_file" | sed -E 's/^[ \t]*//' | sed -E 's/[ \t]*$//' )" 390 | fi 391 | 392 | msgerr white "FILE:\t\t$error_file" 393 | if (($_TRAP_ERR_CALL==1)); then 394 | msgerr white "ROW:\t\t$_TRAP_LAST_LINE\n" 395 | msgerr white "Line which triggered the error:\n\n\t$_TRAP_LAST_CALLER\n\n" 396 | else 397 | msgerr white "ROW:\t\tunknown\n" 398 | fi 399 | 400 | msgerr white "ERROR CODE:\t${error_code}" 401 | if [ -n "${stderr}" ]; then 402 | msgerr yellow "ERROR MESSAGE:\n" 403 | msgerr white "\t${stderr}\n" 404 | else 405 | msgerr yellow "ERROR MESSAGE:\n" 406 | msgerr white "\t${error_message}\n" 407 | fi 408 | fi 409 | fi 410 | _trap_debug "Attempting to print backtrace" 411 | # 412 | # PRINTING THE BACKTRACE: 413 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 414 | 415 | msgerr bold blue "\nTraceback:" 416 | # msgerr bold "\n$_backtrace\n" 417 | msgerr bold "\n$(trap_traceback 1)\n" 418 | 419 | # 420 | # EXITING: 421 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 422 | 423 | msgerr bold red "Exiting!" 424 | 425 | exit "$error_code" 426 | } 427 | 428 | trap_err_handler() { 429 | local _ret="$?" 430 | (($_ret==0)) && return 431 | _handle_ignore_err || return 432 | 433 | _TRAP_LAST_LINE="$1" 434 | _TRAP_LAST_CALLER="$2" 435 | _TRAP_ERR_CALL=1 436 | exit $_ret 437 | } 438 | 439 | trap_prepend 'exit_handler' EXIT # ! ! ! TRAP EXIT ! ! ! 440 | trap_prepend 'trap_err_handler ${LINENO} "$BASH_COMMAND"' ERR # ! ! ! TRAP ERR ! ! ! 441 | 442 | 443 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 444 | # 445 | # FUNCTION: BACKTRACE 446 | # 447 | ###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~## 448 | 449 | function backtrace 450 | { 451 | local _start_from_=0 452 | 453 | local params=( "$@" ) 454 | if (( "${#params[@]}" >= "1" )); then 455 | _start_from_="$1" 456 | fi 457 | 458 | local i=0 459 | local first=0 460 | while caller $i > /dev/null 461 | do 462 | if [ -n "$_start_from_" ] && (( "$i" + 1 >= "$_start_from_" )); then 463 | if (($first==0));then 464 | first=1 465 | fi 466 | echo " $(caller $i)" 467 | fi 468 | let "i=i+1" 469 | done 470 | } 471 | 472 | 473 | function trap_traceback 474 | { 475 | # Hide the trap_traceback() call. 476 | local -i start=$(( ${1:-0} + 1 )) 477 | local -i end=${#BASH_SOURCE[@]} 478 | local -i i=0 479 | local -i j=0 480 | 481 | for ((i=start; i < end; i++)); do 482 | j=$(( i - 1 )) 483 | local function="${FUNCNAME[$i]}" 484 | local file="${BASH_SOURCE[$i]}" 485 | local line="${BASH_LINENO[$j]}" 486 | echo " ${function}() in ${file}:${line}" 487 | done 488 | } 489 | 490 | return 0 491 | -------------------------------------------------------------------------------- /core/000_core_func.sh: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # # 3 | # Privex's Shell Core # 4 | # Cross-platform / Cross-shell helper functions # 5 | # # 6 | # Released under the GNU GPLv3 # 7 | # # 8 | # Official Repo: github.com/Privex/shell-core # 9 | # # 10 | ############################################################# 11 | # 12 | # This file contains essential functions, which are not only 13 | # helpers for use by dependent shellscript projects, but 14 | # also essential for many parts of ShellCore itself, such as 15 | # initialization or installation of ShellCore. 16 | # 17 | # Functions: 18 | # 19 | # has_command has_binary ident_shell sudo 20 | # 21 | ############################################################# 22 | 23 | SRCED_SGCORE=1 24 | 25 | 26 | # just a small wrapper around wc to pipe in all args 27 | # saves constantly piping it in 28 | # $ len "hello" 29 | # 5 30 | # 31 | len() { local l=$(wc -c <<< "${@:1}"); echo $((l-1)); } 32 | 33 | # Returns 0 (true) if a requested command exists (WARNING: this will match functions and aliases too) 34 | # Use `has_binary` if you want to specifically only test for binaries 35 | # Example: 36 | # has_command zip && echo "zip has binary or alias/function" || echo "error: zip not found" 37 | # 38 | has_command() { 39 | command -v "$1" > /dev/null 40 | } 41 | 42 | # Returns 0 (true) if the requested command exists as a binary (not as an alias/function) 43 | # Example: 44 | # has_binary git && echo "the binary 'git' is available" || echo "could not find binary 'git' using which" 45 | # 46 | has_binary() { 47 | /usr/bin/env which "$1" > /dev/null 48 | } 49 | 50 | 51 | ident_shell() { 52 | #### 53 | # Attempt to identify the shell we're running in. 54 | # Example uses: 55 | # 56 | # # Reading the echo output 57 | # { [[ $(ident_shell) == "zsh" ]] && echo "Running in zsh"; } || \ 58 | # { [[ $(ident_shell) == "bash" ]] && echo "Running in bash"; } || \ 59 | # echo "Unsupported Shell!" && exit 1 60 | # 61 | # # Using the CURRENT_SHELL var 62 | # ident_shell >/dev/null 63 | # if [[ "$CURRENT_SHELL" == "bash" ]]; then 64 | # echo "Running in bash"; 65 | # fi; 66 | # 67 | #### 68 | if ! [ -z ${ZSH_VERSION+x} ]; then 69 | export CURRENT_SHELL="zsh" 70 | elif ! [ -z ${BASH_VERSION+x} ]; then 71 | export CURRENT_SHELL="bash" 72 | else 73 | export CURRENT_SHELL="unknown" 74 | return 1 75 | fi 76 | echo "$CURRENT_SHELL" 77 | return 0 78 | } 79 | 80 | # Small shim in-case colors.sh isn't loaded yet. 81 | if ! has_command msg; then msg() { echo "$@"; }; fi 82 | if ! has_command msgerr; then msgerr() { >&2 echo "$@"; }; fi 83 | 84 | # This is an alias function to intercept commands such as 'sudo apt install' and avoid silent failure 85 | # on systems that don't have sudo - especially if it's being ran as root. Some systems don't have sudo, 86 | # but if this script is being ran as root anyway, then we can just bypass sudo anyway and run the raw command. 87 | # 88 | # If we are in-fact a normal user, then check if sudo is installed - alert the user if it's not. 89 | # If sudo is installed, then forward the arguments to the real sudo command. 90 | # 91 | sudo() { 92 | # If user is not root, check if sudo is installed, then use sudo to run the command 93 | if [ "$EUID" -ne 0 ]; then 94 | if ! has_binary sudo; then 95 | msg bold red "ERROR: You are not root, and you don't have sudo installed. Cannot run command '${@:1}'" 96 | msg red "Please either install sudo and add your user to the sudoers group, or run this script as root." 97 | sleep 5 98 | return 3 99 | fi 100 | /usr/bin/env sudo "${@:1}" 101 | return $? 102 | fi 103 | # If we got to this point, then the user is already root, so just drop the 'sudo' and run it raw. 104 | /usr/bin/env "${@:1}" 105 | } 106 | 107 | -------------------------------------------------------------------------------- /core/010_logging.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/sh 2 | 3 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}"; _XDIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 4 | 5 | # # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 6 | # # script is located, and then source map_libs.sh using a relative path from this script. 7 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 8 | # Mark this library script as loaded successfully 9 | SG_LIB_LOADED[logging]=1 10 | sg_load_lib colors 11 | 12 | : ${stderr_log="$(mktemp).log"} # Randomly generated file in a temp folder for logging stderr into 13 | : ${SG_DIR="${_SDIR}/.."} # This is supposed to be set by init.sh. This is just in-case logging.sh is sourced on it's own... 14 | : ${SG_DEBUG=0} # If set to 1, will enable debugging output to stderr 15 | : ${DEBUGLOG="${SG_DIR}/logs/debug.log"} 16 | 17 | DEBUGLOG_DIR=$(dirname "$DEBUGLOG") 18 | [[ ! -d "$DEBUGLOG_DIR" ]] && mkdir -p "$DEBUGLOG_DIR" && touch "$DEBUGLOG" 19 | 20 | ##### 21 | # Debugging output helper function. 22 | # 23 | # Outputs debugging messages with timestamps to $DEBUGLOG 24 | # If $SG_DEBUG is 1 - then will also print any debugging messages to stderr 25 | # 26 | # Example: 27 | # 28 | # _debug yellow "Warning: Something went wrong with x and y because..." 29 | # 30 | ##### 31 | _debug() { 32 | msg ts "$@" >> "$DEBUGLOG" 33 | ((SG_DEBUG<1)) && return 34 | msgerr ts "$@" 35 | } 36 | 37 | # Used by dependant scripts to check if this file has already been sourced 38 | # e.g. [ -z ${SRCED_LOG+x} ] && source "$SG_DIR/base/logging.sh" 39 | SRCED_LOG=1 40 | 41 | #### 42 | # Log stderr to '$stderr_log' using a named pipe (fifo) with tee, this allows us to log stderr 43 | # and have it printed to the screen at the same time. 44 | #### 45 | _sg_log_pipe=$(mktemp -u) 46 | mkfifo "$_sg_log_pipe" 47 | >&2 tee <"$_sg_log_pipe" "$stderr_log" & 48 | # Backup the stderr descriptor (2) into descriptor 4 for later restoration 49 | exec 4>&2 2> "$_sg_log_pipe" 50 | 51 | 52 | log() { 53 | >&4 msgts "$@"; 54 | } 55 | error() { log "ERROR: $@"; } 56 | 57 | fatal() { error "$@"; return 1; } 58 | 59 | exit_fatal() { error "$@"; exit 1; } 60 | 61 | -------------------------------------------------------------------------------- /docker/bashrc: -------------------------------------------------------------------------------- 1 | export LC_ALL="C.UTF-8" 2 | export LC_CTYPE="C.UTF-8" 3 | export LANG="C.UTF-8" 4 | export LANGUAGE="C.UTF-8" 5 | 6 | . /etc/bash_completion 7 | 8 | export PS1="\[\033[38;5;13m\]\u\[$(tput sgr0)\]\[\033[38;5;15m\]@\[$(tput sgr0)\]\[\033[38;5;156m\]\h\[$(tput sgr0)\]\[\033[38;5;15m\] \[$(tput sgr0)\]\[\033[38;5;6m\]\w\[$(tput sgr0)\]\[\033[38;5;15m\] \\$\[$(tput sgr0)\] " 9 | 10 | alias ls="ls --color=always" 11 | alias l="ls -lah" 12 | alias la="ls -la" 13 | 14 | export SG_DEBUG=1 15 | 16 | -------------------------------------------------------------------------------- /docker/zshrc: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/env zsh 3 | export LC_ALL="C.UTF-8" 4 | export LC_CTYPE="C.UTF-8" 5 | export LANG="C.UTF-8" 6 | export LANGUAGE="C.UTF-8" 7 | 8 | if [ -t 1 ]; then 9 | BOLD="$(tput bold)" RED="$(tput setaf 1)" GREEN="$(tput setaf 2)" YELLOW="$(tput setaf 3)" BLUE="$(tput setaf 4)" 10 | MAGENTA="$(tput setaf 5)" CYAN="$(tput setaf 6)" WHITE="$(tput setaf 7)" RESET="$(tput sgr0)" 11 | else 12 | BOLD="" RED="" GREEN="" YELLOW="" BLUE="" 13 | MAGENTA="" CYAN="" WHITE="" RESET="" 14 | fi 15 | 16 | export PS1="[ %B${GREEN}%n${WHITE}@${MAGENTA}%m ${YELLOW}%~%b ]%B %% %b" 17 | 18 | alias ls="ls --color=always" 19 | alias l="ls -lah" 20 | alias la="ls -la" 21 | 22 | export SG_DEBUG=1 23 | 24 | -------------------------------------------------------------------------------- /gpl-3.0.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /init.sh: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # # 3 | # Privex's Shell Core # 4 | # Cross-platform / Cross-shell helper functions # 5 | # # 6 | # Released under the GNU GPLv3 # 7 | # # 8 | # Official Repo: github.com/Privex/shell-core # 9 | # # 10 | ############################################################# 11 | 12 | S_CORE_VER="0.5.0" # Used by sourcing scripts to identify the current version of Privex's Shell Core. 13 | 14 | 15 | ###### 16 | # Directory where the script is located, so we can source files regardless of where PWD is 17 | ###### 18 | 19 | # Detect shell, locate relative path to script, then use dirname/cd/pwd to find 20 | # the absolute path to the folder containing this script. 21 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 22 | DIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 23 | 24 | # SG_DIR holds the absolute path to where Privex SH-CORE is installed. 25 | # If not set in the environment, it defaults to the folder containing this script. 26 | : ${SG_DIR="$DIR"} 27 | : ${SG_LAST_UPDATE_FILE="${SG_DIR}/.last_update"} 28 | 29 | : ${SG_DEBUG=0} # If set to 1, will enable debugging output to stderr 30 | : ${DEBUGLOG="${SG_DIR}/logs/debug.log"} 31 | 32 | : ${SG_LOCALDIR="${HOME}/.pv-shcore"} # Folder to install Privex Shell Core for local installs 33 | : ${SG_GLOBALDIR="/usr/local/share/pv-shcore"} # Folder to install Privex Shell Core for global installs 34 | # How many seconds must've passed since the last update to trigger an auto-update 35 | : ${SG_UPDATE_SECS=604800} 36 | SG_LAST_UPDATE=0 37 | 38 | _ENV_CLEAN_BLACKLIST=('SG_DEBUG') 39 | 40 | last_update_shellcore() { 41 | if [[ -f "${SG_DIR}/.last_update" ]]; then 42 | __sg_lst=$(cat "$SG_LAST_UPDATE_FILE") 43 | SG_LAST_UPDATE=$(($__sg_lst)) 44 | fi 45 | } 46 | 47 | last_update_shellcore 48 | 49 | update_shellcore() { bash "${SG_DIR}/run.sh" update; } 50 | autoupdate_shellcore() { 51 | last_update_shellcore 52 | local _unix_now=$(date +'%s') 53 | local unix_now=$(($_unix_now)) next_update=$((SG_LAST_UPDATE+SG_UPDATE_SECS)) 54 | local last_rel=$((unix_now-SG_LAST_UPDATE)) 55 | if (($next_update<$unix_now)); then 56 | _debug green "Last update was $last_rel seconds ago. Auto-updating Privex ShellCore." 57 | update_shellcore 58 | else 59 | _debug yellow "Auto-update requested, but last update was $last_rel seconds ago (next update due after ${SG_UPDATE_SECS} seconds)" 60 | fi 61 | } 62 | 63 | # DEBUGLOG_DIR=$(dirname "$DEBUGLOG") 64 | # [[ ! -d "$DEBUGLOG_DIR" ]] && mkdir -p "$DEBUGLOG_DIR" && touch "$DEBUGLOG" 65 | 66 | source "${SG_DIR}/map_libs.sh" 67 | 68 | 69 | ######### 70 | # First we source essential "base" scripts, which provide important functions that 71 | # are used by this init script itself. 72 | ######### 73 | 74 | sg_load_lib logging colors permission trap_helper 75 | 76 | 77 | 78 | cleanup_env() { 79 | _debug "[init.cleanup_env] Unsetting any leftover variables" 80 | clean_env_prefix "SG_" 81 | clean_env_prefix "SRCED_" 82 | } 83 | 84 | #### 85 | # Unset all env vars starting with $1 - works with both bash and zsh 86 | # Example: 87 | # # Would unset SG_DEBUG, SG_DIR, SG_GLOBALDIR etc. 88 | # clean_env_prefix "SG_" 89 | # 90 | clean_env_prefix() { 91 | local clean_vars _prefix="$1" 92 | (($#<1)) && fatal "Usage: clean_env_prefix [prefix]" 93 | if [[ $(ident_shell) == "bash" ]]; then 94 | mapfile -t clean_vars < <(set | grep -E "^${_prefix}" | sed -E 's/^('${_prefix}'[a-zA-Z0-9_]+)(\=.*)$/\1/') 95 | for v in "${clean_vars[@]}"; do 96 | if ! containsElement "$v" "${_ENV_CLEAN_BLACKLIST[@]}"; then 97 | _debug "[cleanup_env_prefix] [bash ver] Unsetting variable: $v" 98 | unset "$v" 99 | else 100 | _debug "[cleanup_env_prefix] [bash ver] Skipping blacklisted variable: $v" 101 | fi 102 | done 103 | elif [[ $(ident_shell) == "zsh" ]]; then 104 | _debug "[cleanup_env_prefix] [zsh ver] Unsetting all variables with pattern: ${_prefix}*" 105 | unset -m "${_prefix}*" 106 | else 107 | fatal "Function 'clean_env_prefix' is only compatible with bash or zsh. Detected shell: $(ident_shell)" 108 | return 1 109 | fi 110 | } 111 | 112 | add_on_exit "cleanup_env" 113 | 114 | -------------------------------------------------------------------------------- /lib/000_gnusafe.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/zsh 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | 13 | [ -z ${SG_LIB_LOADED[@]+x} ] || SG_LIB_LOADED[gnusafe]=1 14 | 15 | 16 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 17 | # script is located, and then source map_libs.sh using a relative path from this script. 18 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 19 | SG_LIB_LOADED[gnusafe]=1 # Mark this library script as loaded successfully 20 | sg_load_lib trap_helper # Check whether 'trap_helper' already been sourced, otherwise source it. 21 | 22 | ##### 23 | # 24 | # Due to the fact that BSD utilities can sometimes suck, 25 | # this is a sanity checker, which makes sure we have access 26 | # to the GNU toolset if we're not on a Linux system. 27 | # 28 | # Usage: 29 | # from a function: 30 | # gnusafe || return 1 31 | # from a script (that isn't sourced): 32 | # gnusafe || exit 1 33 | # 34 | # Original code, written by @someguy123 (github.com/@someguy123) 35 | # License: GNU GPLv3 36 | # 37 | ##### 38 | 39 | if [ -t 1 ]; then 40 | if command -v tput &>/dev/null; then 41 | BOLD="$(tput bold)" RED="$(tput setaf 1)" GREEN="$(tput setaf 2)" YELLOW="$(tput setaf 3)" BLUE="$(tput setaf 4)" 42 | PURPLE="$(tput setaf 5)" MAGENTA="$(tput setaf 5)" CYAN="$(tput setaf 6)" WHITE="$(tput setaf 7)" 43 | RESET="$(tput sgr0)" NORMAL="$(tput sgr0)" 44 | else 45 | BOLD='\033[1m' RED='\033[00;31m' GREEN='\033[00;32m' YELLOW='\033[00;33m' BLUE='\033[00;34m' 46 | PURPLE='\033[00;35m' MAGENTA='\033[00;35m' CYAN='\033[00;36m' WHITE='\033[01;37m' 47 | RESET='\033[0m' NORMAL='\033[0m' 48 | fi 49 | else 50 | BOLD="" RED="" GREEN="" YELLOW="" BLUE="" 51 | MAGENTA="" CYAN="" WHITE="" RESET="" 52 | fi 53 | 54 | : ${HAS_GGREP=0} 55 | : ${HAS_GSED=0} 56 | : ${HAS_GAWK=0} 57 | 58 | function gnusafe () { 59 | # Detect if the script is being ran from bash or zsh 60 | # so we can enable aliases for scripts 61 | if ! [ -z ${ZSH_VERSION+x} ]; then 62 | # Enable aliases for zsh 63 | setopt aliases 64 | elif ! [ -z ${BASH_VERSION+x} ]; then 65 | # Enable aliases for bash 66 | shopt -s expand_aliases 67 | else 68 | >&2 echo -e "${RED} 69 | We can't figure out what shell you're running as neither BASH_VERSION 70 | nor ZSH_VERSION are set. This is important as we need to figure out 71 | which grep/sed/awk that we should use, and alias appropriately. 72 | 73 | Different shells have different ways of enabling alias's in scripts 74 | such as this, but since you don't seem to be using zsh or bash, we 75 | can't continue...${RESET} 76 | " 77 | return 3 78 | fi 79 | 80 | if [[ $(uname -s) != 'Linux' ]] && [ -z ${FORCE_UNIX+x} ]; then 81 | # msg warn " --- WARNING: Non-Linux detected. ---" 82 | # echo " - Checking for ggrep" 83 | if [[ $(command -v ggrep) ]]; then 84 | HAS_GGREP=1 85 | # msg pos " + found GNU alternative 'ggrep'. setting alias" 86 | alias grep="ggrep" 87 | alias egrep="ggrep -E" 88 | fi 89 | # echo " - Checking for gsed" 90 | if [[ $(command -v gsed) ]]; then 91 | HAS_GSED=1 92 | # msg pos " + found GNU alternative 'gsed'. setting alias" 93 | alias sed=gsed 94 | fi 95 | if [[ $(command -v gawk) ]]; then 96 | HAS_GAWK=1 97 | # msg pos " + found GNU alternative 'gawk'. setting alias" 98 | alias awk=gawk 99 | fi 100 | if [[ $HAS_GGREP -eq 0 || $HAS_GSED -eq 0 || $HAS_GAWK -eq 0 ]]; then 101 | >&2 echo -e "${RED} 102 | --- ERROR: Non-Linux detected. Missing GNU sed, awk or grep --- 103 | The program could not find ggrep, gawk, or gsed as a fallback. 104 | Due to differences between BSD and GNU Utils the program will now exit 105 | Please install GNU grep and GNU sed, and make sure they work 106 | On BSD systems, including OSX, they should be available as 'ggrep' and 'gsed' 107 | 108 | For OSX, you can install ggrep/gsed/gawk via brew: 109 | brew install gnu-sed 110 | brew install grep 111 | brew install gawk 112 | 113 | If you are certain that both 'sed' and 'grep' are the GNU versions, 114 | you can bypass this and use the default grep/sed with FORCE_UNIX=1${RESET} 115 | " 116 | return 4 117 | else 118 | # msg pos " +++ Both gsed and ggrep are available. Aliases have been set to allow this script to work." 119 | # msg warn "Please be warned. This script may not work as expected on non-Linux systems..." 120 | add_on_exit "gnusafe-cleanup" 121 | return 0 122 | fi 123 | else 124 | # if we're on linux 125 | # make sure any direct uses of gsed, gawk, and ggrep work 126 | alias ggrep="grep" 127 | alias gawk="awk" 128 | alias gsed="sed" 129 | # if we don't have egrep, alias it 130 | if [[ $(command -v egrep) ]]; then 131 | alias egrep="grep -E" 132 | fi 133 | add_on_exit "gnusafe-cleanup" 134 | return 0 135 | fi 136 | } 137 | 138 | function is_alias () { 139 | command -V "$1" 2> /dev/null | grep -qi "alias" 140 | } 141 | # Ran on exit to ensure no aliases leak out into the environment 142 | # and break the users terminal 143 | function gnusafe-cleanup () { 144 | is_alias ggrep && unalias ggrep 2>/dev/null 145 | is_alias gawk && unalias gawk 2>/dev/null 146 | is_alias gsed && unalias gsed 2>/dev/null 147 | is_alias grep && unalias grep 2>/dev/null 148 | is_alias awk && unalias awk 2>/dev/null 149 | is_alias sed && unalias sed 2>/dev/null 150 | } 151 | -------------------------------------------------------------------------------- /lib/000_trap_helper.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | # 13 | # This file contains functions related to managing shell TRAP hooks. 14 | # 15 | # It's recommended to use the function 'add_on_exit' if you're adding standard "cleanup on exit" 16 | # hooks, as it detects the shell and uses the appropriate exit hook for the detected shell. 17 | # 18 | # The function 'trap_add' allows you to append to a trap instead of overwriting it, and is 19 | # compatible with both bash and zsh. 20 | # 21 | # The function 'get_trap_cmd' is primarily just a helper function for 'trap_add', but can 22 | # be used on it's own, to read the code that would be ran for a specific trap signal on 23 | # both bash and zsh. 24 | # 25 | # However, if used within zsh, you cannot view or append to the 'EXIT' trap, as 'EXIT' traps 26 | # are function local with zsh. 27 | # 28 | # ----------------------------------------------------------- 29 | # 30 | # Most parts written by Someguy123 https://github.com/Someguy123 31 | # Some parts copied from elsewhere e.g. StackOverflow - but often improved by Someguy123 32 | # 33 | ##################### 34 | 35 | 36 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 37 | # script is located, and then source map_libs.sh using a relative path from this script. 38 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 39 | SG_LIB_LOADED[trap_helper]=1 # Mark this library script as loaded successfully 40 | sg_load_lib logging colors # Check whether 'colors' and 'logging' have already been sourced, otherwise source them. 41 | 42 | SG_SHELL="$(ident_shell)" 43 | 44 | # Helper function for extracting trap command via get_trap_cmd 45 | extract_trap_cmd() { (($#>2)) && printf '%s\n' "$3" || echo; } 46 | # Get the function attached to a given trap signal 47 | # 48 | # WARNING: If you're using this function in ZSH, this does NOT work for the signal 'EXIT', 49 | # because 'EXIT' traps are always local to a zsh function 50 | # 51 | # Example: 52 | # 53 | # $ trap "echo 'hello world';" INT 54 | # $ get_trap_cmd INT 55 | # echo 'hello world' 56 | # 57 | get_trap_cmd() { 58 | local trap_cmd="$1" trap_res list_traps 59 | 60 | if [[ "$SG_SHELL" == "bash" ]]; then 61 | # For bash, we can directly query the trap signal using trap -p 62 | eval "extract_trap_cmd $(trap -p "$1")" 63 | elif [[ "$SG_SHELL" == "zsh" ]]; then 64 | # With zsh, we need to call 'trap', then scan it's output for the specific signal we're looking for 65 | trap | IFS= read -rd '' list_traps 66 | trap_res=$(egrep ".* $trap_cmd\$" <<< "$list_traps") 67 | # Then extract just the command portion from the 'trap' output line. 68 | eval "extract_trap_cmd $trap_res" 69 | else 70 | fatal "[trap_add.get_trap_cmd] Unsupported shell "$SG_SHELL"" 71 | fi 72 | } 73 | 74 | ####### 75 | # Appends a command to a trap signal. Works with both bash and zsh. 76 | # 77 | # WARNING: If using this function with ZSH, be aware that the signal 'EXIT' is local to a function. 78 | # Attempting to append to the 'EXIT' signal will simply cause the code to be ran immediately after 79 | # trap_add finishes. 80 | # 81 | # - 1st arg: code to add 82 | # - remaining args: names of traps to modify 83 | # 84 | # Usage: 85 | # trap_add 'echo "in trap DEBUG and INT"' DEBUG INT 86 | # 87 | # Source: https://stackoverflow.com/a/7287873/ 88 | # 89 | trap_add() { 90 | trap_add_cmd=$1; shift || fatal "${FUNCNAME} usage error" 91 | for trap_add_name in "$@"; do 92 | trap_out="$(mktemp)" 93 | 94 | get_trap_cmd "$trap_add_name" > "$trap_out" 95 | _trap_cmd="$(cat $trap_out)" 96 | trap -- "$(printf '%s\n%s\n' "${_trap_cmd}" "${trap_add_cmd}")" "${trap_add_name}" \ 97 | || exit_fatal "unable to add to trap ${trap_add_name}" 98 | rm -f "$trap_out" &>/dev/null 99 | done 100 | } 101 | 102 | # Same as trap_add, but adds the trap to the start of the command chain 103 | # Important for traps that need to detect and handle errors, e.g. base/trap.bash 104 | trap_prepend() { 105 | trap_add_cmd=$1; shift || fatal "${FUNCNAME} usage error" 106 | for trap_add_name in "$@"; do 107 | trap_out="$(mktemp)" 108 | 109 | get_trap_cmd "$trap_add_name" > "$trap_out" 110 | _trap_cmd="$(cat $trap_out)" 111 | trap -- "$(printf '%s\n%s\n' "${trap_add_cmd}" "${_trap_cmd}")" "${trap_add_name}" \ 112 | || exit_fatal "unable to prepend to trap ${trap_add_name}" 113 | rm -f "$trap_out" &>/dev/null 114 | done 115 | } 116 | 117 | if [[ "$SG_SHELL" == "bash" ]]; then 118 | declare -f -t trap_add 119 | declare -f -t trap_prepend 120 | fi 121 | 122 | ####### 123 | # Add a piece of code to execute when the script terminates. 124 | # 125 | # This function is for zsh scripts only. Use 'add_on_exit' if you want your script 126 | # to be compatible with both zsh and bash 127 | # 128 | add_zshexit() { 129 | (($#<1)) && >&2 fatal "error: add_zshexit expects at least one argument (the code to run on zsh exit)" 130 | code="$1" 131 | _debug " >> Appending following code to run on exit:" 132 | _debug "# ================================" 133 | _debug "$code" 134 | _debug "# ================================" 135 | if [ -z ${functions[zshexit]+x} ]; then 136 | _debug " +++ zshexit did not yet exist. creating zshexit function." 137 | zshexit() { eval "$code"; } 138 | else 139 | _debug " +++ zshexit already exists. appending your code to the end." 140 | functions[zshexit]=" 141 | $functions[zshexit] 142 | 143 | $code 144 | " 145 | fi 146 | echo 147 | } 148 | 149 | ####### 150 | # Add a piece of code to execute when the script terminates. (compatible with both bash and zsh) 151 | # 152 | # - For bash, we use 'trap_add' to create / append to an EXIT trap 153 | # - For zsh, we use 'add_zshexit' to create / append to the zshexit function 154 | # 155 | # Example: 156 | # 157 | # $ # You can either use plain shellscript code inside of a string 158 | # $ add_on_exit "echo 'hello world'" 159 | # 160 | # $ # Or you can reference a function you've created 161 | # $ my_cleanup() { echo "running some sort-of cleanup..."; } 162 | # $ add_on_exit "my_cleanup" 163 | # 164 | add_on_exit() { 165 | (($#<1)) && >&2 fatal "error: add_on_exit expects at least one argument (the code to run on script exit)" 166 | local exit_cmd=$1 167 | if [[ "$SG_SHELL" == "bash" ]]; then 168 | _debug "[add_on_exit] Detected shell BASH - appending to EXIT trap" 169 | trap_add "$exit_cmd" EXIT 170 | elif [[ "$SG_SHELL" == "zsh" ]]; then 171 | _debug "[add_on_exit] Detected shell ZSH - creating/appending to zshexit function" 172 | add_zshexit "$exit_cmd" 173 | else 174 | fatal "[trap_helper.add_on_exit] Unsupported shell "$SG_SHELL"" 175 | fi 176 | } 177 | -------------------------------------------------------------------------------- /lib/010_helpers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | # 13 | # Various Bash Helper Functions to ease the pain of writing 14 | # complex, user friendly bash scripts. 15 | # 16 | # Several helpers were refactored out of this file into 17 | # core/000_core_func.sh 18 | # Including: 19 | # len has_command has_binary ident_shell sudo 20 | # 21 | # ----------------------------------------------------------- 22 | # 23 | # Most parts written by Someguy123 https://github.com/Someguy123 24 | # Some parts copied from elsewhere e.g. StackOverflow - but often improved by Someguy123 25 | # 26 | ##################### 27 | 28 | 29 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 30 | # script is located, and then source map_libs.sh using a relative path from this script. 31 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 32 | SG_LIB_LOADED[helpers]=1 # Mark this library script as loaded successfully 33 | sg_load_lib logging colors # Check whether 'colors' and 'logging' have already been sourced, otherwise source them. 34 | 35 | 36 | # Remove any lines containing 'source xxxx.sh' 37 | remove_sources() { sed -E "s/.*source \".*\.sh\".*//g" "$@"; } 38 | 39 | # Compress instances of more than one blank line into a singular blank line 40 | # Unlike "tr -s '\n'" this will only compact multiple blank lines into one, instead of 41 | # removing blank lines entirely. 42 | compress_newlines() { cat -s "$@"; } 43 | 44 | # Trim newlines down to singular newlines (no blank lines allowed) 45 | remove_newlines() { tr -s '\n'; } 46 | 47 | # Remove any comments starting with '#' 48 | remove_comments() { sed -E "s/^#.*//g" "$@" | sed -E "s/^[[:space:]]+#.*//g"; } 49 | 50 | # Trim away any /usr/bin/* or /bin/* shebangs - either pipe in data, or pass filename as argument 51 | remove_shebangs() { sed -E "s;^#!/usr/bin.*$;;" "$@" | sed -E "s;^#!/bin.*$;;"; } 52 | 53 | 54 | # From https://stackoverflow.com/a/8574392/2648583 55 | # Usage: containsElement "somestring" "${myarray[@]}" 56 | # Returns 0 (true) if element exists in given array, or 1 if it doesn't. 57 | # 58 | # Example: 59 | # 60 | # a=(hello world) 61 | # if containsElement "hello" "${a[@]}"; then 62 | # echo "The array 'a' contains 'hello'" 63 | # else 64 | # echo "The array 'a' DOES NOT contain 'hello'" 65 | # fi 66 | # 67 | containsElement () { 68 | local e match="$1" 69 | shift 70 | for e; do [[ "$e" == "$match" ]] && return 0; done 71 | return 1 72 | } 73 | 74 | 75 | # Usage: yesno [message] (options...) 76 | # Displays a bash `read -p` prompt, with the given message, and returns 0 (yes) or 1 (no) depending 77 | # on how the user answers the prompt. Allows for handling yes/no user prompt questions in just 78 | # a single line. 79 | # 80 | # Default functionality: returns 0 if yes, 1 if no, and repeat the question if answer is invalid. 81 | # YesNo Function written by @someguy123 82 | # 83 | # Options: 84 | # Default return code: 85 | # defno - If empty answer, return 1 (no) 86 | # defyes - If empty answer, return 0 (yes) 87 | # deferr - If empty answer, return 3 (you must manually check $? return code) 88 | # fail - If empty answer, call 'exit 2' to terminate this script. 89 | # Flip return code: 90 | # invert - Flip the return codes - return 1 for yes, 0 for no. Bash will then assume no == true, yes == false 91 | # 92 | # Example: 93 | # 94 | # if yesno "Do you want to open this? (y/n) > "; then 95 | # echo "user said yes" 96 | # else 97 | # echo "user said no" 98 | # fi 99 | # 100 | # yesno "Are you sure? (y/N) > " defno && echo "user said yes" || echo "user said no, or didn't answer" 101 | # 102 | yesno() { 103 | local MSG invert=0 retcode=3 defact="none" defacts 104 | defacts=('defno' 'defyes' 'deferr' 'fail') 105 | 106 | MSG="Do you want to continue? (y/n) > " 107 | (( $# > 0 )) && MSG="$1" && shift 108 | 109 | while (( $# > 0 )); do 110 | containsElement "$1" "${defacts[@]}" && defact="$1" 111 | [[ "$1" == "invert" ]] && invert=1 112 | shift 113 | done 114 | 115 | local YES=0 NO=1 116 | (( $invert == 1 )) && YES=1 NO=0 117 | 118 | unset answer 119 | while true; do 120 | read -p "$MSG" answer 121 | if [ -z "$answer" ]; then 122 | case "$defact" in 123 | defno) 124 | retcode=$NO 125 | break 126 | ;; 127 | defyes) 128 | retcode=$YES 129 | (( $invert == 0 )) && retcode=0 || retcode=1 130 | break 131 | ;; 132 | fail) 133 | exit 2 134 | break 135 | ;; 136 | *) 137 | ;; 138 | esac 139 | fi 140 | case "$answer" in 141 | y|Y|yes|YES) 142 | retcode=$YES 143 | break 144 | ;; 145 | n|N|no|NO|nope|NOPE|exit) 146 | retcode=$NO 147 | break 148 | ;; 149 | *) 150 | msg red " (!!) Please answer by typing yes or no - or the characters y or n - then press enter." 151 | msg red " (!!) If you want to exit this program, press CTRL-C (hold CTRL and tap the C button on your keyboard)." 152 | msg 153 | ;; 154 | esac 155 | done 156 | return $retcode 157 | } 158 | 159 | # The command used to update the system package manager repos 160 | : ${PKG_MGR_UPDATE="apt-get update -qy"} 161 | # The command used to install a package - where the package name would be 162 | # specified as the first argument following the command. 163 | : ${PKG_MGR_INSTALL="apt-get install -y"} 164 | 165 | PKG_MGR_UPDATED="n" 166 | pkg_not_found() { 167 | # check if a command is available 168 | # if not, install it from the package specified 169 | # Usage: pkg_not_found [cmd] [package-name] 170 | # e.g. pkg_not_found git git 171 | if (($#<2)); then 172 | msg red "ERR: pkg_not_found requires 2 arguments (cmd) (package)" 173 | exit 174 | fi 175 | local cmd=$1 176 | local pkg=$2 177 | if ! has_binary "$cmd"; then 178 | msg yellow "WARNING: Command $cmd was not found. installing now..." 179 | if [[ "$PKG_MGR_UPDATED" == "n" ]]; then 180 | sudo sh -c "${PKG_MGR_UPDATE}" > /dev/null 181 | PKG_MGR_UPDATED="y" 182 | fi 183 | sudo sh -c "${PKG_MGR_INSTALL} ${pkg}" >/dev/null 184 | fi 185 | } 186 | 187 | # Split argument 1 by argument 2, then output the elements separated by newline, allowing you to split a string 188 | # into an array 189 | # 190 | # For associative arrays (AKA dictionaries / hashes), see split_assoc in 015_bash_helpers.bash 191 | # (split_assoc is only compatible with bash) 192 | # 193 | # Usage: 194 | # 195 | # $ x='hello-world-one-two-three' 196 | # # Split variable $x into a bash/zsh array by the dash "-" character 197 | # $ x_data=($(split_by "$x" "-")) 198 | # $ echo "${x_data[0]}" 199 | # hello 200 | # $ echo "${x_data[1]}" 201 | # world 202 | # 203 | split_by() { 204 | if (($# != 2)); then 205 | echo >&2 "Error: split_by requires exactly 2 arguments" 206 | return 1 207 | fi 208 | local split_data="$1" split_sep="$2" data_splitted 209 | 210 | # Backup the field separator so we can restore it once we're done splitting. 211 | _IFS="$IFS" 212 | IFS="$split_sep" 213 | if [[ $(ident_shell) == "bash" ]]; then 214 | read -a data_splitted <<<"$split_data" 215 | elif [[ $(ident_shell) == "zsh" ]]; then 216 | setopt sh_word_split 217 | data_splitted=($split_data) 218 | setopt +o sh_word_split 219 | else 220 | fatal "Function 'split_by' is only compatible with bash or zsh. Detected shell: $(ident_shell)" 221 | return 1 222 | fi 223 | 224 | echo "${data_splitted[@]}" 225 | 226 | IFS="$_IFS" 227 | } 228 | 229 | 230 | 231 | # Split argument 1 into an associative array (AKA dictionary / hash), separating each pair by arg 2, 232 | # and the key/value by arg 3. 233 | # You must source the file location which is outputted to stdout, as bash does not support exporting 234 | # associative arrays. The sourced file will add the associative array 'assoc_result' to your shell. 235 | # 236 | # Usage: 237 | # NOTE: Due to limitations in both bash and zsh, associative arrays cannot be exported. 238 | # As a workaround, the associative array is serialized into a temporary file, and the tempfile location 239 | # is printed from the function. 240 | # You can then source this to load the associative array into your current function, or globally. 241 | # 242 | # In the below example, we split each "item" by commas, then split items into keys and values by ":". 243 | # 244 | # $ x="hello:world,lorem:ipsum,dolor:orange" 245 | # $ source $(split_assoc "$x" "," ":") 246 | # $ echo "${assoc_result[hello]}" 247 | # world 248 | # 249 | # If you want to rename / copy the associative array to a different variable name, you must declare your own 250 | # array and loop over the result array. 251 | # 252 | # $ declare -A my_arr 253 | # $ for key in "${!assoc_result[@]}"; do 254 | # my_arr["$key"]="${assoc_result["$key"]}" 255 | # done 256 | # 257 | # shellcheck disable=SC2207 258 | split_assoc() { 259 | if (($# != 3)); then 260 | echo >&2 "Error: split_assoc requires exactly 3 arguments" 261 | return 1 262 | fi 263 | 264 | local split_data="$1" item_sep="$2" keyval_sep="$3" s_rows row s_cols 265 | 266 | s_rows=($(split_by "$split_data" "$item_sep")) 267 | declare -A assoc_result 268 | export assoc_output="$(mktemp)" 269 | 270 | for row in "${s_rows[@]}"; do 271 | _debug "Row is: $row" 272 | s_cols=($(split_by "$row" "$keyval_sep")) 273 | _debug "s_cols is:" ${s_cols[@]} 274 | 275 | num_cols="${#s_cols[@]}" 276 | num_cols=$((num_cols)) 277 | if ((num_cols != 2)); then 278 | _debug "Warning: split_assoc row does not have 2 columns (has ${num_cols}): '${s_cols[*]}'" 279 | continue 280 | fi 281 | if [[ $(ident_shell) == "bash" ]]; then 282 | assoc_result[${s_cols[0]}]="${s_cols[1]}" 283 | elif [[ $(ident_shell) == "zsh" ]]; then 284 | assoc_result[${s_cols[1]}]="${s_cols[2]}" 285 | else 286 | fatal "Function 'split_assoc' is only compatible with bash or zsh. Detected shell: $(ident_shell)" 287 | return 1 288 | fi 289 | 290 | 291 | done 292 | # Serialize the associative array to the temporary file, then print the temp file location to stdout. 293 | # Source: https://stackoverflow.com/a/55317015 294 | declare -p assoc_result >"$assoc_output" 295 | echo "$assoc_output" 296 | } 297 | 298 | # rm-extension [path] 299 | # Remove the last extension from a filename/path and output the individual filename 300 | # without the last extension 301 | # 302 | # $ rm-extension /backups/mysql/2021-03-17.tar.lz4 303 | # 2021-03-17.tar 304 | # 305 | rm-extension() { 306 | local fname=$(basename -- "$1") 307 | echo "${fname%.*}" 308 | } 309 | 310 | # get-extension [path] 311 | # Extract the last extension from a filename/path and output it. 312 | # 313 | # $ get-extension /backups/mysql/2021-03-17.tar.lz4 314 | # lz4 315 | # 316 | get-extension() { 317 | local fname=$(basename -- "$1") 318 | echo "${fname##*.}" 319 | } 320 | 321 | 322 | if [[ $(ident_shell) == "bash" ]]; then 323 | export -f sudo containsElement yesno pkg_not_found split_by split_assoc rm-extension get-extension >/dev/null 324 | elif [[ $(ident_shell) == "zsh" ]]; then 325 | export sudo containsElement yesno pkg_not_found split_by split_assoc rm-extension get-extension >/dev/null 326 | else 327 | msgerr bold red "WARNING: Could not identify your shell. Attempting to export with plain export..." 328 | export sudo containsElement yesno pkg_not_found split_by split_assoc rm-extension get-extension >/dev/null 329 | fi 330 | 331 | 332 | -------------------------------------------------------------------------------- /lib/020_date_helpers.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | # 13 | # Various Bash Helper Functions for working with dates 14 | # and times, including conversion to and from 15 | # seconds / UNIX epoch time. 16 | # 17 | # Included: 18 | # - rfc-datetime - Simple alias to generate an RFC 3399 / ISO 8601 19 | # format date/time in the UTC timezone 20 | # - date-to-seconds - Convert an RFC/ISO date/time into UNIX epoch 21 | # - seconds-to-date - Convert UNIX epoch into an RFC/ISO datetime 22 | # - compare-dates - Calculates how many seconds there are between two dates 23 | # - human-seconds - Converts a number of seconds into humanized time, 24 | # e.g. human-seconds 500 = 8 minute(s) and 20 second(s) 25 | # ----------------------------------------------------------- 26 | # 27 | # Most parts written by Someguy123 https://github.com/Someguy123 28 | # Some parts copied from elsewhere e.g. StackOverflow - but often improved by Someguy123 29 | # 30 | ##################### 31 | 32 | 33 | # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 34 | # script is located, and then source map_libs.sh using a relative path from this script. 35 | { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ]; } && source "${_XDIR}/../map_libs.sh" || true 36 | SG_LIB_LOADED[datehelpers]=1 # Mark this library script as loaded successfully 37 | # sg_load_lib logging colors # Check whether 'colors' and 'logging' have already been sourced, otherwise source them. 38 | 39 | 40 | ###### 41 | # Very simple alias function which simply calls 'date' with the timezone env var TZ 42 | # locked to 'UTC', and a date formatting string to generate an RFC 3399 / ISO 8601 43 | # standard format date/time. 44 | # Example output: 45 | # $ rfc-datetime 46 | # 2021-03-31T22:36:19 47 | # 48 | rfc-datetime() { 49 | TZ='UTC' date +'%Y-%m-%dT%H:%M:%S' 50 | } 51 | 52 | rfc_datetime() { rfc-datetime "$@"; } 53 | 54 | _OS_NAME="$(uname -s)" 55 | 56 | export SECS_MIN=60 SECS_MINUTE=60 57 | export SECS_HOUR=$(( SECS_MIN * 60 )) 58 | export SECS_DAY=$(( SECS_HOUR * 24 )) 59 | export SECS_WEEK=$(( SECS_DAY * 7 )) 60 | export SECS_MONTH=$(( SECS_WEEK * 4 )) 61 | export SECS_YEAR=$(( SECS_DAY * 365 )) 62 | export SECS_HR="$SECS_HOUR" SECS_WK="$SECS_WEEK" SECS_MON="$SECS_MONTH" SECS_YR="$SECS_YEAR" 63 | 64 | # export SECS_MIN SECS_HOUR SECS_DAY SECS_WEEK SECS_MONTH SECS_YEAR 65 | # export SECS_HR SECS_WK SECS_MON SECS_YR 66 | 67 | export ISO_FMTSTR="%Y-%m-%dT%H:%M:%S" 68 | 69 | # date-to-seconds [date_time] 70 | # Convert a date/time string into UNIX time (epoch seconds) 71 | # (alias 'date-to-unix') 72 | # 73 | # for most reliable conversion, pass date/time in ISO format: 74 | # 2020-02-28T20:08:09 (%Y-%m-%dT%H:%M:%S) 75 | # e.g. 76 | # $ date_to_seconds "2020-02-28T20:08:09" 77 | # 1582920489 78 | # 79 | date-to-seconds() { 80 | if [[ "$_OS_NAME" == "Darwin" ]]; then 81 | date -j -f "$ISO_FMTSTR" "$1" "+%s" 82 | else 83 | date -d "$1" '+%s' 84 | fi 85 | } 86 | 87 | date-to-unix() { date-to-seconds "$@"; } 88 | date_to_seconds() { date-to-seconds "$@"; } 89 | 90 | seconds-to-date() { 91 | if [[ "$_OS_NAME" == "Darwin" ]]; then 92 | date -j -f "%s" "$1" "+${ISO_FMTSTR}" 93 | else 94 | date -d "@$1" "+${ISO_FMTSTR}" 95 | fi 96 | } 97 | unix-to-date() { seconds-to-date "$@"; } 98 | 99 | [[ $(ident_shell) == "bash" ]] && export -f date-to-seconds date-to-unix date_to_seconds seconds-to-date unix-to-date || \ 100 | export date-to-seconds date-to-unix date_to_seconds seconds-to-date unix-to-date 101 | 102 | # compare-dates [rfc_date_1] [rfc_date_2] 103 | # outputs the amount of seconds between date_2 and date_1 104 | # 105 | # e.g. 106 | # $ compare-dates "2020-03-19T23:08:49" "2020-03-19T20:08:09" 107 | # 10840 108 | # means date_1 is 10,840 seconds in the future compared to date_2 109 | # 110 | compare-dates() { 111 | echo "$(($(date_to_seconds "$1")-$(date_to_seconds "$2")))" 112 | } 113 | compare_dates() { compare-dates "$@"; } 114 | 115 | [[ $(ident_shell) == "bash" ]] && export -f compare-dates compare_dates || export compare-dates compare_dates 116 | 117 | ####### 118 | # The following human-seconds-xxx functions are primarily intended for internal 119 | # use by 'human-seconds', however, they're exported to allow you to use them directly, 120 | # for cases where you need to use a specific scale, regardless of the size of your seconds. 121 | ####### 122 | 123 | human-seconds-min() { 124 | local secs="$1" 125 | mins=$(( secs / SECS_MIN )) rem_secs=$(( secs % SECS_MIN )) 126 | (( rem_secs > 0 )) && echo "$mins minute(s) and $rem_secs second(s)" || echo "$mins minute(s)" 127 | } 128 | 129 | human-seconds-hour() { 130 | local secs="$1" 131 | hrs=$(( secs / SECS_HR )) rem_mins=$(( ( secs % SECS_HR ) / SECS_MIN )) 132 | (( rem_mins > 0 )) && echo "$hrs hour(s) and $rem_mins minute(s)" || echo "$hrs hour(s)" 133 | } 134 | 135 | human-seconds-day() { 136 | local secs="$1" 137 | days=$(( secs / SECS_DAY )) rem_hrs=$(( ( secs % SECS_DAY ) / SECS_HR )) 138 | rem_mins=$(( (( secs % SECS_DAY ) % SECS_HR) / SECS_MIN )) 139 | m="$days day(s)" 140 | (( rem_hrs > 0 )) && m="${m} + $rem_hrs hour(s)" 141 | (( rem_mins > 0 )) && m="${m} + $rem_mins minute(s)" 142 | echo "$m" 143 | } 144 | 145 | human-seconds-week() { 146 | local secs="$1" 147 | weeks=$(( secs / SECS_WK )) rem_days=$(( ( secs % SECS_WK ) / SECS_DAY )) 148 | rem_hrs=$(( (( secs % SECS_WK ) % SECS_DAY) / SECS_HR )) 149 | m="$weeks week(s)" 150 | (( rem_days > 0 )) && m="${m} + $rem_days day(s)" 151 | (( rem_hrs > 0 )) && m="${m} + $rem_hrs hour(s)" 152 | echo "$m" 153 | } 154 | 155 | human-seconds-month() { 156 | local secs="$1" 157 | months=$(( secs / SECS_MON )) rem_days=$(( ( secs % SECS_MON ) / SECS_DAY )) 158 | rem_hrs=$(( (( secs % SECS_MON ) % SECS_DAY) / SECS_HR )) 159 | m="$months month(s)" 160 | (( rem_days > 0 )) && m="${m} + $rem_days day(s)" 161 | (( rem_hrs > 0 )) && m="${m} + $rem_hrs hour(s)" 162 | echo "$m" 163 | } 164 | 165 | human-seconds-year() { 166 | local secs="$1" 167 | years=$(( secs / SECS_YR )) rem_months=$(( ( secs % SECS_YR ) / SECS_MON )) 168 | rem_days=$(( (( secs % SECS_YR ) % SECS_MON) / SECS_DAY )) 169 | m="$years years(s)" 170 | (( rem_months > 0 )) && m="${m} + $rem_months month(s)" 171 | (( rem_days > 0 )) && m="${m} + $rem_days day(s)" 172 | echo "$m" 173 | } 174 | 175 | [[ $(ident_shell) == "bash" ]] && export -f human-seconds-min human-seconds-hour human-seconds-day human-seconds-week human-seconds-month human-seconds-year || \ 176 | export human-seconds-min human-seconds-hour human-seconds-day human-seconds-week human-seconds-month human-seconds-year 177 | 178 | # internal function used by human-seconds to parse max_scale 179 | _human_scale() { 180 | case "$1" in 181 | s|sec*|S|SEC*) echo "secs" ;; 182 | m|min*|MIN*) echo "min" ;; 183 | h|hr*|hour*|H|HR*|HOUR*) echo "hr" ;; 184 | d|day*|D|DAY*) echo "day" ;; 185 | w|wk*|week*|W|WK*|WEEK*) echo "week" ;; 186 | M|mo*|MO*) echo "mon";; 187 | y|yr*|yea*|Y|YR*|YEA*) echo "year" ;; 188 | esac 189 | } 190 | 191 | # human-seconds seconds [max_scale='year'] 192 | # convert an amount of seconds into a humanized time (minutes, hours, days) 193 | # 194 | # human-seconds 60 # output: 1 minute(s) 195 | # human-seconds 4000 # output: 1 hour(s) and 6 minute(s) 196 | # human-seconds 90500 # output: 1 day(s) + 1 hour(s) + 8 minute(s) 197 | # 198 | # Limit the maximum scale (mins, hours, days, etc.): 199 | # 200 | # human-seconds 50000000 yr # 1 years(s) + 7 month(s) + 17 day(s) 201 | # human-seconds 50000000 mon # 20 month(s) + 18 day(s) + 16 hour(s) 202 | # human-seconds 50000000 wk # 82 week(s) + 4 day(s) + 16 hour(s) 203 | # human-seconds 90500 hours # 25 hour(s) and 8 minute(s) 204 | # human-seconds 90500 m # 1508 minute(s) and 20 second(s) 205 | # 206 | # NOTE: max_scale supports most unit variations, e.g. m/min/minutes/mins, 207 | # h/hrs/HOURS, M/mo/mons/months, w/wks/week/WEEKS/W, y/yrs/yea/year/Y/YRS 208 | # and others similar variations. 209 | # 210 | human-seconds() { 211 | local secs="$1" mscl="year" mins hrs days 212 | local rem_secs rem_mins rem_hrs m 213 | (( $# > 1 )) && mscl="$(_human_scale "$2")" 214 | if (( secs < 60 )) || [[ "$mscl" == "secs" ]]; then # less than 1 minute 215 | echo "$secs seconds" 216 | elif (( secs < 3600 )) || [[ "$mscl" == "min" ]]; then # less than 1 hour 217 | human-seconds-min "$1" 218 | elif (( secs < 86400 )) || [[ "$mscl" == "hr" ]]; then # less than 1 day 219 | human-seconds-hour "$1" 220 | elif (( secs < SECS_WK )) || [[ "$mscl" == "day" ]]; then 221 | human-seconds-day "$1" 222 | elif (( secs < SECS_MON )) || [[ "$mscl" == "week" ]]; then 223 | human-seconds-week "$1" 224 | elif (( secs < SECS_YR )) || [[ "$mscl" == "mon" ]]; then 225 | human-seconds-month "$1" 226 | else 227 | human-seconds-year "$1" 228 | fi 229 | } 230 | 231 | human_seconds() { human-seconds "$@"; } 232 | 233 | [[ $(ident_shell) == "bash" ]] && export -f human_seconds human-seconds || export human_seconds human-seconds 234 | 235 | if [[ $(ident_shell) == "bash" ]]; then 236 | export -f compare-dates compare_dates date-to-seconds date-to-unix date_to_seconds rfc-datetime rfc_datetime >/dev/null 237 | export -f human-seconds human_seconds human-seconds-min human-seconds-hour human-seconds-day human-seconds-week >/dev/null 238 | export -f human-seconds-month human-seconds-year >/dev/null 239 | elif [[ $(ident_shell) == "zsh" ]]; then 240 | export compare-dates compare_dates date-to-seconds date-to-unix date_to_seconds rfc-datetime rfc_datetime >/dev/null 241 | export human-seconds human_seconds human-seconds-min human-seconds-hour human-seconds-day human-seconds-week >/dev/null 242 | export human-seconds-month human-seconds-year >/dev/null 243 | else 244 | msgerr bold red "WARNING: Could not identify your shell. Attempting to export with plain export..." 245 | export compare-dates compare_dates date-to-seconds date-to-unix date_to_seconds rfc-datetime rfc_datetime >/dev/null 246 | export human-seconds human_seconds human-seconds-min human-seconds-hour human-seconds-day human-seconds-week >/dev/null 247 | export human-seconds-month human-seconds-year >/dev/null 248 | fi 249 | -------------------------------------------------------------------------------- /lib/scripts/shellcore_install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | 13 | set -eE 14 | 15 | if [ -t 1 ]; then 16 | BOLD="$(tput bold)" RED="$(tput setaf 1)" GREEN="$(tput setaf 2)" YELLOW="$(tput setaf 3)" BLUE="$(tput setaf 4)" 17 | MAGENTA="$(tput setaf 5)" CYAN="$(tput setaf 6)" WHITE="$(tput setaf 7)" RESET="$(tput sgr0)" 18 | else 19 | BOLD="" RED="" GREEN="" YELLOW="" BLUE="" MAGENTA="" CYAN="" WHITE="" RESET="" 20 | fi 21 | export BOLD RED GREEN YELLOW BLUE MAGENTA CYAN WHITE RESET 22 | 23 | # just a small wrapper around wc to pipe in all args 24 | # saves constantly piping it in 25 | len() { wc -c <<< "${@:1}"; } 26 | 27 | cleanup() { 28 | if ! [ -z ${clonedir+x} ] && [[ $(len "$clonedir") -gt 5 ]]; then 29 | echo "Removing temporary clone folder '$clonedir'..." && rm -rf "$clonedir"; 30 | fi 31 | } 32 | 33 | sudo() { 34 | if [ "$EUID" -ne 0 ]; then # If user is not root, check if sudo is installed, then use sudo to run the command 35 | if ! has_binary sudo; then 36 | msg bold red "ERROR: You are not root, and you don't have sudo installed. Cannot run command '${@:1}'" 37 | msg red "Please either install sudo and add your user to the sudoers group, or run this script as root." 38 | sleep 5 39 | return 3 40 | fi 41 | /usr/bin/env sudo "${@:1}" 42 | else 43 | /usr/bin/env "${@:1}" # The user is already root, so just drop the 'sudo' and run it raw. 44 | fi 45 | } 46 | 47 | err_trap() { 48 | >&2 echo -e "${RED}${BOLD}ERROR: Could not install Privex ShellCore as a non-zero return code was encountered.\n" \ 49 | "Check for any error messages above. For extra debugging output from ShellCore, run 'export SG_DEBUG=1' ${RESET} \n" 50 | cleanup 51 | } 52 | 53 | trap err_trap ERR 54 | trap cleanup EXIT 55 | 56 | cd /tmp 57 | clonedir="$(mktemp -d)" 58 | 59 | has_binary() { 60 | /usr/bin/env which "$1" > /dev/null 61 | } 62 | 63 | install_git() { 64 | if has_binary apt-get; then 65 | echo "${YELLOW}Attempting to install 'git' using apt-get...${RESET}" 66 | sudo apt-get update -qy > /dev/null 67 | sudo apt-get install -y git 68 | elif has_binary yum; then 69 | echo "${YELLOW}Attempting to install 'git' using yum...${RESET}" 70 | sudo yum -y install git 71 | else 72 | return 1 73 | fi 74 | } 75 | 76 | if ! has_binary git; then 77 | if ! install_git; then 78 | >&2 echo "${RED}${BOLD}ERROR: Could not find 'git', you're not root, and 'sudo' is not available. " \ 79 | "Cannot continue with install of Privex ShellCore... Please install 'git' as root.${RESET}\n" 80 | exit 1 81 | fi 82 | fi 83 | 84 | echo "${GREEN} -> Cloning Privex/shell-core into '$clonedir'${RESET}" 85 | git clone -q https://github.com/Privex/shell-core.git "$clonedir" 86 | echo "${GREEN} -> Using 'run.sh install' to install/update Privex ShellCore${RESET}" 87 | bash "${clonedir}/run.sh" install 88 | 89 | if [[ -d "${HOME}/.pv-shcore" ]]; then 90 | echo "source ${HOME}/.pv-shcore/load.sh" > /tmp/pv-shellcore 91 | elif [[ -d "/usr/local/share/pv-shcore" ]]; then 92 | echo "source /usr/local/share/pv-shcore/load.sh" > /tmp/pv-shellcore 93 | else 94 | >&2 echo "${RED}${BOLD}ERROR: Install appeared successful, but neither the local nor global ShellCore " \ 95 | "installation folder could be found...${RESET}\n" 96 | exit 1 97 | fi 98 | 99 | echo "${GREEN} +++ Privex ShellCore has been installed / updated.${RESET}" 100 | -------------------------------------------------------------------------------- /load.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | 13 | 14 | ###### 15 | # Directory where the script is located, so we can source files regardless of where PWD is 16 | ###### 17 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 18 | DIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 19 | 20 | source "${DIR}/init.sh" 21 | 22 | ident_shell >/dev/null 23 | 24 | if [ -z ${SG_LOAD_LIBS+x} ]; then 25 | SG_LOAD_LIBS=(gnusafe helpers datehelpers) 26 | _debug "SG_LOAD_LIBS not specified from environment. Using default libs: ${SG_LOAD_LIBS[*]}" 27 | else 28 | _debug "SG_LOAD_LIBS was specified in environment. Using environment libs: ${SG_LOAD_LIBS[*]}" 29 | fi 30 | 31 | sg_load_lib "${SG_LOAD_LIBS[@]}" 32 | 33 | -------------------------------------------------------------------------------- /logs/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | -------------------------------------------------------------------------------- /map_libs.sh: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # # 3 | # Privex's Shell Core # 4 | # Cross-platform / Cross-shell helper functions # 5 | # # 6 | # Released under the GNU GPLv3 # 7 | # # 8 | # Official Repo: github.com/Privex/shell-core # 9 | # # 10 | ############################################################# 11 | # 12 | # This file contains an associative array, mapping "libraries" 13 | # to their respective file to assist with sourcing them, 14 | # and ensure that they're only loaded once. 15 | # 16 | ############################################################# 17 | 18 | # Detect shell, locate relative path to script, then use dirname/cd/pwd to find 19 | # the absolute path to the folder containing this script. 20 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 21 | DIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 22 | 23 | : ${SG_DIR="$DIR"} 24 | : ${SRCED_SGCORE=0} 25 | : ${SG_DEBUG=0} 26 | # : ${SG_DEBUG=0} # If set to 1, will enable debugging output to stderr 27 | 28 | if ((SRCED_SGCORE<1)); then 29 | source "${SG_DIR}/core/000_core_func.sh" 30 | fi 31 | 32 | 33 | # Small shim in-case logging isn't loaded yet. 34 | if ! has_command _debug; then 35 | _debug() { ((SG_DEBUG<1)) && return; echo "$@"; } 36 | fi 37 | 38 | 39 | : ${DEBUGLOG="${SG_DIR}/logs/debug.log"} 40 | 41 | # DEBUGLOG_DIR=$(dirname "$DEBUGLOG") 42 | # [[ ! -d "$DEBUGLOG_DIR" ]] && mkdir -p "$DEBUGLOG_DIR" && touch "$DEBUGLOG" 43 | 44 | if [ -z ${SG_LIB_LOADED[@]+x} ]; then 45 | _debug "[map_libs.sh] SG_LIB_LOADED not set. Declaring SG_LIB_LOADED assoc array." 46 | declare -A SG_LIB_LOADED 47 | SG_LIB_LOADED=( 48 | [colors]=0 [identify]=0 [permission]=0 [traplib]=0 49 | [logging]=0 [core_func]=1 50 | [gnusafe]=0 [trap_helper]=0 [helpers]=0 [datehelpers]=0 51 | ) 52 | fi 53 | if [ -z ${SG_LIBS[@]+x} ]; then 54 | _debug "[map_libs.sh] SG_LIBS not set. Declaring SG_LIBS assoc array." 55 | declare -A SG_LIBS 56 | 57 | # We don't quote the keys - while bash ignores quotes, zsh treats them literally and would 58 | # require that the keys are accessed with the same quote style as they were set. 59 | SG_LIBS=( 60 | [colors]="${SG_DIR}/base/colors.sh" [identify]="${SG_DIR}/base/identify.sh" 61 | [logging]="${SG_DIR}/core/010_logging.sh" [permission]="${SG_DIR}/base/permission.sh" 62 | [traplib]="${SG_DIR}/base/trap.bash" 63 | [gnusafe]="${SG_DIR}/lib/000_gnusafe.sh" [trap_helper]="${SG_DIR}/lib/000_trap_helper.sh" 64 | [helpers]="${SG_DIR}/lib/010_helpers.sh" [datehelpers]="${SG_DIR}/lib/020_date_helpers.sh" 65 | ) 66 | fi 67 | 68 | sg_load_lib() { 69 | (( $# < 1 )) && { >&2 msgerr "[ERROR] sg_load_lib expects at least one argument!" && return 1; } 70 | local a 71 | for a in "$@"; do 72 | [[ "$a" == "trap" ]] && a="traplib" 73 | if (( ${SG_LIB_LOADED[$a]} < 1 )); then 74 | _debug "[map_libs.sg_load_lib] Loading library '$a' from location '${SG_LIBS[$a]}' ..." 75 | source "${SG_LIBS[$a]}" 76 | else 77 | _debug "[map_libs.sg_load_lib] Library '$a' is already loaded..." 78 | fi 79 | done 80 | } 81 | 82 | sg_load_lib logging 83 | 84 | 85 | 86 | ################# 87 | # Using map_libs.sh inside of a ShellCore module inside of base/ core/ or lib/ 88 | # 89 | # # Check that both SG_LIB_LOADED and SG_LIBS exist. If one of them is missing, then detect the folder where this 90 | # # script is located, and then source map_libs.sh using a relative path from your script. 91 | # { [ -z ${SG_LIB_LOADED[@]+x} ] || [ -z ${SG_LIBS[@]+x} ] } && { 92 | # ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}"; _XDIR="$( cd "$( dirname "${_SDIR}" )" && pwd )"; 93 | # source "${_XDIR}/../map_libs.sh" 94 | # } || true 95 | # 96 | # # Mark this library script as loaded successfully 97 | # SG_LIB_LOADED[somelib]=1 98 | # 99 | # # Ensure any libraries you plan to use are loaded. If they were already sourced, then they won't be loaded again. 100 | # sg_load_lib colors permission gnusafe 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | ############################################################# 3 | # # 4 | # Privex's Shell Core # 5 | # Cross-platform / Cross-shell helper functions # 6 | # # 7 | # Released under the GNU GPLv3 # 8 | # # 9 | # Official Repo: github.com/Privex/shell-core # 10 | # # 11 | ############################################################# 12 | 13 | ! [ -z ${ZSH_VERSION+x} ] && _SDIR=${(%):-%N} || _SDIR="${BASH_SOURCE[0]}" 14 | __DIR="$( cd "$( dirname "${_SDIR}" )" && pwd )" 15 | 16 | # Load bash error handler library 17 | source "${__DIR}/base/trap.bash" 18 | 19 | source "${__DIR}/load.sh" 20 | 21 | DIR="$__DIR" 22 | INST_DIR="$SG_DIR" 23 | 24 | # This global variable is used for context information - if the calling function is operating 25 | # on a global install, then it may set SG_IS_GLOBAL=1 to inform called functions that the 26 | # installation directory is known to be global, and thus sudo should be used. 27 | SG_IS_GLOBAL=0 28 | 29 | _sg_auto_update() { 30 | (($#<1)) && msgerr bold red "_sg_auto_update expects at least 1 argument..." && return 1 31 | INST_DIR="$1" 32 | [[ ! -d "$INST_DIR" ]] && msgerr bold red "The folder '$INST_DIR' does not exist, so it cannot be updated..." && return 1 33 | cd "$INST_DIR" 34 | _debug green " (+) Updating existing installation at '$INST_DIR'" 35 | 36 | if (($SG_IS_GLOBAL==1)); then 37 | 38 | gp_out=$(sudo git pull -q) 39 | else 40 | gp_out=$(git pull -q) 41 | fi 42 | 43 | _debug green " (+) 'git pull' returned zero - successfully updated?" 44 | _debug "GIT PULL output:\n ${gp_out}" 45 | date +'%s' > "${INST_DIR}/.last_update" 46 | } 47 | 48 | NEED_REINSTALL=0 49 | 50 | _sg_fallback_update() { 51 | local INST_DIR="$1" 52 | if [[ ! -f "${INST_DIR}/load.sh" ]]; then 53 | msgerr bold yellow "WARNING: The folder '$INST_DIR' exists, but doesn't contain load.sh..." 54 | if (($(len "$INST_DIR")<8)); then 55 | msg bold red "The folder '$INST_DIR' appears to be shorter than 8 characters." 56 | msg red "For your safety, no automated removal + re-install will be attempted." 57 | return 1 58 | fi 59 | msgerr yellow "Removing the folder and re-installing." 60 | (($SG_IS_GLOBAL==1)) && sudo rm -rf "$INST_DIR" || rm -rf "$INST_DIR" 61 | NEED_REINSTALL=1 62 | return 63 | else 64 | _debug yellow " -> The folder '$INST_DIR' already exists... Attempting to update it.\n" 65 | _sg_auto_update "$INST_DIR" 66 | return 67 | fi 68 | } 69 | 70 | _sg_install_local() { 71 | INST_DIR="$SG_LOCALDIR" 72 | _debug green " (+) Installing SG Shell Core locally: '$INST_DIR' ...\n" 73 | # If the installation folder already exists, attempt to update it. 74 | # If the install appears to be damaged, NEED_REINSTALL would be set to 1, meaning that the install folder 75 | # was removed by fallback_update, so we should continue with the installation. 76 | if [[ -d "$INST_DIR" ]]; then 77 | _sg_fallback_update "$INST_DIR" 78 | ((${NEED_REINSTALL}==0)) && return 0 79 | fi 80 | _debug yellow " -> Creating folder '$INST_DIR' ..." 81 | mkdir -p "$INST_DIR" &> /dev/null 82 | 83 | _debug yellow " -> Copying all files from '$SG_DIR' to '$INST_DIR' ..." 84 | cp -Rf "${SG_DIR}/." "$INST_DIR" 85 | 86 | _debug yellow " -> Adjusting permissions for '$INST_DIR' and files/folders within it..." 87 | # chmod 755 "$INST_DIR" "$INST_DIR"/*.sh 88 | # chmod -R 755 "$INST_DIR"/{base,lib} 89 | chmod 755 "$INST_DIR" 90 | chmod -R 777 "$INST_DIR"/logs 91 | local u=$(whoami) 92 | chown -R "$u" "$INST_DIR" 93 | 94 | _debug green " +++ Finished installing SG Shell Core locally into '$INST_DIR'" 95 | return 0 96 | } 97 | 98 | _sg_install_global() { 99 | local INST_DIR="$SG_GLOBALDIR" 100 | SG_IS_GLOBAL=1 101 | _debug green " (+) Installing SG Shell Core systemwide: '$INST_DIR' ...\n" 102 | # If the installation folder already exists, attempt to update it. 103 | # If the install appears to be damaged, NEED_REINSTALL would be set to 1, meaning that the install folder 104 | # was removed by fallback_update, so we should continue with the installation. 105 | if [[ -d "$INST_DIR" ]]; then 106 | _sg_fallback_update "$INST_DIR" 107 | ((${NEED_REINSTALL}==0)) && return 0 108 | fi 109 | _debug yellow " -> Creating folder '$INST_DIR' ..." 110 | sudo mkdir -p "$INST_DIR" &> /dev/null 111 | 112 | _debug yellow " -> Copying all files from '$SG_DIR' to '$INST_DIR' ..." 113 | sudo cp -Rf "${SG_DIR}/." "$INST_DIR" 114 | 115 | _debug yellow " -> Adjusting permissions for '$INST_DIR' and files/folders within it..." 116 | # sudo chmod 755 "$INST_DIR" "$INST_DIR"/*.sh 117 | # sudo chmod -R 755 "$INST_DIR"/{base,lib} 118 | sudo chmod 755 "$INST_DIR" 119 | sudo chmod -R 777 "$INST_DIR"/logs 120 | local u=$(whoami) 121 | sudo chown -R "$u" "$INST_DIR" 122 | 123 | _debug green " +++ Finished installing SG Shell Core systemwide into '$INST_DIR'" 124 | return 0 125 | } 126 | 127 | _sg_install() { 128 | local inst_type='auto' 129 | (($#>0)) && inst_type="$1" 130 | case "$inst_type" in 131 | aut*) 132 | if [[ $UID == 0 || $EUID == 0 ]]; then 133 | _sg_install_global 134 | return $? 135 | fi 136 | _sg_install_local 137 | return $? 138 | ;; 139 | glo*) 140 | _sg_install_global 141 | return $? 142 | ;; 143 | loc*) 144 | _sg_install_local 145 | return $? 146 | ;; 147 | *) 148 | msgerr bold red "ERROR: _sg_install was passed an invalid install type: '$inst_type'" 149 | return 1 150 | ;; 151 | esac 152 | } 153 | 154 | remove_sources() { 155 | sed -E "s/.*source \".*\.sh\".*//g" "$@" 156 | # raise_error 157 | } 158 | 159 | remove_comments() { 160 | sed -E "s/^#.*//g" "$@" | sed -E "s/^[[:space:]]+#.*//g" 161 | # raise_error "unexpected error removing comments" "${BASH_SOURCE[0]}" $LINENO 162 | } 163 | 164 | _sg_compile() { 165 | local use_file=0 out_file 166 | (($#>0)) && use_file=1 && out_file="$1" || out_file="$(mktemp)" 167 | : ${SHEBANG_LINE='#!/usr/bin/env bash'} 168 | { 169 | echo "$SHEBANG_LINE" 170 | export __CMP_NOW=$(date) 171 | sg_copyright=" 172 | ############################################################# 173 | # # 174 | # Privex's Shell Core (Version v${S_CORE_VER}) # 175 | # Cross-platform / Cross-shell helper functions # 176 | # # 177 | # Released under the GNU GPLv3 # 178 | # # 179 | # Official Repo: github.com/Privex/shell-core # 180 | # # 181 | # This minified script was compiled at: # 182 | # $__CMP_NOW # 183 | # # 184 | ############################################################# 185 | " 186 | echo "$sg_copyright" 187 | echo -e "\n### --------------------------------------" 188 | echo "### Privex/shell-core/init.sh" 189 | echo "### --------------------------------------" 190 | cat "${SG_DIR}/init.sh" | remove_sources | remove_comments | tr -s '\n' 191 | echo -e "\n### --------------------------------------" 192 | echo "### Privex/shell-core/base/identify.sh" 193 | echo "### --------------------------------------" 194 | cat "${SG_DIR}/base/identify.sh" | remove_sources | remove_comments | tr -s '\n' 195 | echo -e "\n### --------------------------------------" 196 | echo "### Privex/shell-core/base/colors.sh" 197 | echo "### --------------------------------------" 198 | cat "${SG_DIR}/base/colors.sh" | remove_sources | remove_comments | tr -s '\n' 199 | echo -e "\n### --------------------------------------" 200 | echo "### Privex/shell-core/base/permission.sh" 201 | echo "### --------------------------------------" 202 | cat "${SG_DIR}/base/permission.sh" | remove_sources | remove_comments | tr -s '\n' 203 | 204 | for f in "${SG_DIR}/lib"/*.sh; do 205 | local b=$(basename "$f") 206 | echo -e "\n### --------------------------------------" 207 | echo "### Privex/shell-core/lib/$b" 208 | echo "### --------------------------------------" 209 | cat $f | remove_sources | remove_comments | tr -s '\n' 210 | done 211 | echo 212 | echo "$sg_copyright" 213 | echo 214 | } > "$out_file" 215 | 216 | (($use_file==1)) && msg green " -> Compiled ShellCore into file '$out_file'" || { cat "$out_file"; rm -f "$out_file"; } 217 | 218 | return 0 219 | } 220 | 221 | _help() { 222 | msg green "Privex's Shell Core - Version v${S_CORE_VER}" 223 | msg green "(C) 2019 Privex - Released under the GNU GPL v3 license" 224 | msg yellow "-------------------------------------------------------------------" 225 | msg cyan "Official Repo: https://github.com/Privex/shell-core" 226 | msg 227 | msg bold green "Available run.sh commands:\n" 228 | 229 | msg bold magenta "\t - install (global|local|auto)" 230 | msg magenta "\t Install Shell Core to allow other scripts to find it. If you don't specify\n" \ 231 | "\t the install type (global, local, or auto), then it will default to 'auto'.\n" \ 232 | "\t \n" \ 233 | "\t local - Install Shell Core into the home folder: '$SG_LOCALDIR'\n" \ 234 | "\t global - Install Shell Core into the system folder: '$SG_GLOBALDIR'\n" \ 235 | "\t auto - If the current user is 'root', install globally; otherwise locally.\n" 236 | msg cyan "-------------------------------------------------------------------\n" 237 | msg bold magenta "\t - update (localfb)" 238 | msg magenta "\t Updates the installation of Shell Core in this folder '${SG_DIR}'. \n" \ 239 | "\t \n" \ 240 | "\t If you're calling this command on a global installation of Shell Core from a \n" \ 241 | "\t potentially non-privileged user, you may wish to pass the argument 'localfb', \n" \ 242 | "\t which means: \n" \ 243 | "\t \n" \ 244 | "\t 'If the current user has no permissions to update this install, nor sudo, \n" \ 245 | "\t then install or update the local user's Shell Core installation.'\n" 246 | msg cyan "-------------------------------------------------------------------\n" 247 | 248 | } 249 | 250 | case "$1" in 251 | help) 252 | _help 253 | ;; 254 | install) 255 | _sg_install "${@:2}" 256 | exit $? 257 | ;; 258 | update) 259 | localfb=0 260 | (($#>1)) && [[ "$2" == "localfb" ]] && localfb=1 261 | 262 | if can_write "${SG_DIR}/.git/HEAD"; then 263 | _sg_auto_update "${SG_DIR}" 264 | exit $? 265 | fi 266 | msgerr bold yellow "WARNING: ${SG_DIR}/.git/HEAD is not writable by this user." 267 | if (($localfb==1)); then 268 | msgerr yellow "Falling back to local install/update" 269 | _sg_install_local 270 | exit $? 271 | fi 272 | msgerr red "As 'localfb' was not specified, giving up. Cannot update this installation." 273 | exit 5 274 | ;; 275 | compile) 276 | _sg_compile "${@:2}" 277 | exit $? 278 | ;; 279 | dockertest) 280 | error_control 2 281 | cd "$SG_DIR" 282 | msg green " -> Building image tag 'sgshell' from directory '$SG_DIR'" 283 | docker build -t sgshell . 284 | (($?!=0)) && msgerr bold red "Error building image 'sgshell'. Please see log messages above." && exit 1 285 | 286 | msg bold green " + Successfully built image 'sgshell'" 287 | msg green " -> Starting container 'sg-shell' using image 'sgshell'" 288 | docker run --rm --name sg-shell -itd sgshell 289 | 290 | (($?!=0)) && msgerr bold red "Error while launching 'sg-shell'. See log messages above." && exit 1 291 | 292 | msg green " -> Opening a bash prompt in container 'sg-shell'. Start by typing 'source load.sh'" 293 | docker exec -it sg-shell bash 294 | 295 | msg yellow " !! Looks like you're finished. Now stopping and removing container 'sg-shell'..." 296 | docker stop sg-shell 297 | docker rm sg-shell &> /dev/null 298 | msg green " +++ Done. Exiting cleanly." 299 | exit 0 300 | ;; 301 | 302 | *) 303 | error_control 2 304 | msg bold red "Unknown command '$1'\n" 305 | _help 306 | exit 99 307 | ;; 308 | esac 309 | 310 | -------------------------------------------------------------------------------- /tests.bats: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bats 2 | 3 | load $PWD/load.sh 4 | 5 | fail_print() { >&3 echo -n $'\n# ------------\n'; >&3 echo "# [FAIL] $@" $'\n'; return 1; } 6 | 7 | #### core_func.len 8 | #### len() outputs the number of characters in the passed string(s) 9 | 10 | @test "test len() outputs 0 for '' (empty string)" { 11 | run len "" 12 | [ "$status" -eq 0 ] 13 | # echo "len of '' is: $output" >&3 14 | ((output==0)) || fail_print "len of '' is: $output" 15 | } 16 | 17 | @test "test len() outputs 5 for 'hello'" { 18 | run len "hello" 19 | [ "$status" -eq 0 ] 20 | ((output==5)) || fail_print "len of 'hello' is: $output" 21 | } 22 | 23 | @test "test len() outputs 11 for 'hello' 'world' (should expand to 'hello world')" { 24 | run len "hello" "world" 25 | [ "$status" -eq 0 ] 26 | # echo "len of 'hello' 'world' is: $output" >&3 27 | ((output==11)) || fail_print "len of 'hello' 'world' is: $output" 28 | } 29 | 30 | @test "test len() outputs 11 for \$'hello\\nworld' (newlines should count as 1 char)" { 31 | run len $'hello\nworld' 32 | # echo "len of 'hello\\nworld' is: $output" >&3 33 | [ "$status" -eq 0 ] 34 | ((output==11)) || fail_print "len of 'hello\\nworld' is: $output" 35 | } 36 | 37 | 38 | #### core_func.has_binary 39 | #### has_binary should return 0 only for existant binaries on disk. NOT functions / aliases. 40 | 41 | example_test_func() { echo "hello world"; } 42 | 43 | 44 | @test "test has_binary returns zero with existant binary (ls)" { 45 | run has_binary ls 46 | [ "$status" -eq 0 ] 47 | } 48 | 49 | @test "test has_binary returns non-zero with non-existant binary (thisbinaryshouldnotexit)" { 50 | run has_binary thisbinaryshouldnotexit 51 | [ "$status" -eq 1 ] 52 | } 53 | 54 | @test "test has_binary returns non-zero for existing function but non-existant binary (example_test_func)" { 55 | run has_binary example_test_func 56 | [ "$status" -eq 1 ] 57 | } 58 | 59 | #### core_func.has_command 60 | #### has_command should return 0 for both existing functions and existing binaries on disk 61 | 62 | @test "test has_command returns zero for existing function but non-existant binary (example_test_func)" { 63 | run has_command example_test_func 64 | [ "$status" -eq 0 ] 65 | } 66 | 67 | @test "test has_command returns zero for non-existing function but existant binary (ls)" { 68 | run has_command example_test_func 69 | [ "$status" -eq 0 ] 70 | } 71 | 72 | @test "test has_command returns non-zero for non-existing function and non-existant binary (thisbinaryshouldnotexit)" { 73 | run has_command thisbinaryshouldnotexit 74 | [ "$status" -eq 1 ] 75 | } 76 | 77 | ### helpers.split_by 78 | 79 | 80 | @test "test split_by by splitting 'hello:world:test' on char ':'" { 81 | run split_by "hello:world:test" ":" 82 | [ "$status" -eq 0 ] 83 | data=($output) 84 | [ "${data[0]}" == "hello" ] || fail_print "data[0] is: ${data[0]}" 85 | [ "${data[1]}" == "world" ] || fail_print "data[1] is: ${data[1]}" 86 | [ "${data[2]}" == "test" ] || fail_print "data[2] is: ${data[2]}" 87 | } 88 | 89 | @test "test split_by by splitting 'hello:world,testing:orange' on char ','" { 90 | run split_by 'hello:world,testing:orange' "," 91 | [ "$status" -eq 0 ] 92 | data=($output) 93 | [ "${data[0]}" == "hello:world" ] || fail_print "data[0] is: ${data[0]}" 94 | [ "${data[1]}" == "testing:orange" ] || fail_print "data[1] is: ${data[1]}" 95 | } 96 | 97 | @test "test split_by returns 1 with error if not enough args [1 args]" { 98 | run split_by "hello:world:test" 99 | [ "$status" -eq 1 ] 100 | [ "$output" = "Error: split_by requires exactly 2 arguments" ] 101 | } 102 | 103 | @test "test split_by returns 1 with error if not enough args [3 args]" { 104 | run split_by "hello:world:test" "," ":" 105 | [ "$status" -eq 1 ] 106 | [ "$output" = "Error: split_by requires exactly 2 arguments" ] 107 | } 108 | 109 | ### helpers.split_assoc 110 | 111 | @test "test split_assoc by splitting 'hello:world,testing:orange' on char ',' and ':'" { 112 | run split_assoc 'hello:world,testing:orange' "," ":" 113 | [ "$status" -eq 0 ] 114 | source "$output" 115 | [ "${assoc_result[hello]}" == "world" ] || fail_print "assoc_result[hello] is: ${assoc_result[hello]}" 116 | [ "${assoc_result[testing]}" == "orange" ] || fail_print "assoc_result[testing] is: ${assoc_result[testing]}" 117 | } 118 | 119 | @test "test split_assoc by splitting 'hello=world;testing=orange' on char ';' and '='" { 120 | run split_assoc 'hello=world;testing=orange' ";" "=" 121 | [ "$status" -eq 0 ] 122 | source "$output" 123 | [ "${assoc_result[hello]}" == "world" ] 124 | [ "${assoc_result[testing]}" == "orange" ] 125 | } 126 | 127 | 128 | @test "test split_assoc returns 1 with error if not enough args [2 args]" { 129 | run split_assoc 'hello=world;testing=orange' ";" 130 | [ "$status" -eq 1 ] 131 | [ "$output" = "Error: split_assoc requires exactly 3 arguments" ] 132 | } 133 | 134 | @test "test split_assoc returns 1 with error if not enough args [4 args]" { 135 | run split_assoc 'hello=world;testing=orange' ";" "," "/" 136 | [ "$status" -eq 1 ] 137 | [ "$output" = "Error: split_assoc requires exactly 3 arguments" ] 138 | } 139 | 140 | ### helpers.containsElement 141 | 142 | test_array=(hello world example) 143 | 144 | @test "test containsElement returns 0 if array contains specified element" { 145 | run containsElement "world" "${test_array[@]}" 146 | [ "$status" -eq 0 ] 147 | } 148 | 149 | @test "test containsElement returns 1 if array does not contain specified element" { 150 | run containsElement "orange" "${test_array[@]}" 151 | [ "$status" -eq 1 ] 152 | } 153 | 154 | ### trap_helper.trap_add / get_trap_cmd 155 | 156 | _tst_get_trap() { get_trap_cmd "$1" | tr -s '\n'; } 157 | 158 | @test "test trap_add+get_trap_cmd by adding a USR1 trap with trap_add and confirm exists with get_trap_cmd " { 159 | 160 | trap_add "echo 'hello bats test'" USR1 161 | [ "$?" -eq 0 ] 162 | # res=$(get_trap_cmd USR1 | tr -d '\n') 163 | run _tst_get_trap USR1 164 | [ "$?" -eq 0 ] 165 | # echo -E "# get_trap_cmd USR1 - res: $res" >&3 166 | [ "${lines[0]}" = "echo 'hello bats test'" ] || fail_print "get_trap_cmd USR1 - lines[0]: ${lines[0]}" 167 | } 168 | 169 | @test "test trap_add+get_trap_cmd by adding two USR1 traps and confirm both commands in trap " { 170 | trap_add "echo 'hello bats one'" USR1 171 | trap_add "echo 'hello bats two'" USR1 172 | [ "$?" -eq 0 ] 173 | # res=$(get_trap_cmd USR1 | tr -d '\n') 174 | run _tst_get_trap USR1 175 | [ "$status" -eq 0 ] 176 | # echo -E "# get_trap_cmd USR1 x2 - output: $output" >&3 177 | [ "${lines[0]}" = "echo 'hello bats one'" ] || fail_print "get_trap_cmd USR1 x2 - lines[0]: ${lines[0]}" 178 | [ "${lines[1]}" = "echo 'hello bats two'" ] || fail_print "get_trap_cmd USR1 x2 - lines[1]: ${lines[1]}" 179 | } 180 | 181 | @test "test get_trap_cmd does not return anything with non-existent USR2 trap" { 182 | res=$(get_trap_cmd USR2 | tr -d '\n') 183 | [ "$?" -eq 0 ] 184 | [ -z "$res" ] || fail_print "get_trap_cmd USR2 - res: $res" 185 | } --------------------------------------------------------------------------------