// runUserExecutable runs the user executable.
// Requires LogDog server to be running.
// Sends user executable stdout/stderr into logdogServ, with teeing enabled.
550190
func (r *runner) runUserExecutable(ctx context.Context, args *pb.RunnerArgs, userAuth *authctx.Context, logdogServ *logdogServer, logdogNamespace string) (err error) {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	cmd := exec.CommandContext(ctx, args.ExecutablePath)

	// Prepare user env.
	env, err := r.setupUserEnv(ctx, args, userAuth, logdogServ, logdogNamespace)
	if err != nil {
		return err
	}
	cmd.Env = env.Sorted()

	// Setup user working directory. This is the CWD for the user executable itself.
	// Keep it short. This is important to allow tasks on Windows to have as many
	// characters as possible; otherwise they run into MAX_PATH issues.
	cmd.Dir = filepath.Join(args.WorkDir, "u")
	if err := os.MkdirAll(cmd.Dir, 0700); err != nil {
		return errors.Annotate(err, "failed to create user workdir dir at %q", cmd.Dir).Err()
	}

	// Pass initial build on stdin.
	buildBytes, err := proto.Marshal(args.Build)
	if err != nil {
		return
	}
	cmd.Stdin = bytes.NewReader(buildBytes)

	// Prepare stdout/stderr pipes.
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return
	}

	// Start the user executable.
	if err := cmd.Start(); err != nil {
		return errors.Annotate(err, "failed to start the user executable").Err()
	}
	logging.Infof(ctx, "Started user executable successfully")

	// Send subprocess stdout/stderr to logdog.
	if err := r.hookStdoutStderr(ctx, logdogServ, stdout, stderr, streamNamePrefix); err != nil {
		return err
	}

	switch err := cmd.Wait().(type) {
	case *exec.ExitError:
		// The subprocess exited with a non-zero exit code.
		// This is OK. Exit code is not a part of user executable contract.
		logging.Infof(ctx, "user subprocess exited with code %d", err.ExitCode())
		return nil

	case nil:
		logging.Infof(ctx, "user subprocess has exited with zero code")
		return nil

	default:
		return errors.Annotate(err, "failed to wait for the user executable to exit").Err()
	}
}
420825
func (e *loginLoadUser) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("loginLoadUser#Run", func() error { return err })()

	var username string
	username, err = e.findUsername(m)
	if err != nil {
		return err
	}

	m.Debug("loginLoadUser: found username %q", username)

	// NOTE(max) 2018-05-09: ForceReload since older versions of cached users don't
	// have salt stored, ad we need it in DeviceWrap to write out the config file.
	arg := libkb.NewLoadUserArgWithMetaContext(m).WithName(username).WithPublicKeyOptional().WithForceReload()
	user, err := libkb.LoadUser(arg)
	if err != nil {
		return err
	}
	e.user = user

	m.Debug("loginLoadUser: found user %s for username %q", e.user.GetUID(), username)

	return nil
}
556140
func Run() {
	cli.HelpFlag = cli.BoolFlag{Name: HelpKey + ", " + helpKeyShort, Usage: "Show help."}
	cli.AppHelpTemplate = helpTemplate

	cli.VersionFlag = cli.BoolFlag{Name: VersionKey + ", " + versionKeyShort, Usage: "Print the version."}
	cli.VersionPrinter = func(c *cli.Context) { fmt.Println(c.App.Version) }

	app := cli.NewApp()
	app.Name = path.Base(os.Args[0])
	app.Usage = "Environment variable manager"
	app.Version = version.VERSION

	app.Author = ""
	app.Email = ""

	app.Before = before

	app.Flags = flags
	app.Commands = commands

	if err := app.Run(os.Args); err != nil {
		log.Fatal("[ENVMAN] - Finished:", err)
	}
}
919925
func (c *DeprecatedCommand) Run(args []string) int {
	c.warn()
	return c.Command.Run(args)
}
436703
func (c *listKeysCommand) Run(context *cmd.Context) error {
	client, err := c.NewKeyManagerClient()
	if err != nil {
		return err
	}
	defer client.Close()

	mode := ssh.Fingerprints
	if c.showFullKey {
		mode = ssh.FullKeys
	}
	// TODO(alexisb) - currently keys are global which is not ideal.
	// keymanager needs to be updated to allow keys per user
	c.user = "admin"
	results, err := client.ListKeys(mode, c.user)
	if err != nil {
		return errors.Trace(err)
	}
	result := results[0]
	if result.Error != nil {
		return errors.Trace(result.Error)
	}
	if len(result.Result) == 0 {
		context.Infof("No keys to display.")
		return nil
	}
	modelName, err := c.ModelName()
	if err != nil {
		return errors.Trace(err)
	}
	fmt.Fprintf(context.Stdout, "Keys used in model: %s\n", modelName)
	fmt.Fprintln(context.Stdout, strings.Join(result.Result, "\n"))
	return nil
}
16771
func AppRun(appID, command string) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	fmt.Printf("Running '%s'...\n", command)

	out, err := apps.Run(c, appID, command)

	if err != nil {
		return err
	}

	fmt.Print(out.Output)
	os.Exit(out.ReturnCode)
	return nil
}
37
func (s *Service) Run() {
	flag.Usage = s.Usage
	flag.Parse()
	args := flag.Args()
	if len(args) == 0 && s.defaultCommand != "" {
		args = append([]string{s.defaultCommand}, args...)
	}
	if len(args) == 0 {
		s.Usage()
		BootPrintln()
		return
	}
	err := s.RunCommand(args[0], args[1:]...)
	if err != nil {
		panic(err)
	}
}
1145770
func (c Command) Run(ctx *Context) error {

	if len(c.Subcommands) > 0 || c.Before != nil {
		return c.startApp(ctx)
	}

	if !c.HideHelp {
		// append help to flags
		c.Flags = append(
			c.Flags,
			HelpFlag,
		)
	}

	if ctx.App.EnableBashCompletion {
		c.Flags = append(c.Flags, BashCompletionFlag)
	}

	set := flagSet(c.Name, c.Flags)
	set.SetOutput(ioutil.Discard)

	firstFlagIndex := -1
	for index, arg := range ctx.Args() {
		if strings.HasPrefix(arg, "-") {
			firstFlagIndex = index
			break
		}
	}

	var err error
	if firstFlagIndex > -1 && !c.SkipFlagParsing {
		args := ctx.Args()
		regularArgs := args[1:firstFlagIndex]
		flagArgs := args[firstFlagIndex:]
		err = set.Parse(append(flagArgs, regularArgs...))
	} else {
		err = set.Parse(ctx.Args().Tail())
	}

	if err != nil {
		fmt.Printf("Incorrect Usage.\n\n")
		ShowCommandHelp(ctx, c.Name)
		fmt.Println("")
		return err
	}

	nerr := normalizeFlags(c.Flags, set)
	if nerr != nil {
		fmt.Println(nerr)
		fmt.Println("")
		ShowCommandHelp(ctx, c.Name)
		fmt.Println("")
		return nerr
	}
	context := NewContext(ctx.App, set, ctx.globalSet)

	if checkCommandCompletions(context, c.Name) {
		return nil
	}

	if checkCommandHelp(context, c.Name) {
		return nil
	}
	context.Command = c
	c.Action(context)
	return nil
}
497876
func (e *PGPKeyfinder) Run(m libkb.MetaContext) error {
	e.loadUsers(m)
	e.loadKeys(m)
	return e.runerr
}
53091
func (cmd *streamCommandRun) Run(app subcommands.Application, args []string, _ subcommands.Env) int {
	a := app.(*application)

	var (
		streamFile        *os.File
		defaultStreamName streamproto.StreamNameFlag
	)
	if cmd.path == "-" {
		defaultStreamName = "stdin"
		streamFile = os.Stdin
	} else {
		streamName, err := types.MakeStreamName("file:", cmd.path)
		if err != nil {
			log.Fields{
				log.ErrorKey: err,
			}.Errorf(a, "Failed to generate stream name.")
			return runtimeErrorReturnCode
		}
		defaultStreamName = streamproto.StreamNameFlag(streamName)

		file, err := os.Open(cmd.path)
		if err != nil {
			log.Fields{
				log.ErrorKey: err,
				"path":       cmd.path,
			}.Errorf(a, "Failed to open input stream file.")
			return runtimeErrorReturnCode
		}
		streamFile = file
	}
	if cmd.stream.Name == "" {
		cmd.stream.Name = defaultStreamName
	}

	// We think everything should work. Configure our Output instance.
	of, err := a.getOutputFactory()
	if err != nil {
		log.WithError(err).Errorf(a, "Failed to get output factory instance.")
		return runtimeErrorReturnCode
	}
	output, err := of.configOutput(a)
	if err != nil {
		log.WithError(err).Errorf(a, "Failed to create output instance.")
		return runtimeErrorReturnCode
	}
	defer output.Close()

	// Instantiate our Processor.
	err = a.runWithButler(output, func(b *butler.Butler) error {
		if err := b.AddStream(streamFile, cmd.stream.properties()); err != nil {
			return errors.Annotate(err, "failed to add stream").Err()
		}

		b.Activate()
		return b.Wait()
	})
	if err != nil {
		logAnnotatedErr(a, err, "Failed to stream file.")
		return runtimeErrorReturnCode
	}

	return 0
}
153353
func (cmd *CheckCommand) Run(_ context.Context) error {
	for _, path := range cmd.Paths {
		switch filepath.Ext(path) {
		case "":
			if err := cmd.checkBitmapFile(path); err != nil {
				return errors.Wrap(err, "checking bitmap")
			}

		case ".cache":
			if err := cmd.checkCacheFile(path); err != nil {
				return errors.Wrap(err, "checking cache")
			}

		case ".snapshotting":
			if err := cmd.checkSnapshotFile(path); err != nil {
				return errors.Wrap(err, "checking snapshot")
			}
		}
	}

	return nil
}
82798
func run(stdout, stderr io.Writer, cmd string, args ...string) error {
	c := exec.Command(cmd, args...)
	c.Stdin = os.Stdin
	c.Stdout = stdout
	c.Stderr = stderr
	return c.Run()
}
1016222
func (c *disableCommand) Run(ctx *cmd.Context) error {
	if c.api == nil {
		api, err := c.NewUserManagerAPIClient()
		if err != nil {
			return errors.Trace(err)
		}
		c.api = api
		defer c.api.Close()
	}

	if err := c.api.DisableUser(c.User); err != nil {
		return block.ProcessBlockedError(err, block.BlockChange)
	}
	ctx.Infof("User %q disabled", c.User)
	return nil
}
585684
func (c *logoutCommand) Run(ctx *cmd.Context) error {
	controllerName, err := c.ControllerName()
	if err != nil {
		return errors.Trace(err)
	}
	store := c.ClientStore()
	if err := c.logout(store, controllerName); err != nil {
		return errors.Trace(err)
	}

	// Count the number of logged-into controllers to inform the user.
	var loggedInCount int
	controllers, err := store.AllControllers()
	if err != nil {
		return errors.Trace(err)
	}
	for name := range controllers {
		if name == controllerName {
			continue
		}
		_, err := store.AccountDetails(name)
		if errors.IsNotFound(err) {
			continue
		} else if err != nil {
			return errors.Trace(err)
		}
		loggedInCount++
	}
	switch loggedInCount {
	case 0:
		ctx.Infof("Logged out. You are no longer logged into any controllers.")
	case 1:
		ctx.Infof("Logged out. You are still logged into 1 controller.")
	default:
		ctx.Infof("Logged out. You are still logged into %d controllers.", loggedInCount)
	}
	return nil
}
4816
func (c *Command) Run() *ExecResult {

	// shell, args := shellAndArgs()
	var bout, berr bytes.Buffer
	streams := &Streams{
		out: &bout,
		err: &berr,
	}
	result := &ExecResult{
		fullCommand: c.FullCommand(),
		streams:     streams,
	}
	cmd, err := c.buildCmd()
	if err != nil {
		result.err = err
		return result
	}
	cmd.Stdout = &bout
	cmd.Stderr = &berr
	if c.WorkingDir != "" {
		cmd.Dir = c.WorkingDir
	}

	if c.UseEnv {
		flagEnv := filepath.Join(cmd.Dir, ".env")
		env, _ := ReadEnv(flagEnv)
		cmd.Env = env.asArray()
	} else if len(c.Env) > 0 {
		cmd.Env = c.Env.asArray()
	}
	// if runtime.GOOS == "windows" {
	// 	r.Environment = mergeEnvironment(r.Environment)
	// }

	if err := cmd.Run(); err != nil {
		result.err = err
		return result
	}
	return result
}
62655
func Run() {

	flag.Parse()

	if len(flag.Args()) > 0 {
		mustLogFatal(fmt.Errorf("extra command line arguments: %s", flag.Args()))
	}

	// Set up process log before anything bad happens
	if logfile {
		log.SetOutput(os.Stdout)
	}
	log.SetFlags(log.LstdFlags)

	if version {
		showVersion()
		os.Exit(0)
	}
	if plugins {
		fmt.Println(caddy.DescribePlugins())
		os.Exit(0)
	}

	// Set CPU cap
	if err := setCPU(cpu); err != nil {
		mustLogFatal(err)
	}

	// Get Corefile input
	corefile, err := caddy.LoadCaddyfile(serverType)
	if err != nil {
		mustLogFatal(err)
	}

	// Start your engines
	instance, err := caddy.Start(corefile)
	if err != nil {
		mustLogFatal(err)
	}

	logVersion()
	if !dnsserver.Quiet {
		showVersion()
	}

	// Twiddle your thumbs
	instance.Wait()
}
901902
func (cmd *UpdateAccountCommand) Run(c *client.Client, args []string) error {
	var path string
	if len(args) > 0 {
		path = args[0]
	} else {
		path = fmt.Sprintf("/cellar/accounts/%v", cmd.AccountID)
	}
	var payload client.UpdateAccountPayload
	if cmd.Payload != "" {
		err := json.Unmarshal([]byte(cmd.Payload), &payload)
		if err != nil {
			return fmt.Errorf("failed to deserialize payload: %s", err)
		}
	}
	logger := goa.NewLogger(log.New(os.Stderr, "", log.LstdFlags))
	ctx := goa.WithLogger(context.Background(), logger)
	resp, err := c.UpdateAccount(ctx, path, &payload, cmd.ContentType)
	if err != nil {
		goa.LogError(ctx, "failed", "err", err)
		return err
	}

	goaclient.HandleResponse(c.Client, resp, cmd.PrettyPrint)
	return nil
}