예제 #1
0
func (s *FirehoseStatsCmd) Run(cliConnection plugin.CliConnection, args []string) {

	if args[0] != "firehose-stats" {
		return
	}

	s.cfUI = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

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

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		s.cfUI.Failed(err.Error())
	}
	firehoseChan := make(chan *events.Envelope)
	client := firehose.NewClient(authToken, dopplerEndpoint, s.cfUI, firehoseChan)
	client.Start()

	statsUI := stats.New(client, s.cfUI, cliConnection)
	statsUI.Start()

}
예제 #2
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()
}
func NewListAppsCommand(cliConnection api.Connection, orgName string, spaceName string, runtime ui.Runtime) (ui.ListAppsCommand, error) {
	username, err := cliConnection.Username()
	if err != nil {
		return ui.ListAppsCommand{}, err
	}

	if spaceName != "" {
		space, err := cliConnection.GetSpace(spaceName)
		if err != nil || space.Guid == "" {
			return ui.ListAppsCommand{}, err
		}
		orgName = space.Organization.Name
	}

	traceEnv := os.Getenv("CF_TRACE")
	traceLogger := trace.NewLogger(false, traceEnv, "")
	tUI := terminal.NewUI(os.Stdin, terminal.NewTeePrinter(), traceLogger)

	cmd := ui.ListAppsCommand{
		Username:     username,
		Organization: orgName,
		Space:        spaceName,
		UI:           tUI,
		Runtime:      runtime,
	}
	return cmd, nil
}
예제 #4
0
func NewDependency() Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter()
	deps.Ui = terminal.NewUI(os.Stdin, deps.TeePrinter)
	deps.ManifestRepo = manifest.NewManifestDiskRepository()

	errorHandler := func(err error) {
		if err != nil {
			deps.Ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.Config = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)
	deps.PluginConfig = plugin_config.NewPluginConfig(errorHandler)
	deps.Detector = &detection.JibberJabberDetector{}

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	if os.Getenv("CF_TRACE") != "" {
		trace.Logger = trace.NewLogger(os.Getenv("CF_TRACE"))
	} else {
		trace.Logger = trace.NewLogger(deps.Config.Trace())
	}

	deps.Gateways = map[string]net.Gateway{
		"auth":             net.NewUAAGateway(deps.Config, deps.Ui),
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.Ui),
		"uaa":              net.NewUAAGateway(deps.Config, deps.Ui),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways)

	deps.PluginModels = &pluginModels{Application: nil}

	return deps
}
예제 #5
0
func (c *NozzlerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	var options *firehose.ClientOptions

	traceLogger := trace.NewLogger(os.Stdout, true, os.Getenv("CF_TRACE"), "")
	c.ui = terminal.NewUI(os.Stdin, os.Stdout, terminal.NewTeePrinter(os.Stdout), traceLogger)

	switch args[0] {
	case "nozzle":
		options = c.buildClientOptions(args)
	case "app-nozzle":
		options = c.buildClientOptions(args)
		appModel, err := cliConnection.GetApp(args[1])
		if err != nil {
			c.ui.Warn(err.Error())
			return
		}

		options.AppGUID = appModel.Guid
	default:
		return
	}

	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, options, c.ui)
	client.Start()
}
예제 #6
0
func (cmd *Wildcard) WildcardCommandApps(cliConnection plugin.CliConnection, args []string) {
	InitializeCliDependencies()
	defer panic.HandlePanics()
	cmd.getMatchedApps(cliConnection, args)
	cmd.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	table := terminal.NewTable(cmd.ui, []string{T("name"), T("requested state"), T("instances"), T("memory"), T("disk"), T("urls")})
	for _, app := range cmd.matchedApps {
		var urls []string
		for _, route := range app.Routes {
			if route.Host == "" {
				urls = append(urls, route.Domain.Name)
			}
			urls = append(urls, fmt.Sprintf("%s.%s", route.Host, route.Domain.Name))
		}
		table.Add(
			app.Name,
			app.State,
			strconv.Itoa(app.RunningInstances),
			formatters.ByteSize(app.Memory*formatters.MEGABYTE),
			formatters.ByteSize(app.DiskQuota*formatters.MEGABYTE),
			strings.Join(urls, ", "),
		)
	}
	table.Print()
}
예제 #7
0
func HandlePanics() {
	panic_printer.UI = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	commandArgs := strings.Join(os.Args, " ")
	stackTrace := generateBacktrace()

	err := recover()
	panic_printer.DisplayCrashDialog(err, commandArgs, stackTrace)

	if err != nil {
		os.Exit(1)
	}
}
예제 #8
0
/*
*	This function must be implemented by any plugin because it is part of the
*	plugin interface defined by the core CLI.
*
*	Run(....) is the entry point when the core CLI is invoking a command defined
*	by a plugin. The first parameter, plugin.CliConnection, is a struct that can
*	be used to invoke cli commands. The second paramter, args, is a slice of
*	strings. args[0] will be the name of the command, and will be followed by
*	any additional arguments a cli user typed in.
*
*	Any error handling should be handled with the plugin itself (this means printing
*	user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
*	1 should the plugin exits nonzero.
 */
