当前位置: 首页>>代码示例>>Golang>>正文


Golang cmd.Main函数代码示例

本文整理汇总了Golang中github.com/juju/cmd.Main函数的典型用法代码示例。如果您正苦于以下问题:Golang Main函数的具体用法?Golang Main怎么用?Golang Main使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Main函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Main

// Main is not redundant with main(), because it provides an entry point
// for testing with arbitrary command line arguments.
func Main(args []string) int {
	defer func() {
		if r := recover(); r != nil {
			buf := make([]byte, 4096)
			buf = buf[:runtime.Stack(buf, false)]
			logger.Criticalf("Unhandled panic: \n%v\n%s", r, buf)
			os.Exit(exit_panic)
		}
	}()
	var code int = 1
	ctx, err := cmd.DefaultContext()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(exit_err)
	}
	commandName := filepath.Base(args[0])
	if commandName == names.Jujud {
		code, err = jujuDMain(args, ctx)
	} else if commandName == names.Jujuc {
		fmt.Fprint(os.Stderr, jujudDoc)
		code = exit_err
		err = fmt.Errorf("jujuc should not be called directly")
	} else if commandName == names.JujuRun {
		code = cmd.Main(&RunCommand{}, ctx, args[1:])
	} else if commandName == names.JujuDumpLogs {
		code = cmd.Main(dumplogs.NewCommand(), ctx, args[1:])
	} else {
		code, err = jujuCMain(commandName, ctx, args)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
	}
	return code
}
开发者ID:imoapps,项目名称:juju,代码行数:36,代码来源:main.go

示例2: jujuDMain

// Main registers subcommands for the jujud executable, and hands over control
// to the cmd package.
func jujuDMain(args []string, ctx *cmd.Context) (code int, err error) {
	// Assuming an average of 200 bytes per log message, use up to
	// 200MB for the log buffer.
	defer logger.Debugf("jujud complete, code %d, err %v", code, err)
	logCh, err := logsender.InstallBufferedLogWriter(1048576)
	if err != nil {
		return 1, errors.Trace(err)
	}

	jujud := jujucmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujud",
		Doc:  jujudDoc,
	})

	jujud.Log.NewWriter = func(target io.Writer) loggo.Writer {
		return &jujudWriter{target: target}
	}

	jujud.Register(NewBootstrapCommand())

	// TODO(katco-): AgentConf type is doing too much. The
	// MachineAgent type has called out the separate concerns; the
	// AgentConf should be split up to follow suit.
	agentConf := agentcmd.NewAgentConf("")
	machineAgentFactory := agentcmd.MachineAgentFactoryFn(agentConf, logCh, "")
	jujud.Register(agentcmd.NewMachineAgentCmd(ctx, machineAgentFactory, agentConf, agentConf))

	jujud.Register(agentcmd.NewUnitAgent(ctx, logCh))

	jujud.Register(NewUpgradeMongoCommand())

	code = cmd.Main(jujud, ctx, args[1:])
	return code, nil
}
开发者ID:bac,项目名称:juju,代码行数:36,代码来源:main.go

示例3: TestHelp

