gf/internal/cmdenv/cmdenv.go

61 lines
1.6 KiB
Go
Raw Normal View History

// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// 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.
2019-06-13 21:14:46 +08:00
// Package cmdenv provides access to certain variable for both command options and environment.
package cmdenv
import (
"os"
"regexp"
"strings"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/container/gvar"
)
var (
// Console options.
cmdOptions = make(map[string]string)
)
2019-06-19 09:06:52 +08:00
func init() {
2019-06-13 22:58:58 +08:00
doInit()
}
// doInit does the initialization for this package.
func doInit() {
reg := regexp.MustCompile(`\-\-{0,1}(.+?)=(.+)`)
for i := 0; i < len(os.Args); i++ {
result := reg.FindStringSubmatch(os.Args[i])
if len(result) > 1 {
cmdOptions[result[1]] = result[2]
}
}
}
2019-06-13 21:14:46 +08:00
// Get returns the command line argument of the specified <key>.
// If the argument does not exist, then it returns the environment variable with specified <key>.
// It returns the default value <def> if none of them exists.
//
// Fetching Rules:
// 1. Command line arguments are in lowercase format, eg: gf.<package name>.<variable name>;
// 2. Environment arguments are in uppercase format, eg: GF_<package name>_<variable name>
func Get(key string, def ...interface{}) *gvar.Var {
2019-06-19 09:06:52 +08:00
value := interface{}(nil)
if len(def) > 0 {
value = def[0]
}
2019-10-29 17:13:29 +08:00
cmdKey := strings.ToLower(strings.Replace(key, "_", ".", -1))
if v, ok := cmdOptions[cmdKey]; ok {
2019-06-19 09:06:52 +08:00
value = v
} else {
2019-10-29 17:13:29 +08:00
envKey := strings.ToUpper(strings.Replace(key, ".", "_", -1))
if v := os.Getenv(envKey); v != "" {
2019-06-19 09:06:52 +08:00
value = v
}
}
return gvar.New(value)
}