func (c *DoctorPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	fmt.Printf("\n\n")
	var triageApps []string
	var triageRoutes []string
	var triageServices []string

	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	c.ui.Say(terminal.WarningColor("doctor: time to triage cloudfoundry"))
	fmt.Printf("\n")
	c.CFMainChecks(cliConnection)

	listOfRunningApps := c.AppsStateRunning(cliConnection)
	listOfStoppedApps := c.AppsStateStopped(cliConnection)
	triageApps = c.CheckUpApps(cliConnection, triageApps, listOfRunningApps, listOfStoppedApps)
	triageRoutes = c.CheckUpRoutes(cliConnection, triageRoutes)
	triageServices = c.CheckUpServices(cliConnection, triageServices)

	if len(triageApps) == 0 && len(triageRoutes) == 0 && len(triageServices) == 0 {
		c.ui.Say(terminal.SuccessColor("doctor: Everything looks OK!"))
		return
	}

	// doctor run results
	if len(triageApps) > 0 {
		c.ui.Say(terminal.WarningColor("Detected triage points for apps: "))
		for _, v := range triageApps {

			c.ui.Say(terminal.LogStderrColor(strings.Split(v, "___")[0]+" <---> ") + terminal.LogStderrColor(strings.Split(v, "___")[1]))
		}
	}
	c.ui.Say(" ")

	if len(triageRoutes) > 0 {
		c.ui.Say(terminal.WarningColor("Following routes do not have any app bound to them:"))

		for _, y := range triageRoutes {
			c.ui.Say(terminal.LogStderrColor(y))
		}
	}
	fmt.Printf("\n")
	if len(triageServices) > 0 {
		c.ui.Say(terminal.WarningColor("Following services do not have any app bound to them:"))

		for _, y := range triageServices {
			c.ui.Say(terminal.LogStderrColor(y))
		}
	}
}
예제 #9
0
func New(ccTarget string, uaaTarget string, username string, password string) (*CFServices, error) {
	cfs := CFServices{
		CCTarget:  ccTarget,
		UAATarget: uaaTarget,
		Username:  username,
		Password:  password,
		SessionID: uuid.New(),
	}
	cfs.gateways = make(map[string]net.Gateway)
	cfs.configFilePath = strings.Replace(config_helpers.DefaultFilePath(), ".json", "."+cfs.SessionID+".json", -1)
	cfs.config = core_config.NewRepositoryFromFilepath(cfs.configFilePath,
		func(err error) {
			if err != nil {
				fmt.Printf("Config error: %s", err)
			}
		})
	cfs.config.SetApiEndpoint(ccTarget)
	cfs.config.SetAuthenticationEndpoint(uaaTarget)
	cfs.config.SetUaaEndpoint(uaaTarget)
	cfs.config.SetSSLDisabled(true)

	cfs.teePrinter = terminal.NewTeePrinter()
	cfs.termUI = terminal.NewUI(os.Stdin, cfs.teePrinter)
	cfs.detector = &detection.JibberJabberDetector{}

	T = Init(cfs.config, cfs.detector)
	terminal.UserAskedForColors = cfs.config.ColorEnabled()
	terminal.InitColorSupport()

	cfs.gateways["cloud-controller"] = net.NewCloudControllerGateway(cfs.config, time.Now, cfs.termUI)
	cfs.gateways["auth"] = net.NewUAAGateway(cfs.config, cfs.termUI)
	cfs.gateways["uaa"] = net.NewUAAGateway(cfs.config, cfs.termUI)

	cfs.authRepo = authentication.NewUAAAuthenticationRepository(cfs.gateways["uaa"], cfs.config)

	cfs.Organizations = organizations.NewCloudControllerOrganizationRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Spaces = spaces.NewCloudControllerSpaceRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Services = api.NewCloudControllerServiceRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Plans = api.NewCloudControllerServicePlanRepository(cfs.config, cfs.gateways["cloud-controller"])

	err := cfs.authRepo.Authenticate(map[string]string{
		"username": username,
		"password": password,
	})

	return &cfs, err
}
예제 #10
0
/*
*	This function must be implemented by any plugin because it is part of the
*	plugin interface defined by the core CLI.
*
*	Run(....) is the entry point when the core CLI is invoking a command defined
*	by a plugin. The first parameter, plugin.CliConnection, is a struct that can
*	be used to invoke cli commands. The second paramter, args, is a slice of
*	strings. args[0] will be the name of the command, and will be followed by
*	any additional arguments a cli user typed in.
*
*	Any error handling should be handled with the plugin itself (this means printing
*	user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
*	1 should the plugin exits nonzero.
 */
