-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
521 lines (442 loc) · 14.2 KB
/
Copy pathmain.go
File metadata and controls
521 lines (442 loc) · 14.2 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/anmitsu/go-shlex"
"github.com/spf13/cobra"
)
// ANSI color codes
const (
colorReset = "\033[0m"
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorBlue = "\033[34m"
colorPurple = "\033[35m"
colorCyan = "\033[36m"
)
var (
// Flag to disable colored output
noColor bool
// Flag to indicate if colors are supported
colorSupported bool
// Additional environment variables
envVars []string
// Command tags
tags []string
// Active commands
activeCommands sync.Map
// Force shell usage
forceShell bool
// Flag to indicate if we're running in parallel mode
parallelMode bool
// Time of the last SIGINT for double Ctrl+C detection
lastSigIntTime time.Time
// Currently running command in sequential mode
currentSequentialCmd *exec.Cmd
// Mutex to protect currentSequentialCmd
currentCmdMutex sync.Mutex
)
// CommandInfo holds information about a command to be executed
type CommandInfo struct {
Command string
Tag string
Index int
}
// shellSpecialChars contains characters that typically require a shell to interpret
var shellSpecialChars = []string{
"|", "&", ";", "<", ">", "(", ")", "$", "`", "\\", "\"", "'", "*", "?", "[", "]", "#", "~", "=", "%",
}
func main() {
// Try to enable color support
enableVirtualTerminalProcessing()
// Set up signal handling
setupSignalHandling()
var rootCmd = &cobra.Command{
Use: "rufl",
Short: "RunFlow - Run commands in parallel or sequentially",
Long: `RunFlow (rufl) is a command line tool that allows executing
other commands either in parallel or sequentially.
Examples:
rufl p "echo hello world" "cat /etc/hosts" "while true; do echo hello; sleep 1; done"
rufl s "echo hello world" "cat /etc/hosts" "while true; do echo hello; sleep 1; done"
# Tag commands with names using -t flag
rufl p -t "greeting:echo hello" -t "hosts:cat /etc/hosts" -t "loop:while true; do echo hello; sleep 1; done"
# Tag commands with names using + syntax
rufl p "+greeting:echo hello" "+hosts:cat /etc/hosts" "+loop:while true; do echo hello; sleep 1; done"`,
}
// Global flags
rootCmd.PersistentFlags().BoolVar(&noColor, "no-color", false, "Disable colored output")
rootCmd.PersistentFlags().StringArrayVarP(&envVars, "env", "e", []string{}, "Set additional environment variables (format: KEY=VALUE)")
rootCmd.PersistentFlags().StringArrayVarP(&tags, "tag", "t", []string{}, "Tag a command with a name (format: NAME:COMMAND)")
rootCmd.PersistentFlags().BoolVar(&forceShell, "shell", false, "Force the use of a shell for all commands")
var parallelCmd = &cobra.Command{
Use: "=",
Aliases: []string{"p", "parallel"},
Short: "Run commands in parallel",
Long: `Run multiple commands in parallel and output the results as they come in.`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
commands := processCommands(args)
runCommands(commands, true)
},
}
var sequentialCmd = &cobra.Command{
Use: "+",
Aliases: []string{"s", "sequential"},
Short: "Run commands sequentially",
Long: `Run multiple commands one after another and output the results.`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
commands := processCommands(args)
runCommands(commands, false)
},
}
rootCmd.AddCommand(parallelCmd, sequentialCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// setupSignalHandling sets up handlers for various signals
func setupSignalHandling() {
signalChan := make(chan os.Signal, 1)
// Register for SIGINT (Ctrl+C), SIGTERM, and SIGHUP
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
go func() {
for sig := range signalChan {
// Handle SIGINT (Ctrl+C) specially for sequential mode
if sig == syscall.SIGINT && !parallelMode {
now := time.Now()
// Check if this is a double Ctrl+C (within 1 second)
if !lastSigIntTime.IsZero() && now.Sub(lastSigIntTime) < time.Second {
// Double Ctrl+C detected, exit rufl
printColoredMessage("Double Ctrl+C detected. Exiting...", colorYellow)
os.Exit(130) // 128 + SIGINT (2)
}
// Single Ctrl+C, just interrupt the current command
lastSigIntTime = now
printColoredMessage("Interrupting current command. Press Ctrl+C again within 1 second to exit rufl.", colorYellow)
// Forward the signal to the current command only
currentCmdMutex.Lock()
if currentSequentialCmd != nil && currentSequentialCmd.Process != nil {
_ = currentSequentialCmd.Process.Signal(sig)
}
currentCmdMutex.Unlock()
// Continue the loop to handle more signals
continue
}
// For other signals or parallel mode, use the original behavior
printColoredMessage(fmt.Sprintf("Received signal: %v. Forwarding to all child processes...", sig), colorYellow)
// Forward the signal to all active commands
activeCommands.Range(func(key, value interface{}) bool {
cmd := value.(*exec.Cmd)
if cmd.Process != nil {
// On Windows, not all signals are supported
if runtime.GOOS == "windows" && (sig == syscall.SIGHUP) {
// For unsupported signals on Windows, just kill the process
_ = cmd.Process.Kill()
} else {
_ = cmd.Process.Signal(sig)
}
}
return true
})
// For SIGINT and SIGTERM, exit after forwarding
if (sig == syscall.SIGINT || sig == syscall.SIGTERM) && parallelMode {
os.Exit(128 + int(sig.(syscall.Signal)))
}
// For SIGTERM in sequential mode, also exit
if sig == syscall.SIGTERM && !parallelMode {
os.Exit(128 + int(sig.(syscall.Signal)))
}
}
}()
}
// processCommands combines regular command arguments and tagged commands
func processCommands(args []string) []CommandInfo {
var commands []CommandInfo
var regularArgs []string
var taggedCommands []struct {
Tag string
Command string
}
// First, separate regular args from +tag:command args
for _, arg := range args {
if strings.HasPrefix(arg, "+") && strings.Contains(arg, ":") {
// This is a +tag:command format
tagParts := strings.SplitN(arg[1:], ":", 2) // Remove the + prefix
if len(tagParts) != 2 {
fmt.Printf("Warning: Invalid tag format '%s', expected '+NAME:COMMAND'\n", arg)
continue
}
taggedCommands = append(taggedCommands, struct {
Tag string
Command string
}{
Tag: tagParts[0],
Command: tagParts[1],
})
} else {
// This is a regular command
regularArgs = append(regularArgs, arg)
}
}
// Add any tagged commands from the -t flag
for _, tag := range tags {
tagParts := strings.SplitN(tag, ":", 2)
if len(tagParts) != 2 {
fmt.Printf("Warning: Invalid tag format '%s', expected 'NAME:COMMAND'\n", tag)
continue
}
taggedCommands = append(taggedCommands, struct {
Tag string
Command string
}{
Tag: tagParts[0],
Command: tagParts[1],
})
}
// Process regular command arguments first
for i, cmd := range regularArgs {
// Check if this command has a tag
tag := fmt.Sprintf("%d", i+1) // Default tag is the index
// Look for a matching tagged command
for j, taggedCmd := range taggedCommands {
if taggedCmd.Command == cmd {
tag = taggedCmd.Tag
// Remove the tagged command to avoid processing it again
taggedCommands = append(taggedCommands[:j], taggedCommands[j+1:]...)
break
}
}
commands = append(commands, CommandInfo{
Command: cmd,
Tag: tag,
Index: i,
})
}
// Add any remaining tagged commands
remainingIndex := len(regularArgs)
for _, taggedCmd := range taggedCommands {
commands = append(commands, CommandInfo{
Command: taggedCmd.Command,
Tag: taggedCmd.Tag,
Index: remainingIndex,
})
remainingIndex++
}
if len(commands) == 0 {
fmt.Println("Error: No commands specified. Use positional arguments, +tag:command syntax, or -t/--tag flags.")
os.Exit(1)
}
return commands
}
// runCommands executes the given commands either in parallel or sequentially
func runCommands(commands []CommandInfo, parallel bool) {
parallelMode = parallel
if parallel {
runParallel(commands)
} else {
runSequential(commands)
}
}
// runParallel executes commands in parallel
func runParallel(commands []CommandInfo) {
var wg sync.WaitGroup
wg.Add(len(commands))
// Start commands in order, but let them run concurrently
for i, cmd := range commands {
go func(cmdInfo CommandInfo, index int) {
defer wg.Done()
executeCommand(cmdInfo)
}(cmd, i)
// Wait a small amount of time to ensure commands start in order
// This is a simple approach that works well in practice
time.Sleep(10 * time.Millisecond)
}
wg.Wait()
}
// runSequential executes commands one after another
func runSequential(commands []CommandInfo) {
for _, cmd := range commands {
executeCommand(cmd)
}
}
// needsShell determines if a command needs a shell to be executed
func needsShell(command string) bool {
// If shell usage is forced, return true
if forceShell {
return true
}
// If environment variables are set, always use a shell to ensure proper expansion
if len(envVars) > 0 {
return true
}
// Check for shell special characters
for _, char := range shellSpecialChars {
if strings.Contains(command, char) {
return true
}
}
// Check for command chaining
if strings.Contains(command, "&&") || strings.Contains(command, "||") || strings.Contains(command, ";") {
return true
}
// Check for redirections
if strings.Contains(command, ">") || strings.Contains(command, "<") {
return true
}
// Check for pipes
if strings.Contains(command, "|") {
return true
}
// Check for glob patterns
if strings.Contains(command, "*") || strings.Contains(command, "?") || strings.Contains(command, "[") {
return true
}
return false
}
// executeCommand executes a single command
func executeCommand(cmdInfo CommandInfo) {
var cmd *exec.Cmd
// Check if the command needs a shell
if needsShell(cmdInfo.Command) {
// Determine the shell to use based on the OS
var shell, shellArg string
if runtime.GOOS == "windows" {
shell = "cmd"
shellArg = "/C"
} else {
shell = "sh"
shellArg = "-c"
}
// Create the command using the shell
cmd = exec.Command(shell, shellArg, cmdInfo.Command)
printColoredMessage(fmt.Sprintf("[%s] Executing with shell: %s", cmdInfo.Tag, cmdInfo.Command), colorCyan)
} else {
// Parse the command using go-shlex
args, err := shlex.Split(cmdInfo.Command, true)
if err != nil {
printColoredMessage(fmt.Sprintf("[%s] Error parsing command: %v", cmdInfo.Tag, err), colorRed)
return
}
if len(args) == 0 {
printColoredMessage(fmt.Sprintf("[%s] Empty command", cmdInfo.Tag), colorRed)
return
}
// Create the command directly without a shell
cmd = exec.Command(args[0], args[1:]...)
printColoredMessage(fmt.Sprintf("[%s] Executing directly: %s", cmdInfo.Tag, cmdInfo.Command), colorCyan)
}
// If in sequential mode, set this as the current command
if !parallelMode {
currentCmdMutex.Lock()
currentSequentialCmd = cmd
currentCmdMutex.Unlock()
}
// Inherit environment variables from the parent process
env := os.Environ()
// Add any additional environment variables
if len(envVars) > 0 {
env = append(env, envVars...)
}
cmd.Env = env
// Set up pipes for stdout and stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Printf("Error creating stdout pipe for command %s: %v\n", cmdInfo.Tag, err)
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Printf("Error creating stderr pipe for command %s: %v\n", cmdInfo.Tag, err)
return
}
// Print environment variables if any were added
if len(envVars) > 0 {
printColoredMessage(fmt.Sprintf("[%s] With additional environment: %s", cmdInfo.Tag, strings.Join(envVars, ", ")), colorPurple)
}
// Start the command
if err := cmd.Start(); err != nil {
printColoredMessage(fmt.Sprintf("[%s] Error starting command: %v", cmdInfo.Tag, err), colorRed)
return
}
// Store the command in the active commands map
cmdID := fmt.Sprintf("%s-%d", cmdInfo.Tag, cmd.Process.Pid)
activeCommands.Store(cmdID, cmd)
// Create a wait group for the goroutines that read output
var outputWg sync.WaitGroup
outputWg.Add(2)
// Process stdout
go func() {
defer outputWg.Done()
processOutput(stdout, cmdInfo.Tag, "out", colorGreen)
}()
// Process stderr
go func() {
defer outputWg.Done()
processOutput(stderr, cmdInfo.Tag, "err", colorRed)
}()
// Wait for all output to be processed
outputWg.Wait()
// Wait for the command to complete
err = cmd.Wait()
// Remove the command from the active commands map
activeCommands.Delete(cmdID)
// If in sequential mode, clear the current command
if !parallelMode {
currentCmdMutex.Lock()
currentSequentialCmd = nil
currentCmdMutex.Unlock()
}
if err != nil {
// Check if it's an exit error
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
printColoredMessage(fmt.Sprintf("[%s] Command exited with status: %d", cmdInfo.Tag, status.ExitStatus()), colorYellow)
} else {
printColoredMessage(fmt.Sprintf("[%s] Error waiting for command: %v", cmdInfo.Tag, err), colorRed)
}
} else {
printColoredMessage(fmt.Sprintf("[%s] Command completed successfully", cmdInfo.Tag), colorGreen)
}
}
// processOutput reads from a pipe and prints the output with a prefix
func processOutput(pipe io.Reader, tag string, streamType string, color string) {
scanner := bufio.NewScanner(pipe)
for scanner.Scan() {
line := scanner.Text()
// Format the prefix differently based on color settings
var prefix string
if noColor || !colorSupported {
// When color is disabled, include the stream type in the prefix
prefix = fmt.Sprintf("[%s:%s] ", tag, streamType)
fmt.Println(prefix + line)
} else {
// When color is enabled, omit the stream type as the color indicates it
prefix = fmt.Sprintf("[%s] ", tag)
fmt.Print(color + prefix + colorReset + line + "\n")
}
}
if err := scanner.Err(); err != nil {
printColoredMessage(fmt.Sprintf("[%s] Error reading %s: %v", tag, streamType, err), colorRed)
}
}
// printColoredMessage prints a message with the specified color
func printColoredMessage(message string, color string) {
if noColor || !colorSupported {
fmt.Println(message)
} else {
fmt.Println(color + message + colorReset)
}
}