wcarhart / koi

Bashful argument parsing

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add verifyingfunction

wcarhart opened this issue · comments

Sometimes we have multiple command line arguments that need to be verified in the same way. For example, if we want to verify that all of our input parameters are .json files, we might want to run the following function on them:

function __verifyjson {
  for file in "$@" ; do
    if [[ "$file" != *.json ]] ; then
      __errortext "input files must be JSON"
      return 1
    fi
  done
}

It would be cool if we could add a 7th argument to __addarg, which maybe we could call verifyingfunction, where the user could pass in a function that would be called to verify the argument.

For example, if we had our function __verifyjson defined like above, then our __addarg could look something like:

function dosomethingwithjson {
  __addarg "-h" "--help" "help" "optional" "" "Something to do with JSON files"
  __addarg "" "file" "positionalarray" "required" "" "The JSON files to use" "__verifyjson"
  __parseargs "$@"
  # do something with our verified files, which we now know are JSON
}

Within __parseargs, we could transform:

__addarg "" "file" "positionalarray" "required" "" "The JSON files to use" "__verifyjson"

into something along the lines of:

# i is index of argument
for arg in "${file[@]}" ; do
  "${verifyingfunctions[$i]}" "$arg"
done

We could take it one step further by allowing the user to specify arguments after their verifyingfunction. Perhaps we want to generalize __verifyjson to __verifyfiletype, which we could define as:

function __verifytype {
  for file in "$@" ; do
    if [[ "$file" != *."$2" ]] ; then
      __errortext "input files must be of type $2"
      return 1
    fi
  done
}

They could then call it with __addarg:

function dosomethingwithjson {
  __addarg "-h" "--help" "help" "optional" "" "Something to do with JSON files"
  __addarg "" "file" "positionalarray" "required" "" "The JSON files to use" "__verifyfiletype json"
  __parseargs "$@"
  # do something with our verified files, which we now know are JSON
}

Which would transform in __parseargs to something like (this is not tested, just an idea):

# i is index of argument
for arg in "${file[@]}" ; do
  local commandandargs=( "${verifyingfunctions[$i]}" )
  ${commandandargs[@]} "$arg"
done

A check should be done in __addarg to verify that all the functions passed in as verifyingfunctions are actually defined in the context of the script.

Implemented in #35.