github.com/zhongdalu/gf@v1.0.0/g/os/gcmd/gcmd.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 // 7 8 // Package gcmd provides console operations, like options/values reading and command running. 9 package gcmd 10 11 import ( 12 "os" 13 "regexp" 14 15 "github.com/zhongdalu/gf/g/os/glog" 16 ) 17 18 // Console values. 19 type gCmdValue struct { 20 values []string 21 } 22 23 // Console options. 24 type gCmdOption struct { 25 options map[string]string 26 } 27 28 var Value = &gCmdValue{} // Console values. 29 var Option = &gCmdOption{} // Console options. 30 var cmdFuncMap = make(map[string]func()) // Registered callback functions. 31 32 func init() { 33 doInit() 34 } 35 36 // doInit does the initialization for this package. 37 func doInit() { 38 Value.values = Value.values[:0] 39 Option.options = make(map[string]string) 40 reg := regexp.MustCompile(`^\-{1,2}(\w+)={0,1}(.*)`) 41 for i := 0; i < len(os.Args); i++ { 42 result := reg.FindStringSubmatch(os.Args[i]) 43 if len(result) > 1 { 44 Option.options[result[1]] = result[2] 45 } else { 46 Value.values = append(Value.values, os.Args[i]) 47 } 48 } 49 } 50 51 // BindHandle registers callback function <f> with <cmd>. 52 func BindHandle(cmd string, f func()) { 53 if _, ok := cmdFuncMap[cmd]; ok { 54 glog.Fatal("duplicated handle for command:" + cmd) 55 } else { 56 cmdFuncMap[cmd] = f 57 } 58 } 59 60 // RunHandle executes the callback function registered by <cmd>. 61 func RunHandle(cmd string) { 62 if handle, ok := cmdFuncMap[cmd]; ok { 63 handle() 64 } else { 65 glog.Fatal("no handle found for command:" + cmd) 66 } 67 } 68 69 // AutoRun automatically recognizes and executes the callback function 70 // by value of index 0 (the first console parameter). 71 func AutoRun() { 72 if cmd := Value.Get(1); cmd != "" { 73 if handle, ok := cmdFuncMap[cmd]; ok { 74 handle() 75 } else { 76 glog.Fatal("no handle found for command:" + cmd) 77 } 78 } else { 79 glog.Fatal("no command found") 80 } 81 }