gf/os/gcmd/gcmd.go

101 lines
2.3 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
//
2017-12-31 18:19:58 +08:00
2019-01-15 23:27:47 +08:00
// Package gcmd provides console operations, like options/values reading and command running.
package gcmd
2017-11-23 10:21:28 +08:00
import (
"os"
2019-04-11 09:05:27 +08:00
"regexp"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/os/glog"
2017-11-23 10:21:28 +08:00
)
2019-04-11 09:05:27 +08:00
// Console values.
type gCmdValue struct {
values []string
2017-11-23 10:21:28 +08:00
}
2019-04-11 09:05:27 +08:00
// Console options.
type gCmdOption struct {
options map[string]string
2017-11-23 10:21:28 +08:00
}
2019-06-19 09:06:52 +08:00
var Value = &gCmdValue{} // Console values.
var Option = &gCmdOption{} // Console options.
2019-04-11 09:05:27 +08:00
var cmdFuncMap = make(map[string]func()) // Registered callback functions.
2017-11-23 10:21:28 +08:00
func init() {
2019-06-13 22:58:58 +08:00
doInit()
}
// doInit does the initialization for this package.
func doInit() {
2019-06-19 09:06:52 +08:00
Value.values = Value.values[:0]
Option.options = make(map[string]string)
2019-07-19 14:10:02 +08:00
reg := regexp.MustCompile(`^\-{1,2}(\w+)={0,1}(.*)`)
for i := 0; i < len(os.Args); i++ {
result := reg.FindStringSubmatch(os.Args[i])
if len(result) > 1 {
Option.options[result[1]] = result[2]
} else {
Value.values = append(Value.values, os.Args[i])
}
}
2017-11-23 10:21:28 +08:00
}
2019-04-11 09:05:27 +08:00
// BindHandle registers callback function <f> with <cmd>.
func BindHandle(cmd string, f func()) {
if _, ok := cmdFuncMap[cmd]; ok {
glog.Fatal("duplicated handle for command:" + cmd)
} else {
cmdFuncMap[cmd] = f
}
2017-11-23 10:21:28 +08:00
}
2019-04-11 09:05:27 +08:00
// RunHandle executes the callback function registered by <cmd>.
func RunHandle(cmd string) {
if handle, ok := cmdFuncMap[cmd]; ok {
handle()
} else {
glog.Fatal("no handle found for command:" + cmd)
}
2017-11-23 10:21:28 +08:00
}
2019-04-11 09:05:27 +08:00
// AutoRun automatically recognizes and executes the callback function
// by value of index 0 (the first console parameter).
func AutoRun() {
if cmd := Value.Get(1); cmd != "" {
if handle, ok := cmdFuncMap[cmd]; ok {
handle()
} else {
glog.Fatal("no handle found for command:" + cmd)
}
} else {
glog.Fatal("no command found")
}
2017-11-23 10:21:28 +08:00
}
// BuildOptions builds the options as string.
func BuildOptions(m map[string]string, prefix ...string) string {
options := ""
leadstr := "-"
if len(prefix) > 0 {
leadstr = prefix[0]
}
for k, v := range m {
if len(options) > 0 {
options += " "
}
options += leadstr + k
if v != "" {
options += "=" + v
}
}
return options
}