Esempio n. 1
0
func RunCLICommandWithoutDependency(cmdName string, args []string, requirementsFactory requirements.Factory, ui *testterm.FakeUI) bool {
	cmd := commandregistry.Commands.FindCommand(cmdName)
	context := flags.NewFlagContext(cmd.MetaData().Flags)
	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
	err := context.Parse(args...)
	if err != nil {
		fmt.Println("ERROR:", err)
		os.Exit(1)
	}

	defer func() {
		errMsg := recover()

		if errMsg != nil && errMsg != testterm.QuietPanic {
			panic(errMsg)
		}
	}()

	requirements := cmd.Requirements(requirementsFactory, context)

	for _, requirement := range requirements {
		if err = requirement.Execute(); err != nil {
			return false
		}
	}

	err = cmd.Execute(context)
	if err != nil {
		ui.Failed(err.Error())
	}

	return true
}
Esempio n. 2
0
func RunCommandMoreBetter(cmdName string, args []string, requirementsFactory *testreq.FakeReqFactory, updateFunc func(bool), pluginCall bool) (result RunCommandResult) {
	updateFunc(pluginCall)
	cmd := command_registry.Commands.FindCommand(cmdName)
	context := flags.NewFlagContext(cmd.MetaData().Flags)
	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
	err := context.Parse(args...)
	if err != nil {
		fmt.Println("ERROR:", err)
		return RunCommandResultFailed
	}

	defer func() {
		errMsg := recover()

		if errMsg != nil && errMsg != testterm.QuietPanic {
			panic(errMsg)
		}

		result = RunCommandResultFailed
	}()
	requirements, err := cmd.Requirements(requirementsFactory, context)
	if err != nil {
		return RunCommandResultRequirementsFailed
	}

	for _, requirement := range requirements {
		if !requirement.Execute() {
			return RunCommandResultRequirementsFailed
		}
	}

	cmd.Execute(context)

	return RunCommandResultSuccess
}
Esempio n. 3
0
func RunCliCommandWithoutDependency(cmdName string, args []string, requirementsFactory *testreq.FakeReqFactory) (passedRequirements bool) {
	cmd := command_registry.Commands.FindCommand(cmdName)
	context := flags.NewFlagContext(cmd.MetaData().Flags)
	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
	err := context.Parse(args...)
	if err != nil {
		fmt.Println("ERROR:", err)
		os.Exit(1)
	}

	defer func() {
		errMsg := recover()

		if errMsg != nil && errMsg != testterm.QuietPanic {
			panic(errMsg)
		}
	}()
	requirements, err := cmd.Requirements(requirementsFactory, context)
	if err != nil {
		return false
	}

	for _, requirement := range requirements {
		if !requirement.Execute() {
			return false
		}
	}

	passedRequirements = true

	cmd.Execute(context)

	return
}
func (c *commandRunner) Command(args []string, deps command_registry.Dependency, pluginApiCall bool) error {
	var err error

	cmdRegistry := command_registry.Commands

	if cmdRegistry.CommandExists(args[0]) {
		fc := flags.NewFlagContext(cmdRegistry.FindCommand(args[0]).MetaData().Flags)
		err = fc.Parse(args[1:]...)
		if err != nil {
			return err
		}

		cfCmd := cmdRegistry.FindCommand(args[0])
		cfCmd = cfCmd.SetDependency(deps, pluginApiCall)

		reqs := cfCmd.Requirements(requirements.NewFactory(deps.Config, deps.RepoLocator), fc)

		for _, r := range reqs {
			if err = r.Execute(); err != nil {
				return err
			}
		}

		cfCmd.Execute(fc)
	}

	return nil
}
Esempio n. 5
0
func (c *NozzlerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	var debug bool
	if args[0] != "nozzle" {
		return
	}
	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	fc := flags.NewFlagContext(setupFlags())
	err := fc.Parse(args[1:]...)
	if err != nil {
		c.ui.Failed(err.Error())
	}
	if fc.IsSet("debug") {
		debug = fc.Bool("debug")
	}

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	client := firehose.NewClient(authToken, dopplerEndpoint, debug, c.ui)
	client.Start()
}
Esempio n. 6
0
func (u *usagePresenter) Usage() string {
	metadata := u.cmd.MetaData()

	output := T("NAME:") + "\n"
	output += "   " + metadata.Name + " - " + metadata.Description + "\n\n"

	output += T("USAGE:") + "\n"
	output += "   " + strings.Replace(strings.Join(metadata.Usage, ""), "CF_NAME", cf.Name, -1) + "\n"

	if len(metadata.Examples) > 0 {
		output += "\n"
		output += fmt.Sprintf("%s:\n", T("EXAMPLES"))
		for _, e := range metadata.Examples {
			output += fmt.Sprintf("   %s\n", strings.Replace(e, "CF_NAME", cf.Name, -1))
		}
	}

	if metadata.ShortName != "" {
		output += "\n" + T("ALIAS:") + "\n"
		output += "   " + metadata.ShortName + "\n"
	}

	if metadata.Flags != nil {
		output += "\n" + T("OPTIONS:") + "\n"
		output += flags.NewFlagContext(metadata.Flags).ShowUsage(3)
	}

	return output
}
Esempio n. 7
0
func RunCLICommand(cmdName string, args []string, requirementsFactory *testreq.FakeReqFactory, updateFunc func(bool), pluginCall bool) (passedRequirements bool) {
	updateFunc(pluginCall)
	cmd := commandregistry.Commands.FindCommand(cmdName)
	context := flags.NewFlagContext(cmd.MetaData().Flags)
	context.SkipFlagParsing(cmd.MetaData().SkipFlagParsing)
	err := context.Parse(args...)
	if err != nil {
		fmt.Println("ERROR:", err)
		os.Exit(1)
	}

	defer func() {
		errMsg := recover()

		if errMsg != nil && errMsg != testterm.QuietPanic {
			panic(errMsg)
		}
	}()
	requirements := cmd.Requirements(requirementsFactory, context)

	for _, requirement := range requirements {
		if err = requirement.Execute(); err != nil {
			return false
		}
	}

	passedRequirements = true

	cmd.Execute(context)

	return
}
Esempio n. 8
0
func (r *registry) CommandUsage(cmdName string) string {
	output := ""
	cmd := r.FindCommand(cmdName)

	output = i18n.T("NAME") + ":" + "\n"
	output += "   " + cmd.MetaData().Name + " - " + cmd.MetaData().Description + "\n\n"

	output += i18n.T("USAGE") + ":" + "\n"
	output += "   " + strings.Replace(cmd.MetaData().Usage, "CF_NAME", cf.Name(), -1) + "\n"

	if cmd.MetaData().ShortName != "" {
		output += "\n" + i18n.T("ALIAS") + ":" + "\n"
		output += "   " + cmd.MetaData().ShortName + "\n"
	}

	if cmd.MetaData().Flags != nil {
		output += "\n" + i18n.T("OPTIONS") + ":" + "\n"
		output += flags.NewFlagContext(cmd.MetaData().Flags).ShowUsage(3)
	}

	return output
}
Esempio n. 9
0
func (cmd *CliRpcCmd) CallCoreCommand(args []string, retVal *bool) error {
	defer func() {
		recover()
	}()

	var err error
	cmdRegistry := command_registry.Commands

	if cmdRegistry.CommandExists(args[0]) {
		//non-codegangsta path
		deps := command_registry.NewDependency()

		//set deps objs to be the one used by all other codegangsta commands
		//once all commands are converted, we can make fresh deps for each command run
		deps.Config = cmd.cliConfig
		deps.RepoLocator = cmd.repoLocator

		fc := flags.NewFlagContext(cmdRegistry.FindCommand(args[0]).MetaData().Flags)
		err = fc.Parse(args[1:]...)
		if err == nil {
			cmdRegistry.SetCommand(cmdRegistry.FindCommand(args[0]).SetDependency(deps))
			cmdRegistry.FindCommand(args[0]).Execute(fc)
		}
	} else {
		//call codegangsta command
		err = cmd.coreCommandRunner.Run(append([]string{"CF_NAME"}, args...))
	}

	if err != nil {
		*retVal = false
		return err
	}

	*retVal = true
	return nil
}
Esempio n. 10
0
File: cmd.go Progetto: Reejoshi/cli
func Main(traceEnv string, args []string) {

	//handle `cf -v` for cf version
	if len(args) == 2 && (args[1] == "-v" || args[1] == "--version") {
		args[1] = "version"
	}

	//handles `cf`
	if len(args) == 1 {
		args = []string{args[0], "help"}
	}

	//handles `cf [COMMAND] -h ...`
	//rearrange args to `cf help COMMAND` and let `command help` to print out usage
	args = append([]string{args[0]}, handleHelp(args[1:])...)

	newArgs, isVerbose := handleVerbose(args)
	args = newArgs

	errFunc := func(err error) {
		if err != nil {
			ui := terminal.NewUI(
				os.Stdin,
				Writer,
				terminal.NewTeePrinter(Writer),
				trace.NewLogger(Writer, isVerbose, traceEnv, ""),
			)
			ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}

	// Only used to get Trace, so our errorHandler doesn't matter, since it's not used
	configPath, err := confighelpers.DefaultFilePath()
	if err != nil {
		errFunc(err)
	}
	config := coreconfig.NewRepositoryFromFilepath(configPath, errFunc)
	defer config.Close()

	traceConfigVal := config.Trace()

	// Writer is assigned in writer_unix.go/writer_windows.go
	traceLogger := trace.NewLogger(Writer, isVerbose, traceEnv, traceConfigVal)

	deps := commandregistry.NewDependency(Writer, traceLogger, os.Getenv("CF_DIAL_TIMEOUT"))
	defer handlePanics(args, deps.TeePrinter, deps.Logger)
	defer deps.Config.Close()

	//handle `cf --build`
	if len(args) == 2 && (args[1] == "--build" || args[1] == "-b") {
		deps.UI.Say(T("{{.CFName}} was built with Go version: {{.GoVersion}}",
			map[string]interface{}{
				"CFName":    args[0],
				"GoVersion": runtime.Version(),
			}))
		os.Exit(0)
	}

	warningProducers := []net.WarningProducer{}
	for _, warningProducer := range deps.Gateways {
		warningProducers = append(warningProducers, warningProducer)
	}

	warningsCollector := net.NewWarningsCollector(deps.UI, warningProducers...)

	commandsloader.Load()

	//run core command
	cmdName := args[1]
	cmd := cmdRegistry.FindCommand(cmdName)
	if cmd != nil {
		meta := cmd.MetaData()
		flagContext := flags.NewFlagContext(meta.Flags)
		flagContext.SkipFlagParsing(meta.SkipFlagParsing)

		cmdArgs := args[2:]
		err = flagContext.Parse(cmdArgs...)
		if err != nil {
			usage := cmdRegistry.CommandUsage(cmdName)
			deps.UI.Failed(T("Incorrect Usage") + "\n\n" + err.Error() + "\n\n" + usage)
		}

		cmd = cmd.SetDependency(deps, false)
		cmdRegistry.SetCommand(cmd)

		requirementsFactory := requirements.NewFactory(deps.Config, deps.RepoLocator)
		reqs := cmd.Requirements(requirementsFactory, flagContext)

		for _, req := range reqs {
			err = req.Execute()
			if err != nil {
				deps.UI.Failed(err.Error())
			}
		}

		err = cmd.Execute(flagContext)
		if err != nil {
			ui := terminal.NewUI(os.Stdin, Writer, terminal.NewTeePrinter(Writer), traceLogger)
			ui.Failed(err.Error())
		}

		warningsCollector.PrintWarnings()

		os.Exit(0)
	}

	//non core command, try plugin command
	server := netrpc.NewServer()
	rpcService, err := rpc.NewRpcService(deps.TeePrinter, deps.TeePrinter, deps.Config, deps.RepoLocator, rpc.NewCommandRunner(), deps.Logger, Writer, server)
	if err != nil {
		deps.UI.Say(T("Error initializing RPC service: ") + err.Error())
		os.Exit(1)
	}

	pluginPath := filepath.Join(confighelpers.PluginRepoDir(), ".cf", "plugins")
	pluginConfig := pluginconfig.NewPluginConfig(
		func(err error) {
			deps.UI.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error()))
		},
		configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
		pluginPath,
	)
	pluginList := pluginConfig.Plugins()

	ran := rpc.RunMethodIfExists(rpcService, args[1:], pluginList)
	if !ran {
		deps.UI.Say("'" + args[1] + T("' is not a registered command. See 'cf help'"))
		suggestCommands(cmdName, deps.UI, append(cmdRegistry.ListCommands(), pluginConfig.ListCommands()...))
		os.Exit(1)
	}
}
Esempio n. 11
0
			var (
				fCtx       flags.FlagContext
				cmdFlagMap map[string]flags.FlagSet
			)

			BeforeEach(func() {
				cmdFlagMap = make(map[string]flags.FlagSet)

				cmdFlagMap["name"] = &flags.StringFlag{Name: "name", ShortName: "n", Usage: "test string flag"}
				cmdFlagMap["skip"] = &flags.BoolFlag{Name: "skip", Usage: "test bool flag"}
				cmdFlagMap["instance"] = &flags.IntFlag{Name: "instance", Usage: "test int flag"}
				cmdFlagMap["float"] = &flags.Float64Flag{Name: "float", Usage: "test float64 flag"}
				cmdFlagMap["skip2"] = &flags.BoolFlag{Name: "skip2", Usage: "test bool flag"}
				cmdFlagMap["slice"] = &flags.StringSliceFlag{Name: "slice", Usage: "test stringSlice flag"}

				fCtx = flags.NewFlagContext(cmdFlagMap)
			})

			It("accepts flags with either single '-' or double '-' ", func() {
				err := fCtx.Parse("--name", "blue")
				Expect(err).NotTo(HaveOccurred())

				err = fCtx.Parse("-name", "")
				Expect(err).NotTo(HaveOccurred())
			})

			It("sets a flag with it's full name", func() {
				err := fCtx.Parse("-name", "blue")
				Expect(err).NotTo(HaveOccurred())
				Expect(fCtx.IsSet("name")).To(BeTrue())
				Expect(fCtx.IsSet("n")).To(BeTrue())
Esempio n. 12
0
File: main.go Progetto: exg77/cli
func main() {
	commands_loader.Load()

	defer handlePanics(deps.TeePrinter)
	defer deps.Config.Close()

	//////////////// non-codegangsta path  ///////////////////////
	//handles `cf` | `cf -h` || `cf -help`
	if len(os.Args) == 1 || os.Args[1] == "--help" || os.Args[1] == "-help" ||
		os.Args[1] == "--h" || os.Args[1] == "-h" {
		help.ShowHelp(help.GetHelpTemplate())
		os.Exit(0)
	}

	//handle `cf -v` for cf version
	if len(os.Args) == 2 && os.Args[1] == "-v" {
		deps.Ui.Say(os.Args[0] + " version " + cf.Version + "-" + cf.BuiltOnDate)
		os.Exit(0)
	}

	//handles `cf [COMMAND] -h ...`
	//rearrage args to `cf help COMMAND` and let `command help` to print out usage
	if requestHelp(os.Args[2:]) {
		os.Args[2] = os.Args[1]
		os.Args[1] = "help"
	}

	if len(os.Args) > 1 {
		cmd := os.Args[1]

		if cmdRegistry.CommandExists(cmd) {
			meta := cmdRegistry.FindCommand(os.Args[1]).MetaData()
			fc := flags.NewFlagContext(meta.Flags)
			fc.SkipFlagParsing(meta.SkipFlagParsing)

			if requestHelp(os.Args[2:]) {
				deps.Ui.Say(cmdRegistry.CommandUsage(cmd))
				os.Exit(0)
			} else {
				err := fc.Parse(os.Args[2:]...)
				if err != nil {
					deps.Ui.Failed("Incorrect Usage\n\n" + err.Error() + "\n\n" + cmdRegistry.CommandUsage(cmd))
				}
			}
			cmdRegistry.SetCommand(cmdRegistry.FindCommand(cmd).SetDependency(deps, false))

			cfCmd := cmdRegistry.FindCommand(cmd)
			reqs, err := cfCmd.Requirements(requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator), fc)
			if err != nil {
				deps.Ui.Failed(err.Error())
			}

			for _, r := range reqs {
				if !r.Execute() {
					os.Exit(1)
				}
			}

			cfCmd.Execute(fc)
			os.Exit(0)
		}
	}
	//////////////////////////////////////////

	rpcService := newCliRpcServer(deps.TeePrinter, deps.TeePrinter)

	cmdFactory := command_factory.NewFactory(deps.Ui, deps.Config, deps.ManifestRepo, deps.RepoLocator, deps.PluginConfig, rpcService)
	requirementsFactory := requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator)
	cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory, deps.Ui)
	pluginsConfig := plugin_config.NewPluginConfig(func(err error) { deps.Ui.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error())) })
	pluginList := pluginsConfig.Plugins()

	var badFlags string
	metaDatas := cmdFactory.CommandMetadatas()
	//return only metadata for current command
	metaDatas = mergePluginMetaData(metaDatas, pluginList)

	if len(os.Args) > 1 {
		flags := cmdFactory.GetCommandFlags(os.Args[1])
		totalArgs, _ := cmdFactory.GetCommandTotalArgs(os.Args[1])

		if args2skip := totalArgs + 2; len(os.Args) >= args2skip {
			badFlags = matchArgAndFlags(flags, os.Args[args2skip:])
		}

		if badFlags != "" {
			badFlags = badFlags + "\n\n"
		}
	}

	injectHelpTemplate(badFlags)

	theApp := app.NewApp(cmdRunner, metaDatas...)
	rpcService.SetTheApp(theApp)

	if cmdFactory.CheckIfCoreCmdExists(os.Args[1]) {
		callCoreCommand(os.Args[0:], theApp)
	} else {
		// run each plugin and find the method/
		// run method if exist
		ran := rpc.RunMethodIfExists(rpcService, os.Args[1:], pluginList)
		if !ran {
			deps.Ui.Say("'" + os.Args[1] + "' is not a registered command. See 'cf help'")
			os.Exit(1)
		}
	}
}
Esempio n. 13
0
func (cmd *LogalyzerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	port := 8080
	aggregationWindow := 2 * time.Second
	bufferSize := 100

	cmd.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	cmd.sendChan = make(chan []byte, 256)

	if len(args) < 2 {
		cmd.ui.Say("Usage: %s\n", cmd.Usage())
		cmd.ui.Failed("No App Name given")
	}

	fc := flags.NewFlagContext(setupFlags())
	err := fc.Parse(args[2:]...)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	if fc.IsSet("p") {
		port = fc.Int("p")
	}

	if fc.IsSet("agg-window") {
		aggregationWindow = time.Duration(fc.Int("agg-window")) * time.Second
	}

	if fc.IsSet("buffer-size") {
		bufferSize = fc.Int("buffer-size")
	}

	appName := args[1]

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	appModel, err := cliConnection.GetApp(appName)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	outputChan := make(chan *events.LogMessage)
	errorChan := make(chan error)
	dopplerConnection := noaa.NewConsumer(dopplerEndpoint, &tls.Config{InsecureSkipVerify: true}, nil)
	go dopplerConnection.TailingLogs(appModel.Guid, authToken, outputChan, errorChan)

	go cmd.happyCalcer(aggregationWindow, bufferSize)

	go cmd.startServer(cmd.getAssetsDir(), port)
	cmd.ui.Say("Webserver is started at http://localhost:%d", port)

	for {
		select {
		case log := <-outputChan:
			if log.GetMessageType() == events.LogMessage_ERR {
				cmd.errCount++
			}
			cmd.logCount++
			cmd.sendChan <- log.GetMessage()
		case err := <-errorChan:
			cmd.ui.Failed(err.Error())
		}
	}
}
Esempio n. 14
0
		repoLocator := deps.RepoLocator.SetUserRepository(userRepo)
		spaceRepo = new(apifakes.FakeSpaceRepository)
		repoLocator = repoLocator.SetSpaceRepository(spaceRepo)
		flagRepo = new(featureflagsfakes.FakeFeatureFlagRepository)
		repoLocator = repoLocator.SetFeatureFlagRepository(flagRepo)

		deps = commandregistry.Dependency{
			UI:          ui,
			Config:      configRepo,
			RepoLocator: repoLocator,
		}

		cmd = &user.UnsetSpaceRole{}
		cmd.SetDependency(deps, false)

		flagContext = flags.NewFlagContext(map[string]flags.FlagSet{})

		factory = new(requirementsfakes.FakeFactory)

		loginRequirement = &passingRequirement{}
		factory.NewLoginRequirementReturns(loginRequirement)

		userRequirement = new(requirementsfakes.FakeUserRequirement)
		userRequirement.ExecuteReturns(nil)
		factory.NewUserRequirementReturns(userRequirement)

		organizationRequirement = new(requirementsfakes.FakeOrganizationRequirement)
		organizationRequirement.ExecuteReturns(nil)
		factory.NewOrganizationRequirementReturns(organizationRequirement)
	})
