Page MenuHomec4science

cmdline_parser.sh
No OneTemporary

File Metadata

Created
Sat, Apr 27, 14:26

cmdline_parser.sh

#!/bin/bash
# Reusable command line parser
# USAGE: [in the calling script]
# 1) set the global variables: $DEFAULT_ITEMS, $DEFAULT_PARAMS and $DEFAULT_ACTIONS
# 2) set the global variable: $CALLBACK_PREFIX (default: cb_ )
# 3) implement each the callback: e.g. function cb_list() { ... } to implement the list action
# 4) call: run $@
ACTIONS=''
PARAMS=''
ITEMS=''
CALLBACK_PREFIX=${CALLBACK_PREFIX:-cb_}
function parse_args() {
while [ $# -gt 0 ]; do
case $1 in
"-o"|"--only")
shift
ITEMS=$1
shift
continue
;;
"-p"|"--params")
shift
PARAMS=$1
shift
continue
;;
*)
if [ -z "$ACTIONS" ]; then ACTIONS=$1; else ACTIONS="$ACTIONS $1"; fi
shift
;;
esac
done
# Source local configuration (if any)
source_workspace_configuration
# Compute final ITEMS
if [ -z "$ITEMS" ]; then ITEMS=$(get_default_items); fi
if [ -z "$ITEMS" ]; then ITEMS='~no~items~'; fi
# Compute final ACTIONS
if [ -z "$ACTIONS" ]; then ACTIONS=$(get_default_actions); fi
if [ -z "$ACTIONS" ]; then ACTIONS='help'; fi
# Compute final PARAMS
PARAMS=$(echo $PARAMS,$(get_default_params) | tr "," "\n" | sort -u | grep -v '^$' | tr "\n" "," | sed 's/,$//')
debug "End of command line parsing. ACTIONS: '$ACTIONS' | ITEMS: '$ITEMS' | PARAMS: '$PARAMS'"
}
function get_items() {
echo "$ITEMS" | sed "s/,/\n/g"
}
function get_actions() {
echo "$ACTIONS" | sed "s/ /\n/g"
}
function get_params() {
echo "$PARAMS" | sed "s/,/\n/g"
}
function get_parameter() {
key=$1
# Key alone
line=$(echo $PARAMS | sed "s/,/\n/g" | grep "^$key$")
if [ -n "$line" ]; then echo "set"; return; fi
# Key + value
line=$(echo $PARAMS | sed "s/,/\n/g" | grep "^$key=" | cut -d '=' -f 2-)
if [ -n "$line" ]; then echo $line; return; fi
# unset
echo "unset"
}
function is_set() {
param=$1
value=$(get_parameter $param)
if [ "$value" != "unset" ]; then return 1; else return 0; fi
}
function run() {
local action
local item
local global_rc=0 rc
parse_args $@
for action in $(get_actions); do
rc=0
main_switch $action $item
rc=$?
if [ $rc -ne 0 ]; then echo "rc: $rc"; fi
global_rc=$((rc+$rc))
done
if [ $global_rc -ne 0 ]; then echo "global_rc: $global_rc"; fi
return $global_rc
}
function get_default_items() {
echo $DEFAULT_ITEMS
}
function get_default_params() {
echo $DEFAULT_PARAMS
}
function get_default_actions() {
echo $DEFAULT_ACTIONS
}
function check_action() {
function_exists $1
return $?
}
function main_switch() {
local action=$1
local function_to_call="${CALLBACK_PREFIX}${action}"
check_action $function_to_call
if [ $? -eq 0 ]; then
debug "Calling action '$action' => '$function_to_call' on item(s) '$(get_items)'"
$function_to_call $(get_items)
return $?
else
error "invalid action: '$action' => '${CALLBACK_PREFIX}${action}' (not implemented ?)"
return 1
fi
return 0
}
# EOF

Event Timeline