-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommands.go
More file actions
208 lines (194 loc) · 6.36 KB
/
commands.go
File metadata and controls
208 lines (194 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// Copyright 2017 Javier Arevalo <jare@iguanademos.com>
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Cross platform command execution and some file system operations
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// RunShell runs an interactive shell.
// Since the current program is still running, so may be
// its coroutines, which will trigger all sorts of weirdness
// For example, Ctrl-C may be caught by our Go runtime, killing us
// but leaving the spawned shell still running, with I/O shared with
// our parent (possibly another shell!). That's pretty ugly.
func RunShell(cwd string) error {
attr := os.ProcAttr{
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
Dir: cwd,
}
var args []string
shell, ok := os.LookupEnv("COMSPEC")
if !ok {
args = []string{"-i"}
shell, ok = os.LookupEnv("SHELL")
if !ok {
shell = "/bin/sh"
}
}
process, err := os.StartProcess(shell, args, &attr)
if err != nil {
return err
}
state, err := process.Wait()
if err != nil {
return err
}
if state.Success() {
return nil
}
return fmt.Errorf("<< Exited shell: %s", state.String())
}
// RunCommand executes the given command and arguments under the system'
// default shell. Really only tested under CMD and ksh
// If command fails, returns the system error and the output of the command
func RunCommand(command string, args ...string) error {
var ret []string
var finalargs []string
var shell string
if runtime.GOOS == "windows" {
sh, ok := os.LookupEnv("COMSPEC")
if !ok {
shell = "C:\\Windows\\System32\\cmd.exe"
}
shell = sh
args = append([]string{command}, args...)
finalargs = []string{"/C", strings.Join(args, " ") + " 2>&1"}
} else {
sh, ok := os.LookupEnv("SHELL")
if !ok {
shell = "/bin/sh"
}
shell = sh
for i, v := range args {
args[i] = strconv.Quote(v)
}
args = append([]string{command}, args...)
finalargs = []string{"-c", strings.Join(args, " ") + " 2>&1"}
}
Logf("Running command:\n>%s<\n>>%s<<\n", shell, strings.Join(finalargs, "<<\n>>"))
cmd := exec.Command(shell, finalargs...)
// See comment in sys_windows.go for this
SetProcCmdline(cmd, strings.Join(finalargs, " "))
outp, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("Failed to attach stdout: %v", err)
}
err = cmd.Start()
if err != nil {
Logf("ERROR: %s: %s\n", err, strings.Join(ret, "\n"))
return fmt.Errorf("%s -> %s: %s", strings.Join(finalargs[1:], " "), err, strings.Join(ret, " \n"))
}
scanner := bufio.NewScanner(outp)
for scanner.Scan() {
line := scanner.Text()
ret = append(ret, line)
}
err = cmd.Wait()
Logf("Output: %s\n", strings.Join(ret, "\n"))
if err != nil {
Logf("ERROR: %s: %s\n", err, strings.Join(ret, "\n"))
return fmt.Errorf("%s -> %s: %s", strings.Join(finalargs[1:], " "), err, strings.Join(ret, " \n"))
}
return nil
}
func quoteString(src string) string {
if l := len(src); l > 2 && src[0] != '"' && src[l-1] != '"' {
return "\"" + src + "\""
}
return src
}
// CommandCopy copies a given file or folder into the target folder
// Does not verify that the target folder exists nor if
// it is in fact a folder
// Fails if the target is the root folder
// If command fails, returns the system error and the output of the command
func CommandCopy(src string, dst string) error {
dst = filepath.Clean(dst)
if dst[len(dst)-1] == os.PathSeparator {
return fmt.Errorf("Copy to root folder %s not allowed for safety", dst)
}
dst += string(os.PathSeparator)
// Many safety checks to perform here...
if runtime.GOOS == "windows" {
// We end up using xcopy because copy will NOT handle hidden files ever
stat, err := os.Stat(src)
if err != nil {
return err
}
if stat.IsDir() {
fullDest := filepath.Join(dst, filepath.Base(src))
return RunCommand("xcopy", "/Q", "/I", "/K", "/H", "/Y", "/R", "/S", "/E", quoteString(src), quoteString(fullDest))
}
return RunCommand("xcopy", "/Q", "/K", "/H", "/Y", "/R", quoteString(src), quoteString(dst))
}
return RunCommand("cp", "-R", src, dst)
}
// CommandMove moves a given file or folder into the target folder
// Does not verify that the target folder exists nor if
// it is in fact a folder
// Fails if the target is the root folder
// If command fails, returns the system error and the output of the command
func CommandMove(src string, dst string) error {
dst = filepath.Clean(dst)
if dst[len(dst)-1] == os.PathSeparator {
return fmt.Errorf("Move to root folder %s not allowed for safety", dst)
}
dst += string(os.PathSeparator)
dir := filepath.Dir(src)
if dir[len(dir)-1] == os.PathSeparator {
return fmt.Errorf("Moving %s from root folder not allowed for safety", dst)
}
// Many safety checks to perform here...
if runtime.GOOS == "windows" {
// hidden files will wreak havoc with move across devices
err := RunCommand("move", "/Y", quoteString(src), quoteString(dst))
if err != nil {
// So if we get any errors we retry via copy & delete
err = CommandCopy(src, dst)
if err == nil {
err = CommandDelete(src)
}
}
return err
}
return RunCommand("mv", "-f", src, dst)
}
// CommandDelete deletes a given file or folder
// Fails if the target is the root folder
// If command fails, returns the system error and the output of the command
func CommandDelete(dst string) error {
dst = filepath.Clean(dst)
dir := filepath.Dir(dst)
if dir[len(dir)-1] == os.PathSeparator {
return fmt.Errorf("Deleting %s from root folder not allowed for safety", dst)
}
// Many safety checks to perform here...
if runtime.GOOS == "windows" {
// Deleting files in directories and deleting directories are two
// separate things :(
err := RunCommand("del", "/Q", "/A", "/F", quoteString(dst))
if err == nil {
// Must ignore the error because dst may have been fully deleted by prev command
// UGH
/*err = */
RunCommand("rd", "/S", "/Q", quoteString(dst))
}
return err
}
return RunCommand("rm", "-rf", dst)
}