Example #1
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
}
Example #2
0
func RunCLICommand(cmdName string, args []string, requirementsFactory requirements.Factory, updateFunc func(bool), pluginCall bool, ui *testterm.FakeUI) 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)
	}

	var requirements []requirements.Requirement
	requirements, err = cmd.Requirements(requirementsFactory, context)
	if err != nil {
		return false
	}
	for _, requirement := range requirements {
		if err = requirement.Execute(); err != nil {
			return false
		}
	}

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

	return true
}
Example #3
0
func (c *commandRunner) Command(args []string, deps commandregistry.Dependency, pluginApiCall bool) (err error) {
	cmdRegistry := commandregistry.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, reqErr := cfCmd.Requirements(requirements.NewFactory(deps.Config, deps.RepoLocator), fc)
		if reqErr != nil {
			return reqErr
		}

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

		defer func() {
			if r := recover(); r != nil {
				err = fmt.Errorf("command panic: %v", r)
			}
		}()

		return cfCmd.Execute(fc)
	}

	return nil
}
Example #4
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 {
			panic(errMsg)
		}
	}()

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

	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
}
Example #5
0
		buildpackRepo = new(apifakes.OldFakeBuildpackRepository)
		requirementsFactory = new(requirementsfakes.FakeFactory)
	})

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

	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, err := cmd.Requirements(requirementsFactory, flagContext)
			Expect(err).NotTo(HaveOccurred())

			err = testcmd.RunRequirements(reqs)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Incorrect Usage"))
			Expect(err.Error()).To(ContainSubstring("No argument required"))
		})
	})
Example #6
0
		configRepo = testconfig.NewRepositoryWithDefaults()
		userRepo = &testapi.FakeUserRepository{}
		repoLocator := deps.RepoLocator.SetUserRepository(userRepo)
		flagRepo = new(featureflagsfakes.FakeFeatureFlagRepository)
		repoLocator = repoLocator.SetFeatureFlagRepository(flagRepo)

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

		cmd = &user.UnsetOrgRole{}
		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)
	})
Example #7
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())
Example #8
0
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))
			os.Exit(1)
		}
	}

	// 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 deps.Config.Close()

	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, reqErr := cmd.Requirements(requirementsFactory, flagContext)
		if reqErr != nil {
			os.Exit(1)
		}

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

		err = cmd.Execute(flagContext)
		if err != nil {
			deps.UI.Failed(err.Error())
			os.Exit(1)
		}

		err = warningsCollector.PrintWarnings()
		if err != nil {
			deps.UI.Failed(err.Error())
			os.Exit(1)
		}

		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)
	}
}
Example #9
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",
				}))
			})
		})
	})
})