Skip to content

Commit

Permalink
Enhance ParseDuration with configurable parsing options
Browse files Browse the repository at this point in the history
Introduce ParseDuration() as the primary and simplest entrypoint for
parsing durations. By default it operates in "single-unit mode",
meaning only one unit type is allowed per input string (e.g., "1d" as
opposed to permitting "1d3h5m"). Assumes milliseconds as the default
unit when none is specified.

In addition, a new parser configuration is introduced which provides
flexibility to specify a subset of permissible units. Allows custom
defaults and parsing behaviors tailored for specific use cases.
  • Loading branch information
frobware committed Aug 20, 2023
1 parent 298a36d commit 7a6a4c7
Show file tree
Hide file tree
Showing 4 changed files with 657 additions and 256 deletions.
41 changes: 28 additions & 13 deletions cmd/haproxy-timeout-checker/haproxy-timeout-checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,47 @@ package main
import (
"fmt"
"os"
"time"

"github.com/frobware/haproxytime"
)

const HAProxyMaxTimeoutValue = 2147483647 * time.Millisecond
func printErrorWithPosition(input string, err error, position int) {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, input)
fmt.Fprintf(os.Stderr, "%"+fmt.Sprint(position)+"s", "")
fmt.Fprintln(os.Stderr, "^")
}

func main() {
if len(os.Args) < 2 {
fmt.Println(`usage: <duration>`)
fmt.Println("usage: <duration>")
os.Exit(1)
}

duration, position, err := haproxytime.ParseDuration(os.Args[1])
parserCfg, err := haproxytime.NewParserConfig(haproxytime.UnitMillisecond, haproxytime.MultiUnitMode)
if err != nil {
fmt.Fprintln(os.Stderr, os.Args[1])
fmt.Fprintf(os.Stderr, "%"+fmt.Sprint(position)+"s", "")
fmt.Fprintln(os.Stderr, "^")
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
fmt.Fprintf(os.Stderr, "error: failed to created parser configuration: %v\n", err)
os.Exit(2)
}

if duration.Milliseconds() > HAProxyMaxTimeoutValue.Milliseconds() {
fmt.Fprintf(os.Stderr, "duration %vms exceeds HAProxy's maximum value of %vms\n", duration.Milliseconds(), HAProxyMaxTimeoutValue.Milliseconds())
os.Exit(1)
duration, err := haproxytime.ParseDurationWithConfig(os.Args[1], parserCfg)
if err != nil {
switch actualErr := err.(type) {
case *haproxytime.SyntaxError:
printErrorWithPosition(os.Args[1], actualErr, actualErr.Position)
os.Exit(3)
case *haproxytime.OverflowError:
printErrorWithPosition(os.Args[1], actualErr, actualErr.Position)
os.Exit(4)
}
}

if haproxytime.DurationExceedsMaxTimeout(duration) {
fmt.Fprintf(os.Stderr, "%vms exceeds HAProxy's maximum duration (%vms)\n",
duration.Milliseconds(),
haproxytime.MaxTimeoutInMilliseconds.Milliseconds())
os.Exit(5)
}

fmt.Println(duration.Milliseconds())
fmt.Printf("%vms\n", duration.Milliseconds())
}
Loading

0 comments on commit 7a6a4c7

Please sign in to comment.