github.com/richardwilkes/toolbox@v1.121.0/cmdline/option.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package cmdline 11 12 import ( 13 "fmt" 14 15 "github.com/richardwilkes/toolbox/atexit" 16 "github.com/richardwilkes/toolbox/errs" 17 "github.com/richardwilkes/toolbox/i18n" 18 ) 19 20 // Value represents a value that can be set for an Option. 21 type Value interface { 22 // Set the contents of this value. 23 Set(value string) error 24 // String implements the fmt.Stringer interface. 25 String() string 26 } 27 28 // Option represents an option available on the command line. 29 type Option struct { 30 value Value 31 name string 32 usage string 33 arg string 34 def string 35 single rune 36 } 37 38 func (op *Option) isValid() (bool, error) { 39 if op.value == nil { 40 return false, errs.New(i18n.Text("Option must have a value")) 41 } 42 if op.single == 0 && op.name == "" { 43 return false, errs.New(i18n.Text("Option must be named")) 44 } 45 return true, nil 46 } 47 48 func (op *Option) isBool() bool { 49 if generalValue, ok := op.value.(*GeneralValue); ok { 50 if _, ok = generalValue.Value.(*bool); ok { 51 return true 52 } 53 } 54 return false 55 } 56 57 // SetName sets the name for this option. Returns self for easy chaining. 58 func (op *Option) SetName(name string) *Option { 59 if len(name) > 1 { 60 op.name = name 61 } else { 62 fmt.Println("Name must be 2+ characters") 63 atexit.Exit(1) 64 } 65 return op 66 } 67 68 // SetSingle sets the single character name for this option. Returns self for easy chaining. 69 func (op *Option) SetSingle(ch rune) *Option { 70 op.single = ch 71 return op 72 } 73 74 // SetArg sets the argument name for this option. Returns self for easy chaining. 75 func (op *Option) SetArg(name string) *Option { 76 op.arg = name 77 return op 78 } 79 80 // SetDefault sets the default value for this option. Returns self for easy chaining. 81 func (op *Option) SetDefault(def string) *Option { 82 op.def = def 83 return op 84 } 85 86 // SetUsage sets the usage message for this option. Returns self for easy chaining. 87 func (op *Option) SetUsage(usage string) *Option { 88 op.usage = usage 89 return op 90 }