github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/cli/cmd/cmd.go (about) 1 /* 2 Copyright [2014] - [2023] The Last.Backend authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cmd 18 19 import ( 20 "os" 21 "runtime/debug" 22 23 "github.com/urfave/cli/v2" 24 ) 25 26 type Option func(o *Options) 27 28 type Options struct { 29 Name string 30 Description string 31 Version string 32 } 33 34 type CLI interface { 35 App() *cli.App 36 Options() Options 37 Run() error 38 } 39 40 type cmd struct { 41 app *cli.App 42 opts Options 43 } 44 45 func (c *cmd) App() *cli.App { 46 return c.app 47 } 48 49 func (c *cmd) Options() Options { 50 return c.opts 51 } 52 53 func (c *cmd) Run() error { 54 return c.app.Run(os.Args) 55 } 56 57 func NewCLI(opts ...Option) CLI { 58 options := Options{} 59 60 for _, o := range opts { 61 o(&options) 62 } 63 64 if len(options.Name) == 0 { 65 options.Name = name 66 } 67 if len(options.Description) == 0 { 68 options.Description = description 69 } 70 if len(options.Version) == 0 { 71 if bi, ok := debug.ReadBuildInfo(); ok { 72 options.Version = bi.Main.Version 73 } else { 74 options.Version = version 75 } 76 } 77 78 c := new(cmd) 79 c.app = cli.NewApp() 80 c.opts = options 81 c.app.Name = c.opts.Name 82 c.app.Usage = c.opts.Description 83 c.app.Version = c.opts.Version 84 c.app.EnableBashCompletion = true 85 c.app.HideVersion = len(options.Version) == 0 86 87 return c 88 }