func (s *statusGetSuite) TestHelp(c *gc.C) {
	hctx := s.GetStatusHookContext(c)
	com, err := jujuc.NewCommand(hctx, cmdString("status-get"))
	c.Assert(err, jc.ErrorIsNil)
	ctx := testing.Context(c)
	code := cmd.Main(com, ctx, []string{"--help"})
	c.Assert(code, gc.Equals, 0)
	expectedHelp := "" +
		"Usage: status-get [options] [--include-data] [--service]\n" +
		"\n" +
		"Summary:\n" +
		"print status information\n" +
		"\n" +
		"Options:\n" +
		"--format  (= smart)\n" +
		"    Specify output format (json|smart|yaml)\n" +
		"--include-data  (= false)\n" +
		"    print all status data\n" +
		"-o, --output (= \"\")\n" +
		"    Specify an output file\n" +
		"--service  (= false)\n" +
		"    print status for all units of this service if this unit is the leader\n" +
		"\n" +
		"Details:\n" +
		"By default, only the status value is printed.\n" +
		"If the --include-data flag is passed, the associated data are printed also.\n"

	c.Assert(bufferString(ctx.Stdout), gc.Equals, expectedHelp)
	c.Assert(bufferString(ctx.Stderr), gc.Equals, "")
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:30,代码来源:status-get_test.go

示例4: TestServiceStatus

func (s *statusGetSuite) TestServiceStatus(c *gc.C) {
	expected := map[string]interface{}{
		"service-status": map[interface{}]interface{}{
			"status-data": map[interface{}]interface{}{},
			"units": map[interface{}]interface{}{
				"": map[interface{}]interface{}{
					"message":     "this is a unit status",
					"status":      "active",
					"status-data": map[interface{}]interface{}{},
				},
			},
			"message": "this is a service status",
			"status":  "active"},
	}
	hctx := s.GetStatusHookContext(c)
	setFakeServiceStatus(hctx)
	com, err := jujuc.NewCommand(hctx, cmdString("status-get"))
	c.Assert(err, jc.ErrorIsNil)
	ctx := testing.Context(c)
	code := cmd.Main(com, ctx, []string{"--format", "json", "--include-data", "--service"})
	c.Assert(code, gc.Equals, 0)

	var out map[string]interface{}
	c.Assert(goyaml.Unmarshal(bufferBytes(ctx.Stdout), &out), gc.IsNil)
	c.Assert(out, gc.DeepEquals, expected)

}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:27,代码来源:status-get_test.go

示例5: jujuDMain

// Main registers subcommands for the jujud executable, and hands over control
// to the cmd package.
func jujuDMain(args []string, ctx *cmd.Context) (code int, err error) {
	// Assuming an average of 200 bytes per log message, use up to
	// 200MB for the log buffer.
	logCh, err := logsender.InstallBufferedLogWriter(1048576)
	if err != nil {
		return 1, errors.Trace(err)
	}

	jujud := jujucmd.NewSuperCommand(cmd.SuperCommandParams{
		Name: "jujud",
		Doc:  jujudDoc,
	})
	jujud.Log.Factory = &writerFactory{}
	jujud.Register(NewBootstrapCommand())

	// TODO(katco-): AgentConf type is doing too much. The
	// MachineAgent type has called out the separate concerns; the
	// AgentConf should be split up to follow suit.
	agentConf := agentcmd.NewAgentConf("")
	machineAgentFactory := agentcmd.MachineAgentFactoryFn(
		agentConf, logCh, looputil.NewLoopDeviceManager(),
	)
	jujud.Register(agentcmd.NewMachineAgentCmd(ctx, machineAgentFactory, agentConf, agentConf))

	jujud.Register(agentcmd.NewUnitAgent(ctx, logCh))

	code = cmd.Main(jujud, ctx, args[1:])
	return code, nil
}
开发者ID:kakamessi99,项目名称:juju,代码行数:31,代码来源:main.go

示例6: TestMainSuccess

func (s *CmdSuite) TestMainSuccess(c *gc.C) {
	ctx := cmdtesting.Context(c)
	result := cmd.Main(&TestCommand{Name: "verb"}, ctx, []string{"--option", "success!"})
	c.Assert(result, gc.Equals, 0)
	c.Assert(bufferString(ctx.Stdout), gc.Equals, "success!\n")
	c.Assert(bufferString(ctx.Stderr), gc.Equals, "")
}
开发者ID:bogdanteleaga,项目名称:cmd,代码行数:7,代码来源:cmd_test.go

示例7: Main

// Main runs the Command specified by req, and fills in resp. A single command
// is run at a time.
func (j *Jujuc) Main(req Request, resp *exec.ExecResponse) error {
	if req.CommandName == "" {
		return badReqErrorf("command not specified")
	}
	if !filepath.IsAbs(req.Dir) {
		return badReqErrorf("Dir is not absolute")
	}
	c, err := j.getCmd(req.ContextId, req.CommandName)
	if err != nil {
		return badReqErrorf("%s", err)
	}
	var stdin, stdout, stderr bytes.Buffer
	ctx := &cmd.Context{
		Dir:    req.Dir,
		Stdin:  &stdin,
		Stdout: &stdout,
		Stderr: &stderr,
	}
	j.mu.Lock()
	defer j.mu.Unlock()
	logger.Infof("running hook tool %q %q", req.CommandName, req.Args)
	logger.Debugf("hook context id %q; dir %q", req.ContextId, req.Dir)
	resp.Code = cmd.Main(c, ctx, req.Args)
	resp.Stdout = stdout.Bytes()
	resp.Stderr = stderr.Bytes()
	return nil
}
开发者ID:jimmiebtlr,项目名称:juju,代码行数:29,代码来源:server.go

示例8: assertSetWarning

func (s *SetSuite) assertSetWarning(c *gc.C, dir string, args []string, w string) {
	ctx := coretesting.ContextForDir(c, dir)
	code := cmd.Main(service.NewSetCommandWithAPI(s.fakeClientAPI, s.fakeServiceAPI), ctx, append([]string{"dummy-service"}, args...))
	c.Check(code, gc.Equals, 0)

	c.Assert(strings.Replace(c.GetTestLog(), "\n", " ", -1), gc.Matches, ".*WARNING.*"+w+".*")
}
开发者ID:imoapps,项目名称:juju,代码行数:7,代码来源:set_test.go

示例9: TestUnknownOutputFormat

func (s *CmdSuite) TestUnknownOutputFormat(c *gc.C) {
	ctx := cmdtesting.Context(c)
	result := cmd.Main(&OutputCommand{}, ctx, []string{"--format", "cuneiform"})
	c.Check(result, gc.Equals, 2)
	c.Check(bufferString(ctx.Stdout), gc.Equals, "")
	c.Check(bufferString(ctx.Stderr), gc.Matches, ".*: unknown format \"cuneiform\"\n")
}
开发者ID:davecheney,项目名称:cmd,代码行数:7,代码来源:output_test.go

示例10: TestHelp

func (s *storageGetSuite) TestHelp(c *gc.C) {
	hctx, _ := s.newHookContext()
	com, err := jujuc.NewCommand(hctx, cmdString("storage-get"))
	c.Assert(err, jc.ErrorIsNil)
	ctx := testing.Context(c)
	code := cmd.Main(com, ctx, []string{"--help"})
	c.Assert(code, gc.Equals, 0)
	c.Assert(bufferString(ctx.Stdout), gc.Equals, `Usage: storage-get [options] [<key>]

Summary:
print information for storage instance with specified id

Options:
--format  (= smart)
    Specify output format (json|smart|yaml)
-o, --output (= "")
    Specify an output file
-s  (= data/0)
    specify a storage instance by id

Details:
When no <key> is supplied, all keys values are printed.
`)
	c.Assert(bufferString(ctx.Stderr), gc.Equals, "")
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:25,代码来源:storage-get_test.go

示例11: TestNotifyRun

func (s *SuperCommandSuite) TestNotifyRun(c *gc.C) {
	notifyTests := []struct {
		usagePrefix string
		name        string
		expectName  string
	}{
		{"juju", "juju", "juju"},
		{"something", "else", "something else"},
		{"", "juju", "juju"},
		{"", "myapp", "myapp"},
	}
	for i, test := range notifyTests {
		c.Logf("test %d. %q %q", i, test.usagePrefix, test.name)
		notifyName := ""
		sc := cmd.NewSuperCommand(cmd.SuperCommandParams{
			UsagePrefix: test.usagePrefix,
			Name:        test.name,
			NotifyRun: func(name string) {
				notifyName = name
			},
		})
		sc.Register(&TestCommand{Name: "blah"})
		ctx := cmdtesting.Context(c)
		code := cmd.Main(sc, ctx, []string{"blah", "--option", "error"})
		c.Assert(bufferString(ctx.Stderr), gc.Matches, "")
		c.Assert(code, gc.Equals, 1)
		c.Assert(notifyName, gc.Equals, test.expectName)
	}
}
开发者ID:bogdanteleaga,项目名称:cmd,代码行数:29,代码来源:supercommand_test.go

示例12: Main

// Main registers subcommands for the juju-metadata executable, and hands over control
// to the cmd package. This function is not redundant with main, because it
// provides an entry point for testing with arbitrary command line arguments.
func Main(args []string) {
	ctx, err := cmd.DefaultContext()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(2)
	}
	if err := juju.InitJujuHome(); err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(2)
	}
	metadatacmd := cmd.NewSuperCommand(cmd.SuperCommandParams{
		Name:        "metadata",
		UsagePrefix: "juju",
		Doc:         metadataDoc,
		Purpose:     "tools for generating and validating image and tools metadata",
		Log:         &cmd.Log{}})

	metadatacmd.Register(envcmd.Wrap(&ValidateImageMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ImageMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ToolsMetadataCommand{}))
	metadatacmd.Register(envcmd.Wrap(&ValidateToolsMetadataCommand{}))
	metadatacmd.Register(&SignMetadataCommand{})
	metadatacmd.Register(envcmd.Wrap(&ListImagesCommand{}))
	metadatacmd.Register(envcmd.Wrap(&AddImageMetadataCommand{}))

	os.Exit(cmd.Main(metadatacmd, ctx, args[1:]))
}
开发者ID:kakamessi99,项目名称:juju,代码行数:30,代码来源:metadata.go