Esempio n. 15
0
File: main.go Progetto: CodeWire/cli
func main() {
	//make a reference to something in cf/commands/domain, so all init() in the directory will run
	_ = domain.CreateDomain{}

	defer handlePanics(deps.TeePrinter)
	defer deps.Config.Close()

	//////////////// non-codegangsta path  ///////////////////////
	if len(os.Args) > 1 {
		cmd := os.Args[1]
		if cmdRegistry.CommandExists(cmd) {

			meta := cmdRegistry.FindCommand(os.Args[1]).MetaData()
			fc := flags.NewFlagContext(meta.Flags)
			fc.SkipFlagParsing(meta.SkipFlagParsing)

			if requestHelp(os.Args[2:]) {
				deps.Ui.Say(cmdRegistry.CommandUsage(cmd))
				os.Exit(0)
			} else {
				err := fc.Parse(os.Args[2:]...)
				if err != nil {
					deps.Ui.Failed("Incorrect Usage\n\n" + err.Error() + "\n\n" + cmdRegistry.CommandUsage(cmd))
				}
			}
			cmdRegistry.SetCommand(cmdRegistry.FindCommand(cmd).SetDependency(deps, false))

			cfCmd := cmdRegistry.FindCommand(cmd)
			reqs, err := cfCmd.Requirements(requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator), fc)
			if err != nil {
				deps.Ui.Failed(err.Error())
			}

			for _, r := range reqs {
				if !r.Execute() {
					os.Exit(1)
				}
			}

			cfCmd.Execute(fc)
			os.Exit(0)
		}
	}
	//////////////////////////////////////////

	rpcService := newCliRpcServer(deps.TeePrinter, deps.TeePrinter)

	cmdFactory := command_factory.NewFactory(deps.Ui, deps.Config, deps.ManifestRepo, deps.RepoLocator, deps.PluginConfig, rpcService)
	requirementsFactory := requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator)
	cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory, deps.Ui)
	pluginsConfig := plugin_config.NewPluginConfig(func(err error) { deps.Ui.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error())) })
	pluginList := pluginsConfig.Plugins()

	var badFlags string
	metaDatas := cmdFactory.CommandMetadatas()
	//return only metadata for current command
	metaDatas = mergePluginMetaData(metaDatas, pluginList)

	if len(os.Args) > 1 {
		flags := cmdFactory.GetCommandFlags(os.Args[1])
		totalArgs, _ := cmdFactory.GetCommandTotalArgs(os.Args[1])

		if args2skip := totalArgs + 2; len(os.Args) >= args2skip {
			badFlags = matchArgAndFlags(flags, os.Args[args2skip:])
		}

		if badFlags != "" {
			badFlags = badFlags + "\n\n"
		}
	}

	injectHelpTemplate(badFlags)

	theApp := app.NewApp(cmdRunner, metaDatas...)
	rpcService.SetTheApp(theApp)

	//command `cf` without argument
	if len(os.Args) == 1 || os.Args[1] == "help" || requestHelp(os.Args[2:]) {
		theApp.Run(os.Args)
	} else if cmdFactory.CheckIfCoreCmdExists(os.Args[1]) {
		callCoreCommand(os.Args[0:], theApp)
	} else {
		// run each plugin and find the method/
		// run method if exist
		ran := rpc.RunMethodIfExists(rpcService, os.Args[1:], pluginList)
		if !ran {
			theApp.Run(os.Args)
		}
	}
}
Esempio n. 16
0
File: main.go Progetto: ralfcam/cli
func main() {
	commands_loader.Load()

	defer handlePanics(deps.TeePrinter)
	defer deps.Config.Close()

	//handles `cf` | `cf -h` || `cf -help`
	if len(os.Args) == 1 || os.Args[1] == "--help" || os.Args[1] == "-help" ||
		os.Args[1] == "--h" || os.Args[1] == "-h" {
		help.ShowHelp(help.GetHelpTemplate())
		os.Exit(0)
	}

	//handle `cf -v` for cf version
	if len(os.Args) == 2 && os.Args[1] == "-v" {
		deps.Ui.Say(os.Args[0] + " version " + cf.Version + "-" + cf.BuiltOnDate)
		os.Exit(0)
	}

	//handles `cf [COMMAND] -h ...`
	//rearrage args to `cf help COMMAND` and let `command help` to print out usage
	if requestHelp(os.Args[2:]) {
		os.Args[2] = os.Args[1]
		os.Args[1] = "help"
	}

	//run core command
	cmd := os.Args[1]

	if cmdRegistry.CommandExists(cmd) {
		meta := cmdRegistry.FindCommand(os.Args[1]).MetaData()
		fc := flags.NewFlagContext(meta.Flags)
		fc.SkipFlagParsing(meta.SkipFlagParsing)

		err := fc.Parse(os.Args[2:]...)
		if err != nil {
			deps.Ui.Failed("Incorrect Usage\n\n" + err.Error() + "\n\n" + cmdRegistry.CommandUsage(cmd))
		}

		cmdRegistry.SetCommand(cmdRegistry.FindCommand(cmd).SetDependency(deps, false))
		cfCmd := cmdRegistry.FindCommand(cmd)

		reqs, err := cfCmd.Requirements(requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator), fc)
		if err != nil {
			deps.Ui.Failed(err.Error())
		}

		for _, r := range reqs {
			if !r.Execute() {
				os.Exit(1)
			}
		}

		cfCmd.Execute(fc)
		os.Exit(0)
	}

	//non core command, try plugin command
	rpcService := newCliRpcServer(deps.TeePrinter, deps.TeePrinter)

	pluginsConfig := plugin_config.NewPluginConfig(func(err error) { deps.Ui.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error())) })
	pluginList := pluginsConfig.Plugins()

	ran := rpc.RunMethodIfExists(rpcService, os.Args[1:], pluginList)

	if !ran {
		deps.Ui.Say("'" + os.Args[1] + T("' is not a registered command. See 'cf help'"))
		os.Exit(1)
	}
}
Esempio n. 17
0
func main() {
	defer handlePanics(deps.TeePrinter)
	defer deps.Config.Close()

	//handles `cf` | `cf -h` || `cf -help`
	if len(os.Args) == 1 || os.Args[1] == "--help" || os.Args[1] == "-help" ||
		os.Args[1] == "--h" || os.Args[1] == "-h" {
		help.ShowHelp(help.GetHelpTemplate())
		os.Exit(0)
	}

	//handle `cf -v` for cf version
	if len(os.Args) == 2 && (os.Args[1] == "-v" || os.Args[1] == "--version") {
		deps.Ui.Say(os.Args[0] + " version " + cf.Version + "-" + cf.BuiltOnDate)
		os.Exit(0)
	}

	//handle `cf --build`
	if len(os.Args) == 2 && (os.Args[1] == "--build" || os.Args[1] == "-b") {
		deps.Ui.Say(T("{{.CFName}} was built with Go version: {{.GoVersion}}",
			map[string]interface{}{
				"CFName":    os.Args[0],
				"GoVersion": runtime.Version(),
			}))
		os.Exit(0)
	}

	//handles `cf [COMMAND] -h ...`
	//rearrage args to `cf help COMMAND` and let `command help` to print out usage
	if requestHelp(os.Args[2:]) {
		os.Args[2] = os.Args[1]
		os.Args[1] = "help"
	}

	warningProducers := []net.WarningProducer{}
	for _, warningProducer := range deps.Gateways {
		warningProducers = append(warningProducers, warningProducer)
	}

	warningsCollector := net.NewWarningsCollector(deps.Ui, warningProducers...)

	commands_loader.Load()

	//run core command
	cmdName := os.Args[1]
	cmd := cmdRegistry.FindCommand(cmdName)
	if cmd != nil {
		meta := cmd.MetaData()
		flagContext := flags.NewFlagContext(meta.Flags)
		flagContext.SkipFlagParsing(meta.SkipFlagParsing)

		cmdArgs := os.Args[2:]
		err := flagContext.Parse(cmdArgs...)
		if err != nil {
			usage := cmdRegistry.CommandUsage(cmdName)
			deps.Ui.Failed("Incorrect Usage\n\n" + err.Error() + "\n\n" + usage)
		}

		cmd = cmd.SetDependency(deps, false)
		cmdRegistry.SetCommand(cmd)

		requirementsFactory := requirements.NewFactory(deps.Ui, deps.Config, deps.RepoLocator)
		reqs, err := cmd.Requirements(requirementsFactory, flagContext)
		if err != nil {
			deps.Ui.Failed(err.Error())
		}

		for _, req := range reqs {
			req.Execute()
		}

		cmd.Execute(flagContext)

		warningsCollector.PrintWarnings()

		os.Exit(0)
	}

	//non core command, try plugin command
	rpcService := newCliRpcServer(deps.TeePrinter, deps.TeePrinter)

	pluginConfig := plugin_config.NewPluginConfig(func(err error) {
		deps.Ui.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error()))
	})
	pluginList := pluginConfig.Plugins()

	ran := rpc.RunMethodIfExists(rpcService, os.Args[1:], pluginList)
	if !ran {
		deps.Ui.Say("'" + os.Args[1] + T("' is not a registered command. See 'cf help'"))
		os.Exit(1)
	}

}
Esempio n. 18
0
		buildpackRepo = new(apifakes.OldFakeBuildpackRepository)
		requirementsFactory = &testreq.FakeReqFactory{}
	})

	runCommand := func(args ...string) bool {
		return testcmd.RunCLICommand("buildpacks", args, requirementsFactory, updateCommandDependency, false)
	}

	Context("when arguments are provided", func() {
		var cmd commandregistry.Command
		var flagContext flags.FlagContext

		BeforeEach(func() {
			cmd = &buildpack.ListBuildpacks{}
			cmd.SetDependency(deps, false)
			flagContext = flags.NewFlagContext(cmd.MetaData().Flags)
		})

		It("should fail with usage", func() {
			flagContext.Parse("blahblah")

			reqs := cmd.Requirements(requirementsFactory, flagContext)

			err := testcmd.RunRequirements(reqs)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Incorrect Usage"))
			Expect(err.Error()).To(ContainSubstring("No argument required"))
		})
	})

	It("fails requirements when login fails", func() {
Esempio n. 19
0
				Expect(outputLines).To(Equal([]string{
					"-d                Usage for d",
					"--foo-a, -a       Usage for foo-a",
					"--foo-c, -c       Usage for foo-c",
					"--someflag-b      Usage for someflag-b",
				}))
			}
		})

		Context("hidden flag", func() {
			BeforeEach(func() {
				fs := make(map[string]flags.FlagSet)
				fs["hostname"] = &flags.StringFlag{Name: "hostname", ShortName: "n", Usage: "Hostname used to identify the HTTP route", Hidden: true}
				fs["path"] = &flags.StringFlag{Name: "path", Usage: "Path used to identify the HTTP route"}
				fc = flags.NewFlagContext(fs)
			})

			It("prints the flags in order", func() {
				output := fc.ShowUsage(0)

				outputLines := strings.Split(output, "\n")

				Expect(outputLines).To(Equal([]string{
					"--path      Path used to identify the HTTP route",
				}))
			})
		})
	})
})