Skip to content

Commit

Permalink
flag: add optionalIntValue
Browse files Browse the repository at this point in the history
Signed-off-by: Giuseppe Scrivano <[email protected]>
  • Loading branch information
giuseppe committed Jul 17, 2019
1 parent 5f45112 commit 7ea853a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions cmd/skopeo/flag.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"strconv"

"github.com/urfave/cli"
Expand Down Expand Up @@ -73,3 +74,37 @@ func (ob *optionalStringValue) String() string {
}
return ob.value
}

// optionalInt is a int with a separate presence flag.
type optionalInt struct {
present bool
value int
}

// optionalInt is a cli.Generic == flag.Value implementation equivalent to
// the one underlying flag.Int, except that it records whether the flag has been set.
// This is distinct from optionalInt to (pretend to) force callers to use
// newoptionalInt
type optionalIntValue optionalInt

func newOptionalIntValue(p *optionalInt) cli.Generic {
p.present = false
return (*optionalIntValue)(p)
}

func (ob *optionalIntValue) Set(s string) error {
v, err := strconv.Atoi(s)
if err != nil {
return err
}
ob.value = v
ob.present = true
return nil
}

func (ob *optionalIntValue) String() string {
if !ob.present {
return "" // This is, sadly, not round-trip safe: --flag= is interpreted as {present:true, value:""}
}
return fmt.Sprintf("%d", ob.value)
}

0 comments on commit 7ea853a

Please sign in to comment.