示例13: TestHelp

func (s *RelationIdsSuite) TestHelp(c *gc.C) {
	template := `
usage: %s
purpose: list all relation ids with the given relation name

options:
--format  (= smart)
    specify output format (json|smart|yaml)
-o, --output (= "")
    specify an output file
%s`[1:]

	for relid, t := range map[int]struct {
		usage, doc string
	}{
		-1: {"relation-ids [options] <name>", ""},
		0:  {"relation-ids [options] [<name>]", "\nCurrent default relation name is \"x\".\n"},
		3:  {"relation-ids [options] [<name>]", "\nCurrent default relation name is \"y\".\n"},
	} {
		c.Logf("relid %d", relid)
		hctx := s.GetHookContext(c, relid, "")
		com, err := jujuc.NewCommand(hctx, "relation-ids")
		c.Assert(err, gc.IsNil)
		ctx := testing.Context(c)
		code := cmd.Main(com, ctx, []string{"--help"})
		c.Assert(code, gc.Equals, 0)
		expect := fmt.Sprintf(template, t.usage, t.doc)
		c.Assert(bufferString(ctx.Stdout), gc.Equals, expect)
		c.Assert(bufferString(ctx.Stderr), gc.Equals, "")
	}
}
开发者ID:jiasir,项目名称:juju,代码行数:31,代码来源:relation-ids_test.go

