V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
guonaihong
V2EX  ›  Go 编程语言

从零实现一个命令行解析器

  •  
  •   guonaihong ·
    guonaihong · 2020-02-17 12:33:22 +08:00 · 2546 次点击
    这是一个创建于 1530 天前的主题,其中的信息可能已经有所发展或是发生改变。

    出发点

    分享下从零实现一个命令解析器的所有细节。

    项目地址

    https://github.com/guonaihong/clop

    一个简单的例子(以 linux cat 命令举例)

    package main
    
    import (
    	"fmt"
    	"github.com/guonaihong/clop"
    )
    
    type cat struct {
    	NumberNonblank bool `clop:"-c;--number-nonblank" 
    	                     usage:"number nonempty output lines, overrides"`
    
    	ShowEnds bool `clop:"-E;--show-ends" 
    	               usage:"display $ at end of each line"`
    
    	Number bool `clop:"-n;--number" 
    	             usage:"number all output lines"`
    
    	SqueezeBlank bool `clop:"-s;--squeeze-blank" 
    	                   usage:"suppress repeated empty output lines"`
    
    	ShowTab bool `clop:"-T;--show-tabs" 
    	              usage:"display TAB characters as ^I"`
    
    	ShowNonprinting bool `clop:"-v;--show-nonprinting" 
    	                      usage:"use ^ and M- notation, except for LFD and TAB" `
    
    	Files []string `clop:"args=files"`
    }
    
    func main() {
    
    	c := cat{}
    	err := clop.Bind(&c)
    
    	fmt.Printf("%#v, %s\n", c, err)
    }
    
    5 条回复    2020-02-17 20:23:05 +08:00
    guonaihong
        1
    guonaihong  
    OP
       2020-02-17 16:08:34 +08:00
    看来我发消息,要有个强劲的大心脏。一不小心就没人看了,哈哈。
    unicloud
        2
    unicloud  
       2020-02-17 16:45:15 +08:00
    确实有点尴尬啊~哈哈
    guonaihong
        3
    guonaihong  
    OP
       2020-02-17 19:13:36 +08:00
    @unicloud 这是在微笑在中掩示尴尬。。。哈哈
    hijoker
        4
    hijoker  
       2020-02-17 19:40:18 +08:00
    加油,奥力给
    guonaihong
        5
    guonaihong  
    OP
       2020-02-17 20:23:05 +08:00
    @hijoker 恩,加油,奥力给是啥意思?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4834 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 05:38 · PVG 13:38 · LAX 22:38 · JFK 01:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.