本文整理汇总了Golang中flag.NewFlagSet函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFlagSet函数的具体用法?Golang NewFlagSet怎么用?Golang NewFlagSet使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFlagSet函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
invalidateflags := flag.NewFlagSet("invalidate", flag.ExitOnError)
sync := invalidateflags.Bool("sync", true, "Make request synchronously")
verbose := invalidateflags.Bool("verbose", false, "Verbose output")
runflags := flag.NewFlagSet("run", flag.ExitOnError)
bail := runflags.Bool("bail", false, "Bail after a single test failure")
runverbose := runflags.Bool("verbose", false, "Verbose response output")
grepHelp := "Grep for the given pattern"
grep := runflags.String("grep", "", grepHelp)
runflags.StringVar(grep, "g", "", grepHelp+" (shorthand)")
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "invalidate":
err := invalidateflags.Parse(os.Args[2:])
if err != nil {
handleError(err, true)
}
doInvalidate(invalidateflags, *sync, *verbose)
case "run":
err := runflags.Parse(os.Args[2:])
if err != nil {
handleError(err, true)
}
doRun(runflags, *bail, *runverbose, *grep)
default:
usage()
}
}
示例2: TestCliFlagsToCfnStackParams
func TestCliFlagsToCfnStackParams(t *testing.T) {
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-up", 0)
flagSet.Bool(capabilityIAMFlag, true, "")
flagSet.String(keypairNameFlag, "default", "")
context := cli.NewContext(nil, flagSet, globalContext)
params := cliFlagsToCfnStackParams(context)
_, err := params.GetParameter(cloudformation.ParameterKeyAsgMaxSize)
if err == nil {
t.Fatalf("Expected error for parameter '%s'", cloudformation.ParameterKeyAsgMaxSize)
}
if cloudformation.ParameterNotFoundError != err {
t.Error("Enexpected error returned: ", err)
}
flagSet.String(asgMaxSizeFlag, "2", "")
context = cli.NewContext(nil, flagSet, globalContext)
params = cliFlagsToCfnStackParams(context)
_, err = params.GetParameter(cloudformation.ParameterKeyAsgMaxSize)
if err != nil {
t.Error("Error getting parameter '%s'", cloudformation.ParameterKeyAsgMaxSize)
}
}
示例3: TestNewContext
func TestNewContext(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("myflag", 12, "doc")
set.Int64("myflagInt64", int64(12), "doc")
set.Uint("myflagUint", uint(93), "doc")
set.Uint64("myflagUint64", uint64(93), "doc")
set.Float64("myflag64", float64(17), "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Int("myflag", 42, "doc")
globalSet.Int64("myflagInt64", int64(42), "doc")
globalSet.Uint("myflagUint", uint(33), "doc")
globalSet.Uint64("myflagUint64", uint64(33), "doc")
globalSet.Float64("myflag64", float64(47), "doc")
globalCtx := NewContext(nil, globalSet, nil)
command := Command{Name: "mycommand"}
c := NewContext(nil, set, globalCtx)
c.Command = command
expect(t, c.Int("myflag"), 12)
expect(t, c.Int64("myflagInt64"), int64(12))
expect(t, c.Uint("myflagUint"), uint(93))
expect(t, c.Uint64("myflagUint64"), uint64(93))
expect(t, c.Float64("myflag64"), float64(17))
expect(t, c.GlobalInt("myflag"), 42)
expect(t, c.GlobalInt64("myflagInt64"), int64(42))
expect(t, c.GlobalUint("myflagUint"), uint(33))
expect(t, c.GlobalUint64("myflagUint64"), uint64(33))
expect(t, c.GlobalFloat64("myflag64"), float64(47))
expect(t, c.Command.Name, "mycommand")
}
示例4: commandWorker
func commandWorker(wi *Instance, wr *wrangler.Wrangler, args []string, cell string, runFromCli bool) (Worker, error) {
action := args[0]
actionLowerCase := strings.ToLower(action)
for _, group := range commands {
for _, cmd := range group.Commands {
if strings.ToLower(cmd.Name) == actionLowerCase {
var subFlags *flag.FlagSet
if runFromCli {
subFlags = flag.NewFlagSet(action, flag.ExitOnError)
} else {
subFlags = flag.NewFlagSet(action, flag.ContinueOnError)
}
// The command may be run from an RPC and may not log to the console.
// The Wrangler logger defines where the output has to go.
subFlags.SetOutput(logutil.NewLoggerWriter(wr.Logger()))
subFlags.Usage = func() {
wr.Logger().Printf("Usage: %s %s %s\n\n", os.Args[0], cmd.Name, cmd.Params)
wr.Logger().Printf("%s\n\n", cmd.Help)
subFlags.PrintDefaults()
}
return cmd.Method(wi, wr, subFlags, args[1:])
}
}
}
if runFromCli {
flag.Usage()
} else {
PrintAllCommands(wr.Logger())
}
return nil, fmt.Errorf("unknown command: %v", action)
}
示例5: TestClusterUp
func TestClusterUp(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockEcs := mock_ecs.NewMockECSClient(ctrl)
mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
mockEcs.EXPECT().Initialize(gomock.Any())
mockEcs.EXPECT().CreateCluster(gomock.Any()).Do(func(in interface{}) {
if in.(string) != clusterName {
t.Fatal("Expected to be called with " + clusterName + " not " + in.(string))
}
}).Return(clusterName, nil)
mockCloudformation.EXPECT().Initialize(gomock.Any())
mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(errors.New("error"))
mockCloudformation.EXPECT().CreateStack(gomock.Any(), gomock.Any(), gomock.Any()).Return("", nil)
mockCloudformation.EXPECT().WaitUntilCreateComplete(gomock.Any()).Return(nil)
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-up", 0)
flagSet.Bool(capabilityIAMFlag, true, "")
flagSet.String(keypairNameFlag, "default", "")
context := cli.NewContext(nil, flagSet, globalContext)
err := createCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation, ami.NewStaticAmiIds())
if err != nil {
t.Fatal("Error bringing up cluster: ", err)
}
}
示例6: TestClusterDown
func TestClusterDown(t *testing.T) {
newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
return &config.CliParams{
Cluster: clusterName,
}, nil
}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mock_ecs.NewMockECSClient(ctrl)
mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
gomock.InOrder(
mockECS.EXPECT().Initialize(gomock.Any()),
mockECS.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil),
mockCloudformation.EXPECT().Initialize(gomock.Any()),
mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(nil),
mockCloudformation.EXPECT().DeleteStack(stackName).Return(nil),
mockCloudformation.EXPECT().WaitUntilDeleteComplete(stackName).Return(nil),
mockECS.EXPECT().DeleteCluster(clusterName).Return(clusterName, nil),
)
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-down", 0)
flagSet.Bool(forceFlag, true, "")
context := cli.NewContext(nil, flagSet, globalContext)
err := deleteCluster(context, newMockReadWriter(), mockECS, mockCloudformation)
if err != nil {
t.Fatal("Error deleting cluster: ", err)
}
}
示例7: main
func main() {
start := flag.NewFlagSet("start", flag.ExitOnError)
dbIp := start.String("db_ip", "127.0.0.1", "ip address for databse host")
startHelp := start.Bool("help", false, "show this help message")
stop := flag.NewFlagSet("stop", flag.ExitOnError)
flushDb := stop.Bool("flush_db", false, "flush database")
if len(os.Args) == 1 {
showUsage()
return
}
if os.Args[1] == "start" {
start.Parse(os.Args[2:])
if *startHelp {
start.PrintDefaults()
return
}
fmt.Printf("Database ip address: %v\n", *dbIp)
return
}
if os.Args[1] == "stop" {
stop.Parse(os.Args[2:])
if *flushDb {
fmt.Println("stopping and flushing db")
return
}
fmt.Println("stopping")
return
}
showUsage()
}
示例8: TestClusterUpWithout2AvailabilityZones
func TestClusterUpWithout2AvailabilityZones(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mock_ecs.NewMockECSClient(ctrl)
mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
vpcAZs := "us-west-2c"
os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
os.Setenv("AWS_SECRET_KEY", "secret")
defer func() {
os.Unsetenv("AWS_ACCESS_KEY")
os.Unsetenv("AWS_SECRET_KEY")
}()
gomock.InOrder(
mockCloudformation.EXPECT().Initialize(gomock.Any()),
mockCloudformation.EXPECT().ValidateStackExists(stackName).Return(errors.New("error")),
)
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-up", 0)
flagSet.Bool(capabilityIAMFlag, true, "")
flagSet.String(keypairNameFlag, "default", "")
flagSet.Bool(forceFlag, true, "")
flagSet.String(vpcAzFlag, vpcAZs, "")
context := cli.NewContext(nil, flagSet, globalContext)
err := createCluster(context, newMockReadWriter(), mockECS, mockCloudformation, ami.NewStaticAmiIds())
if err == nil {
t.Fatal("Expected error for 2 AZs")
}
}
示例9: TestClusterUpWithClusterNameEmpty
func TestClusterUpWithClusterNameEmpty(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockECS := mock_ecs.NewMockECSClient(ctrl)
mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
os.Setenv("AWS_ACCESS_KEY", "AKIDEXAMPLE")
os.Setenv("AWS_SECRET_KEY", "secret")
defer func() {
os.Unsetenv("AWS_ACCESS_KEY")
os.Unsetenv("AWS_SECRET_KEY")
}()
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-up", 0)
flagSet.Bool(capabilityIAMFlag, true, "")
flagSet.String(keypairNameFlag, "default", "")
context := cli.NewContext(nil, flagSet, globalContext)
err := createCluster(context, &mockReadWriter{clusterName: ""}, mockECS, mockCloudformation, ami.NewStaticAmiIds())
if err == nil {
t.Fatal("Expected error bringing up cluster")
}
}
示例10: TestShowLoginToken
/*
* This does spot checking (not 100% thorough, since the format will change)
* on the output of "show-login-token"
*/
func TestShowLoginToken(t *testing.T) {
config := configuration.Configuration{
Token: accessToken,
}
globalFlags := flag.NewFlagSet("global-flags", flag.ContinueOnError)
err := globalFlags.Parse([]string{})
if err != nil {
t.Error(err)
}
globalCtx := cli.NewContext(nil, globalFlags, nil)
commandFlags := flag.NewFlagSet("command-flags", flag.ContinueOnError)
err = commandFlags.Parse([]string{})
if err != nil {
t.Error(err)
}
cxt := cli.NewContext(nil, commandFlags, globalCtx)
var output bytes.Buffer
err = showLoginTokenWriter(cxt, &output, &config)
// Verify it didn't fail
if err != nil {
t.Error(err)
}
// Verify we printed the subject
err = checkRegExp(`Subject:\s+`+expectedSubject, output)
if err != nil {
t.Error(err)
}
// Verify we printed the admin group
err = checkRegExp(`Groups:.*`+expectedAdminGroup, output)
if err != nil {
t.Error(err)
}
// Verify we printed the everyone group
err = checkRegExp(`Groups:.*`+expectedEveryoneGroup, output)
if err != nil {
t.Error(err)
}
// Verify we printed the date for Issued and Expires
err = checkRegExp(`Issued:.*`+expectedDate, output)
if err != nil {
t.Error(err)
}
err = checkRegExp(`Expires:.*`+expectedDate, output)
if err != nil {
t.Error(err)
}
// Verify we printed the token itself
err = checkRegExp(`Token:\s+`+accessToken, output)
if err != nil {
t.Error(err)
}
}
示例11: TestShowLoginTokenNonInteractive
/*
* This validates the output of "show-login-token --non-interactive"
*/
func TestShowLoginTokenNonInteractive(t *testing.T) {
config := configuration.Configuration{
Token: accessToken,
}
globalFlags := flag.NewFlagSet("global-flags", flag.ContinueOnError)
globalFlags.Bool("non-interactive", true, "non-interactive")
err := globalFlags.Parse([]string{"--non-interactive"})
if err != nil {
t.Error(err)
}
globalCtx := cli.NewContext(nil, globalFlags, nil)
commandFlags := flag.NewFlagSet("command-flags", flag.ContinueOnError)
err = commandFlags.Parse([]string{})
if err != nil {
t.Error(err)
}
cxt := cli.NewContext(nil, commandFlags, globalCtx)
var output bytes.Buffer
err = showLoginTokenWriter(cxt, &output, &config)
// Verify it didn't fail
if err != nil {
t.Error(err)
}
// Verify we printed the token and only the token (well, with a newline)
outputString := output.String()
if outputString != accessToken+"\n" {
t.Errorf("Expected just access token, found '%s'", outputString)
}
}
示例12: withinTest
func withinTest(cs Config, fs *flag.FlagSet, fn func(*cli.Context)) {
ogSource := DefaultConfig
DefaultConfig = cs
defer func() {
DefaultConfig = ogSource
}()
var b bytes.Buffer
app := cli.NewApp()
app.Writer = bufio.NewWriter(&b)
globalSet := flag.NewFlagSet("global test", 0)
globalSet.String("token", "token", "token")
globalCtx := cli.NewContext(app, globalSet, nil)
if fs == nil {
fs = flag.NewFlagSet("local test", 0)
}
c := cli.NewContext(app, fs, globalCtx)
fn(c)
}
示例13: init
func init() {
listFlags := flag.NewFlagSet("network-list", flag.ExitOnError)
initCommonFlags(listFlags)
listFlags.BoolVar(&networkListOpts.allTenants, "all-tenants", false,
"Display networks for all tenants")
listFlags.BoolVar(&networkListOpts.brief, "brief", false,
"Multiline format")
listFlags.BoolVar(&networkListOpts.detail, "detail", false,
"Multiline format (detailed information)")
RegisterCliCommand("network-list", listFlags, networkList)
createFlags := flag.NewFlagSet("network-create", flag.ExitOnError)
initCommonFlags(createFlags)
createFlags.StringVar(&networkCreateOpts.subnet, "subnet", "",
"Subnet prefix for network")
createFlags.Usage = networkCreateUsage(createFlags)
RegisterCliCommand("network-create", createFlags, networkCreate)
deleteFlags := flag.NewFlagSet("network-delete", flag.ExitOnError)
initCommonFlags(deleteFlags)
deleteFlags.BoolVar(&networkDeleteOpts.purge, "purge", false,
"Delete all dependent objects")
deleteFlags.Usage = networkNameOrIdUsage(deleteFlags)
RegisterCliCommand("network-delete", deleteFlags, networkDelete)
showFlags := flag.NewFlagSet("network-show", flag.ExitOnError)
initCommonFlags(showFlags)
showFlags.BoolVar(&networkShowOpts.detail, "detail", false,
"Detail output")
showFlags.Usage = networkNameOrIdUsage(showFlags)
RegisterCliCommand("network-show", showFlags, networkShow)
}
示例14: TestClusterPSTaskGetInfoFail
func TestClusterPSTaskGetInfoFail(t *testing.T) {
newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
return &config.CliParams{
Cluster: clusterName,
}, nil
}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockEcs := mock_ecs.NewMockECSClient(ctrl)
mockEcs.EXPECT().Initialize(gomock.Any())
mockEcs.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil)
mockEcs.EXPECT().GetTasksPages(gomock.Any(), gomock.Any()).Do(func(x, y interface{}) {
}).Return(errors.New("error"))
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-down", 0)
context := cli.NewContext(nil, flagSet, globalContext)
_, err := clusterPS(context, &mockReadWriter{}, mockEcs)
if err == nil {
t.Fatal("Expected error in cluster ps")
}
}
示例15: TestClusterScale
func TestClusterScale(t *testing.T) {
newCliParams = func(context *cli.Context, rdwr config.ReadWriter) (*config.CliParams, error) {
return &config.CliParams{
Cluster: clusterName,
}, nil
}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockEcs := mock_ecs.NewMockECSClient(ctrl)
mockCloudformation := mock_cloudformation.NewMockCloudformationClient(ctrl)
mockEcs.EXPECT().Initialize(gomock.Any())
mockEcs.EXPECT().IsActiveCluster(gomock.Any()).Return(true, nil)
mockCloudformation.EXPECT().Initialize(gomock.Any())
mockCloudformation.EXPECT().ValidateStackExists(gomock.Any()).Return(nil)
mockCloudformation.EXPECT().UpdateStack(gomock.Any(), gomock.Any()).Return("", nil)
mockCloudformation.EXPECT().WaitUntilUpdateComplete(gomock.Any()).Return(nil)
globalSet := flag.NewFlagSet("ecs-cli", 0)
globalSet.String("region", "us-west-1", "")
globalContext := cli.NewContext(nil, globalSet, nil)
flagSet := flag.NewFlagSet("ecs-cli-down", 0)
flagSet.Bool(capabilityIAMFlag, true, "")
flagSet.String(asgMaxSizeFlag, "1", "")
context := cli.NewContext(nil, flagSet, globalContext)
err := scaleCluster(context, &mockReadWriter{}, mockEcs, mockCloudformation)
if err != nil {
t.Fatal("Error scaling cluster: ", err)
}
}