diff --git a/helpers.go b/helpers.go index d1d117f..f2f847c 100644 --- a/helpers.go +++ b/helpers.go @@ -2,6 +2,7 @@ package getoptions import ( "fmt" + "strconv" "github.com/DavidGamba/go-getoptions/text" ) @@ -29,3 +30,29 @@ func (gopt *GetOpt) GetRequiredArg(args []string, sections ...HelpSection) (stri gopt.programTree.SynopsisArgsIdx++ return args[0], args[1:], nil } + +// Same as GetRequiredArg but converts the argument to an int. +func (gopt *GetOpt) GetRequiredArgInt(args []string, sections ...HelpSection) (int, []string, error) { + arg, args, err := gopt.GetRequiredArg(args, sections...) + if err != nil { + return 0, args, err + } + i, err := strconv.Atoi(arg) + if err != nil { + return 0, args, fmt.Errorf(text.ErrorConvertArgumentToInt, arg) + } + return i, args, nil +} + +// Same as GetRequiredArg but converts the argument to a float64. +func (gopt *GetOpt) GetRequiredArgFloat64(args []string, sections ...HelpSection) (float64, []string, error) { + arg, args, err := gopt.GetRequiredArg(args, sections...) + if err != nil { + return 0, args, err + } + f, err := strconv.ParseFloat(arg, 64) + if err != nil { + return 0, args, fmt.Errorf(text.ErrorConvertArgumentToFloat64, arg) + } + return f, args, nil +} diff --git a/text/variables.go b/text/variables.go index 3032918..5d4cced 100644 --- a/text/variables.go +++ b/text/variables.go @@ -38,10 +38,14 @@ var ErrorArgumentWithDash = "Missing argument for option '%s'!\n" + // It has two string placeholders ('%s'). The first one for the name of the option with the wrong argument and the second one for the argument that could not be converted. var ErrorConvertToInt = "Argument error for option '%s': Can't convert string to int: '%s'" +var ErrorConvertArgumentToInt = "Argument error: Can't convert string to int: '%s'" + // ErrorConvertToFloat64 holds the text for Float64 Coversion argument error. // It has two string placeholders ('%s'). The first one for the name of the option with the wrong argument and the second one for the argument that could not be converted. var ErrorConvertToFloat64 = "Argument error for option '%s': Can't convert string to float64: '%s'" +var ErrorConvertArgumentToFloat64 = "Argument error: Can't convert string to float64: '%s'" + // WarningOnUnknown holds the text for the unknown option message. // It has a string placeholder '%s' for the name of the option missing the argument. // This one includes the WARNING prefix because it is printed directly to the Writer output.