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/utility/source.func

126 lines
2.8 KiB
Plaintext
Raw Normal View History

#!/bin/bash
function source_dir () {
# USAGE
# will never source source .files or .directories
# all option arguments that contain globs/wildcards must be quoted to avoid expansion
# f sets path and file excludes from a supplied file path
# p option excludes additional paths below of the given name (and depth)
# d option sets the directory depth which is current directy by default, 0 is all
# x excludes file globs
# n inclucdes only file globs otherwise it's all except .files
# if no directory is given it will attempt to source the present working directory
# example:
# source_dir -p "archive" -x '"*.off" "*.md"' -d 0 # $DIR/$SUBDIR
declare OPTION
declare OPTARG
declare OPTIND
local EXCLUDE_FILE
local PATHS
local NAMES
local ENAMES
local DEPTH=1
local VERBOSE=0
while getopts 'p:d:e:n:f:' OPTION; do
case "$OPTION" in
f)
EXCLUDE_FILE=$OPTARG
# echo EXCLUDE FILE $EXCLUDE_FILE
;;
p)
# PATHS=("$OPTARG")
IFS=',' read -r -a PATHS <<< "$OPTARG"
# echo EXCLUDING THESE PATHS ${PATHS[*]}
;;
e)
IFS=',' read -r -a ENAMES <<< "${OPTARG}"
# echo EXCLUDING THESE FILE NAMES ${ENAMES[*]}
;;
n)
# NAMES=("$OPTARG")
IFS=',' read -r -a NAMES <<< "${OPTARG}"
# echo INCLUDING ONLY THESE FILE NAMES ${NAMES[*]}
;;
d)
DEPTH=$OPTARG
# echo "SOURCING TO DEPTH (0=any)" "$DEPTH"
;;
*)
echo unknown option $OPTION
;;
esac
done
shift $(( OPTIND - 1 ))
local DIR
DIR="$@"
if [ ! "$DIR" ]; then
if [ -v PS1 ]; then
echo no directory to source provided
echo sourcing present working directory $(pwd)
read -p "Do you want to continue? " -n 1 -r
[[ $REPLY =~ ^[Yy]$ ]] && DIR=$(pwd) || return 1
else
return 1
fi
fi
[ ! -d "$DIR" ] && echo " directory $DIR does not exist, aborting" && return 1
# echo dir $DIR
local FIND
FIND="find $DIR"
FIND+=$([ ! $DEPTH == 0 ] && echo " -maxdepth $DEPTH ")
# ignore all .name and .path by default
# TODO change to having a string
FIND+=" -type f ! -path \"*/.*/*\" ! -name \".*\" "
local name
local path
if [[ -f $EXCLUDE_FILE ]]; then
local ignores=$(cat "$EXLUCDE_FILE")
for exclude in $ignores ; do
[[ "$exclude" =~ '/'$ ]] && PATHS+=(${exclude::-1}) || ENAMES+=($exclude)
done
fi
if [[ ${PATHS[0]} ]]; then
for path in ${PATHS[@]}; do
# echo excluding $path
FIND+=$(echo ' ! -path "*/'$path'/*"')
done
fi
if [[ ${ENAMES[0]} ]]; then
for name in ${ENAMES[@]}; do
# echo excluding name $name
FIND+=$(echo " ! -name ${name}")
done
fi
if [[ ${NAMES[0]} ]]; then
for name in ${NAMES[@]}; do
# echo only finding $name
FIND+=$(echo " -name ${name}")
done
fi
echo
echo find dir: $DIR
echo find command: $FIND
local FILES
FILES=$(eval $FIND | sort)
# echo $FILES | xargs -n 1
for f in $FILES; do
echo sourcing: $f
# source "$f"
done
}