Home > database >  Is there a way to unpack a config file to cli flags in general?
Is there a way to unpack a config file to cli flags in general?

Time:10-23

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 with yq.
  • In this version, the cursor must be next to the yaml filename - otherwise the last value in words will be empty. You can add code to detect that case and then alter the words array with compset -n.
  • compadd and compset are described in the zshcompwid man page.
  • zshcompsys has details on compdef; the section on autoloaded files describes another way to deploy something like this.
  • Related