├── LICENSE ├── README.md ├── application.go ├── application_test.go ├── argv ├── argv.go └── parse.go ├── command.go ├── error.go ├── flag ├── arguments.go ├── flag.go ├── flag_test.go ├── options.go └── parse.go ├── go.mod ├── go.sum └── process └── daemon.go /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > OpenMix 出品:[https://openmix.org](https://openmix.org/mix-go) 2 | 3 | ## Mix XCLI 4 | 5 | 命令行交互指挥官 6 | 7 | CLI Interactive Commander 8 | 9 | ## Overview 10 | 11 | 一个命令行交互与指挥管理工具,它可以让单个 CLI 可执行多种功能,同时它还包括命令行参数获取、全局 panic 捕获与处理、程序后台执行等命令行开发常用功能。 12 | 13 | ## Installation 14 | 15 | ``` 16 | go get github.com/mix-go/xcli 17 | ``` 18 | 19 | ## Quick start 20 | 21 | ```go 22 | package main 23 | 24 | import ( 25 | "github.com/mix-go/xcli" 26 | "github.com/mix-go/xcli/flag" 27 | ) 28 | 29 | func main() { 30 | xcli.SetName("app").SetVersion("0.0.0-alpha") 31 | cmd := &xcli.Command{ 32 | Name: "hello", 33 | Short: "Echo demo", 34 | RunF: func() { 35 | name := flag.Match("n", "name").String("default") 36 | // do something 37 | }, 38 | } 39 | opt := &xcli.Option{ 40 | Names: []string{"n", "name"}, 41 | Usage: "Your name", 42 | } 43 | cmd.AddOption(opt) 44 | xcli.AddCommand(cmd).Run() 45 | } 46 | ``` 47 | 48 | 上面是采用闭包,也可以使用对象 49 | 50 | ```go 51 | type FooCommand struct { 52 | } 53 | func (t *FooCommand) Main() { 54 | // do something 55 | } 56 | cmd := &xcli.Command{ 57 | Name: "hello", 58 | Short: "Echo demo", 59 | RunI: &FooCommand{}, 60 | } 61 | ``` 62 | 63 | 编译后,查看整个命令行程序的帮助 64 | 65 | ``` 66 | $ ./go_build_main_go 67 | Usage: ./go_build_main_go [OPTIONS] COMMAND [opt...] 68 | 69 | Commands: 70 | hello Echo demo 71 | 72 | Global Options: 73 | -h, --help Print usage 74 | -v, --version Print version information 75 | 76 | Run './go_build_main_go COMMAND --help' for more information on a command. 77 | 78 | Developed with Mix Go framework. (openmix.org/mix-go) 79 | ``` 80 | 81 | 查看命令行程序的版本信息 82 | 83 | ``` 84 | $ ./go_build_main_go -v 85 | app 0.0.0-alpha 86 | ``` 87 | 88 | 查看 `hello` 命令的帮助 89 | 90 | ``` 91 | $ ./go_build_main_go hello --help 92 | Usage: ./go_build_main_go hello [opt...] 93 | 94 | Command Options: 95 | -n, --name Your name 96 | 97 | Developed with Mix Go framework. (openmix.org/mix-go) 98 | ``` 99 | 100 | 执行 `hello` 命令 101 | 102 | ``` 103 | $ ./go_build_main_go hello 104 | ``` 105 | 106 | ## Flag 参数获取 107 | 108 | > 该 flag 比 golang 自带的更加好用,不需要 Parse 操作 109 | 110 | 参数规则 (部分UNIX风格+GNU风格) 111 | 112 | ``` 113 | /examples/app home -d -rf --debug -v vvv --page 23 -s=test --name=john arg0 114 | ``` 115 | - 命令: 116 | - 第一个参数,可以为空:`home` 117 | - 选项: 118 | - 短选项:一个中杠,如 `-d`、`-rf` 119 | - 长选项:二个中杠,如:`--debug` 120 | - 选项值: 121 | - 无值:`-d`、`-rf`、 `--debug` 122 | - 有值(空格):`-v vvv`、`--page 23` 123 | - 有值(等号):`-s=test`、`--name=john` 124 | - 参数: 125 | - 没有定义 `-` 的参数:`arg0` 126 | 127 | 获取选项,可以获取 `String`、`Bool`、`Int64`、`Float64` 多种类型,也可以指定默认值。 128 | 129 | ``` 130 | name := flag.Match("n", "name").String("Xiao Ming") 131 | ``` 132 | 133 | 获取第一个参数 134 | 135 | ``` 136 | arg0 := flag.Arguments().First().String() 137 | ``` 138 | 139 | 获取全部参数 140 | 141 | ``` 142 | for k, v := range flag.Arguments().Values() { 143 | // do something 144 | } 145 | ``` 146 | 147 | ## Daemon 后台执行 148 | 149 | 将命令行程序变为后台执行,该方法只可在 Main 协程中使用。 150 | 151 | ``` 152 | process.Daemon() 153 | ``` 154 | 155 | 我们可以通过配合 `flag` 获取参数,实现通过某几个参数控制程序后台执行。 156 | 157 | ```go 158 | if flag.Match("d", "daemon").Bool() { 159 | process.Daemon() 160 | } 161 | ``` 162 | 163 | 上面就实现了一个当命令行参数中带有 `-d/--daemon` 参数时,程序就在后台执行。 164 | 165 | ## Handle panic 错误处理 166 | 167 | 使用中间件处理异常,也可以单独对某个命令配置中间件 168 | 169 | ```go 170 | h := func(next func()) { 171 | defer func() { 172 | if err := recover(); err != nil { 173 | // handle panic 174 | } 175 | }() 176 | next() 177 | } 178 | cmd := &xcli.Command{ 179 | Name: "hello", 180 | Short: "Echo demo", 181 | RunF: func() { 182 | // do something 183 | }, 184 | } 185 | xcli.Use(h).AddCommand(cmd).Run() 186 | ``` 187 | 188 | ## Application 189 | 190 | 我们在编写代码时,可能会要用到 App 中的一些信息。 191 | 192 | ``` 193 | // 获取基础路径(二进制所在目录路径) 194 | xcli.App().BasePath 195 | 196 | // App名称 197 | xcli.App().Name 198 | 199 | // App版本号 200 | xcli.App().Version 201 | 202 | // 是否开启debug 203 | xcli.App().Debug 204 | ``` 205 | 206 | ## Singleton 单命令 207 | 208 | 当我们的 CLI 只有一个命令时,只需要配置一下 `Singleton`: 209 | 210 | ~~~go 211 | cmd := &xcli.Command{ 212 | Name: "hello", 213 | Short: "Echo demo", 214 | RunF: func() { 215 | // do something 216 | }, 217 | Singleton: true, 218 | } 219 | ~~~ 220 | 221 | 命令的 Options 将会在 `-h/--help` 中打印 222 | 223 | ~~~ 224 | $ ./go_build_main_go 225 | Usage: ./go_build_main_go [OPTIONS] COMMAND [opt...] 226 | 227 | Command Options: 228 | -n, --name Your name 229 | 230 | Global Options: 231 | -h, --help Print usage 232 | -v, --version Print version information 233 | 234 | Run './go_build_main_go --help' for more information on a command. 235 | 236 | Developed with Mix Go framework. (openmix.org/mix-go) 237 | ~~~ 238 | 239 | ## Default 默认执行 240 | 241 | 当我们的 CLI 有 CUI 时,需要实现点击后默认启动 UI 界面,只需要配置一下 `Default`: 242 | 243 | ~~~go 244 | cmd := &xcli.Command{ 245 | Name: "hello", 246 | Short: "Echo demo", 247 | RunF: func() { 248 | // do something 249 | }, 250 | Default: true, 251 | } 252 | ~~~ 253 | 254 | ## License 255 | 256 | Apache License Version 2.0, http://www.apache.org/licenses/ 257 | -------------------------------------------------------------------------------- /application.go: -------------------------------------------------------------------------------- 1 | package xcli 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/mix-go/xcli/argv" 7 | "github.com/mix-go/xcli/flag" 8 | "os" 9 | "strings" 10 | ) 11 | 12 | var ( 13 | // App 14 | iApp *application 15 | ) 16 | 17 | func init() { 18 | iApp = New("app", "0.0.0") 19 | } 20 | 21 | // New 22 | func New(name, version string) *application { 23 | app := &application{ 24 | Name: name, 25 | Version: version, 26 | } 27 | app.BasePath = argv.Program().Dir 28 | return app 29 | } 30 | 31 | // App 32 | func App() *application { 33 | return iApp 34 | } 35 | 36 | // SetName 37 | func SetName(name string) *application { 38 | return iApp.SetName(name) 39 | } 40 | 41 | // SetVersion 42 | func SetVersion(version string) *application { 43 | return iApp.SetVersion(version) 44 | } 45 | 46 | // SetDebug 47 | func SetDebug(debug bool) *application { 48 | return iApp.SetDebug(debug) 49 | } 50 | 51 | // Use 52 | func Use(h ...HandlerFunc) *application { 53 | return iApp.Use(h...) 54 | } 55 | 56 | // AddCommand 57 | func AddCommand(cmds ...*Command) *application { 58 | iApp.AddCommand(cmds...) 59 | return iApp 60 | } 61 | 62 | // Run 63 | func Run() { 64 | iApp.Run() 65 | } 66 | 67 | // application 68 | type application struct { 69 | // 应用名称 70 | Name string 71 | // 应用版本 72 | Version string 73 | // 应用调试 74 | Debug bool 75 | // 基础路径 76 | BasePath string 77 | 78 | // 是否单命令 79 | singleton bool 80 | // 默认命令 81 | defaultCommand string 82 | // 命令集合 83 | commands []*Command 84 | // handlers 85 | handlers []HandlerFunc 86 | } 87 | 88 | // HandlerFunc 89 | type HandlerFunc func(next func()) 90 | 91 | // SetName 92 | func (t *application) SetName(name string) *application { 93 | t.Name = name 94 | return t 95 | } 96 | 97 | // SetVersion 98 | func (t *application) SetVersion(version string) *application { 99 | t.Version = version 100 | return t 101 | } 102 | 103 | // SetDebug 104 | func (t *application) SetDebug(debug bool) *application { 105 | t.Debug = debug 106 | return t 107 | } 108 | 109 | // Use 110 | func (t *application) Use(h ...HandlerFunc) *application { 111 | t.handlers = append(t.handlers, h...) 112 | return t 113 | } 114 | 115 | // AddCommand 116 | func (t *application) AddCommand(cmds ...*Command) *application { 117 | t.commands = append(t.commands, cmds...) 118 | // init 119 | for _, c := range t.commands { 120 | if c.Singleton { 121 | t.singleton = true 122 | } 123 | if c.Default { 124 | t.defaultCommand = c.Name 125 | } 126 | } 127 | if t.singleton { 128 | argv.Parse(true) 129 | flag.Parse() 130 | } 131 | return t 132 | } 133 | 134 | // Run 执行 135 | func (t *application) Run() { 136 | defer func() { 137 | if err := recover(); err != nil { 138 | switch err.(type) { 139 | case *NotFoundError, *UnsupportedError: 140 | fmt.Println(err) 141 | return 142 | default: 143 | panic(err) 144 | } 145 | } 146 | }() 147 | 148 | if len(t.commands) == 0 { 149 | panic(errors.New("command cannot be empty")) 150 | } 151 | 152 | command := argv.Command() 153 | if command == "" { 154 | if flag.Match("h", "help").Bool(false) { 155 | t.globalHelp() 156 | return 157 | } 158 | if flag.Match("v", "version").Bool(false) { 159 | t.version() 160 | return 161 | } 162 | 163 | options := flag.Options().Map() 164 | if len(options) == 0 { 165 | if t.defaultCommand != "" && len(os.Args) == 1 { 166 | os.Args = append(os.Args, t.defaultCommand) 167 | argv.Parse() 168 | flag.Parse() 169 | t.Run() 170 | } else { 171 | t.globalHelp() 172 | } 173 | return 174 | } 175 | 176 | if t.singleton { 177 | t.call() 178 | return 179 | } 180 | 181 | f := "" 182 | for k := range options { 183 | f = k 184 | break 185 | } 186 | p := argv.Program().Path 187 | panic(NewNotFoundError(fmt.Errorf("flag provided but not defined: '%s', see '%s --help'.", f, p))) 188 | } else if flag.Match("help").Bool(false) { 189 | t.commandHelp() 190 | return 191 | } 192 | t.call() 193 | } 194 | 195 | func (t *application) getCommand(n string) *Command { 196 | var cmd *Command 197 | if t.singleton { 198 | // 单命令 199 | for _, c := range t.commands { 200 | if c.Singleton { 201 | cmd = c 202 | break 203 | } 204 | } 205 | } else { 206 | for _, c := range t.commands { 207 | if c.Name == n { 208 | cmd = c 209 | break 210 | } 211 | } 212 | } 213 | return cmd 214 | } 215 | 216 | // 执行命令 217 | func (t *application) call() { 218 | // 命令行选项效验 219 | t.validateOptions() 220 | 221 | // 提取命令 222 | command := argv.Command() 223 | cmd := t.getCommand(command) 224 | if cmd == nil { 225 | panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path))) 226 | } 227 | if cmd.RunF == nil && cmd.RunI == nil { 228 | panic(fmt.Errorf("'%s' command RunF & RunI field is empty", cmd.Name)) 229 | } 230 | 231 | // 执行命令 232 | exec := func() { 233 | rf := cmd.RunF 234 | if rf != nil { 235 | rf() 236 | return 237 | } 238 | ri := cmd.RunI 239 | if ri != nil { 240 | ri.Main() 241 | return 242 | } 243 | } 244 | if len(t.handlers)+len(cmd.handlers) > 0 { 245 | tmp := append(t.handlers, cmd.handlers...) 246 | for i, j := 0, len(tmp)-1; i < j; i, j = i+1, j-1 { 247 | tmp[i], tmp[j] = tmp[j], tmp[i] 248 | } 249 | var next func() 250 | for k, f := range tmp { 251 | if k == 0 { 252 | n := exec 253 | c := f 254 | next = func() { 255 | c(n) 256 | } 257 | if len(tmp) == 1 { 258 | c(n) 259 | } 260 | } else if len(tmp)-1 == k { 261 | f(next) 262 | } else { 263 | n := next 264 | c := f 265 | next = func() { 266 | c(n) 267 | } 268 | } 269 | } 270 | } else { 271 | exec() 272 | } 273 | } 274 | 275 | // 命令行选项效验 276 | func (t *application) validateOptions() { 277 | command := argv.Command() 278 | cmd := t.getCommand(command) 279 | if cmd == nil { 280 | return 281 | } 282 | options := cmd.Options 283 | if len(options) == 0 { 284 | return 285 | } 286 | 287 | var flags []string 288 | for _, o := range options { 289 | for _, v := range o.Names { 290 | if len(v) == 1 { 291 | flags = append(flags, fmt.Sprintf("-%s", v)) 292 | } else { 293 | flags = append(flags, fmt.Sprintf("--%s", v)) 294 | } 295 | } 296 | } 297 | inArray := func(value string, values []string) bool { 298 | for _, v := range values { 299 | if v == value { 300 | return true 301 | } 302 | } 303 | return false 304 | } 305 | for f := range flag.Options().Map() { 306 | if !inArray(f, flags) { 307 | p := argv.Program().Path 308 | c := argv.Command() 309 | if c != "" { 310 | c = fmt.Sprintf(" %s", c) 311 | } 312 | panic(NewNotFoundError(fmt.Errorf("flag provided but not defined: '%s', see '%s%s --help'.", f, p, c))) 313 | } 314 | } 315 | } 316 | 317 | // 全局帮助 318 | func (t *application) globalHelp() { 319 | command := argv.Command() 320 | cmd := t.getCommand(command) 321 | if command != "" && cmd == nil { 322 | panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path))) 323 | } 324 | 325 | if cmd != nil && cmd.Long != "" { 326 | fmt.Println(cmd.Long) 327 | fmt.Println("") 328 | } 329 | program := argv.Program().Path 330 | if !t.singleton { 331 | fmt.Println(fmt.Sprintf("Usage: %s [GLOBAL OPTIONS] COMMAND [ARG...]", program)) 332 | } else { 333 | if cmd != nil && cmd.UsageFormat != "" { 334 | fmt.Println(fmt.Sprintf(cmd.UsageFormat, program)) 335 | } else { 336 | fmt.Println(fmt.Sprintf("Usage: %s [ARG...]", program)) 337 | } 338 | } 339 | if !t.singleton { 340 | t.printCommands() 341 | } else { 342 | t.printCommandOptions() 343 | } 344 | t.printGlobalOptions() 345 | fmt.Println("") 346 | fg := "" 347 | if !t.singleton { 348 | fg = " COMMAND" 349 | } 350 | fmt.Println(fmt.Sprintf("Run '%s%s --help' for more information on a command.", program, fg)) 351 | fmt.Println("") 352 | fmt.Println("Developed with Mix Go framework. (openmix.org/mix-go)") 353 | } 354 | 355 | // 命令帮助 356 | func (t *application) commandHelp() { 357 | command := argv.Command() 358 | cmd := t.getCommand(command) 359 | if cmd == nil { 360 | panic(NewNotFoundError(fmt.Errorf("'%s' is not command, see '%s --help'.", command, argv.Program().Path))) 361 | } 362 | 363 | if cmd.Long != "" { 364 | fmt.Println(cmd.Long) 365 | fmt.Println("") 366 | } 367 | program := argv.Program().Path 368 | if cmd.UsageFormat != "" { 369 | fmt.Println(fmt.Sprintf(cmd.UsageFormat, program, command)) 370 | } else { 371 | fmt.Println(fmt.Sprintf("Usage: %s %s [ARG...]", program, command)) 372 | } 373 | t.printCommandOptions() 374 | fmt.Println("") 375 | fmt.Println("Developed with Mix Go framework. (openmix.org/mix-go)") 376 | } 377 | 378 | // 打印全局选项 379 | func (t *application) printGlobalOptions() { 380 | tabs := "\t" 381 | fmt.Println("") 382 | fmt.Println("Global Options:") 383 | fmt.Println(fmt.Sprintf(" -h, --help%sPrint usage", tabs)) 384 | fmt.Println(fmt.Sprintf(" -v, --version%sPrint version information", tabs)) 385 | } 386 | 387 | // 打印命令 388 | func (t *application) printCommands() { 389 | fmt.Println("") 390 | fmt.Println("Commands:") 391 | for _, v := range t.commands { 392 | command := v.Name 393 | short := v.Short 394 | fmt.Println(fmt.Sprintf(" %s\t%s", command, short)) 395 | } 396 | } 397 | 398 | // 打印命令选项 399 | func (t *application) printCommandOptions() { 400 | command := argv.Command() 401 | cmd := t.getCommand(command) 402 | if cmd == nil { 403 | return 404 | } 405 | options := cmd.Options 406 | if len(options) == 0 { 407 | return 408 | } 409 | 410 | fmt.Println("") 411 | fmt.Println("Command Options:") 412 | for _, o := range options { 413 | var flags []string 414 | for _, v := range o.Names { 415 | if len(v) == 1 { 416 | flags = append(flags, fmt.Sprintf("-%s", v)) 417 | } else { 418 | flags = append(flags, fmt.Sprintf("--%s", v)) 419 | } 420 | } 421 | fg := strings.Join(flags, ", ") 422 | fmt.Println(fmt.Sprintf(" %s\t%s", fg, o.Usage)) 423 | } 424 | } 425 | 426 | // 版本号 427 | func (t *application) version() { 428 | fmt.Println(fmt.Sprintf("%s %s", t.Name, t.Version)) 429 | } 430 | -------------------------------------------------------------------------------- /application_test.go: -------------------------------------------------------------------------------- 1 | package xcli 2 | 3 | import ( 4 | "fmt" 5 | "github.com/mix-go/xcli/argv" 6 | "github.com/mix-go/xcli/flag" 7 | "github.com/stretchr/testify/assert" 8 | "os" 9 | "testing" 10 | ) 11 | 12 | var ok = false 13 | 14 | func TestCommandRun(t *testing.T) { 15 | a := assert.New(t) 16 | 17 | os.Args = []string{os.Args[0], "foo"} 18 | argv.Parse() 19 | flag.Parse() 20 | 21 | cmd := &Command{ 22 | Name: "foo", 23 | Short: "bar", 24 | RunF: func() { 25 | ok = true 26 | }, 27 | } 28 | opt := &Option{ 29 | Names: []string{"a", "bc"}, 30 | Usage: "foo", 31 | } 32 | cmd.AddOption(opt) 33 | app := New("test", "1.0.0") 34 | app.AddCommand(cmd) 35 | app.Run() 36 | 37 | a.NotEqual(app.BasePath, nil) 38 | a.True(ok) 39 | ok = false 40 | } 41 | 42 | func TestSingletonCommandRun(t *testing.T) { 43 | a := assert.New(t) 44 | 45 | os.Args = []string{os.Args[0], "-a"} 46 | argv.Parse() 47 | flag.Parse() 48 | 49 | cmd := &Command{ 50 | Name: "foo", 51 | Short: "bar", 52 | RunF: func() { 53 | ok = true 54 | }, 55 | Singleton: true, 56 | } 57 | app := New("test", "1.0.0") 58 | app.AddCommand(cmd) 59 | app.Run() 60 | 61 | a.NotEqual(app.BasePath, nil) 62 | a.True(ok) 63 | ok = false 64 | } 65 | 66 | func TestDefaultCommandRun(t *testing.T) { 67 | a := assert.New(t) 68 | 69 | // 多命令 70 | os.Args = []string{os.Args[0]} 71 | argv.Parse() 72 | flag.Parse() 73 | 74 | cmd := &Command{ 75 | Name: "foo", 76 | Short: "bar", 77 | RunF: func() { 78 | ok = true 79 | }, 80 | Default: true, 81 | } 82 | app := New("test", "1.0.0") 83 | app.AddCommand(cmd) 84 | app.Run() 85 | 86 | a.NotEqual(app.BasePath, nil) 87 | a.True(ok) 88 | ok = false 89 | 90 | // 单命令 91 | os.Args = []string{os.Args[0]} 92 | argv.Parse() 93 | flag.Parse() 94 | 95 | cmd = &Command{ 96 | Name: "foo", 97 | Short: "bar", 98 | RunF: func() { 99 | ok = true 100 | }, 101 | Singleton: true, 102 | Default: true, 103 | } 104 | app = New("test", "1.0.0") 105 | app.AddCommand(cmd) 106 | app.Run() 107 | 108 | a.NotEqual(app.BasePath, nil) 109 | a.True(ok) 110 | ok = false 111 | } 112 | 113 | func TestCommandNotFound(t *testing.T) { 114 | os.Args = []string{os.Args[0], "bar"} 115 | argv.Parse() 116 | flag.Parse() 117 | 118 | cmd := &Command{ 119 | Name: "foo", 120 | Short: "bar", 121 | RunF: func() { 122 | ok = true 123 | }, 124 | } 125 | app := New("test", "1.0.0") 126 | app.AddCommand(cmd) 127 | app.Run() 128 | 129 | fmt.Println("-----------------------") 130 | 131 | // 默认 + 找不到 132 | os.Args = []string{os.Args[0], "中文foo"} 133 | argv.Parse() 134 | flag.Parse() 135 | 136 | cmd = &Command{ 137 | Name: "foo", 138 | Short: "bar", 139 | RunF: func() { 140 | ok = true 141 | }, 142 | Default: true, 143 | } 144 | app = New("test", "1.0.0") 145 | app.AddCommand(cmd) 146 | app.Run() 147 | } 148 | 149 | func TestHandlers(t *testing.T) { 150 | a := assert.New(t) 151 | 152 | os.Args = []string{os.Args[0], "foo"} 153 | argv.Parse() 154 | flag.Parse() 155 | 156 | var result []int 157 | 158 | cmd := &Command{ 159 | Name: "foo", 160 | Short: "bar", 161 | RunF: func() { 162 | result = append(result, 0) 163 | }, 164 | } 165 | h := func(next func()) { 166 | defer func() { 167 | if err := recover(); err != nil { 168 | fmt.Println(err) 169 | } 170 | }() 171 | result = append(result, 1) 172 | next() 173 | } 174 | h1 := func(next func()) { 175 | result = append(result, 2) 176 | next() 177 | } 178 | h2 := func(next func()) { 179 | result = append(result, 3) 180 | next() 181 | } 182 | app := New("test", "1.0.0") 183 | app.Use(h, h1, h2) 184 | app.AddCommand(cmd) 185 | app.Run() 186 | 187 | a.Equal(result, []int{1, 2, 3, 0}) 188 | } 189 | 190 | func TestCommandPrint(t *testing.T) { 191 | os.Args = []string{os.Args[0]} 192 | fmt.Println(os.Args) 193 | argv.Parse() 194 | flag.Parse() 195 | cmd := &Command{ 196 | Name: "foo", 197 | Short: "bar", 198 | Long: "bar bar", 199 | UsageFormat: "Usage: %s %s [ABC..]", 200 | RunF: func() { 201 | }, 202 | } 203 | opt := &Option{ 204 | Names: []string{"a", "bc"}, 205 | Usage: "foo", 206 | } 207 | cmd.AddOption(opt) 208 | app := New("test", "1.0.0") 209 | app.AddCommand(cmd) 210 | app.Run() 211 | 212 | fmt.Println("-----------------------") 213 | 214 | os.Args = []string{os.Args[0], "-h"} 215 | fmt.Println(os.Args) 216 | argv.Parse() 217 | flag.Parse() 218 | app = New("test", "1.0.0") 219 | app.AddCommand(cmd) 220 | app.Run() 221 | 222 | fmt.Println("-----------------------") 223 | 224 | os.Args = []string{os.Args[0], "-v"} 225 | fmt.Println(os.Args) 226 | argv.Parse() 227 | flag.Parse() 228 | app = New("test", "1.0.0") 229 | app.AddCommand(cmd) 230 | app.Run() 231 | 232 | fmt.Println("-----------------------") 233 | 234 | os.Args = []string{os.Args[0], "foo", "--help"} 235 | fmt.Println(os.Args) 236 | argv.Parse() 237 | flag.Parse() 238 | app = New("test", "1.0.0") 239 | app.AddCommand(cmd) 240 | app.Run() 241 | 242 | fmt.Println("-----------------------") 243 | 244 | os.Args = []string{os.Args[0]} 245 | fmt.Println(os.Args) 246 | argv.Parse() 247 | flag.Parse() 248 | cmd = &Command{ 249 | Name: "foo", 250 | Short: "bar", 251 | Long: "bar bar", 252 | UsageFormat: "Usage: %s [ABC..]", 253 | RunF: func() { 254 | }, 255 | Singleton: true, 256 | } 257 | opt = &Option{ 258 | Names: []string{"a", "bc"}, 259 | Usage: "foo", 260 | } 261 | cmd.AddOption(opt) 262 | app = New("test", "1.0.0") 263 | app.AddCommand(cmd) 264 | app.Run() 265 | } 266 | 267 | func TestArgvProgram(t *testing.T) { 268 | fmt.Printf("%+v\n", argv.Program()) 269 | } 270 | -------------------------------------------------------------------------------- /argv/argv.go: -------------------------------------------------------------------------------- 1 | package argv 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path/filepath" 7 | "regexp" 8 | ) 9 | 10 | // 命令行信息 11 | var ( 12 | prog program 13 | cmd string 14 | ) 15 | 16 | // Program 返回命令行程序信息 17 | func Program() *program { 18 | return &prog 19 | } 20 | 21 | // Command 返回当前命令信息 22 | func Command() string { 23 | return cmd 24 | } 25 | 26 | // 命令行程序信息 27 | type program struct { 28 | Path string `json:"path"` 29 | AbsPath string `json:"absPath"` 30 | Dir string `json:"dir"` 31 | ParentDir string `json:"parentDir"` 32 | File string `json:"file"` 33 | } 34 | 35 | // 创建命令行程序信息 36 | func newProgram() program { 37 | p := program{ 38 | Path: os.Args[0], 39 | AbsPath: "", 40 | Dir: "", 41 | ParentDir: "", 42 | File: "", 43 | } 44 | 45 | absPath, err := filepath.Abs(os.Args[0]) 46 | if err != nil { 47 | return p 48 | } 49 | p.AbsPath = absPath 50 | 51 | dirRaw, file := filepath.Split(absPath) 52 | dir := dirRaw[:len(dirRaw)-1] 53 | p.Dir = dir 54 | p.File = file 55 | 56 | parentDir, err := filepath.Abs(fmt.Sprintf("%s/../", dir)) 57 | if err != nil { 58 | return p 59 | } 60 | p.ParentDir = parentDir 61 | return p 62 | } 63 | 64 | // 创建当前命令信息 65 | func newCommand(singleton bool) string { 66 | if len(os.Args) <= 1 || singleton { 67 | return "" 68 | } 69 | cmd := "" 70 | if ok, _ := regexp.MatchString(`^[a-zA-Z0-9_\-:]+$`, os.Args[1]); ok { 71 | cmd = os.Args[1] 72 | if cmd[:1] == "-" { 73 | cmd = "" 74 | } 75 | } 76 | return cmd 77 | } 78 | -------------------------------------------------------------------------------- /argv/parse.go: -------------------------------------------------------------------------------- 1 | package argv 2 | 3 | // 初始化 4 | func init() { 5 | Parse() 6 | } 7 | 8 | // Parse 解析命令行参数 9 | func Parse(singleton ...bool) { 10 | var s bool 11 | switch len(singleton) { 12 | case 0: 13 | s = false 14 | default: 15 | s = singleton[0] 16 | } 17 | 18 | prog = newProgram() 19 | cmd = newCommand(s) 20 | } 21 | -------------------------------------------------------------------------------- /command.go: -------------------------------------------------------------------------------- 1 | package xcli 2 | 3 | // Command 4 | type Command struct { 5 | // 命令名称 6 | Name string 7 | // 简短描述 8 | Short string 9 | // 详细描述 10 | Long string 11 | // 使用范例 12 | // 子命令:"Usage: %s %s [ARG...]" 13 | // 单命令:"Usage: %s [ARG...]" 14 | UsageFormat string 15 | // 选项 16 | Options []*Option 17 | // 执行 18 | RunF func() 19 | RunI RunI 20 | // 是否单命令 21 | Singleton bool 22 | // 是否为默认命令 23 | Default bool 24 | 25 | // handlers 26 | handlers []HandlerFunc 27 | } 28 | 29 | // AddOption 30 | func (t *Command) AddOption(options ...*Option) *Command { 31 | t.Options = append(t.Options, options...) 32 | return t 33 | } 34 | 35 | // Use 36 | func (t *Command) Use(h ...HandlerFunc) *Command { 37 | t.handlers = append(t.handlers, h...) 38 | return t 39 | } 40 | 41 | // RunI 42 | type RunI interface { 43 | Main() 44 | } 45 | 46 | // Option 47 | type Option struct { 48 | Names []string 49 | Usage string 50 | } 51 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package xcli 2 | 3 | // NotFoundError 未找到错误 4 | type NotFoundError struct { 5 | error 6 | } 7 | 8 | // NewNotFoundError 创建未找到错误 9 | func NewNotFoundError(err error) *NotFoundError { 10 | return &NotFoundError{err} 11 | } 12 | 13 | // UnsupportedError 不支持错误 14 | type UnsupportedError struct { 15 | error 16 | } 17 | 18 | // NewUnsupportedError 创建不支持错误 19 | func NewUnsupportedError(err error) *UnsupportedError { 20 | return &UnsupportedError{err} 21 | } 22 | -------------------------------------------------------------------------------- /flag/arguments.go: -------------------------------------------------------------------------------- 1 | package flag 2 | 3 | var args arguments 4 | 5 | type arguments []string 6 | 7 | // Array 返回数组 8 | func (t *arguments) Array() []string { 9 | return *t 10 | } 11 | 12 | // Values 返回值 13 | func (t *arguments) Values() []*flagValue { 14 | args := *t 15 | var values []*flagValue 16 | for _, v := range args { 17 | values = append(values, &flagValue{v, true}) 18 | } 19 | return values 20 | } 21 | 22 | // First 获取第一个参数 23 | func (t *arguments) First() *flagValue { 24 | args := *t 25 | if len(args) == 0 { 26 | return &flagValue{} 27 | } 28 | return &flagValue{args[0], true} 29 | } 30 | 31 | // Arguments 获取全部命令行参数 32 | func Arguments() *arguments { 33 | return &args 34 | } 35 | -------------------------------------------------------------------------------- /flag/flag.go: -------------------------------------------------------------------------------- 1 | package flag 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | // Match 匹配参数名称 9 | func Match(names ...string) *flagValue { 10 | for _, name := range names { 11 | v, exist := find(name) 12 | if exist { 13 | return &flagValue{v, exist} 14 | } 15 | } 16 | return &flagValue{} 17 | } 18 | 19 | // 获取指定参数的值 20 | func find(name string) (string, bool) { 21 | key := "" 22 | if len(name) == 1 { 23 | key = fmt.Sprintf("-%s", name) 24 | } else { 25 | key = fmt.Sprintf("--%s", name) 26 | } 27 | if v, ok := Options().Map()[key]; ok { 28 | return v, true 29 | } 30 | return "", false 31 | } 32 | 33 | // 参数值 34 | type flagValue struct { 35 | v string 36 | exist bool 37 | } 38 | 39 | // String 转换为字符串 40 | func (t *flagValue) String(val ...string) string { 41 | d := "" 42 | if len(val) >= 1 { 43 | d = val[0] 44 | } 45 | 46 | if t.v == "" { 47 | return d 48 | } 49 | 50 | return t.v 51 | } 52 | 53 | // Bool 转换为布尔 54 | func (t *flagValue) Bool(val ...bool) bool { 55 | d := false 56 | if len(val) >= 1 { 57 | d = val[0] 58 | } 59 | 60 | if !t.exist { 61 | return d 62 | } 63 | 64 | switch t.v { 65 | case "false": 66 | return false 67 | default: 68 | return true 69 | } 70 | } 71 | 72 | // Int64 转换为整型 73 | func (t *flagValue) Int64(val ...int64) int64 { 74 | d := int64(0) 75 | if len(val) >= 1 { 76 | d = val[0] 77 | } 78 | 79 | if t.v == "" { 80 | return d 81 | } 82 | 83 | v, _ := strconv.ParseInt(t.v, 10, 64) 84 | return v 85 | } 86 | 87 | // Float64 转换为浮点 88 | func (t *flagValue) Float64(val ...float64) float64 { 89 | d := float64(0) 90 | if len(val) >= 1 { 91 | d = val[0] 92 | } 93 | 94 | if t.v == "" { 95 | return d 96 | } 97 | 98 | v, _ := strconv.ParseFloat(t.v, 64) 99 | return v 100 | } 101 | -------------------------------------------------------------------------------- /flag/flag_test.go: -------------------------------------------------------------------------------- 1 | package flag 2 | 3 | import ( 4 | "github.com/mix-go/xcli/argv" 5 | "github.com/stretchr/testify/assert" 6 | "os" 7 | "testing" 8 | ) 9 | 10 | func TestSingle(t *testing.T) { 11 | a := assert.New(t) 12 | 13 | os.Args = []string{os.Args[0], "foo", "-a=a1", "-b", "--cd", "--ab=ab1", "--de", "de1", "-c", "c1", "--sw", "false"} 14 | argv.Parse() 15 | Parse() 16 | 17 | v1 := Match("a").String() 18 | a.Equal(v1, "a1") 19 | 20 | v2 := Match("b").Bool() 21 | a.Equal(v2, true) 22 | 23 | v3 := Match("cd").Bool() 24 | a.Equal(v3, true) 25 | 26 | v4 := Match("sw").Bool() 27 | a.Equal(v4, false) 28 | 29 | v5 := Match("ab", "").String() 30 | a.Equal(v5, "ab1") 31 | 32 | v6 := Match("de", "").String() 33 | a.Equal(v6, "de1") 34 | 35 | v7 := Match("c", "").String() 36 | a.Equal(v7, "c1") 37 | } 38 | 39 | func TestMatch(t *testing.T) { 40 | a := assert.New(t) 41 | 42 | os.Args = []string{os.Args[0], "foo", "-a=a1", "-b", "--bc", "--ab=ab1", "--de", "de1", "-c", "c1", "--sw", "false"} 43 | argv.Parse() 44 | Parse() 45 | 46 | v1 := Match("b", "bc").Bool() 47 | a.Equal(v1, true) 48 | 49 | v2 := Match("a", "ab").String() 50 | a.Equal(v2, "a1") 51 | } 52 | 53 | func TestNotFound(t *testing.T) { 54 | a := assert.New(t) 55 | 56 | os.Args = []string{os.Args[0]} 57 | argv.Parse() 58 | Parse() 59 | 60 | v1 := Match("cde").Bool() 61 | a.Equal(v1, false) 62 | 63 | v2 := Match("x").String() 64 | a.Equal(v2, "") 65 | 66 | v3 := Match("b", "bc").Bool() 67 | a.Equal(v3, false) 68 | 69 | v4 := Match("a", "ab").String() 70 | a.Equal(v4, "") 71 | } 72 | 73 | func TestOptions(t *testing.T) { 74 | a := assert.New(t) 75 | 76 | os.Args = []string{os.Args[0], "foo", "-a=a1", "-b", "-bc", "--cd", "--ab=ab1", "arg0", "--de", "de1", "-c", "c1", "--sw", "false", "arg1", "arg2"} 77 | argv.Parse() 78 | Parse() 79 | 80 | a.Equal(Options().Map(), map[string]string{"--ab": "ab1", "--cd": "", "--de": "de1", "--sw": "false", "-a": "a1", "-b": "", "-bc": "", "-c": "c1"}) 81 | } 82 | 83 | func TestArguments(t *testing.T) { 84 | a := assert.New(t) 85 | 86 | os.Args = []string{os.Args[0], "foo", "-a=a1", "-b", "--cd", "--ab=ab1", "arg0", "--de", "de1", "-c", "c1", "--sw", "false", "arg1", "arg2"} 87 | argv.Parse() 88 | Parse() 89 | 90 | a.Equal(Arguments().Array(), []string{"arg0", "arg1", "arg2"}) 91 | 92 | a.Equal(Arguments().First().String(), "arg0") 93 | a.Equal(Arguments().First().Bool(), true) 94 | } 95 | -------------------------------------------------------------------------------- /flag/options.go: -------------------------------------------------------------------------------- 1 | package flag 2 | 3 | var opts options 4 | 5 | type options map[string]string 6 | 7 | // Map {"--foo": "bar"} 8 | func (t *options) Map() map[string]string { 9 | return *t 10 | } 11 | 12 | // Options 获取全部命令行选项 13 | func Options() *options { 14 | return &opts 15 | } 16 | -------------------------------------------------------------------------------- /flag/parse.go: -------------------------------------------------------------------------------- 1 | package flag 2 | 3 | import ( 4 | "github.com/mix-go/xcli/argv" 5 | "os" 6 | "regexp" 7 | "strings" 8 | ) 9 | 10 | // 初始化 11 | func init() { 12 | Parse() 13 | } 14 | 15 | // Parse 解析参数 16 | func Parse() { 17 | var o = make(map[string]string, 0) 18 | var a []string 19 | s := 1 20 | if argv.Command() == "" { 21 | s = 0 22 | } 23 | ignore := "" 24 | for k, v := range os.Args { 25 | if k <= s { 26 | continue 27 | } 28 | name := v 29 | value := "" 30 | if strings.Contains(v, "=") { 31 | name = strings.Split(v, "=")[0] 32 | value = v[strings.Index(v, "=")+1:] 33 | } 34 | if (len(name) >= 1 && name[:1] == "-") || (len(name) >= 2 && name[:2] == "--") { 35 | if name[:1] == "-" && value == "" && len(os.Args)-1 >= k+1 && os.Args[k+1][:1] != "-" { 36 | next := os.Args[k+1] 37 | ok, _ := regexp.MatchString(`^[\S\s]+$`, next) 38 | if ok { 39 | value = next 40 | ignore = next 41 | } 42 | } 43 | } else { 44 | name = "" 45 | if v != ignore { 46 | a = append(a, v) 47 | } 48 | } 49 | if name != "" { 50 | o[name] = value 51 | } 52 | } 53 | opts = options(o) 54 | args = arguments(a) 55 | } 56 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mix-go/xcli 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.1 // indirect 7 | github.com/stretchr/testify v1.7.0 8 | gopkg.in/yaml.v3 v3.0.0 // indirect 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 5 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 6 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 7 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 8 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 11 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 12 | gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA= 13 | gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 14 | -------------------------------------------------------------------------------- /process/daemon.go: -------------------------------------------------------------------------------- 1 | package process 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/mix-go/xcli" 7 | "os" 8 | "os/exec" 9 | "runtime" 10 | "strconv" 11 | ) 12 | 13 | // Daemon 使当前进程蜕变为一个守护进程 14 | func Daemon() { 15 | var ok bool 16 | switch runtime.GOOS { 17 | case "darwin", "linux": 18 | ok = true 19 | case "windows": 20 | ok = false 21 | default: 22 | ok = true 23 | } 24 | if !ok { 25 | panic(xcli.NewUnsupportedError(fmt.Errorf("error: the current operating system does not support daemon execution"))) 26 | } 27 | 28 | if getgid() != 1 { 29 | panic(fmt.Errorf("error: Daemon() can only be used in the main goroutine")) 30 | } 31 | 32 | // Getppid 父进程ID: 当父进程已经结束,在Unix中返回的ID是初始进程(1),在Windows中仍然是同一个进程ID,该进程ID有可能已经被其他进程占用 33 | if os.Getppid() != 1 { 34 | cmd := exec.Command(os.Args[0], os.Args[1:]...) 35 | if err := cmd.Start(); err != nil { 36 | panic(err) 37 | } 38 | os.Exit(0) 39 | } 40 | } 41 | 42 | // 获取协程id 43 | func getgid() uint64 { 44 | b := make([]byte, 64) 45 | runtime.Stack(b, false) 46 | b = bytes.TrimPrefix(b, []byte("goroutine ")) 47 | b = b[:bytes.IndexByte(b, ' ')] 48 | n, _ := strconv.ParseUint(string(b), 10, 64) 49 | return n 50 | } 51 | --------------------------------------------------------------------------------