Last active
August 29, 2015 14:05
-
-
Save alecthomas/ebfc847c574981e873c2 to your computer and use it in GitHub Desktop.
Version of http://learngowith.me/gos-flag-package-creating-a-cli-tool/ using Kingpin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"strconv" | |
"github.com/alecthomas/kingpin" | |
) | |
var ( | |
versionUsageText = "0.1" | |
textArg = kingpin.Arg("text", "Text to repeat (defaults to 'y').").Default("y").String() | |
limitFlagCustom = CustomFlag(kingpin.Flag("limit", "0 or greater integer value, determines times output is displayed")) | |
) | |
func main() { | |
kingpin.Version(versionUsageText) | |
kingpin.Parse() | |
if *limitFlagCustom == 0 { | |
*limitFlagCustom = -1 | |
} | |
for i := 0; i != *limitFlagCustom; i++ { | |
fmt.Println(*textArg) | |
} | |
} | |
type PositiveInt int | |
func (p *PositiveInt) Set(s string) error { | |
i, _ := strconv.Atoi(s) | |
if i < 0 { | |
return errors.New("flag must be >= 0") | |
} | |
*p = PositiveInt(i) | |
return nil | |
} | |
func (p *PositiveInt) String() string { | |
return strconv.Itoa(int(*p)) | |
} | |
func CustomFlag(s kingpin.Settings) (target *int) { | |
target = new(int) | |
s.SetValue((*PositiveInt)(target)) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment