// PrepareEnvironmentAndRunCommand ...
// Returns the exit code of the command and any error occured in the function
359602
func PrepareEnvironmentAndRunCommand(userConfig config.UserConfigModel, cmdName string, cmdArgs ...string) (int, error) {
	projectConfig, err := config.LoadProjectConfigFromFile()
	if err != nil {
		log.Info("Run " + colorstring.Green("gows init") + " to initialize a workspace & gows config for this project")
		return 0, fmt.Errorf("Failed to read Project Config: %s", err)
	}

	gowsConfig, err := config.LoadGOWSConfigFromFile()
	if err != nil {
		return 0, fmt.Errorf("Failed to read gows configs: %s", err)
	}
	currWorkDir, err := os.Getwd()
	if err != nil {
		return 0, fmt.Errorf("[PrepareEnvironmentAndRunCommand] Failed to get current working directory: %s", err)
	}

	wsConfig, isFound := gowsConfig.WorkspaceForProjectLocation(currWorkDir)
	if !isFound {
		log.Debugln("No initialized workspace dir found for this project, initializing one ...")
		if err := initWorkspaceForProjectPath(currWorkDir, false); err != nil {
			return 0, fmt.Errorf("[PrepareEnvironmentAndRunCommand] Failed to initialize Workspace for Project: %s", err)
		}
		log.Debugln("[DONE] workspace dir initialized - continue running ...")

		// reload config
		gowsConfig, err := config.LoadGOWSConfigFromFile()
		if err != nil {
			return 0, fmt.Errorf("Failed to read gows configs: %s", err)
		}
		wsConfig, isFound = gowsConfig.WorkspaceForProjectLocation(currWorkDir)
	}
	if !isFound {
		log.Info("Run " + colorstring.Green("gows init") + " to initialize a workspace & gows config for this project")
		return 0, fmt.Errorf("No Workspace configuration found for the current project / working directory: %s", currWorkDir)
	}

	origGOPATH := os.Getenv("GOPATH")
	if origGOPATH == "" {
		// since Go 1.8 GOPATH is no longer required, it defaults to $HOME/go if not set:
		// https://golang.org/doc/go1.8#gopath
		p, err := pathutil.AbsPath("$HOME/go")
		if err != nil {
			return 0, errors.Wrap(err, "No GOPATH environment variable specified, and failed to get Abs path of default $HOME/go dir")
		}
		origGOPATH = p
	}

	if err := pathutil.EnsureDirExist(origGOPATH); err != nil {
		return 0, errors.Wrapf(err, "Failed to ensure that GOPATH exists at path: %s", origGOPATH)
	}

	if wsConfig.WorkspaceRootPath == "" {
		return 0, fmt.Errorf("No gows Workspace root path found for the current project / working directory: %s", currWorkDir)
	}
	if projectConfig.PackageName == "" {
		return 0, errors.New("No Package Name specified - make sure you initialized the workspace (with: gows init)")
	}

	if err := pathutil.EnsureDirExist(wsConfig.WorkspaceRootPath); err != nil {
		return 0, fmt.Errorf("Failed to create workspace root directory (path: %s), error: %s", wsConfig.WorkspaceRootPath, err)
	}

	if err := gows.CreateGopathBinSymlink(origGOPATH, wsConfig.WorkspaceRootPath); err != nil {
		return 0, fmt.Errorf("Failed to create GOPATH/bin symlink, error: %s", err)
	}

	fullPackageWorkspacePath := filepath.Join(wsConfig.WorkspaceRootPath, "src", projectConfig.PackageName)

	userConfigSyncMode := userConfig.SyncMode
	if userConfigSyncMode == "" {
		userConfigSyncMode = config.DefaultSyncMode
	}
	log.Debug("[PrepareEnvironmentAndRunCommand] specified Sync Mode : ", userConfigSyncMode)

	// --- prepare ---
	{
		fullPackageWorkspacePathFileInfo, fullPackageWorkspaceIsExists, err := pathutil.PathCheckAndInfos(fullPackageWorkspacePath)
		if err != nil {
			return 0, fmt.Errorf("Failed to check Symlink status (at: %s), error: %s", fullPackageWorkspacePath, err)
		}

		switch userConfigSyncMode {
		case config.SyncModeSymlink:
			// create symlink for Project->Workspace
			if fullPackageWorkspaceIsExists && fullPackageWorkspacePathFileInfo.Mode()&os.ModeSymlink == 0 {
				// directory (non symlink) exists - remove it
				log.Warningf("Directory exists (at: %s)", fullPackageWorkspacePath)
				log.Warning("Removing it ...")
				if err := os.RemoveAll(fullPackageWorkspacePath); err != nil {
					return 0, fmt.Errorf("Failed to remove Directory (at: %s), error: %s", fullPackageWorkspacePath, err)
				}
			}

			log.Debugf("=> Creating Symlink: (%s) -> (%s)", currWorkDir, fullPackageWorkspacePath)
			if err := gows.CreateOrUpdateSymlink(currWorkDir, fullPackageWorkspacePath); err != nil {
				return 0, fmt.Errorf("Failed to create Project->Workspace symlink, error: %s", err)
			}
			log.Debugf(" [DONE] Symlink is in place")
		case config.SyncModeCopy:
			// Sync project into workspace
			if fullPackageWorkspaceIsExists && fullPackageWorkspacePathFileInfo.Mode()&os.ModeSymlink != 0 {
				// symlink exists - remove it
				log.Warningf("Symlink exists (at: %s)", fullPackageWorkspacePath)
				log.Warning("Removing it ...")
				if err := os.Remove(fullPackageWorkspacePath); err != nil {
					return 0, fmt.Errorf("Failed to remove Symlink (at: %s), error: %s", fullPackageWorkspacePath, err)
				}
			}

			log.Debugf("=> Sync project content into workspace: (%s) -> (%s)", currWorkDir, fullPackageWorkspacePath)
			if err := syncDirWithDir(currWorkDir, fullPackageWorkspacePath); err != nil {
				return 0, fmt.Errorf("Failed to sync the project path / workdir into the Workspace, error: %s", err)
			}
			if err := writeGowsCopySyncActiveFileToPath(gowsCopyModeActiveFilePath, fullPackageWorkspacePath, currWorkDir); err != nil {
				log.Warningf(" [!] Failed to write gows-copy-mode-active file to path: %s", gowsCopyModeActiveFilePath)
			}
			log.Debugf(" [DONE] Sync project content into workspace")
		default:
			return 0, fmt.Errorf("Unsupported Sync Mode: %s", userConfigSyncMode)
		}
	}

	// Run the command, in the prepared Workspace
	exitCode, cmdErr := runCommand(fullPackageWorkspacePath, wsConfig, cmdName, cmdArgs...)

	// cleanup / finishing
	{
		switch userConfigSyncMode {
		case config.SyncModeSymlink:
			// nothing to do
		case config.SyncModeCopy:
			// Sync back from workspace into project
			log.Debugf("=> Sync workspace content into project: (%s) -> (%s)", fullPackageWorkspacePath, currWorkDir)
			if err := syncDirWithDir(fullPackageWorkspacePath, currWorkDir); err != nil {
				// we should return the command's exit code and error (if any)
				// maybe if the exitCode==0 and cmdErr==nil only then we could return an error here ...
				// for now we'll just print an error log, but it won't change the "output" of this function
				log.Errorf("Failed to sync back the project content from the Workspace, error: %s", err)
			} else {
				log.Debugf(" [DONE] Sync back project content from workspace")
			}
		default:
			return 0, fmt.Errorf("Unsupported Sync Mode: %s", userConfigSyncMode)
		}
	}

	return exitCode, cmdErr
}
375611
func ValidateEnvironment(wenv map[string]string) (r results) {
	for wkey, wval := range wenv {
		gval := os.Getenv(wkey)
		if gval != wval {
			err := fmt.Errorf("environment variable %q not set appropriately (need %q, got %q)", wkey, wval, gval)
			r = append(r, err)
		}
	}
	return
}
1285622
func (cfg *cloudConfig) AddRunCmd(args ...string) {
	cfg.attrs["runcmd"] = append(cfg.RunCmds(), strings.Join(args, " "))
}
743325
func (s *CreateApplicationInput) SetRuntimeEnvironment(v string) *CreateApplicationInput {
	s.RuntimeEnvironment = &v
	return s
}
869915
func NewEnvironment() (env *Environment, err error) {
	env = &Environment{
		Invocation: os.Args[0],
		Response:   &Response{},
	}

	input := flag.String("input", "", "API description (in binary protocol buffer form)")
	output := flag.String("output", "-", "Output file or directory")
	plugin := flag.Bool("plugin", false, "Run as a gnostic plugin (other flags are ignored).")
	flag.Parse()

	env.RunningAsPlugin = *plugin
	programName := path.Base(os.Args[0])

	if (*input == "") && !*plugin {
		flag.Usage = func() {
			fmt.Fprintf(os.Stderr, "\n")
			fmt.Fprintf(os.Stderr, programName+" is a gnostic plugin.\n")
			fmt.Fprintf(os.Stderr, `
When it is run from gnostic, the -plugin option is specified and gnostic
writes a binary request to stdin and waits for a binary response on stdout.

This program can also be run standalone using the other flags listed below.
When the -plugin option is specified, these flags are ignored.`)
			fmt.Fprintf(os.Stderr, "\n\nUsage:\n")
			flag.PrintDefaults()
		}
		flag.Usage()
		os.Exit(0)
	}

	if env.RunningAsPlugin {
		// Handle invocation as a plugin.

		// Read the plugin input.
		pluginData, err := ioutil.ReadAll(os.Stdin)
		env.RespondAndExitIfError(err)
		if len(pluginData) == 0 {
			env.RespondAndExitIfError(fmt.Errorf("no input data"))
		}

		// Deserialize the request from the input.
		request := &Request{}
		err = proto.Unmarshal(pluginData, request)
		env.RespondAndExitIfError(err)

		// Collect parameters passed to the plugin.
		parameters := request.Parameters
		for _, parameter := range parameters {
			env.Invocation += " " + parameter.Name + "=" + parameter.Value
		}

		// Log the invocation.
		//log.Printf("Running plugin %s", env.Invocation)

		env.Request = request

	} else {
		// Handle invocation from the command line.

		// Read the input document.
		apiData, err := ioutil.ReadFile(*input)
		if len(apiData) == 0 {
			env.RespondAndExitIfError(fmt.Errorf("no input data"))
		}

		env.Request = &Request{}
		env.Request.OutputPath = *output
		env.Request.SourceName = path.Base(*input)

		// First try to unmarshal OpenAPI v2.
		documentv2 := &openapiv2.Document{}
		err = proto.Unmarshal(apiData, documentv2)
		if err == nil {
			env.Request.AddModel("openapi.v2.Document", documentv2)
			// include experimental API surface model
			surfaceModel, err := surface.NewModelFromOpenAPI2(documentv2)
			if err == nil {
				env.Request.AddModel("surface.v1.Model", surfaceModel)
			}
			return env, err
		}
		// If that failed, ignore deserialization errors and try to unmarshal OpenAPI v3.
		documentv3 := &openapiv3.Document{}
		err = proto.Unmarshal(apiData, documentv3)
		if err == nil {
			env.Request.AddModel("openapi.v3.Document", documentv3)
			// include experimental API surface model
			surfaceModel, err := surface.NewModelFromOpenAPI3(documentv3)
			if err == nil {
				env.Request.AddModel("surface.v1.Model", surfaceModel)
			}
			return env, err
		}
		// If that failed, ignore deserialization errors and try to unmarshal a Discovery document.
		discoveryDocument := &discovery.Document{}
		err = proto.Unmarshal(apiData, discoveryDocument)
		if err == nil {
			env.Request.AddModel("discovery.v1.Document", discoveryDocument)
			return env, err
		}
		// If we get here, we don't know what we got
		err = errors.New("Unrecognized format for input")
		return env, err
	}
	return env, err
}
448063
func (r *RunListener) RunCommands(args RunCommandsArgs) (results *exec.ExecResponse, err error) {
	logger.Tracef("run commands: %s", args.Commands)
	return r.CommandRunner.RunCommands(args)
}
401093
func prepareCommandLine(cmd string, args ...string) (string, error) {
	if isBlank(cmd) {
		return "", errors.AssertionErrorf("command cannot be empty")
	}

	for i, arg := range args {
		if strings.ContainsRune(arg, '"') {
			return "", errors.Errorf(errors.ParseError, "arg at index %d contains an invalid double quote: %s", i, arg)
		}
		if containsWhitespace(arg) {
			args[i] = fmt.Sprintf("\"%s\"", arg)
		}
	}

	// Prepend the command to the args array.
	if len(args) > 0 {
		cmd = fmt.Sprintf("%s %s", cmd, strings.Join(args, " "))
	}

	return cmd, nil
}
239198
func runScript(script config.Script, env *initialize.Environment) error {
	err := initialize.PrepWorkspace(env.Workspace())
	if err != nil {
		log.Printf("Failed preparing workspace: %v\n", err)
		return err
	}
	path, err := initialize.PersistScriptInWorkspace(script, env.Workspace())
	if err == nil {
		var name string
		name, err = system.ExecuteScript(path)
		initialize.PersistUnitNameInWorkspace(name, env.Workspace())
	}
	return err
}
1352765
func runCommand(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
	var stderrBuffer bytes.Buffer
	var stdoutBuffer bytes.Buffer
	cmd.Stderr = &stderrBuffer
	cmd.Stdout = &stdoutBuffer
	cmdErr := cmd.Run()
	exitCode, success := utils.GetExitStatus(cmdErr)
	if success {
		cmdErr = nil
	}
	return stdoutBuffer.String(), stderrBuffer.String(), exitCode, cmdErr
}
721410
func (p *provisioner) runCommand(o terraform.UIOutput, comm communicator.Communicator, command string) error {
	// Unless prevented, prefix the command with sudo
	if p.useSudo {
		command = "sudo " + command
	}

	outR, outW := io.Pipe()
	errR, errW := io.Pipe()
	go p.copyOutput(o, outR)
	go p.copyOutput(o, errR)
	defer outW.Close()
	defer errW.Close()

	cmd := &remote.Cmd{
		Command: command,
		Stdout:  outW,
		Stderr:  errW,
	}

	err := comm.Start(cmd)
	if err != nil {
		return fmt.Errorf("Error executing command %q: %v", cmd.Command, err)
	}

	if err := cmd.Wait(); err != nil {
		return err
	}

	return nil
}
779079
func (a *App) RunAsSubcommand(ctx *Context) error {
	// append help to commands
	if len(a.Commands) > 0 {
		if a.Command(helpCommand.Name) == nil && !a.HideHelp {
			a.Commands = append(a.Commands, helpCommand)
			a.appendFlag(HelpFlag)
		}
	}

	// append flags
	if a.EnableBashCompletion {
		a.appendFlag(BashCompletionFlag)
	}

	// parse flags
	set := flagSet(a.Name, a.Flags)
	set.SetOutput(ioutil.Discard)
	err := set.Parse(ctx.Args().Tail())
	nerr := normalizeFlags(a.Flags, set)
	context := NewContext(a, set, ctx.globalSet)

	if nerr != nil {
		fmt.Println(nerr)
		if len(a.Commands) > 0 {
			ShowSubcommandHelp(context)
		} else {
			ShowCommandHelp(ctx, context.Args().First())
		}
		fmt.Println("")
		return nerr
	}

	if err != nil {
		fmt.Printf("Incorrect Usage.\n\n")
		ShowSubcommandHelp(context)
		return err
	}

	if checkCompletions(context) {
		return nil
	}

	if len(a.Commands) > 0 {
		if checkSubcommandHelp(context) {
			return nil
		}
	} else {
		if checkCommandHelp(ctx, context.Args().First()) {
			return nil
		}
	}

	if a.Before != nil {
		err := a.Before(context)
		if err != nil {
			return err
		}
	}

	args := context.Args()
	if args.Present() {
		name := args.First()
		c := a.Command(name)
		if c != nil {
			return c.Run(context)
		}
	}

	// Run default Action
	if len(a.Commands) > 0 {
		a.Action(context)
	} else {
		a.Action(ctx)
	}

	return nil
}
1067647
func main() {
	os.Setenv("NAME", "foo")
	os.Setenv("PORT", "9001")
	os.Setenv("ADAPTER", "shell")
	// os.Setenv("IS_ENABLED", "asdf")
	c := &Config{}
	if err := env.Process(c); err != nil {
		panic(err)
	}
	fmt.Printf("name: %s, port: %d, adapter: %s, enabled: %v\n", c.Name, c.Port, c.Adapter, c.Enabled)
}
65703
func RunCommand(fs *flag.FlagSet, cmd *Command, projectroot, goroot string, args []string) error {
	if cmd.AddFlags != nil {
		cmd.AddFlags(fs)
	}
	if err := fs.Parse(args); err != nil {
		fs.Usage()
		os.Exit(1)
	}
	args = fs.Args() // reset to the remaining arguments

	ctx, err := NewContext(projectroot, gb.GcToolchain())
	if err != nil {
		return errors.Wrap(err, "unable to construct context")
	}
	defer ctx.Destroy()

	ctx.Debug("args: %v", args)
	return cmd.Run(ctx, args)
}
1311789
func RunCommand() {
	if len(os.Args) < 2 || os.Args[1] != "orm" {
		return
	}

	BootStrap()

	args := argString(os.Args[2:])
	name := args.Get(0)

	if name == "help" {
		printHelp()
	}

	if cmd, ok := commands[name]; ok {
		cmd.Parse(os.Args[3:])
		cmd.Run()
		os.Exit(0)
	} else {
		if name == "" {
			printHelp()
		} else {
			printHelp(fmt.Sprintf("unknown command %s", name))
		}
	}
}
4640
func runCommand(ctx context.Context, command []string) error {
	cmd := exec.Command(command[0], command[1:]...)
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	return cmd.Run()
}
814684
func (ra *runAction) Prepare(state State) (*State, error) {
	rnr, err := ra.runnerFactory.NewActionRunner(ra.actionId)
	if cause := errors.Cause(err); charmrunner.IsBadActionError(cause) {
		if err := ra.callbacks.FailAction(ra.actionId, err.Error()); err != nil {
			return nil, err
		}
		return nil, ErrSkipExecute
	} else if cause == charmrunner.ErrActionNotAvailable {
		return nil, ErrSkipExecute
	} else if err != nil {
		return nil, errors.Annotatef(err, "cannot create runner for action %q", ra.actionId)
	}
	actionData, err := rnr.Context().ActionData()
	if err != nil {
		// this should *really* never happen, but let's not panic
		return nil, errors.Trace(err)
	}
	err = rnr.Context().Prepare()
	if err != nil {
		return nil, errors.Trace(err)
	}
	ra.name = actionData.Name
	ra.runner = rnr
	return stateChange{
		Kind:     RunAction,
		Step:     Pending,
		ActionId: &ra.actionId,
		Hook:     state.Hook,
	}.apply(state), nil
}
1045890
func runCommand(cmd string, args ...string) error {
	command := exec.Command(cmd, args...)
	out, err := command.CombinedOutput()
	if err == nil {
		return nil
	}
	if _, ok := err.(*exec.ExitError); ok && len(out) > 0 {
		return errors.Errorf(
			"error executing %q: %s",
			cmd,
			strings.Replace(string(out), "\n", "; ", -1),
		)
	}
	return errors.Annotatef(err, "error executing %q", cmd)
}