【问题标题】:Is there a way to unpack a config file to cli flags in general?一般有没有办法将配置文件解压缩到cli标志?
【发布时间】:2021-10-21 09:02:04
【问题描述】:

基本上foo(**bar) 在 python 中的作用,这里我想要类似的东西

foo **bar.yaml

那会变成

foo --bar1=1 --bar2=2

bar.yaml 在哪里

bar1: 1
bar2: 2

【问题讨论】:

  • 最大的区别在于 Python 知道自己的 dict 格式和关键字参数传递。 bash 不知道 YAML foo 接受的选项。

标签: bash command-line-interface zsh


【解决方案1】:

您可以使用sedxargs 的组合:

sed -E 's/^(.+):[[:space:]]+(.+)$/--\1=\2/' bar.yaml | xargs -d '\n' foo

sed 转换bar.yaml 行的格式(例如bar1: 1 -> --bar1=1),xargs 将转换后的行作为参数提供给foo

您当然可以修改/扩展 sed 部分以支持其他格式或单破折号选项,例如 -v


要测试这是否符合您的要求,您可以运行此 Bash 脚本而不是 foo

#!/usr/bin/env bash
echo "Arguments: $#"
for ((i=1; i <= $#; i++)); do
    echo "Argument $i: '${!i}'"
done

【讨论】:

    【解决方案2】:

    这是zsh 的版本。运行这段代码或者添加到~/.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'
    

    zsh shell 提示符下,输入命令和 yaml 文件名:

    % print -l -- ./bar.yaml▃
    

    将光标紧跟在 yaml 文件名之后,点击 ctrl+y。 yaml 文件名将替换为扩展参数:

    % print -l -- --bar1='1' --bar2='2' ▃
    

    现在你准备好了;您可以按回车键或添加参数,就像任何其他命令行一样。


    注意事项:

    • 这仅支持您示例中的 yaml 子集。
    • 您可以在函数中添加更多yaml 解析,可能使用yq
    • 在此版本中,光标必须位于yaml 文件名旁边 - 否则words 中的最后一个值将为空。您可以添加代码来检测这种情况,然后将 words 数组更改为 compset -n
    • compaddcompsetzshcompwid 手册页中进行了描述。
    • zshcompsyscompdef 的详细信息;关于自动加载文件的部分描述了另一种部署此类内容的方法。

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 2013-03-18
      • 2020-02-08
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2019-01-21
      相关资源
      最近更新 更多