示例14: TestSSHCommand

func (s *SSHSuite) TestSSHCommand(c *gc.C) {
	m := s.makeMachines(3, c, true)
	ch := charmtesting.Charms.Dir("dummy")
	curl := charm.MustParseURL(
		fmt.Sprintf("local:quantal/%s-%d", ch.Meta().Name, ch.Revision()),
	)
	bundleURL, err := url.Parse("http://bundles.testing.invalid/dummy-1")
	c.Assert(err, gc.IsNil)
	dummy, err := s.State.AddCharm(ch, curl, bundleURL, "dummy-1-sha256")
	c.Assert(err, gc.IsNil)
	srv := s.AddTestingService(c, "mysql", dummy)
	s.addUnit(srv, m[0], c)

	srv = s.AddTestingService(c, "mongodb", dummy)
	s.addUnit(srv, m[1], c)
	s.addUnit(srv, m[2], c)

	for i, t := range sshTests {
		c.Logf("test %d: %s -> %s\n", i, t.about, t.args)
		ctx := coretesting.Context(c)
		jujucmd := cmd.NewSuperCommand(cmd.SuperCommandParams{})
		jujucmd.Register(envcmd.Wrap(&SSHCommand{}))

		code := cmd.Main(jujucmd, ctx, t.args)
		c.Check(code, gc.Equals, 0)
		c.Check(ctx.Stderr.(*bytes.Buffer).String(), gc.Equals, "")
		c.Check(ctx.Stdout.(*bytes.Buffer).String(), gc.Equals, t.result)
	}
}
开发者ID:rogpeppe,项目名称:juju,代码行数:29,代码来源:ssh_test.go

示例15: TestHelp

func (s *ActionSetSuite) TestHelp(c *gc.C) {
	hctx := &actionSettingContext{}
	com, err := jujuc.NewCommand(hctx, cmdString("action-set"))
	c.Assert(err, jc.ErrorIsNil)
	ctx := testing.Context(c)
	code := cmd.Main(com, ctx, []string{"--help"})
	c.Assert(code, gc.Equals, 0)
	c.Assert(bufferString(ctx.Stdout), gc.Equals, `usage: action-set <key>=<value> [<key>=<value> ...]
purpose: set action results

action-set adds the given values to the results map of the Action.  This map
is returned to the user after the completion of the Action.  Keys must start
and end with lowercase alphanumeric, and contain only lowercase alphanumeric,
hyphens and periods.

Example usage:
 action-set outfile.size=10G
 action-set foo.bar=2
 action-set foo.baz.val=3
 action-set foo.bar.zab=4
 action-set foo.baz=1

 will yield:

 outfile:
   size: "10G"
 foo:
   bar:
     zab: "4"
   baz: "1"
`)
	c.Assert(bufferString(ctx.Stderr), gc.Equals, "")
}
开发者ID:imoapps,项目名称:juju,代码行数:33,代码来源:action-set_test.go


注:本文中的github.com/juju/cmd.Main函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。