shell-base/module.base.src

96 lines
2.8 KiB
Bash

#!/bin/bash
# echo loading module library
# source with set -a and set +a to have these bootstrap functions available in the environment
module_confirm() {
local FILE
local DIR
local NAME
DIR=$1
NAME=$2
# TODO use file instead for valid extensions
# will look for valid module extensions and also look for duplicate modules with a directory which is not allowed
FILE="$($(which find) -L ${DIR} -type f -name "${NAME}.mod" -o -name "${NAME}".lib -o -name "${NAME}".func -o -name "${NAME}".sh -o -name "${NAME}".env)"
# echo files found $FILE
COUNT=0
if [ "$FILE" ]; then
COUNT=$(echo $FILE | xargs -n 1 | wc -l)
fi
if [ $COUNT -gt 1 ]; then
>&2 echo two or more modules of same name found, aborting
>&2 echo $FILE | xargs -n 1
return 1
fi
[[ $COUNT == 1 ]] && echo $FILE
}
# Returns path to module if succesful
module_find() {
[ ! $1 ] && >&2 echo "no module specified" && return 1
local MDIRS
local MDIR
local DIRS
local MODULE=$1
# MODULE_DIRS is array set in the environment and is an array of additional directories to
# search for modules. This makes is easy to include a custom module libraries outside
# the shell system. These take precedence over any modules found in shell directories below.
# Precedence is first in list to last.
# BASH_SHELL_DIRS holds shell directories to search for modules. If will be searched
# in revsere order, user or network repos over host over base
DIRS=( ${BASH_SHELL_DIRS:-$BASH_SHELL_BASE} ${BASH_SHELL_NETWORKS_LOADED} )
[ -d BASH_SHELL_USER_DIR ] && DIRS=("${DIRS[@]}" "BASH_SHELL_USER_DIR")
[ -d $BASH_SHELL_DEV ] && DIRS=("${DIRS[@]}" "$BASH_SHELL_DEV")
# echo "before: ${DIRS[@]}";
DIRS=("${DIRS[@]/%/\/modules}")
DIRS=("${MODULE_DIRS[@]}" "${DIRS[@]}")
# echo "after: ${DIRS[@]}"
cnt=${#DIRS[@]}
for ((i=1;i<=cnt;i++)); do
# find modules in reverse order so more specific ones override
DIR="${DIRS[cnt-i]}"
if [[ -d $DIR ]]; then
# echo $DIR $MODULE
RES=$(module_confirm "$DIR" "$MODULE")
[ $? -eq 0 ] && echo $RES && return 0
fi
done
>&2 echo no module found anywhere
return 1
}
module_load() {
local module;local mpath
[ ! $1 ] && >&2 echo "no module specified" && return 1
local FILE
for module in "$@"
do
# is there way to not reload modules??
# if [[ $(eval "echo \"\$MODULE_$module_LOADED\"") ]]; then
# echo $module already loaded
# else
eval "_${module}_ () { echo "$fname test"; }"
mpath=$(module_find $module)
[ $? -ne 0 ] && >&2 echo extreme warning: no module $1 found, so was not loaded
source $mpath "$@"
# eval "MODULE_$module_LOADED=true"
# fi
done
}
# put here so it's globally available
# runs a script but loads the current interactive shell environment, not recommended unless there is a need
# mostly for testing. Better to source some part of the shell as needed using shell-process-directory module
shell_run () {
bash -ci ". ${1}"
}