-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstdio_utils.go
More file actions
875 lines (751 loc) · 22.5 KB
/
Copy pathstdio_utils.go
File metadata and controls
875 lines (751 loc) · 22.5 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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
package utils
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
)
type SetGlobalVarsOptions struct {
NonInteractive ProcessIfDefaultIsPresentStruct
Infinity int
}
var GLOBAL_VARS SetGlobalVarsOptions
func SetGlobalVars(options SetGlobalVarsOptions) {
GLOBAL_VARS = options
GLOBAL_VARS.Infinity = 1<<31 - 1
}
type KillPortsOptions struct {
Ports []string
ProgramNames []string
OutputFile string
OpenOutputFile bool
DryRun bool
}
type KillPortsProcessInfo struct {
ColumnNameIndex int
PIDIndex int
Output string
Columns []string
Lines []string
Rows []map[string]string
Regex *regexp.Regexp
}
func getColumnIndex(headers []string, columnName string) int {
for i, header := range headers {
if strings.Contains(strings.ToLower(header), strings.ToLower(columnName)) {
return i
}
}
return -1
}
func findPIDIndex(info *KillPortsProcessInfo) {
for i, line := range info.Lines {
if strings.Contains(line, "PID") {
fields := info.Regex.Split(line, -1)
info.ColumnNameIndex = i
for j, field := range fields {
if strings.Contains(field, "PID") {
info.PIDIndex = j
return
}
}
}
}
info.PIDIndex = -1 // set to -1 if "PID" not found
}
func initProcessInfo(processInfo *KillPortsProcessInfo) {
processInfo.Columns = processInfo.Regex.Split(strings.TrimSpace(processInfo.Lines[processInfo.ColumnNameIndex]), -1)
for i, line := range processInfo.Lines {
if i <= processInfo.ColumnNameIndex {
continue
}
columns := processInfo.Columns
var fields = processInfo.Regex.Split(strings.TrimSpace(line), -1)
processMap := make(map[string]string)
for i, column := range columns {
if i < len(fields) {
// TODO instead of the key use an additional number map?
processMap[column] = fields[i]
} else {
processMap[column] = ""
}
}
processInfo.Rows = append(processInfo.Rows, processMap)
}
}
func KillPorts(options KillPortsOptions) {
var findProcessOptions, findNameOptions, killCmdOptions CommandOptions
switch runtime.GOOS {
case "windows":
netstatPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "netstat.ps1"))
if err != nil {
fmt.Printf("Failed to extract netstat.ps1: %v", err)
}
tasklistPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "tasklist.ps1"))
if err != nil {
fmt.Printf("Failed to extract tasklist.ps1: %v", err)
}
findProcessOptions = CommandOptions{
Command: "powershell",
Args: []string{"-ExecutionPolicy", "Bypass", "-NoProfile", "-c", netstatPath},
GetOutput: true,
}
findNameOptions = CommandOptions{
Command: "powershell",
Args: []string{"-ExecutionPolicy", "Bypass", "-NoProfile", "-c", tasklistPath},
GetOutput: true,
}
case "darwin":
netstatPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "netstat_macos.sh"))
if err != nil {
fmt.Printf("Failed to extract netstat_macos.sh: %v", err)
}
psPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "ps_macos.sh"))
if err != nil {
fmt.Printf("Failed to extract ps_macos.sh: %v", err)
}
findProcessOptions = CommandOptions{
Command: "sh",
Args: []string{netstatPath},
GetOutput: true,
}
findNameOptions = CommandOptions{
Command: "sh",
Args: []string{psPath},
GetOutput: true,
}
case "linux":
netstatPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "netstat_linux.sh"))
if err != nil {
fmt.Printf("Failed to extract netstat_linux.sh: %v", err)
}
psPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "ps_linux.sh"))
if err != nil {
fmt.Printf("Failed to extract ps_linux.sh: %v", err)
}
findProcessOptions = CommandOptions{
Command: "sh",
Args: []string{netstatPath},
GetOutput: true,
}
findNameOptions = CommandOptions{
Command: "sh",
Args: []string{psPath},
GetOutput: true,
}
case "freebsd", "openbsd", "netbsd", "dragonfly":
netstatPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "netstat_bsd.sh"))
if err != nil {
fmt.Printf("Failed to extract netstat_bsd.sh: %v", err)
}
psPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "ps_bsd.sh"))
if err != nil {
fmt.Printf("Failed to extract ps_bsd.sh: %v", err)
}
findProcessOptions = CommandOptions{
Command: "sh",
Args: []string{netstatPath},
GetOutput: true,
}
findNameOptions = CommandOptions{
Command: "sh",
Args: []string{psPath},
GetOutput: true,
}
case "aix", "solaris", "illumos":
netstatPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "netstat_unix.sh"))
if err != nil {
fmt.Printf("Failed to extract netstat_unix.sh: %v", err)
}
psPath, err := GetFilePathFromPackage(JoinAndConvertPathToOSFormat("scripts", "ps_unix.sh"))
if err != nil {
fmt.Printf("Failed to extract ps_unix.sh: %v", err)
}
findProcessOptions = CommandOptions{
Command: "sh",
Args: []string{netstatPath},
GetOutput: true,
}
findNameOptions = CommandOptions{
Command: "sh",
Args: []string{psPath},
GetOutput: true,
}
default:
fmt.Printf("Unsupported OS: %s", runtime.GOOS)
return
}
findProcessOutput, err := RunCommandWithOptions(findProcessOptions)
if err != nil {
fmt.Printf("Error finding processes: %v\n", err)
return
}
findNameOutput, err := RunCommandWithOptions(findNameOptions)
if err != nil {
fmt.Printf("Error finding processes: %v\n", err)
return
}
infoFindProcess := KillPortsProcessInfo{
PIDIndex: -1,
Output: findProcessOutput,
Lines: strings.Split(findProcessOutput, "\n"),
Regex: regexp.MustCompile(`\s{2,}`),
}
infoFindName := KillPortsProcessInfo{
PIDIndex: -1,
Output: findNameOutput,
Lines: strings.Split(findNameOutput, "\n"),
Regex: regexp.MustCompile(`\s{2,}`),
}
switch runtime.GOOS {
case "darwin":
infoFindProcess.Regex = regexp.MustCompile(`\s{2,}|->`)
}
findPIDIndex(&infoFindProcess)
findPIDIndex(&infoFindName)
processMap := make(map[string]string)
for _, line := range strings.Split(findNameOutput, "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
pid := fields[0]
name := fields[1]
processMap[pid] = name
}
}
initProcessInfo(&infoFindProcess)
initProcessInfo(&infoFindName)
var rowsWithPIDAndName []map[string]string
for _, row := range infoFindProcess.Rows {
var nameRow map[string]string
for _, r := range infoFindName.Rows {
if r["PID"] == row["PID"] {
nameRow = r
break
}
}
unionRow := make(map[string]string)
for k, v := range row {
unionRow[k] = v
}
for k, v := range nameRow {
unionRow[k] = v
}
rowsWithPIDAndName = append(rowsWithPIDAndName, unionRow)
}
var pidsToDelete []string
for _, row := range rowsWithPIDAndName {
for _, port := range options.Ports {
formattedPort := fmt.Sprintf(":%s", port)
isInTargetProgramNames := true
if len(options.ProgramNames) != 0 {
isInTargetProgramNames = ArrayContainsAny(options.ProgramNames, []string{row["Name"]})
}
foreignAddressContainsPort := strings.Contains(row["Foreign Address"], formattedPort)
localAddressContainsPort := strings.Contains(row["Local Address"], formattedPort)
pidIsNotZero := row["PID"] != "0"
stateIsListen := strings.Contains(strings.ToLower(row["State"]), "listen")
stateIsTimeWait := strings.Contains(strings.ToLower(row["State"]), "timewait")
switch runtime.GOOS {
// TODO see if you need listening
case "windows":
cantKillByName := ArrayContainsAny([]string{"svchost", "SearchHost"}, []string{row["Name"]})
if ((foreignAddressContainsPort || localAddressContainsPort) && stateIsListen || (stateIsTimeWait && pidIsNotZero && isInTargetProgramNames)) && !cantKillByName {
pid := row["PID"]
pidsToDelete = append(pidsToDelete, pid)
}
case "darwin":
cantKillByName := ArrayContainsAny([]string{"svchost", "SearchHost"}, []string{row["Name"]})
if ((foreignAddressContainsPort || localAddressContainsPort) && stateIsListen || (stateIsTimeWait && pidIsNotZero && isInTargetProgramNames)) && !cantKillByName {
pid := row["PID"]
pidsToDelete = append(pidsToDelete, pid)
}
default:
fmt.Printf("Unsupported OS: %s", runtime.GOOS)
return
}
}
}
pidsToDelete = RemoveDuplicates(pidsToDelete)
if options.OutputFile != "" {
file, err := os.Create(ConvertPathToOSFormat(options.OutputFile))
if err != nil {
fmt.Printf("Failed to create output file: %v\n", err)
return
}
defer file.Close()
writer := bufio.NewWriter(file)
defer writer.Flush()
firstRow := rowsWithPIDAndName[0]
columnNames := make([]string, 0, len(firstRow))
for key := range firstRow {
columnNames = append(columnNames, key)
}
// Write column names
writer.WriteString(strings.Join(columnNames, ",") + "\n")
// Write each row
for _, row := range rowsWithPIDAndName {
values := make([]string, len(columnNames))
for i, columnName := range columnNames {
values[i] = row[columnName]
}
writer.WriteString(strings.Join(values, ",") + "\n")
}
var deleteProcessHeader = strings.Join(
append([]string{"Processes", "to", "Delete:"}, strings.Split(strings.Repeat("==== ", len(columnNames)-1), " ")...), ",",
) + "\n"
writer.WriteString(deleteProcessHeader)
writer.WriteString(strings.Join(columnNames, ",") + "\n")
for _, row := range rowsWithPIDAndName {
for _, pid := range pidsToDelete {
if row["PID"] == pid {
values := make([]string, len(columnNames))
for i, columnName := range columnNames {
values[i] = row[columnName]
}
writer.WriteString(strings.Join(values, ",") + "\n")
}
}
}
fmt.Printf("Process details saved to %s\n", options.OutputFile)
if options.OpenOutputFile {
vscodeOpenFileOptions := CommandOptions{
Command: "code",
Args: []string{options.OutputFile},
NonBlocking: true,
}
RunCommandWithOptions(vscodeOpenFileOptions)
}
}
if len(pidsToDelete) == 0 {
fmt.Println("No processes found on the specified ports")
return
}
if options.DryRun {
return
}
var killArgs []string
if runtime.GOOS == "windows" {
killArgs = append(killArgs, "/F")
for _, pid := range pidsToDelete {
killArgs = append(killArgs, "/PID", pid)
}
killCmdOptions = CommandOptions{
Command: "taskkill",
Args: killArgs,
}
} else {
killArgs = append(killArgs, "-9")
killArgs = append(killArgs, pidsToDelete...)
killCmdOptions = CommandOptions{
Command: "kill",
Args: killArgs,
}
}
_, err = RunCommandWithOptions(killCmdOptions)
if err != nil {
fmt.Printf("Failed to kill processes: %v\n", err)
} else {
fmt.Println("Killed processes on the specified ports")
}
}
type TakeVariableArgsStruct struct {
Prompt string
ErrMsg string
Default string
Delimiter string
}
type TakeVariableArgsResultStruct struct {
InputString string
InputArray []string
}
func TakeVariableArgs(obj TakeVariableArgsStruct) TakeVariableArgsResultStruct {
var innerScriptArguments []string
prompt0 := obj.Prompt
if obj.Delimiter == "" {
obj.Delimiter = " "
}
if obj.Default != "" {
prompt0 = fmt.Sprintf("%s (Default is %s)", obj.Prompt, obj.Default)
}
var input string
if obj.Default != "" && GLOBAL_VARS.NonInteractive.Global {
input = obj.Default
innerScriptArguments = strings.Split(input, obj.Delimiter)
} else {
fmt.Println(prompt0)
fmt.Println("Enter the arguments to pass to the script (press ENTER to enter another argument, leave blank and press ENTER once done):")
for {
var argument string
fmt.Scanln(&argument)
if strings.TrimSpace(argument) == "" {
break
}
innerScriptArguments = append(innerScriptArguments, argument)
}
}
input = strings.Join(innerScriptArguments, obj.Delimiter)
if input == "" && obj.ErrMsg != "" {
panic(obj.ErrMsg)
} else if input == "" && obj.Default != "" {
input = obj.Default
innerScriptArguments = strings.Split(obj.Default, obj.Delimiter)
}
return TakeVariableArgsResultStruct{
InputString: input,
InputArray: innerScriptArguments,
}
}
type GetInputFromStdinStruct struct {
Prompt []string
ErrMsg string
Default string
}
func GetInputFromStdin(obj GetInputFromStdinStruct) string {
if len(obj.Default) != 0 && GLOBAL_VARS.NonInteractive.Global {
return obj.Default
}
if len(obj.Prompt) == 0 {
obj.Prompt = []string{"Enter your input: "} // Default value
} else {
obj.Prompt[0] += " "
}
// Create a new scanner to read from stdin
scanner := bufio.NewScanner(os.Stdin)
if obj.Default != "" {
fmt.Printf("%s (Default is %s) ", obj.Prompt[0], obj.Default)
} else {
fmt.Print(obj.Prompt[0])
}
// Read the next line of input from stdin
if !scanner.Scan() && scanner.Err() != nil {
fmt.Println("Error reading input:", scanner.Err())
return ""
}
input := scanner.Text()
if input == "" && obj.Default != "" {
input = obj.Default
} else if input == "" && obj.ErrMsg != "" {
panic(obj.ErrMsg)
}
return input
}
type ShellCommandOutput struct{}
func (c ShellCommandOutput) Write(p []byte) (int, error) {
fmt.Println(string(p))
return len(p), nil
}
func RunCommand(command string, args []string) {
fullCommand := fmt.Sprintf("Running command: %s %s", command, strings.Join(args, " "))
fmt.Println(fullCommand)
cmd := exec.Command(command, args...)
// cmd.Stdout = ShellCommandOutput{}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
msg := fmt.Sprintf("Could not run command %s %s \n This was the err %s", command, strings.Join(args, " "), err.Error())
fmt.Println(msg)
// panic(msg)
}
}
// Deprecated: Its recommended to use RunCommandWithOptions instead. Wont be moved anytime soon
func RunCommandInSpecificDirectory(command string, args []string, targetDir string) {
fullCommand := fmt.Sprintf("Running command: %s %s", command, strings.Join(args, " "))
fmt.Println(fullCommand)
cmd := exec.Command(command, args...)
cmd.Dir = targetDir
// cmd.Stdout = ShellCommandOutput{}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
msg := fmt.Sprintf("Could not run command %s %s \n This was the err %s", command, strings.Join(args, " "), err.Error())
fmt.Println(msg)
// panic(msg)
}
}
// Deprecated: Its recommended to use RunCommandWithOptions instead. Wont be moved anytime soon
func RunCommandAndGetOutput(command string, args []string) string {
fullCommand := fmt.Sprintf("Running command: %s %s", command, strings.Join(args, " "))
fmt.Println(fullCommand)
output, err := exec.Command(command, args...).Output()
if err != nil {
msg := fmt.Sprintf("Could not run command %s %s \n This was the err %s", command, strings.Join(args, " "), err.Error())
fmt.Println(msg)
// panic(msg)
}
return string(output)
}
// Deprecated: Its recommended to use RunCommandWithOptions instead. Wont be moved anytime soon
func RunCommandInSpecifcDirectoryAndGetOutput(command string, args []string, targetDir string) string {
fullCommand := fmt.Sprintf("Running command: %s %s", command, strings.Join(args, " "))
fmt.Println(fullCommand)
cmd := exec.Command(command, args...)
cmd.Dir = targetDir
output, err := cmd.Output()
if err != nil {
msg := fmt.Sprintf("Could not run command %s %s \n This was the err %s", command, strings.Join(args, " "), err.Error())
fmt.Println(msg)
// panic(msg)
}
return string(output)
}
type DualWriter struct {
TerminalWriter io.Writer
Buffer *bytes.Buffer
}
func (w DualWriter) Write(p []byte) (n int, err error) {
n, err = w.TerminalWriter.Write(p)
if err != nil {
return n, err
}
// Write to the buffer as well
bufferBytes, bufferErr := w.Buffer.Write(p)
if bufferErr != nil {
return bufferBytes, bufferErr
}
return n, nil
}
type CommandOptions struct {
CmdObj *exec.Cmd
Self *CommandOptions
Command string
Args []string
TargetDir string
GetOutput bool
PrintOutput bool
PrintOutputOnly bool
PanicOnError bool
NonBlocking bool
IsInputFromProgram bool
IsElevated bool
EnvVars map[string]string
ExitRegex string
}
func (c CommandOptions) EndProcess() error {
var cmd *exec.Cmd
if c.Self != nil && c.Self.CmdObj != nil {
cmd = c.Self.CmdObj
} else {
cmd = c.CmdObj
}
if cmd != nil {
return cmd.Process.Kill()
}
return nil
}
func RunCommandWithOptions(options CommandOptions) (string, error) {
if options.IsElevated {
return "", RunElevatedCommand(options.Command, options.Args)
}
fullCommand := fmt.Sprintf("Running command: %s %s\n", options.Command, strings.Join(options.Args, " "))
fmt.Println(fullCommand)
cmd := exec.Command(options.Command, options.Args...)
if options.Self != nil {
options.Self.CmdObj = cmd
}
if options.TargetDir != "" {
cmd.Dir = options.TargetDir
}
if options.IsInputFromProgram != true {
cmd.Stdin = os.Stdin
}
if options.EnvVars != nil {
for key, value := range options.EnvVars {
os.Setenv(key, value)
}
cmd.Env = nil
}
// Creating buffers and DualWriters for stdout and stderr
if options.ExitRegex == "" {
var stdoutBuffer, stderrBuffer bytes.Buffer
stdoutWriter := DualWriter{TerminalWriter: os.Stdout, Buffer: &stdoutBuffer}
stderrWriter := DualWriter{TerminalWriter: os.Stderr, Buffer: &stderrBuffer}
cmd.Stdout = stdoutWriter
if options.PrintOutput == false {
cmd.Stdout = &stdoutBuffer
}
if options.PrintOutputOnly == true {
cmd.Stdout = os.Stdout
}
cmd.Stderr = stderrWriter
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
if cmd.Process != nil {
cmd.Process.Signal(sig)
}
}()
var err error
if options.NonBlocking {
err = cmd.Start() // Non-blocking execution if NonBlocking is true
} else {
err = cmd.Run() // Default to blocking execution
}
if err != nil {
// Construct error message
msg := fmt.Sprintf(
"Could not run command %s %s\n\nThis was the err: %s \n %s\n\n",
options.Command,
strings.Join(options.Args, " "),
err.Error(),
fmt.Sprintf("Standard Error: %s\n", stderrBuffer.String()),
)
fmt.Println(msg)
if options.PanicOnError {
panic(msg)
}
return "", err
}
if options.GetOutput {
return stdoutBuffer.String(), nil
}
return "", nil
} else {
re, compileErr := regexp.Compile(options.ExitRegex)
if compileErr != nil {
return "", fmt.Errorf("invalid regex pattern '%s': %w", options.ExitRegex, compileErr)
}
// We'll read from StdoutPipe to monitor lines in real-time
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return "", err
}
// Start the command
if options.NonBlocking {
// Non-blocking: start now, but we'll watch the stdout in a goroutine
err = cmd.Start()
if err != nil {
return "", err
}
} else {
// We'll block on .Run() after we finish setting up the reading logic
// but we must start first to get the pipes.
err = cmd.Start()
if err != nil {
return "", err
}
}
// Buffers for final output
var stdoutBuffer, stderrBuffer bytes.Buffer
// Start a goroutine to handle stderr (if you want to capture it)
go func() {
ioScanner := bufio.NewScanner(stderrPipe)
for ioScanner.Scan() {
line := ioScanner.Text()
stderrBuffer.WriteString(line + "\n")
// Optionally, print live
if options.PrintOutput || options.PrintOutputOnly {
fmt.Fprintln(os.Stderr, line)
}
}
}()
// We'll monitor stdout line by line for a match
foundRegex := make(chan bool, 1)
go func() {
ioScanner := bufio.NewScanner(stdoutPipe)
for ioScanner.Scan() {
line := ioScanner.Text()
// Always store in the buffer
stdoutBuffer.WriteString(line + "\n")
// Optionally print
if options.PrintOutput || options.PrintOutputOnly {
fmt.Fprintln(os.Stdout, line)
}
// Check regex
if re.MatchString(line) {
foundRegex <- true
return
}
}
close(foundRegex)
}()
// Also forward signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
if cmd.Process != nil {
cmd.Process.Signal(sig)
}
}()
if options.NonBlocking {
// NonBlocking: we wait in the background for a match
go func() {
<-foundRegex
// We found the line => kill the process or do what you'd like
cmd.Process.Kill()
}()
return "", nil
} else {
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-foundRegex:
_ = cmd.Process.Kill()
// Optionally wait for final exit
<-done
case err = <-done:
// The process ended on its own
}
// Now check for any run error
if err != nil {
msg := fmt.Sprintf(
"Could not run command %s %s\n\nThis was the err: %s\n%s\n\n",
options.Command,
strings.Join(options.Args, " "),
err.Error(),
fmt.Sprintf("Standard Error: %s\n", stderrBuffer.String()),
)
fmt.Println(msg)
if options.PanicOnError {
panic(msg)
}
return stdoutBuffer.String(), err
}
// Finally, return the captured stdout if requested
if options.GetOutput {
return stdoutBuffer.String(), nil
}
return "", nil
}
}
}
// Deprecated: Its recommended to use RunCommandWithOptions instead. Wont be moved anytime soon
func RunElevatedCommand(command string, args []string) error {
var elevatedCommand string
var elevatedArgs []string
switch runtime.GOOS {
case "windows":
elevatedCommand = "powershell"
elevatedArgs = []string{"-Command", fmt.Sprintf(`Start-Process cmd -ArgumentList '/c %s %s' -Verb RunAs -Wait`, command, JoinArgs(args))}
case "darwin", "linux":
elevatedCommand = "sudo"
elevatedArgs = append([]string{command}, args...)
default:
return fmt.Errorf("unsupported platform")
}
options := CommandOptions{
Command: elevatedCommand,
Args: elevatedArgs,
GetOutput: true,
PrintOutput: true,
NonBlocking: false,
}
_, err := RunCommandWithOptions(options)
return err
}