github.com/gogf/gf@v1.16.9/internal/command/command.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
     6  //
     7  
     8  // Package command provides console operations, like options/arguments reading.
     9  package command
    10  
    11  import (
    12  	"os"
    13  	"regexp"
    14  	"strings"
    15  )
    16  
    17  var (
    18  	defaultParsedArgs    = make([]string, 0)
    19  	defaultParsedOptions = make(map[string]string)
    20  	argumentRegex        = regexp.MustCompile(`^\-{1,2}([\w\?\.\-]+)(=){0,1}(.*)$`)
    21  )
    22  
    23  // Init does custom initialization.
    24  func Init(args ...string) {
    25  	if len(args) == 0 {
    26  		if len(defaultParsedArgs) == 0 && len(defaultParsedOptions) == 0 {
    27  			args = os.Args
    28  		} else {
    29  			return
    30  		}
    31  	} else {
    32  		defaultParsedArgs = make([]string, 0)
    33  		defaultParsedOptions = make(map[string]string)
    34  	}
    35  	// Parsing os.Args with default algorithm.
    36  	for i := 0; i < len(args); {
    37  		array := argumentRegex.FindStringSubmatch(args[i])
    38  		if len(array) > 2 {
    39  			if array[2] == "=" {
    40  				defaultParsedOptions[array[1]] = array[3]
    41  			} else if i < len(args)-1 {
    42  				if len(args[i+1]) > 0 && args[i+1][0] == '-' {
    43  					// Eg: gf gen -d -n 1
    44  					defaultParsedOptions[array[1]] = array[3]
    45  				} else {
    46  					// Eg: gf gen -n 2
    47  					defaultParsedOptions[array[1]] = args[i+1]
    48  					i += 2
    49  					continue
    50  				}
    51  			} else {
    52  				// Eg: gf gen -h
    53  				defaultParsedOptions[array[1]] = array[3]
    54  			}
    55  		} else {
    56  			defaultParsedArgs = append(defaultParsedArgs, args[i])
    57  		}
    58  		i++
    59  	}
    60  }
    61  
    62  // GetOpt returns the option value named `name`.
    63  func GetOpt(name string, def ...string) string {
    64  	Init()
    65  	if v, ok := defaultParsedOptions[name]; ok {
    66  		return v
    67  	}
    68  	if len(def) > 0 {
    69  		return def[0]
    70  	}
    71  	return ""
    72  }
    73  
    74  // GetOptAll returns all parsed options.
    75  func GetOptAll() map[string]string {
    76  	Init()
    77  	return defaultParsedOptions
    78  }
    79  
    80  // ContainsOpt checks whether option named `name` exist in the arguments.
    81  func ContainsOpt(name string) bool {
    82  	Init()
    83  	_, ok := defaultParsedOptions[name]
    84  	return ok
    85  }
    86  
    87  // GetArg returns the argument at `index`.
    88  func GetArg(index int, def ...string) string {
    89  	Init()
    90  	if index < len(defaultParsedArgs) {
    91  		return defaultParsedArgs[index]
    92  	}
    93  	if len(def) > 0 {
    94  		return def[0]
    95  	}
    96  	return ""
    97  }
    98  
    99  // GetArgAll returns all parsed arguments.
   100  func GetArgAll() []string {
   101  	Init()
   102  	return defaultParsedArgs
   103  }
   104  
   105  // GetOptWithEnv returns the command line argument of the specified `key`.
   106  // If the argument does not exist, then it returns the environment variable with specified `key`.
   107  // It returns the default value `def` if none of them exists.
   108  //
   109  // Fetching Rules:
   110  // 1. Command line arguments are in lowercase format, eg: gf.<package name>.<variable name>;
   111  // 2. Environment arguments are in uppercase format, eg: GF_<package name>_<variable name>;
   112  func GetOptWithEnv(key string, def ...string) string {
   113  	cmdKey := strings.ToLower(strings.Replace(key, "_", ".", -1))
   114  	if ContainsOpt(cmdKey) {
   115  		return GetOpt(cmdKey)
   116  	} else {
   117  		envKey := strings.ToUpper(strings.Replace(key, ".", "_", -1))
   118  		if r, ok := os.LookupEnv(envKey); ok {
   119  			return r
   120  		} else {
   121  			if len(def) > 0 {
   122  				return def[0]
   123  			}
   124  		}
   125  	}
   126  	return ""
   127  }