Skip to content

Instantly share code, notes, and snippets.

@blakek
Created September 15, 2023 21:07
Show Gist options
  • Save blakek/da8751e1a1444446c756e6ad9daa7838 to your computer and use it in GitHub Desktop.
Save blakek/da8751e1a1444446c756e6ad9daa7838 to your computer and use it in GitHub Desktop.
Bash module idea
#!/usr/bin/env bash
declare -A IMPORTS
# Returns the path of the script of the caller
function relative_path() {
dirname "${BASH_SOURCE[1]}"
}
# Imports a module
import() {
# Relative path to module
local caller_dir=$(dirname "${BASH_SOURCE[1]}")
local module_path=$(realpath "$caller_dir/$1")
local module_name=$(basename "${module_path%.*}") # Use the basename as default module_name
# Check if "as" keyword is used for aliasing
if [[ $2 == "as" && -n $3 ]]; then
module_name=$3
fi
local caller_script=$(realpath "${BASH_SOURCE[1]}")
# Create a unique namespace for each module based on its real path
local namespace="$module_name"
# Check if this script has already imported this module
if [[ ${IMPORTS["$caller_script:$module_path"]} == 1 ]]; then
return
fi
# Mark this module as imported by this script
IMPORTS["$caller_script:$module_path"]=1
while read -r function_name; do
eval "
$namespace.$function_name() {
source \"$module_path\"
$function_name \"\$@\"
}
"
done < <(
source "$module_path"
compgen -A function
)
}
# Source the entry-point script
source "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment