Debian Codegraph @

cmd.go

raw symbols SCIP
1 package godo
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "strings"
9
10 "github.com/mgutz/ansi"
11 "gopkg.in/godo.v2/util"
12 )
13
14 // Processes are the processes spawned by Start()
15 var Processes = make(map[string]*os.Process)
16
17 const (
18 // CaptureStdout is a bitmask to capture STDOUT
19 CaptureStdout = 1
20 // CaptureStderr is a bitmask to capture STDERR
21 CaptureStderr = 2
22 // CaptureBoth captures STDOUT and STDERR
23 CaptureBoth = CaptureStdout + CaptureStderr
24 )
25
26 type command struct {
27 // original command string
28 commandstr string
29 // parsed executable
30 executable string
31 // parsed argv
32 argv []string
33 // parsed env
34 env []string
35 // working directory
36 wd string
37 // bitmask to capture output
38 capture int
39 // the output buf
40 buf bytes.Buffer
41 }
42
43 func (gcmd *command) toExecCmd() (cmd *exec.Cmd, err error) {
44 cmd = exec.Command(gcmd.executable, gcmd.argv...)
45 if gcmd.wd != "" {
46 cmd.Dir = gcmd.wd
47 }
48
49 cmd.Env = EffectiveEnv(gcmd.env)
50 cmd.Stdin = os.Stdin
51
52 if gcmd.capture&CaptureStderr > 0 {
53 cmd.Stderr = newFileWrapper(os.Stderr, &gcmd.buf, ansi.Red)
54 } else {
55 cmd.Stderr = os.Stderr
56 }
57 if gcmd.capture&CaptureStdout > 0 {
58 cmd.Stdout = newFileWrapper(os.Stdout, &gcmd.buf, "")
59 } else {
60 cmd.Stdout = os.Stdout
61 }
62
63 if verbose {
64 if Env != "" {
65 util.Debug("#", "Env: %s\n", Env)
66 }
67 if gcmd.wd != "" {
68 util.Debug("#", "Dir: %s\n", gcmd.wd)
69 }
70 util.Debug("#", "%s\n", gcmd.commandstr)
71 }
72
73 return cmd, nil
74 }
75
76 func (gcmd *command) run() (string, error) {
77 var err error
78 cmd, err := gcmd.toExecCmd()
79 if err != nil {
80 return "", err
81 }
82
83 err = cmd.Run()
84 if gcmd.capture > 0 {
85 return gcmd.buf.String(), err
86 }
87 return "", err
88
89 }
90
91 func (gcmd *command) runAsync() error {
92 cmd, err := gcmd.toExecCmd()
93 if err != nil {
94 return err
95 }
96
97 id := gcmd.commandstr
98
99 // kills previously spawned process (if exists)
100 killSpawned(id)
101 runnerWaitGroup.Add(1)
102 waitExit = true
103 go func() {
104 err = cmd.Start()
105 if err != nil {
106 fmt.Println(err.Error())
107 return
108 }
109 Processes[id] = cmd.Process
110 if verbose {
111 util.Debug("#", "Processes[%q] added\n", id)
112 }
113 cmd.Wait()
114 runnerWaitGroup.Done()
115 }()
116 return nil
117 }
118
119 func killSpawned(command string) {
120 process := Processes[command]
121 if process == nil {
122 return
123 }
124
125 err := process.Kill()
126 //err := syscall.Kill(-process.Pid, syscall.SIGKILL)
127 delete(Processes, command)
128 if err != nil && !strings.Contains(err.Error(), "process already finished") {
129 util.Error("Start", "Could not kill existing process %+v\n%s\n", process, err.Error())
130 return
131 }
132 if verbose {
133 util.Debug("#", "Processes[%q] killed\n", command)
134 }
135 }