Linux fish shell 中自动补全 go Cobra 创建的命令

文章目录

    书接上回,自从基于 cobra 完成了 Golang AST 解析 struct 字段,自动生成 CRUD 代码,又添加了部分功能。这个自动帮我搬砖的代码生成器基本完成了。😊

    但是,在项目中使用的时候,还是有点小瑕疵,就是不能在 fish shell 中自动补全命令,主要是我创建的命令,命令我自己都记不住🥲。每次靠输入 cobra 帮助参数来查看,也略显麻烦。于是,我想能否像 smug 一样,实现自动补全命令。查了一下,果然可以:

    添加 fish 自动补全

    cobra 内置了针对各种 shell 的自动补全功能。诸如,fish,bash,zsh,powershell。

    例如,我的搬砖工具名为 go_snip,要查看如何生成 fish 自动补全配置,可以输入命令查看

    > go_snip completion fish --help
    
    Generate the autocompletion script for the fish shell.
    
    To load completions in your current shell session:
    
            go_snip completion fish | source
    
    To load completions for every new session, execute once:
    
            go_snip completion fish > ~/.config/fish/completions/go_snip.fish
    
    You will need to start a new shell for this setup to take effect.
    
    Usage:
      go_snip completion fish [flags]
    
    Flags:
      -h, --help              help for fish
          --no-descriptions   disable completion descriptions
    

    如果,之前 fish shell 没有配置过自动补全,需要新建一个目录:

    mkdir ~/.config/fish/completions/
    

    然后执行导入配置操作:

    > go_snip completion fish > ~/.config/fish/completions/go_snip.fish
    

    然后,就可以正常使用自动补全了。

    实际效果

    按一次 tab 就会出现命令提示,按两次 tab 就能看到所有命令:

    linux fish shell 中自动补全 go cobra 创建的命令

    生成的 fish 配置内容是啥

    纯好奇,打开 ~/.config/fish/completions/go_snip.fish

    略去了前面的函数定义。完全如同画鬼符一般,看不懂。。。

    # Remove any pre-existing completions for the program since we will be handling all of them.
    complete -c go_snip -e
    
    # this will get called after the two calls below and clear the $__go_snip_perform_completion_once_result global
    complete -c go_snip -n '__go_snip_clear_perform_completion_once_result'
    # The call to __go_snip_prepare_completions will setup __go_snip_comp_results
    # which provides the program's completion choices.
    # If this doesn't require order preservation, we don't use the -k flag
    complete -c go_snip -n 'not __go_snip_requires_order_preservation && __go_snip_prepare_completions' -f -a '$__go_snip_comp_results'
    # otherwise we use the -k flag
    complete -k -c go_snip -n '__go_snip_requires_order_preservation && __go_snip_prepare_completions' -f -a '$__go_snip_comp_results'
    

    新建命令后,是否需要重新导入

    例如,我再新添加一个子命令

    > cobra-cli add test1
    > go install
    

    并不需要再次导入 fish 补全配置,之前的配置支持列出所有的命令。

    fish 的配置目录结构

    > tree ~/.config/fish/
    /home/zhongwei/.config/fish/
    ├── completions
    │   └── go_snip.fish
    ├── config.fish
    └── fish_variables
    
    1 directory, 3 files
    

    Makefile

    这个操作不太容易记住,特别是电脑比较多的情况,还是记录到 Makefile 中比较靠谱。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式