Files
dotfiles/env/.local/scripts/newx

99 lines
1.9 KiB
Bash
Executable File

#!/bin/zsh
# Creates a new executable file.
declare -a localOpt
declare -a functionOpt
declare -a shellOpt=("zsh")
declare -a helpOpt
DEBUG="$(env | grep DEBUG)"
zparseopts -D -K -- \
{l,-local}+:=localOpt \
{f,-function}+:=functionOpt \
{s,-shell}+=shellOpt \
{h,-help}=helpOpt
shell=${shellOpt[-1]}
localPath=${localOpt[-1]}
#-------------------- Helpers --------------------
function usage() {
cat << EOF
newx: Create new executable (script, function, or local script).
Typical usage:
newx foo (creates new script named 'foo')
Usage: newx [-l <name>] [-f <name>] [-s <shell>]
-l | --local <name>: Create a script in current directory.
-f | --function <name>: Create a function.
Advanced options:
-s | --shell <shell>: Customize the shell for the script.
EOF
}
function debug_print() {
[ -n "$DEBUG" ] \
&& echo "DEBUG: $1"
}
function create_script() {
local script_path="$1"
debug_print "shell: $shell"
debug_print "script-path: $script_path"
printf "#!/bin/%s\n\n" "${shell}" > "${script_path}"
chmod +x "${script_path}"
exec "${EDITOR}" +2 "${script_path}"
}
function parse_local_path() {
if [ -z "$localPath" ]; then
local prefix="${1[1]}${1[2]}"
debug_print "prefix: $prefix"
[ "$prefix" = "./" ] && localPath="$1"
fi
}
#-------------------- Main --------------------
debug_print "first-arg: $1"
if [ -n "${helpOpt}" ]; then
usage && exit 0
fi
if [ -n "${functionOpt[-1]}" ]; then
debug_print "function-opt: $functionOpt"
[ ! -d "$ZFUNCDIR" ] \
&& echo "Function directory not found" \
&& return 1
create_script "$ZFUNCDIR/${functionOpt[-1]}"
return 0
fi
parse_local_path "$1"
if [ -n "$localPath" ]; then
debug_print "local: $localPath"
create_script "$localPath"
return 0
fi
debug_print "scripts: $1"
[ ! -d "$SCRIPTS" ] \
&& echo "Scripts directory not found. Set the SCRIPTS environment variable." \
&& return 1
create_script "${SCRIPTS}/$1"