This repository has been archived on 2022-02-20. You can view files and clone it, but cannot push or open issues/pull-requests.
bash-shell-base/modules/module.sh

142 lines
2.4 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
# shebang for syntax detection, not a command
# do *not* set executable!
declare -Ag _modules_
shopt -s expand_aliases
alias _args_='(( $# ))'
alias _to_args_='set --'
module.already_loaded () {
declare -Ag _modules_
[[ -v _modules_[${BASH_SOURCE[1]}] ]]
}
_blank_ () {
[[ -z ${1:-} ]]
}
_defined_ () {
[[ -v $1 ]]
}
_eq_ () {
[[ $1 == "${2:-}" ]]
}
_functions_ () {
env -i bash <<END
shopt -s expand_aliases
alias source=:
\\source $1 &>/dev/null
compgen -A function;:
END
}
_in_ () {
[[ $IFS$1$IFS == *"$IFS$2$IFS"* ]]
}
_pop_ () {
local -n ref1=$1
local ref2=${2:-}
_present_ $ref2 && printf -v $ref2 %s "${ref1[-1]}"
unset -v $1[-1]
}
_present_ () {
[[ -n ${1:-} ]]
}
_push_ () {
local -n ref=$1
ref+=( "$2" )
}
_parent_=${BASH_SOURCE[1]:-}
[[ ${1:-} != module ]] && return
set -- ${*:2}
_numargs_+=( $# )
{ ! _args_ && _present_ ${_file_:-} && _eq_ $_parent_ $_file_ ;} && return
{ ! _args_ && _present_ $_parent_ && ! _eq_ ${_parent_##*/} module ;} && {
_in_ "${_ancestors_[*]:-}" $_parent_ && return
_push_ _ancestors_ $_parent_
}
! _args_ && _to_args_ $_parent_
for _file_; do
_module_=${_file_%%=*}
_file_=${_file_#*=}
_defined_ _modules_[$_file_] && continue
_eq_ $_module_ $_file_ && {
_module_=${_module_##*/}
_module_=${_module_%.*}
}
_prefixes_+=( $_module_ )
_push_ _aliases_ "$(alias)"
unalias -a
_functions_=$(_functions_ $_file_)
for _function_ in $_functions_; do
printf -v _prefix_ %s. ${_prefixes_[*]}
alias $_function_=$_prefix_$_function_
done
_push_ _files_ $_file_
_push_ _funcs_ "$_functions_"
set --
source $_file_
unset -v _prefixes_[-1]
_pop_ _files_ _file_
_pop_ _funcs_ _functions_
_modules_[$_file_]=''
for _function_ in $_functions_; do
unalias $_function_
done
eval "${_aliases_[-1]}"
_pop_ _aliases_
done
! (( ${#_files_[*]} )) && {
unalias _args_
unalias _to_args_
unset -f _blank_
unset -f _defined_
unset -f _eq_
unset -f _in_
unset -f _pop_
unset -f _present_
unset -f _push_
unset -v _file_
unset -v _funcs_
unset -v _function_
unset -v _functions_
unset -v _module_
unset -v _name_
unset -v _parent_
unset -v _prefix_
unset -v _prefixes_
}
{ ! (( _numargs_[-1] )) && [[ -n ${BASH_SOURCE[1]} && ${BASH_SOURCE[1]##*/} != module ]] ;} && unset -v _ancestors_[-1]
unset -v _numargs_[-1]