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
}
예제 #2
0
파일: main.go 프로젝트: raghulsid/cli
func main() {
	defer handlePanics(deps.teePrinter)
	defer deps.configRepo.Close()

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

	cmdFactory := command_factory.NewFactory(deps.termUI, deps.configRepo, deps.manifestRepo, deps.apiRepoLocator, deps.pluginConfig, rpcService)
	requirementsFactory := requirements.NewFactory(deps.termUI, deps.configRepo, deps.apiRepoLocator)
	cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory, deps.termUI)
	pluginsConfig := plugin_config.NewPluginConfig(func(err error) { panic(err) })
	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)
		}
	}
}
예제 #3
0
파일: main.go 프로젝트: palakmathur/cli
func main() {
	defer handlePanics()

	deps := setupDependencies()
	defer deps.configRepo.Close()

	cmdFactory := command_factory.NewFactory(deps.termUI, deps.configRepo, deps.manifestRepo, deps.apiRepoLocator)
	requirementsFactory := requirements.NewFactory(deps.termUI, deps.configRepo, deps.apiRepoLocator)
	cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory)

	app.NewApp(cmdRunner, cmdFactory.CommandMetadatas()...).Run(os.Args)

	gateways := gatewaySliceFromMap(deps.gateways)
	net.NewWarningsCollector(deps.termUI, gateways...).PrintWarnings()
}
예제 #4
0
파일: cmd.go 프로젝트: 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)
	}
}
예제 #5
0
파일: main.go 프로젝트: 0976254669/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" || 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"
	}

	//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)
	}
}
예제 #6
0
파일: main.go 프로젝트: 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)
		}
	}
}
예제 #7
0
파일: main.go 프로젝트: 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)
		}
	}
}