func (c *FastPushPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	// Ensure that the user called the command fast-push
	// alias fp is auto mapped
	var dryRun bool
	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

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

	if cliLogged == false {
		panic("cannot perform fast-push without being logged in to CF")
	}

	if args[0] == "fast-push" || args[0] == "fp" {
		if len(args) == 1 {
			c.showUsage(args)
			return
		}
		// set flag for dry run
		fc := flags.New()
		fc.NewBoolFlag("dry", "d", "bool dry run flag")

		err := fc.Parse(args[1:]...)
		if err != nil {
			c.ui.Failed(err.Error())
		}
		// check if the user asked for a dry run or not
		if fc.IsSet("dry") {
			dryRun = fc.Bool("dry")
		} else {
			c.ui.Warn("warning: dry run not set, commencing fast push")
		}

		c.ui.Say("Running the fast-push command")
		c.ui.Say("Target app: %s \n", args[1])
		c.FastPush(cliConnection, args[1], dryRun)
	} else if args[0] == "fast-push-status" || args[0] == "fps" {
		c.FastPushStatus(cliConnection, args[1])
	} else {
		return
	}

}
예제 #11
0
파일: main.go 프로젝트: raghulsid/cli
func setupDependencies() (deps *cliDependencies) {
	deps = new(cliDependencies)

	deps.teePrinter = terminal.NewTeePrinter()

	deps.termUI = terminal.NewUI(os.Stdin, deps.teePrinter)

	deps.manifestRepo = manifest.NewManifestDiskRepository()

	errorHandler := func(err error) {
		if err != nil {
			deps.termUI.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.configRepo = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)
	deps.pluginConfig = plugin_config.NewPluginConfig(errorHandler)
	deps.detector = &detection.JibberJabberDetector{}

	T = Init(deps.configRepo, deps.detector)

	terminal.UserAskedForColors = deps.configRepo.ColorEnabled()
	terminal.InitColorSupport()

	if os.Getenv("CF_TRACE") != "" {
		trace.Logger = trace.NewLogger(os.Getenv("CF_TRACE"))
	} else {
		trace.Logger = trace.NewLogger(deps.configRepo.Trace())
	}

	deps.gateways = map[string]net.Gateway{
		"auth":             net.NewUAAGateway(deps.configRepo, deps.termUI),
		"cloud-controller": net.NewCloudControllerGateway(deps.configRepo, time.Now, deps.termUI),
		"uaa":              net.NewUAAGateway(deps.configRepo, deps.termUI),
	}
	deps.apiRepoLocator = api.NewRepositoryLocator(deps.configRepo, deps.gateways)

	return
}
예제 #12
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())
		}
	}
}
예제 #13
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)
	}
}
func NewDependency(logger trace.Printer) Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter()
	deps.Ui = terminal.NewUI(os.Stdin, deps.TeePrinter, logger)

	errorHandler := func(err error) {
		if err != nil {
			deps.Ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.Config = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)

	deps.ManifestRepo = manifest.NewManifestDiskRepository()
	deps.AppManifest = manifest.NewGenerator()
	deps.PluginConfig = plugin_config.NewPluginConfig(errorHandler)

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	deps.Gateways = map[string]net.Gateway{
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.Ui, logger),
		"uaa":              net.NewUAAGateway(deps.Config, deps.Ui, logger),
		"routing-api":      net.NewRoutingApiGateway(deps.Config, time.Now, deps.Ui, logger),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways, logger)

	deps.PluginModels = &PluginModels{Application: nil}

	deps.PlanBuilder = plan_builder.NewBuilder(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
	)

	deps.ServiceBuilder = service_builder.NewBuilder(
		deps.RepoLocator.GetServiceRepository(),
		deps.PlanBuilder,
	)

	deps.BrokerBuilder = broker_builder.NewBuilder(
		deps.RepoLocator.GetServiceBrokerRepository(),
		deps.ServiceBuilder,
	)

	deps.PluginRepo = plugin_repo.NewPluginRepo()

	deps.ServiceHandler = actors.NewServiceHandler(
		deps.RepoLocator.GetOrganizationRepository(),
		deps.BrokerBuilder,
		deps.ServiceBuilder,
	)

	deps.ServicePlanHandler = actors.NewServicePlanHandler(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
		deps.PlanBuilder,
		deps.ServiceBuilder,
	)

	deps.WordGenerator = generator.NewWordGenerator()

	deps.AppZipper = app_files.ApplicationZipper{}
	deps.AppFiles = app_files.ApplicationFiles{}

	deps.PushActor = actors.NewPushActor(deps.RepoLocator.GetApplicationBitsRepository(), deps.AppZipper, deps.AppFiles)

	deps.ChecksumUtil = utils.NewSha1Checksum("")

	deps.Logger = logger

	return deps
}
예제 #15
0
파일: main.go 프로젝트: pivotal-cf/cf-watch
func main() {
	plugin.Start(&watch.Plugin{
		Session: &scp.Session{},
		UI:      terminal.NewUI(os.Stdin, terminal.NewTeePrinter()),
	})
}
예제 #16
0
파일: dependency.go 프로젝트: jsloyer/cli
func NewDependency(writer io.Writer, logger trace.Printer) Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter(writer)
	deps.UI = terminal.NewUI(os.Stdin, writer, deps.TeePrinter, logger)

	errorHandler := func(err error) {
		if err != nil {
			deps.UI.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}

	configPath, err := confighelpers.DefaultFilePath()
	if err != nil {
		errorHandler(err)
	}
	deps.Config = coreconfig.NewRepositoryFromFilepath(configPath, errorHandler)

	deps.ManifestRepo = manifest.NewDiskRepository()
	deps.AppManifest = manifest.NewGenerator()

	pluginPath := filepath.Join(confighelpers.PluginRepoDir(), ".cf", "plugins")
	deps.PluginConfig = pluginconfig.NewPluginConfig(
		errorHandler,
		configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
		pluginPath,
	)

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	deps.Gateways = map[string]net.Gateway{
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.UI, logger),
		"uaa":              net.NewUAAGateway(deps.Config, deps.UI, logger),
		"routing-api":      net.NewRoutingAPIGateway(deps.Config, time.Now, deps.UI, logger),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways, logger)

	deps.PluginModels = &PluginModels{Application: nil}

	deps.PlanBuilder = planbuilder.NewBuilder(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
	)

	deps.ServiceBuilder = servicebuilder.NewBuilder(
		deps.RepoLocator.GetServiceRepository(),
		deps.PlanBuilder,
	)

	deps.BrokerBuilder = brokerbuilder.NewBuilder(
		deps.RepoLocator.GetServiceBrokerRepository(),
		deps.ServiceBuilder,
	)

	deps.PluginRepo = pluginrepo.NewPluginRepo()

	deps.ServiceHandler = actors.NewServiceHandler(
		deps.RepoLocator.GetOrganizationRepository(),
		deps.BrokerBuilder,
		deps.ServiceBuilder,
	)

	deps.ServicePlanHandler = actors.NewServicePlanHandler(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
		deps.PlanBuilder,
		deps.ServiceBuilder,
	)

	deps.WordGenerator = generator.NewWordGenerator()

	deps.AppZipper = appfiles.ApplicationZipper{}
	deps.AppFiles = appfiles.ApplicationFiles{}

	deps.PushActor = actors.NewPushActor(deps.RepoLocator.GetApplicationBitsRepository(), deps.AppZipper, deps.AppFiles)

	deps.ChecksumUtil = utils.NewSha1Checksum("")

	deps.Logger = logger

	return deps
}
예제 #17
0
   "properties":{
      "stringtest":{
         "type":"string"
      }
   },
   "required":[
      "stringtest"
   ]
}`

				out := bytes.Buffer{}

				ui := term.NewUI(
					&bytes.Buffer{},
					&out,
					term.NewTeePrinter(&out),
					nil,
				)

				schema.NewSchemaParser(ui).ParseSchema(str)

				Expect(out.String()).To(ContainSubstring("Insert string value for /stringtest [required]"))
			})
		})
	})

	Describe("Test if schema asks correctly for a integer", func() {
		Context("ask for integer", func() {
			It("should be Insert integer value for /integertest [required]", func() {

				str := `{
예제 #18
0
		})

		It("set the rpc command's Return Data", func() {
			var success bool
			err = client.Call("CliRpcCmd.SetPluginMetadata", metadata, &success)

			Expect(err).ToNot(HaveOccurred())
			Expect(success).To(BeTrue())
			Expect(rpcService.RpcCmd.PluginMetadata).To(Equal(metadata))
		})
	})

	Describe(".GetOutputAndReset", func() {
		Context("success", func() {
			BeforeEach(func() {
				outputCapture := terminal.NewTeePrinter(os.Stdout)
				rpcService, err = NewRpcService(outputCapture, nil, nil, api.RepositoryLocator{}, cmdRunner.NewCommandRunner(), nil, nil, rpc.DefaultServer)
				Expect(err).ToNot(HaveOccurred())

				err := rpcService.Start()
				Expect(err).ToNot(HaveOccurred())

				pingCli(rpcService.Port())
			})

			AfterEach(func() {
				rpcService.Stop()

				//give time for server to stop
				time.Sleep(50 * time.Millisecond)
			})
예제 #19
0
		})

		It("set the rpc command's Return Data", func() {
			var success bool
			err = client.Call("CliRpcCmd.SetPluginMetadata", metadata, &success)

			Expect(err).ToNot(HaveOccurred())
			Expect(success).To(BeTrue())
			Expect(rpcService.RpcCmd.PluginMetadata).To(Equal(metadata))
		})
	})

	Describe(".GetOutputAndReset", func() {
		Context("success", func() {
			BeforeEach(func() {
				outputCapture := terminal.NewTeePrinter()
				rpcService, err = NewRpcService(nil, outputCapture, nil, nil, api.RepositoryLocator{}, cmdRunner.NewNonCodegangstaRunner())
				Expect(err).ToNot(HaveOccurred())

				err := rpcService.Start()
				Expect(err).ToNot(HaveOccurred())

				pingCli(rpcService.Port())
			})

			AfterEach(func() {
				rpcService.Stop()

				//give time for server to stop
				time.Sleep(50 * time.Millisecond)
			})