// Run starts the dialog after the options are set. It uses the given story list
// to prompt the user for a story using the given options.
175873
func (dialog *Dialog) Run(stories []common.Story) (common.Story, error) {
	// Return an error when no options are set.
	if len(dialog.opts) == 0 {
		return nil, errors.New("storyprompt.Dialog.Run(): no options were specified")
	}

	// Increment the dialog depth on enter.
	dialog.depth++
	// Decrement the dialog depth on return.
	defer func() {
		dialog.depth--
	}()

	// Enter the dialog loop.
DialogLoop:
	for {
		var (
			opts  = dialog.opts
			depth = dialog.depth
		)

		// Present the stories to the user.
		if err := ListStories(stories, os.Stdout); err != nil {
			return nil, err
		}

		// Print the options based on the dialog depth.
		fmt.Println()
		fmt.Println("Now you can do one of the following:")
		fmt.Println()

		// Collect the list of active options.
		activeOpts := make([]*DialogOption, 0, len(opts))
		for _, opt := range opts {
			if isActive := opt.IsActive; isActive != nil && isActive(stories, depth) {
				activeOpts = append(activeOpts, opt)
			}
		}

		// Print the description for the active options.
		for _, opt := range activeOpts {
			if desc := opt.Description; len(desc) != 0 {
				fmt.Println("  -", strings.Join(desc, "\n    "))
			}
		}
		fmt.Println()

		// Prompt the user for their choice.
		fmt.Println("Current dialog depth:", depth)
		input, err := prompt.Prompt("Choose what to do next: ")
		// We ignore prompt.ErrCanceled here and simply continue.
		// That is because an empty input is a valid input here as well.
		if err != nil && err != prompt.ErrCanceled {
			return nil, err
		}
		input = strings.TrimSpace(input)

		// Find the first matching option.
		var matchingOpt *DialogOption
		for _, opt := range activeOpts {
			if matchFunc := opt.MatchesInput; matchFunc != nil && matchFunc(input, stories) {
				matchingOpt = opt
				break
			}
		}
		// Loop again in case no match is found.
		if matchingOpt == nil {
			fmt.Println()
			fmt.Println("Error: no matching option found")
			fmt.Println()
			continue DialogLoop
		}

		// Run the selected select function.
		if selectFunc := matchingOpt.SelectStory; selectFunc != nil {
			story, err := selectFunc(input, stories, dialog)
			if err != nil {
				switch err {
				case ErrContinue:
					// Continue looping on ErrContinue.
					fmt.Println()
					continue DialogLoop
				case ErrReturn:
					// Go one dialog up by returning ErrContinue.
					// This makes the dialog loop of the parent dialog continue,
					// effectively re-printing and re-running that dialog.
					if dialog.isSub {
						return nil, ErrContinue
					}

					// In case this is a top-level dialog, abort.
					fallthrough
				case ErrAbort:
					// Panic prompt.ErrCanceled on ErrAbort, returning immediately
					// from any dialog depth.
					prompt.PanicCancel()
				}

				// In case the error is not any of the recognized control errors,
				// print the error and loop again, making the user choose again.
				fmt.Println()
				fmt.Println("Error:", err)
				fmt.Println()
				continue DialogLoop
			}
			return story, nil
		}

		// No SelectStory function specified for the matching option,
		// that is a programming error, let's just panic.
		panic(errors.New("SelectStory function not specified"))
	}
}
424002
func (cfg Config) Run(ctx context.Context, fn func(context.Context) error) error {
	retryDelay := func() time.Duration { return 2 * time.Second }
	if cfg.RetryDelay != nil {
		retryDelay = cfg.RetryDelay
	}
	shouldRetry := func(error) bool { return true }
	if cfg.ShouldRetry != nil {
		shouldRetry = cfg.ShouldRetry
	}
	var startTimeout <-chan time.Time // nil chans never unlock !
	if cfg.StartTimeout != 0 {
		startTimeout = time.After(cfg.StartTimeout)
	}

	var err error
	for try := 0; ; try++ {
		if cfg.Tries != 0 && try == cfg.Tries {
			return &RetryExhaustedError{err}
		}
		if err = fn(ctx); err == nil {
			return nil
		}
		if !shouldRetry(err) {
			return err
		}

		log.Print(fmt.Errorf("Retryable error: %s", err))

		select {
		case <-ctx.Done():
			return err
		case <-startTimeout:
			return err
		default:
			time.Sleep(retryDelay())
		}
	}
}
1281334
func (e *Empire) Run(ctx context.Context, opts RunOpts) error {
	event := opts.Event()

	if err := opts.Validate(e); err != nil {
		return err
	}

	if e.RunRecorder != nil && (opts.Stdout != nil || opts.Stderr != nil) {
		w, err := e.RunRecorder()
		if err != nil {
			return err
		}

		// Add the log url to the event, if there is one.
		if w, ok := w.(interface {
			URL() string
		}); ok {
			event.URL = w.URL()
		}

		msg := fmt.Sprintf("Running `%s` on %s as %s", opts.Command, opts.App.Name, opts.User.Name)
		msg = appendCommitMessage(msg, opts.Message)
		io.WriteString(w, fmt.Sprintf("%s\n", msg))

		// Write output to both the original output as well as the
		// record.
		if opts.Stdout != nil {
			opts.Stdout = io.MultiWriter(w, opts.Stdout)
		}
		if opts.Stderr != nil {
			opts.Stderr = io.MultiWriter(w, opts.Stderr)
		}
	}

	if err := e.PublishEvent(event); err != nil {
		return err
	}

	if err := e.runner.Run(ctx, opts); err != nil {
		return err
	}

	event.Finish()
	return e.PublishEvent(event)
}
375223
func (ca Actions) Run(ctx context.Context, c *cli.Context, i int) error {
	if len(ca) < i || i >= len(ca) {
		return errors.New("action not found")
	}
	if ca[i].Fn == nil {
		return errors.New("action invalid")
	}
	return ca[i].Fn(ctx, c)
}
919925
func (c *DeprecatedCommand) Run(args []string) int {
	c.warn()
	return c.Command.Run(args)
}
1370288
func (p *Prompt) Run() {
	defer debug.Teardown()
	debug.Log("start prompt")
	p.setUp()
	defer p.tearDown()

	if p.completion.showAtStart {
		p.completion.Update(*p.buf.Document())
	}

	p.renderer.Render(p.buf, p.completion)

	bufCh := make(chan []byte, 128)
	stopReadBufCh := make(chan struct{})
	go p.readBuffer(bufCh, stopReadBufCh)

	exitCh := make(chan int)
	winSizeCh := make(chan *WinSize)
	stopHandleSignalCh := make(chan struct{})
	go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)

	for {
		select {
		case b := <-bufCh:
			if shouldExit, e := p.feed(b); shouldExit {
				p.renderer.BreakLine(p.buf)
				stopReadBufCh <- struct{}{}
				stopHandleSignalCh <- struct{}{}
				return
			} else if e != nil {
				// Stop goroutine to run readBuffer function
				stopReadBufCh <- struct{}{}
				stopHandleSignalCh <- struct{}{}

				// Unset raw mode
				// Reset to Blocking mode because returned EAGAIN when still set non-blocking mode.
				debug.AssertNoError(p.in.TearDown())
				p.executor(e.input)

				p.completion.Update(*p.buf.Document())
				p.renderer.Render(p.buf, p.completion)

				// Set raw mode
				debug.AssertNoError(p.in.Setup())
				go p.readBuffer(bufCh, stopReadBufCh)
				go p.handleSignals(exitCh, winSizeCh, stopHandleSignalCh)
			} else {
				p.completion.Update(*p.buf.Document())
				p.renderer.Render(p.buf, p.completion)
			}
		case w := <-winSizeCh:
			p.renderer.UpdateWinSize(w)
			p.renderer.Render(p.buf, p.completion)
		case code := <-exitCh:
			p.renderer.BreakLine(p.buf)
			p.tearDown()
			os.Exit(code)
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}
}
1094705
func (c *listCommand) Run(ctx *cmd.Context) (err error) {
	api, err := c.newAPIFunc()
	if err != nil {
		return err
	}
	defer api.Close()

	params := GetCombinedStorageInfoParams{
		Context: ctx, APIClient: api, Ids: c.ids,
	}
	switch {
	case c.filesystem:
		params.WantFilesystems = true
	case c.volume:
		params.WantVolumes = true
	default:
		params.WantStorage = true
		params.WantVolumes = true
		params.WantFilesystems = true
	}

	combined, err := GetCombinedStorageInfo(params)
	if err != nil {
		return err
	}
	if combined.Empty() {
		if c.out.Name() == "tabular" {
			ctx.Infof("No storage to display.")
		}
		return nil
	}
	return c.out.Write(ctx, *combined)
}
976022
func (e *Runner) Run(args []string) error {
	e.prepareForExecution()

	// determine which phase should be run according to RunnerOptions
	phaseRunFlags, err := e.computePhaseRunFlags()
	if err != nil {
		return err
	}

	// builds the runner data
	var data RunData
	if data, err = e.InitData(args); err != nil {
		return err
	}

	err = e.visitAll(func(p *phaseRunner) error {
		// if the phase should not be run, skip the phase.
		if run, ok := phaseRunFlags[p.generatedName]; !run || !ok {
			return nil
		}

		// Errors if phases that are meant to create special subcommands only
		// are wrongly assigned Run Methods
		if p.RunAllSiblings && (p.RunIf != nil || p.Run != nil) {
			return errors.Wrapf(err, "phase marked as RunAllSiblings can not have Run functions %s", p.generatedName)
		}

		// If the phase defines a condition to be checked before executing the phase action.
		if p.RunIf != nil {
			// Check the condition and returns if the condition isn't satisfied (or fails)
			ok, err := p.RunIf(data)
			if err != nil {
				return errors.Wrapf(err, "error execution run condition for phase %s", p.generatedName)
			}

			if !ok {
				return nil
			}
		}

		// Runs the phase action (if defined)
		if p.Run != nil {
			if err := p.Run(data); err != nil {
				return errors.Wrapf(err, "error execution phase %s", p.generatedName)
			}
		}

		return nil
	})

	return err
}
52810
func (c *listCommand) Run(ctx *cmd.Context) error {
	api, err := c.NewActionAPIClient()
	if err != nil {
		return err
	}
	defer api.Close()

	actions, err := api.ApplicationCharmActions(params.Entity{Tag: c.applicationTag.String()})
	if err != nil {
		return err
	}

	if c.fullSchema {
		verboseSpecs := make(map[string]interface{})
		for k, v := range actions {
			verboseSpecs[k] = v.Params
		}

		if c.out.Name() == "default" {
			return c.out.WriteFormatter(ctx, cmd.FormatYaml, verboseSpecs)
		} else {
			return c.out.Write(ctx, verboseSpecs)
		}
	}

	shortOutput := make(map[string]string)
	var sortedNames []string
	for name, action := range actions {
		shortOutput[name] = action.Description
		if shortOutput[name] == "" {
			shortOutput[name] = "No description"
		}
		sortedNames = append(sortedNames, name)
	}
	naturalsort.Sort(sortedNames)

	var output interface{}
	switch c.out.Name() {
	case "yaml", "json":
		output = shortOutput
	default:
		if len(sortedNames) == 0 {
			ctx.Infof("No actions defined for %s.", c.applicationTag.Id())
			return nil
		}
		var list []listOutput
		for _, name := range sortedNames {
			list = append(list, listOutput{name, shortOutput[name]})
		}
		output = list
	}

	if c.out.Name() == "default" {
		return c.out.WriteFormatter(ctx, c.printTabular, output)
	} else {
		return c.out.Write(ctx, output)
	}

}
601894
func (o *PruneOptions) Run() error {
	bindPassword, err := config.ResolveStringValue(o.Config.BindPassword)
	if err != nil {
		return err
	}
	clientConfig, err := ldaputil.NewLDAPClientConfig(o.Config.URL, o.Config.BindDN, bindPassword, o.Config.CA, o.Config.Insecure)
	if err != nil {
		return fmt.Errorf("could not determine LDAP client configuration: %v", err)
	}

	pruneBuilder, err := buildPruneBuilder(clientConfig, o.Config)
	if err != nil {
		return err
	}

	// populate schema-independent pruner fields
	pruner := &syncgroups.LDAPGroupPruner{
		Host:        clientConfig.Host(),
		GroupClient: o.GroupClient.Groups(),
		DryRun:      !o.Confirm,

		Out: o.Out,
		Err: o.ErrOut,
	}

	listerMapper, err := getOpenShiftGroupListerMapper(clientConfig.Host(), o)
	if err != nil {
		return err
	}
	pruner.GroupLister = listerMapper
	pruner.GroupNameMapper = listerMapper

	pruner.GroupDetector, err = pruneBuilder.GetGroupDetector()
	if err != nil {
		return err
	}

	// Now we run the pruner and report any errors
	pruneErrors := pruner.Prune()
	return kerrs.NewAggregate(pruneErrors)

}
572579
func (c *disableCommand) Run(ctx *cmd.Context) error {
	api, err := c.apiFunc(c)
	if err != nil {
		return errors.Annotate(err, "cannot connect to the API")
	}
	defer api.Close()

	return api.SwitchBlockOn(c.target, c.message)
}
1062481
func (cli *CLI) Run(args []string) {
	configFile = cli.app.Flag("configFile", "Specifies the config file to load the configuration from").String()
	persist := cli.app.Command(saveConfigCommand, fmt.Sprintf("Save the config passed by flags into the file specified by --configFile"))
	configureFlags(cli.app)

	command := kingpin.MustParse(cli.app.Parse(args))
	if command == persist.FullCommand() {
		if *configFile == "" {
			out("--configFile must be used to specify the configuration file")
			return
		}
		persistConfig(parseFlagsToConfig(), *configFile)
		return
	}

	var conf Config
	if *configFile == "" {
		conf = parseFlagsToConfig()
	} else {
		conf = loadConfig(*configFile)
	}

	f, exists := cli.dispatchers[command]
	if !exists {
		out("Unknown command:", command)
		terminate(1)
		return
	}
	err := f(conf)
	if err != nil {
		out(err)
		terminate(1)
		return
	}
}
1123248
func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error) {
	opts := map[string]interface{}{}
	var ctx context.Context = nil // if it's nil connection will form context from connection opts
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
		ctx = optArgs[0].Context
	}

	if s == nil || !s.IsConnected() {
		return nil, ErrConnectionClosed
	}

	q, err := s.newQuery(t, opts)
	if err != nil {
		return nil, err
	}

	return s.Query(ctx, q)
}
1249370
func (o *RolloutHistoryOptions) Run() error {

	r := o.Builder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		NamespaceParam(o.Namespace).DefaultNamespace().
		FilenameParam(o.EnforceNamespace, &o.FilenameOptions).
		ResourceTypeOrNameArgs(true, o.Resources...).
		ContinueOnError().
		Latest().
		Flatten().
		Do()
	if err := r.Err(); err != nil {
		return err
	}

	return r.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			return err
		}

		mapping := info.ResourceMapping()
		historyViewer, err := o.HistoryViewer(o.RESTClientGetter, mapping)
		if err != nil {
			return err
		}
		historyInfo, err := historyViewer.ViewHistory(info.Namespace, info.Name, o.Revision)
		if err != nil {
			return err
		}

		withRevision := ""
		if o.Revision > 0 {
			withRevision = fmt.Sprintf("with revision #%d", o.Revision)
		}

		printer, err := o.ToPrinter(fmt.Sprintf("%s\n%s", withRevision, historyInfo))
		if err != nil {
			return err
		}

		return printer.PrintObj(info.Object, o.Out)
	})
}
646243
func Run(config *Config) {
	var err error
	ctx := context.Background()
	httpChatClient, err = google.DefaultClient(ctx, chatAuthScope)
	if err != nil {
		log.Printf("Error setting http client: %v\n", err)
		return
	}

	client, err := pubsub.NewClient(ctx, config.PubSubProject)
	if err != nil {
		log.Printf("Error creating client: %v\n", err)
		return
	}

	topic := client.Topic(config.TopicName)

	// Create a new subscription to the previously created topic
	// with the given name.
	sub := client.Subscription(config.SubscriptionName)
	ok, err := sub.Exists(ctx)
	if err != nil {
		log.Printf("Error getting subscription: %v\n", err)
		return
	}
	if !ok {
		// Subscription doesn't exist.
		sub, err = client.CreateSubscription(ctx, config.SubscriptionName,
			pubsub.SubscriptionConfig{
				Topic:       topic,
				AckDeadline: 10 * time.Second,
			})
		if err != nil {
			log.Printf("Error subscribing: %v\n", err)
			return
		}
	}

	b = bot.New(&bot.Handlers{
		Response: responseHandler,
	},
		&bot.Config{
			Protocol: protocol,
			Server:   server,
		},
	)

	err = sub.Receive(context.Background(),
		func(ctx context.Context, m *pubsub.Message) {
			var msg ChatMessage
			err = json.Unmarshal(m.Data, &msg)
			if err != nil {
				log.Printf("Failed message unmarshal(%v): %s\n", err, m.Data)
				m.Ack()
				return
			}
			if msg.Token != config.Token {
				log.Printf("Failed to verify token: %s", msg.Token)
				m.Ack()
				return
			}

			log.Printf("Space: %s (%s)\n", msg.Space.Name, msg.Space.DisplayName)
			log.Printf("Message type: %s\n", msg.Type)
			log.Printf("From: %s (%s)\n", msg.User.Name, msg.User.DisplayName)
			switch msg.Type {
			case "ADDED_TO_SPACE":
				if config.WelcomeMessage != "" {
					log.Printf("Sending welcome message to %s\n", msg.Space.Name)
					b.SendMessage(msg.Space.Name, config.WelcomeMessage, nil)
				}
			case "REMOVED_FROM_SPACE":
				break
			case "MESSAGE":
				log.Printf("Message: %s\n", msg.Message.ArgumentText)
				b.MessageReceived(
					&bot.ChannelData{
						Protocol:  protocol,
						Server:    server,
						HumanName: msg.Space.DisplayName,
						Channel:   msg.Space.Name + ":" + msg.Message.Thread.Name,
						IsPrivate: msg.Space.Type == "DM",
					},
					&bot.Message{
						Text:     msg.Message.ArgumentText,
						IsAction: false,
					},
					&bot.User{
						ID:       msg.User.Name,
						Nick:     msg.User.DisplayName,
						RealName: msg.User.DisplayName,
					})
			}

			m.Ack()
		})
	if err != nil {
		log.Printf("Error setting up receiving: %v\n", err)
		return
	}
	// Wait indefinetely
	select {}
}
779520
func (e *SigsList) Run(m libkb.MetaContext) error {
	arg := libkb.NewLoadUserArgWithMetaContext(m)
	if len(e.Username) > 0 {
		arg = arg.WithName(e.Username)
	} else {
		arg = arg.WithSelf(true)
	}

	var err error
	e.user, err = libkb.LoadUser(arg)
	if err != nil {
		return err
	}

	e.sigs = e.user.IDTable().Order
	return e.processSigs()
}
643613
func (f *CLI) Run() bool {
	err := f.validate()
	if err != nil {
		os.Stderr.WriteString(err.Error() + "\n")
		os.Exit(1)
	}

	switch {
	case f.install:
		f.prompt()
		err = install.Install(f.Name)
	case f.uninstall:
		f.prompt()
		err = install.Uninstall(f.Name)
	default:
		// non of the action flags matched,
		// returning false should make the real program execute
		return false
	}

	if err != nil {
		fmt.Printf("%s failed! %s\n", f.action(), err)
		os.Exit(3)
	}
	fmt.Println("Done!")
	return true
}