Пример #1
0
func (s *sourceExec) start(cmd *exec.Cmd) error {
	s.cmd = exec.Command(s.name, s.arg...)
	r, err := s.cmd.StdoutPipe()
	if err != nil {
		return err
	}
	cmd.Stdin = r
	if err := s.cmd.Start(); err != nil {
		cmd.Stdin = nil
		return err
	}
	return nil
}
Пример #2
0
func doHighlight(code, lexer string) string {
	if lexer == "none" || lexer == "" {
		lexer = "text"
	}

	defaults := []string{"-f", "html", "-O", "linenos=table,style=colorful,encoding=utf-8"}

	var cmd *exec.Cmd
	var args []string
	if lexer == "autodetect" {
		args = append(args, "-g")
	} else {
		args = append(args, "-l", lexer)
	}
	args = append(args, defaults...)

	log.Debugf("Running Pygments with args: %v", args)
	cmd = exec.Command(pygpath, args...)
	cmd.Stdin = strings.NewReader(code)

	var out, stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		log.Errorf("Failed to run Pygments: %s. Stderr: %s", err, stderr.String())
		return code
	}

	return out.String()
}
Пример #3
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	if *version {
		fmt.Printf("%s", Version)
		os.Exit(0)
	}

	if *unset != "" {
		os.Unsetenv(*unset)
	}

	cmd := new(exec.Cmd)
	cmd.Env = env

	// Check for "-" as an argument, because it means the same as "-i"
	if flag.Arg(0) == "-" {
		cmd.Env = make([]string, 0)
	}

	for i, arg := range flag.Args() {
		if strings.Index(arg, delim) > 0 {
			cmd.Env = append(cmd.Env, arg)
		} else if arg != "-" {
			if *nullEol {
				fatal.Fatalln("cannot specify --null (-0) with command")
			}

			cmd.Path = arg

			cmd.Args = append(cmd.Args, flag.Args()[i:]...)
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr

			err := execvp(cmd)
			if err != nil {
				fatal.Fatalln(err)
			}
			return
		}

		i++
	}

	eol := '\n'
	if *nullEol {
		eol = '\x00'
	}

	for _, e := range env {
		fmt.Printf("%s%c", e, eol)
	}

	return
}
Пример #4
0
func (ctx *Context) debug_cmd(cmd *exec.Cmd) {
	if ctx.Verbose {
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
}
Пример #5
0
func (self *LocalCommand) Start() error {
	var cmd *exec.Cmd
	if self.ScriptMode {
		cmd = exec.Command("sh")
		cmd.Stdin = strings.NewReader(self.CmdString)
	} else {
		cmd = exec.Command("sh", "-c", self.CmdString)
	}

	// create the command, set the options
	if self.WorkingDirectory != "" {
		cmd.Dir = self.WorkingDirectory
	}
	cmd.Env = self.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = self.Stdout
	cmd.Stderr = self.Stderr

	// cache the command running
	self.Cmd = cmd

	// start the command
	return cmd.Start()
}
Пример #6
0
func (pipe *Pipe) runPtyCmd(cmd *exec.Cmd) error {
	py, tty, err := pty.Open()
	if err != nil {
		return err
	}
	defer tty.Close()
	env := os.Environ()
	env = append(env, "TERM=xterm")
	cmd.Env = env
	cmd.Stdout = tty
	cmd.Stdin = tty
	cmd.Stderr = tty
	cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
	ws := &Winsize{
		Width:  uint16(pipe.opts.Width),
		Height: uint16(pipe.opts.Height),
	}
	_, _, syserr := syscall.Syscall(syscall.SYS_IOCTL, py.Fd(), uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
	if syserr != 0 {
		return syserr
	}
	pCmd := pipedCmd{
		pipe:   pipe,
		cmd:    cmd,
		stdin:  py,
		stdout: py,
		stderr: nil,
	}
	return pCmd.run()
}
Пример #7
0
func (lc *LocalCommand) Start() error {
	if lc.Shell == "" {
		lc.Shell = "sh"
	}

	var cmd *exec.Cmd
	if lc.ScriptMode {
		cmd = exec.Command(lc.Shell)
		cmd.Stdin = strings.NewReader(lc.CmdString)
	} else {
		cmd = exec.Command(lc.Shell, "-c", lc.CmdString)
	}

	// create the command, set the options
	if lc.WorkingDirectory != "" {
		cmd.Dir = lc.WorkingDirectory
	}
	cmd.Env = lc.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = lc.Stdout
	cmd.Stderr = lc.Stderr

	// cache the command running
	lc.Cmd = cmd

	// start the command
	return cmd.Start()
}
Пример #8
0
func (self *Login) Run() (err error) {
	locationPathAbs, _ := filepath.Abs(ConvPath(LocationPath))
	var buf bytes.Buffer
	buf.WriteString(locationPathAbs)
	buf.WriteString(ServerListPath)
	list := NewList(buf.String())
	buf.Reset()

	if list.ExistServer(self.Name) {
		server, _ := list.GetServer(self.Name)

		var cmd *exec.Cmd

		if server.UsePassword {
			cmd = exec.Command("ssh", server.Host, "-l", server.LoginUser, "-p", strconv.Itoa(server.Port))
		} else {
			cmd = exec.Command("ssh", server.Host, "-l", server.LoginUser, "-p", strconv.Itoa(server.Port), "-i", ConvPath(server.IdentityFile))
		}
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Stdin = os.Stdin
		err = cmd.Run()
	} else {
		help := NewHelp()
		help.Run()
	}

	return
}
Пример #9
0
func main() {
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() < 1 {
		usage()
	}
	args := flag.Args()

	ck(syscall.Chroot(args[0]))
	ck(syscall.Chdir("/"))

	var cmd *exec.Cmd
	if len(args) == 1 {
		shell := os.Getenv("SHELL")
		if shell == "" {
			shell = "/bin/sh"
		}
		cmd = exec.Command(shell, "-i")
	} else {
		cmd = exec.Command(args[1], args[2:]...)
	}
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	ck(cmd.Run())
}
Пример #10
0
func verifyCertWithSystem(block *pem.Block, add func(*Certificate)) {
	data := pem.EncodeToMemory(block)
	var cmd *exec.Cmd
	if needsTmpFiles() {
		f, err := ioutil.TempFile("", "cert")
		if err != nil {
			fmt.Fprintf(os.Stderr, "can't create temporary file for cert: %v", err)
			return
		}
		defer os.Remove(f.Name())
		if _, err := f.Write(data); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		if err := f.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", f.Name(), "-l")
	} else {
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", "/dev/stdin", "-l")
		cmd.Stdin = bytes.NewReader(data)
	}
	if cmd.Run() == nil {
		// Non-zero exit means untrusted
		cert, err := ParseCertificate(block.Bytes)
		if err != nil {
			return
		}

		add(cert)
	}
}
Пример #11
0
func (h *Host) Run(command string) error {
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", command)
	} else {
		cmd = exec.Command("sh", "-c", command)
	}

	realWriter := &RealWriter{
		NewLine: true,
		Prefix:  "[" + h.Name + "]: ",
	}
	outWriter := &writer{
		realWriter: realWriter,
		Type:       1,
	}
	errWriter := &writer{
		realWriter: realWriter,
		Type:       2,
	}

	cmd.Stdout = outWriter
	cmd.Stderr = errWriter
	cmd.Stdin = os.Stdin

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

	return nil
}
Пример #12
0
func GetDiff(repoPath, commitid string) (*Diff, error) {
	repo, err := git.OpenRepository(repoPath)
	if err != nil {
		return nil, err
	}

	commit, err := repo.GetCommit(commitid)
	if err != nil {
		return nil, err
	}

	rd, wr := io.Pipe()
	var cmd *exec.Cmd
	// First commit of repository.
	if commit.ParentCount() == 0 {
		cmd = exec.Command("git", "show", commitid)
	} else {
		c, _ := commit.Parent(0)
		cmd = exec.Command("git", "diff", c.Id.String(), commitid)
	}
	cmd.Dir = repoPath
	cmd.Stdout = wr
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	go func() {
		cmd.Run()
		wr.Close()
	}()
	defer rd.Close()
	return ParsePatch(cmd, rd)
}
Пример #13
0
Файл: exec.go Проект: yl10/goxc
func RedirectIOTo(cmd *exec.Cmd, myin io.Reader, myout, myerr io.Writer) {
	// redirect IO
	cmd.Stdout = myout
	cmd.Stderr = myerr
	cmd.Stdin = myin
	//return nil, err
}
Пример #14
0
func start(c *exec.Cmd) (pty *os.File, err error) {
	pty, tty, err := open()
	if err != nil {
		return nil, err
	}
	defer tty.Close()

	err = setEcho(pty, false)
	if err != nil {
		return nil, err
	}

	err = setEcho(tty, false)
	if err != nil {
		return nil, err
	}

	c.Stdout = tty
	c.Stdin = tty
	c.Stderr = tty
	if c.SysProcAttr == nil {
		c.SysProcAttr = &syscall.SysProcAttr{}
	}
	c.SysProcAttr.Setctty = true
	c.SysProcAttr.Setsid = true
	err = c.Start()
	if err != nil {
		pty.Close()
		return nil, err
	}

	return pty, err
}
Пример #15
0
func blastCoarse(
	db *cablastp.DB, stdin *bytes.Reader, stdout *bytes.Buffer) error {
	var cmd *exec.Cmd

	if flagShortQueries {
		cmd = exec.Command(
			flagBlastn,
			"-db", path.Join(db.Path, cablastp.FileBlastCoarse),
			"-num_threads", s(flagGoMaxProcs),
			"-max_target_seqs", "100000",
			"-task", "blastn-short", "-evalue", sf(flagCoarseEval), "-penalty", "-1",
			"-outfmt", "5", "-dbsize", su(db.BlastDBSize))
	} else {
		cmd = exec.Command(
			flagBlastn,
			"-db", path.Join(db.Path, cablastp.FileBlastCoarse),
			"-num_threads", s(flagGoMaxProcs),
			"-max_target_seqs", "100000",
			"-evalue", sf(flagCoarseEval),
			"-outfmt", "5", "-dbsize", su(db.BlastDBSize))
	}
	cmd.Stdin = stdin
	cmd.Stdout = stdout
	return cablastp.Exec(cmd)
}
Пример #16
0
func run(src string) error {
	// Create a temp folder.
	tempDir, err := ioutil.TempDir("", "goexec_")
	if err != nil {
		return err
	}
	defer func() {
		err := os.RemoveAll(tempDir)
		if err != nil {
			fmt.Fprintln(os.Stderr, "warning: error removing temp dir:", err)
		}
	}()

	// Write the source code file.
	tempFile := filepath.Join(tempDir, "gen.go")
	err = ioutil.WriteFile(tempFile, []byte(src), 0600)
	if err != nil {
		return err
	}

	// Compile and run the program.
	var cmd *exec.Cmd
	switch *compilerFlag {
	case "gc":
		cmd = exec.Command("go", "run", tempFile)
	case "gopherjs":
		cmd = exec.Command("gopherjs", "run", tempFile)
	}
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}
Пример #17
0
func (a *ERBAsset) Compile() (io.Reader, error) {
	data, err := a.input.Compile()
	if err != nil {
		return nil, err
	}

	a.l.Info("Compiling ERB")

	var buf bytes.Buffer
	var cmd *exec.Cmd
	if _, err := os.Stat("Gemfile"); err == nil {
		cmd = exec.Command("bundle", "exec", "ruby", a.erbRBPath)
	} else {
		cmd = exec.Command("ruby", a.erbRBPath)
	}
	cmd.Stdin = data
	cmd.Stdout = &buf
	cmd.Stderr = os.Stderr
	cmd.Env = os.Environ()
	cmd.Env = append(cmd.Env, fmt.Sprintf("CACHE_BREAKER=%s", a.cacheBreaker))
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	return &buf, nil
}
Пример #18
0
func runEditor(filename string) error {
	ed := os.Getenv("VISUAL")
	if ed == "" {
		ed = os.Getenv("EDITOR")
	}
	if ed == "" {
		ed = "ed"
	}

	// If the editor contains spaces or other magic shell chars,
	// invoke it as a shell command. This lets people have
	// environment variables like "EDITOR=emacs -nw".
	// The magic list of characters and the idea of running
	// sh -c this way is taken from git/run-command.c.
	var cmd *exec.Cmd
	if strings.ContainsAny(ed, "|&;<>()$`\\\"' \t\n*?[#~=%") {
		cmd = exec.Command("sh", "-c", ed+` "$@"`, "$EDITOR", filename)
	} else {
		cmd = exec.Command(ed, filename)
	}

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("invoking editor: %v", err)
	}
	return nil
}
Пример #19
0
func buildCmd(cmd Cmd) *Result {
	var execCmd *exec.Cmd
	switch len(cmd.Command) {
	case 1:
		execCmd = exec.Command(cmd.Command[0])
	default:
		execCmd = exec.Command(cmd.Command[0], cmd.Command[1:]...)
	}
	outBuffer := new(lockedBuffer)
	errBuffer := new(lockedBuffer)

	execCmd.Stdin = cmd.Stdin
	execCmd.Dir = cmd.Dir
	execCmd.Env = cmd.Env
	if cmd.Stdout != nil {
		execCmd.Stdout = io.MultiWriter(outBuffer, cmd.Stdout)
	} else {
		execCmd.Stdout = outBuffer
	}
	execCmd.Stderr = errBuffer
	return &Result{
		Cmd:       execCmd,
		outBuffer: outBuffer,
		errBuffer: errBuffer,
	}
}
Пример #20
0
func runUtility() {
	var cmd *exec.Cmd

	args := flag.Args()
	if len(args) < 1 {
		return
	}

	cmd = exec.Command(args[0], args[1:]...)
	*title = args[0]

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err := cmd.Run()
	if exerr, is := err.(*exec.ExitError); is {
		if !exerr.Success() {
			*title = *title + " failed"
		}
	}
	if err != nil {
		*message = err.Error()
	}
}
Пример #21
0
func doHelp(sh *Shell, args []*Token) (*Response, error) {
	pager := os.Getenv("PAGER")
	if pager != "" {
		var cmd *exec.Cmd
		if runtime.GOOS == "windows" {
			cmd = exec.Command(pager)
		} else {
			cmd = exec.Command(pager)
		}

		cmd.Stdout = sh.Stdout
		cmd.Stderr = sh.Stderr
		cmd.Stdin = strings.NewReader(helpText)

		err := cmd.Run()
		if err != nil {
			return nil, err
		}

		return nil, nil
	}

	fmt.Fprintf(sh.Stdout, helpText)
	return nil, nil
}
Пример #22
0
// Runs diffstat on some diff output.  Returns diffstat command.
func diffstat(output string) (*exec.Cmd, error) {
	var err error
	var cmd *exec.Cmd

	if len(DIFFSTAT) == 0 {
		DIFFSTAT, _ = exec.LookPath("diffstat")
		if len(DIFFSTAT) == 0 {
			return nil, errors.New("Could not find suitable diffstat executable in your PATH.")
		}
	}

	if runtime.GOOS == "darwin" {
		cmd = exec.Command(DIFFSTAT)
	} else {
		cmd = exec.Command(DIFFSTAT, "-C")
	}
	if err != nil {
		return nil, err
	}

	cmd.Stdin = strings.NewReader(output)
	if err != nil {
		return nil, err
	}
	return cmd, nil
}
Пример #23
0
func (w *Spawn) spawnNoninteractive(cmd *exec.Cmd) ([]*os.File, error) {
	var pipes [3]struct {
		r *os.File
		w *os.File
	}

	var err error
	for i := 0; i < 3; i++ {
		pipes[i].r, pipes[i].w, err = os.Pipe()
		if err != nil {
			return nil, fmt.Errorf("container_daemon: create pipe: %s", err)
		}
	}

	cmd.Stdin = pipes[0].r
	cmd.Stdout = pipes[1].w
	cmd.Stderr = pipes[2].w

	exitStatusR, err := wireExit(cmd, w.Runner)
	if err != nil {
		for _, p := range pipes {
			p.r.Close()
			p.w.Close()
		}

		return nil, err
	}

	return []*os.File{pipes[0].w, pipes[1].r, pipes[2].r, exitStatusR}, nil
}
Пример #24
0
func (w *Spawn) spawnWithTty(cmd *exec.Cmd) ([]*os.File, error) {
	pty, tty, err := w.PTY.Open()
	if err != nil {
		return nil, fmt.Errorf("container_daemon: open pipe: %s", err)
	}

	cmd.Stdin = tty
	cmd.Stdout = tty
	cmd.Stderr = tty

	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}

	cmd.SysProcAttr.Setctty = true
	cmd.SysProcAttr.Setsid = true

	exitFd, err := wireExit(cmd, w.Runner)
	if err != nil {
		pty.Close()
		tty.Close()
		return nil, err
	}

	return []*os.File{pty, exitFd}, err
}
Пример #25
0
// cmdStream executes a command, and returns its stdout as a stream.
// If the command fails to run or doesn't complete successfully, an error
// will be returned, including anything written on stderr.
func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, <-chan struct{}, error) {
	chdone := make(chan struct{})
	cmd.Stdin = input
	pipeR, pipeW := io.Pipe()
	cmd.Stdout = pipeW
	var errBuf bytes.Buffer
	cmd.Stderr = &errBuf

	// Run the command and return the pipe
	if err := cmd.Start(); err != nil {
		return nil, nil, err
	}

	// Copy stdout to the returned pipe
	go func() {
		if err := cmd.Wait(); err != nil {
			pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String()))
		} else {
			pipeW.Close()
		}
		close(chdone)
	}()

	return pipeR, chdone, nil
}
Пример #26
0
func (me *App) execs(cmd *exec.Cmd) error {
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return cmd.Run()
}
Пример #27
0
func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error {
	command.Stdout = t.SlavePty
	command.Stderr = t.SlavePty

	go func() {
		if wb, ok := pipes.Stdout.(interface {
			CloseWriters() error
		}); ok {
			defer wb.CloseWriters()
		}

		io.Copy(pipes.Stdout, t.MasterPty)
	}()

	if pipes.Stdin != nil {
		command.Stdin = t.SlavePty
		command.SysProcAttr.Setctty = true

		go func() {
			io.Copy(t.MasterPty, pipes.Stdin)

			pipes.Stdin.Close()
		}()
	}
	return nil
}
Пример #28
0
func runCmdWithStdIo(cmd exec.Cmd) error {
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return cmd.Run()
}
Пример #29
0
func ExecGPG(args []string, in io.Reader) ([]byte, error) {
	var cmd *exec.Cmd
	var stdout, stderr bytes.Buffer

	for _, name := range []string{"gpg2", "gpg"} {
		exe, err := exec.LookPath(name)
		if err != nil {
			continue
		}

		cmd = exec.Command(exe, args...)
		break
	}

	if cmd == nil {
		return nil, fmt.Errorf("Could not find gpg executable")
	}

	cmd.Stdin = in
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err := cmd.Run()
	if err != nil {
		return nil, fmt.Errorf("%s", stderr.String())
	}

	return stdout.Bytes(), nil
}
Пример #30
0
func main() {

	flag.Parse()

	data := Data{
		"SVG -> PDF",
		time.Now().Format("_2 Jan 2006 15:04:05"),
		20150803,
		"Строка кириллицей",
		true,
	}

	var err error

	// Load template from file
	template, err := template.ParseFiles(*inputFile)
	chk(err)

	// Store template to buffer
	buf := new(bytes.Buffer)
	err = template.Execute(buf, data)
	chk(err)

	// Convert via external application
	// Install before use
	// # apt-get install librsvg2-bin
	// or
	// # apt-get install inkscape
	var cmd *exec.Cmd

	if *converter == "inkscape" {
		fmt.Println("Generate via inkscape")
		cmd = exec.Command("inkscape", "--without-gui", "/dev/stdin", "--export-pdf=/dev/stdout")
		if *outputPng != "" {
			cmd.Args = append(cmd.Args, "--export-png", *outputPng)
		}
	} else {
		fmt.Println("Generate via rsvg-convert")
		cmd = exec.Command("rsvg-convert", "-f", "pdf")
	}
	cmd.Stdin = bytes.NewReader(buf.Bytes())

	// Write pdf to file
	out, err := os.OpenFile(*outputFile, os.O_CREATE|os.O_WRONLY, 0666)
	chk(err)
	defer out.Close()
	cmd.Stdout = out

	timeStart := time.Now().UnixNano()
	err = cmd.Run() // Syncronous run external application
	chk(err)
	timeEnd := time.Now().UnixNano()

	fmt.Println("Conversion time (ms)", (timeEnd-timeStart)/1000000)

	// Open output file using the OS's default application
	open.Run(*outputFile)

}