/
cmdenv.go
58 lines (52 loc) · 1.54 KB
/
cmdenv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 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.
// Package cmdenv provides access to certain variable for both command options and environment.
package cmdenv
import (
"github.com/gogf/gf/g/container/gvar"
"os"
"regexp"
"strings"
)
var (
// Console options.
cmdOptions = make(map[string]string)
)
func init() {
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]
}
}
}
// 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 {
value := interface{}(nil)
if len(def) > 0 {
value = def[0]
}
if v, ok := cmdOptions[key]; ok {
value = v
} else {
key = strings.ToUpper(strings.Replace(key, ".", "_", -1))
if v := os.Getenv(key); v != "" {
value = v
}
}
return gvar.New(value, true)
}