Skip to content

Commit

Permalink
add GetRequiredArgInt and GetRequiredArgFloat64 helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidGamba committed Dec 29, 2023
1 parent f6f46c4 commit b599ac9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
27 changes: 27 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package getoptions

import (
"fmt"
"strconv"

"github.com/DavidGamba/go-getoptions/text"
)
Expand Down Expand Up @@ -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
}
4 changes: 4 additions & 0 deletions text/variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit b599ac9

Please sign in to comment.