pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/options/example_test.go (about) 1 package options 2 3 // ////////////////////////////////////////////////////////////////////////////////// // 4 // // 5 // Copyright (c) 2022 ESSENTIAL KAOS // 6 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 7 // // 8 // ////////////////////////////////////////////////////////////////////////////////// // 9 10 import ( 11 "fmt" 12 "os" 13 ) 14 15 // ////////////////////////////////////////////////////////////////////////////////// // 16 17 func Example_NewOptions() { 18 opts := NewOptions() 19 20 // Add options 21 opts.Add("S:string2", &V{Type: STRING, Value: "Default value"}) 22 opts.Add("I:int2", &V{Type: INT, Min: 1, Max: 10}) 23 24 // args contains unparsed values 25 args, errs := opts.Parse(os.Args[1:]) 26 27 if len(errs) != 0 { 28 for _, err := range errs { 29 fmt.Printf("Error: %v\n", err) 30 os.Exit(1) 31 } 32 } 33 34 fmt.Printf("Arguments: %v\n", args) 35 fmt.Printf("First argument: %s\n\n", args.Get(0)) 36 } 37 38 func Example_Parse() { 39 // Key is option in format "short-name:long-name" or "long-name" 40 // We highly recommend defining options names as constants 41 optMap := Map{ 42 "s:string": {}, // By default, argument has string type 43 "S:string2": {Type: STRING, Value: "Default value"}, // You can predefine default values 44 "int": {Type: INT}, // Integer without short name 45 "I:int2": {Type: INT, Min: 1, Max: 10}, // Integer with limits 46 "f:float": {Type: FLOAT, Value: 10.0}, // Float 47 "b:boolean": {Type: BOOL}, // Boolean 48 "r:required": {Type: INT, Required: true}, // Some options can be marked as required 49 "m:merg": {Type: STRING, Mergeble: true}, // Mergeble options can be defined more than one time 50 "h:help": {Type: BOOL, Alias: "u:usage about"}, // You can define argument aliases 51 "e:example": {Conflicts: "s:string S:string2"}, // Option conflicts with string and string2 (options can't be set at same time) 52 "E:example2": {Bound: "int I:int2"}, // Option bound with int and int2 (options must be set at same time) 53 } 54 55 // args contains unparsed values 56 args, errs := Parse(optMap) 57 58 if len(errs) != 0 { 59 for _, err := range errs { 60 fmt.Printf("Error: %v\n", err) 61 os.Exit(1) 62 } 63 } 64 65 if Has("s:string") { 66 fmt.Println("\"--string/-s\" is set") 67 } 68 69 fmt.Printf("Arguments: %v\n", args) 70 fmt.Printf("First argument: %s\n\n", args.Get(0)) 71 72 fmt.Printf("string → %s\n", GetS("string")) 73 fmt.Printf("int → %d\n", GetI("int")) 74 fmt.Printf("float → %f\n", GetF("f:float")) 75 fmt.Printf("boolean → %t\n", GetB("b:boolean")) 76 }