2019-02-02 16:18:25 +08:00
|
|
|
|
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2019-01-23 13:01:58 +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,
|
2019-02-02 16:18:25 +08:00
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2019-01-23 13:01:58 +08:00
|
|
|
|
|
2019-06-13 21:14:46 +08:00
|
|
|
|
// Package cmdenv provides access to certain variable for both command options and environment.
|
2019-01-23 13:01:58 +08:00
|
|
|
|
package cmdenv
|
|
|
|
|
|
|
|
|
|
import (
|
2019-04-11 09:26:52 +08:00
|
|
|
|
"os"
|
|
|
|
|
"regexp"
|
|
|
|
|
"strings"
|
2019-07-29 21:01:19 +08:00
|
|
|
|
|
|
|
|
|
"github.com/gogf/gf/container/gvar"
|
2019-01-23 13:01:58 +08:00
|
|
|
|
)
|
|
|
|
|
|
2019-04-11 09:26:52 +08:00
|
|
|
|
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() {
|
2019-04-11 09:26:52 +08:00
|
|
|
|
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>;
|
2020-06-29 13:40:19 +08:00
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-07-23 23:20:27 +08:00
|
|
|
|
return gvar.New(value)
|
2019-01-23 13:01:58 +08:00
|
|
|
|
}
|