Basically what foo(**bar)
does in python, here I’d want something like
foo **bar.yaml
and that would become
foo --bar1=1 --bar2=2
Where bar.yaml
would be
bar1: 1
bar2: 2
CodePudding user response:
You could use a combination of sed
and xargs
:
sed -E 's/^(. ):[[:space:]] (. )$/--\1=\2/' bar.yaml | xargs -d '\n' foo
sed
converts the format of bar.yaml
lines (e.g. bar1: 1
-> --bar1=1
) and xargs
feeds the converted lines as arguments to foo
.
You could of course modify/extend the sed
part to support other formats or single-dash options like -v
.
To test if this does what you want, you can run this Bash script instead of foo
:
#!/usr/bin/env bash
echo "Arguments: $#"
for ((i=1; i <= $#; i )); do
echo "Argument $i: '${!i}'"
done
CodePudding user response:
Here's a version for zsh
. Run this code or add it to ~/.zshrc
:
function _yamlExpand {
setopt local_options extended_glob
# 'words' array contains the current command line
# yaml filename is the last value
yamlFile=${words[-1]}
# parse 'key : value' lines from file, create associative array
typeset -A parms=("${(@s.:.)${(f)"$(<${yamlFile})"}}")
# trim leading and trailing whitespace from keys and values
# requires extended_glob
parms=("${(kv@)${(kv@)parms##[[:space:]]##}%%[[:space:]]##}")
# add -- and = to create flags
typeset -a flags
for key val in "${(@kv)parms}"; do
flags =("--${key}='${val}'")
done
# replace the value on the command line
compadd -QU -- "$flags"
}
# add the function as a completion and map it to ctrl-y
compdef -k _yamlExpand expand-or-complete '^Y'
Type in the command and the yaml file name:
print -l -- ./bar.yaml
With the cursor immediately after the yaml file name, hit ctrl y. The yaml filename will be replaced with the expanded parameters:
print -l -- --bar1='1' --bar2='2'
Now you're set - you can hit enter, or add any other parameters, just like any other command line.
Notes:
- This only supports the
yaml
subset in your example. - You can add more
yaml
parsing to the function, possibly withyq
. - In this version, the cursor must be next to the
yaml
filename - otherwise the last value inwords
will be empty. You can add code to detect that case and then alter thewords
array withcompset -n
. compadd
andcompset
are described in thezshcompwid
man page.zshcompsys
has details oncompdef
; the section on autoloaded files describes another way to deploy something like this.