-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecx.go
More file actions
1386 lines (1289 loc) · 31.4 KB
/
execx.go
File metadata and controls
1386 lines (1289 loc) · 31.4 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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package execx
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/term"
)
type envMode int
type pipeMode int
const (
envInherit envMode = iota
envOnly
envAppend
)
const (
pipeStrict pipeMode = iota
pipeBestEffort
)
// Command constructs a new command without executing it.
// @group Construction
//
// Example: command
//
// cmd := execx.Command("printf", "hello")
// out, _ := cmd.Output()
// fmt.Print(out)
// // hello
func Command(name string, args ...string) *Cmd {
cmd := &Cmd{
name: name,
args: append([]string{}, args...),
envMode: envInherit,
pipeMode: pipeStrict,
}
cmd.root = cmd
return cmd
}
// Cmd represents a single command invocation or a pipeline stage.
type Cmd struct {
name string
args []string
env map[string]string
envMode envMode
ctx context.Context
cancel context.CancelFunc
dir string
stdin io.Reader
onStdout func(string)
onStderr func(string)
stdoutW io.Writer
stderrW io.Writer
sysProcAttr *syscall.SysProcAttr
onExecCmd func(*exec.Cmd)
usePTY bool
next *Cmd
root *Cmd
pipeMode pipeMode
shadowPrint bool
shadowConfig shadowConfig
}
// Arg appends arguments to the command.
// @group Arguments
//
// Example: add args
//
// cmd := execx.Command("printf").Arg("hello")
// out, _ := cmd.Output()
// fmt.Print(out)
// // hello
func (c *Cmd) Arg(values ...any) *Cmd {
for _, value := range values {
switch v := value.(type) {
case string:
c.args = append(c.args, v)
case []string:
c.args = append(c.args, v...)
case map[string]string:
keys := make([]string, 0, len(v))
for key := range v {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
c.args = append(c.args, key, v[key])
}
default:
c.args = append(c.args, fmt.Sprint(v))
}
}
return c
}
// Env adds environment variables to the command.
// @group Environment
//
// Example: set env
//
// cmd := execx.Command("go", "env", "GOOS").Env("MODE=prod")
// fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// // #bool true
func (c *Cmd) Env(values ...any) *Cmd {
if c.env == nil {
c.env = map[string]string{}
}
for _, value := range values {
switch v := value.(type) {
case string:
key, val, _ := strings.Cut(v, "=")
c.env[key] = val
case []string:
for _, entry := range v {
key, val, _ := strings.Cut(entry, "=")
c.env[key] = val
}
case map[string]string:
for key, val := range v {
c.env[key] = val
}
default:
key, val, _ := strings.Cut(fmt.Sprint(v), "=")
c.env[key] = val
}
}
return c
}
// EnvInherit restores default environment inheritance.
// @group Environment
//
// Example: inherit env
//
// cmd := execx.Command("go", "env", "GOOS").EnvInherit()
// fmt.Println(len(cmd.EnvList()) > 0)
// // #bool true
func (c *Cmd) EnvInherit() *Cmd {
c.envMode = envInherit
return c
}
// EnvOnly ignores the parent environment.
// @group Environment
//
// Example: replace env
//
// cmd := execx.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
// fmt.Println(strings.Join(cmd.EnvList(), ","))
// // #string A=1
func (c *Cmd) EnvOnly(values map[string]string) *Cmd {
c.envMode = envOnly
c.env = map[string]string{}
for key, val := range values {
c.env[key] = val
}
return c
}
// EnvAppend merges variables into the inherited environment.
// @group Environment
//
// Example: append env
//
// cmd := execx.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
// fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// // #bool true
func (c *Cmd) EnvAppend(values map[string]string) *Cmd {
c.envMode = envAppend
if c.env == nil {
c.env = map[string]string{}
}
for key, val := range values {
c.env[key] = val
}
return c
}
// Dir sets the working directory.
// @group WorkingDir
//
// Example: change dir
//
// dir := os.TempDir()
// out, _ := execx.Command("pwd").
// Dir(dir).
// OutputTrimmed()
// fmt.Println(out == dir)
// // #bool true
func (c *Cmd) Dir(path string) *Cmd {
c.dir = path
return c
}
// WithContext binds the command to a context.
// @group Context
//
// Example: with context
//
// ctx, cancel := context.WithTimeout(context.Background(), time.Second)
// defer cancel()
// res, _ := execx.Command("go", "env", "GOOS").WithContext(ctx).Run()
// fmt.Println(res.ExitCode == 0)
// // #bool true
func (c *Cmd) WithContext(ctx context.Context) *Cmd {
if c.cancel != nil {
c.cancel()
c.cancel = nil
}
c.ctx = ctx
return c
}
// WithTimeout binds the command to a timeout.
// @group Context
//
// Example: with timeout
//
// res, _ := execx.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
// fmt.Println(res.ExitCode == 0)
// // #bool true
func (c *Cmd) WithTimeout(d time.Duration) *Cmd {
parent := c.ctx
if c.cancel != nil {
c.cancel()
c.cancel = nil
parent = nil
}
if parent == nil || parent.Err() != nil {
parent = context.Background()
}
c.ctx, c.cancel = context.WithTimeout(parent, d)
return c
}
// WithDeadline binds the command to a deadline.
// @group Context
//
// Example: with deadline
//
// res, _ := execx.Command("go", "env", "GOOS").WithDeadline(time.Now().Add(2 * time.Second)).Run()
// fmt.Println(res.ExitCode == 0)
// // #bool true
func (c *Cmd) WithDeadline(t time.Time) *Cmd {
parent := c.ctx
if c.cancel != nil {
c.cancel()
c.cancel = nil
parent = nil
}
if parent == nil || parent.Err() != nil {
parent = context.Background()
}
c.ctx, c.cancel = context.WithDeadline(parent, t)
return c
}
// StdinString sets stdin from a string.
// @group Input
//
// Example: stdin string
//
// out, _ := execx.Command("cat").
// StdinString("hi").
// Output()
// fmt.Println(out)
// // #string hi
func (c *Cmd) StdinString(input string) *Cmd {
c.stdin = strings.NewReader(input)
return c
}
// StdinBytes sets stdin from bytes.
// @group Input
//
// Example: stdin bytes
//
// out, _ := execx.Command("cat").
// StdinBytes([]byte("hi")).
// Output()
// fmt.Println(out)
// // #string hi
func (c *Cmd) StdinBytes(input []byte) *Cmd {
c.stdin = bytes.NewReader(input)
return c
}
// StdinReader sets stdin from an io.Reader.
// @group Input
//
// Example: stdin reader
//
// out, _ := execx.Command("cat").
// StdinReader(strings.NewReader("hi")).
// Output()
// fmt.Println(out)
// // #string hi
func (c *Cmd) StdinReader(reader io.Reader) *Cmd {
c.stdin = reader
return c
}
// StdinFile sets stdin from a file.
// @group Input
//
// Example: stdin file
//
// file, _ := os.CreateTemp("", "execx-stdin")
// _, _ = file.WriteString("hi")
// _, _ = file.Seek(0, 0)
// out, _ := execx.Command("cat").
// StdinFile(file).
// Output()
// fmt.Println(out)
// // #string hi
func (c *Cmd) StdinFile(file *os.File) *Cmd {
c.stdin = file
return c
}
// OnStdout registers a line callback for stdout.
// @group Streaming
//
// Example: stdout lines
//
// _, _ = execx.Command("printf", "hi\n").
// OnStdout(func(line string) { fmt.Println(line) }).
// Run()
// // hi
func (c *Cmd) OnStdout(fn func(string)) *Cmd {
c.onStdout = fn
return c
}
// OnStderr registers a line callback for stderr.
// @group Streaming
//
// Example: stderr lines
//
// _, err := execx.Command("go", "env", "-badflag").
// OnStderr(func(line string) {
// fmt.Println(line)
// }).
// Run()
// fmt.Println(err == nil)
// // flag provided but not defined: -badflag
// // usage: go env [-json] [-changed] [-u] [-w] [var ...]
// // Run 'go help env' for details.
// // false
func (c *Cmd) OnStderr(fn func(string)) *Cmd {
c.onStderr = fn
return c
}
// StdoutWriter sets a raw writer for stdout.
// @group Streaming
//
// When the writer is a terminal and no line callbacks or combined output are enabled,
// execx passes stdout through directly and does not buffer it for results.
//
// Example: stdout writer
//
// var out strings.Builder
// _, _ = execx.Command("printf", "hello").
// StdoutWriter(&out).
// Run()
// fmt.Print(out.String())
// // hello
func (c *Cmd) StdoutWriter(w io.Writer) *Cmd {
c.stdoutW = w
return c
}
// StderrWriter sets a raw writer for stderr.
// @group Streaming
//
// When the writer is a terminal and no line callbacks or combined output are enabled,
// execx passes stderr through directly and does not buffer it for results.
//
// Example: stderr writer
//
// var out strings.Builder
// _, err := execx.Command("go", "env", "-badflag").
// StderrWriter(&out).
// Run()
// fmt.Print(out.String())
// fmt.Println(err == nil)
// // flag provided but not defined: -badflag
// // usage: go env [-json] [-changed] [-u] [-w] [var ...]
// // Run 'go help env' for details.
// // false
func (c *Cmd) StderrWriter(w io.Writer) *Cmd {
c.stderrW = w
return c
}
// WithPTY attaches stdout/stderr to a pseudo-terminal.
// @group Streaming
//
// When enabled, stdout and stderr are merged into a single stream. OnStdout and
// OnStderr both receive the same lines, and Result.Stderr remains empty.
// Platforms without PTY support return an error when the command runs.
//
// Example: with pty
//
// _, _ = execx.Command("printf", "hi").
// WithPTY().
// OnStdout(func(line string) { fmt.Println(line) }).
// Run()
// // hi
func (c *Cmd) WithPTY() *Cmd {
c.rootCmd().usePTY = true
return c
}
// OnExecCmd registers a callback to mutate the underlying exec.Cmd before start.
// @group Execution
//
// Example: exec cmd
//
// _, _ = execx.Command("printf", "hi").
// OnExecCmd(func(cmd *exec.Cmd) {
// cmd.SysProcAttr = &syscall.SysProcAttr{}
// }).
// Run()
func (c *Cmd) OnExecCmd(fn func(*exec.Cmd)) *Cmd {
c.onExecCmd = fn
return c
}
// Pipe appends a new command to the pipeline. Pipelines run on all platforms.
// @group Pipelining
//
// Example: pipe
//
// out, _ := execx.Command("printf", "go").
// Pipe("tr", "a-z", "A-Z").
// OutputTrimmed()
// fmt.Println(out)
// // #string GO
func (c *Cmd) Pipe(name string, args ...string) *Cmd {
root := c.rootCmd()
next := &Cmd{
name: name,
args: append([]string{}, args...),
envMode: envInherit,
pipeMode: root.pipeMode,
root: root,
}
last := root
for last.next != nil {
last = last.next
}
last.next = next
return next
}
// PipeStrict sets strict pipeline semantics (stop on first failure).
// @group Pipelining
//
// Example: strict
//
// res, _ := execx.Command("false").
// Pipe("printf", "ok").
// PipeStrict().
// Run()
// fmt.Println(res.ExitCode != 0)
// // #bool true
func (c *Cmd) PipeStrict() *Cmd {
c.rootCmd().pipeMode = pipeStrict
return c
}
// PipeBestEffort sets best-effort pipeline semantics (run all stages, surface the first error).
// @group Pipelining
//
// Example: best effort
//
// res, _ := execx.Command("false").
// Pipe("printf", "ok").
// PipeBestEffort().
// Run()
// fmt.Print(res.Stdout)
// // ok
func (c *Cmd) PipeBestEffort() *Cmd {
c.rootCmd().pipeMode = pipeBestEffort
return c
}
// Args returns the argv slice used for execution.
// @group Debugging
//
// Example: args
//
// cmd := execx.Command("go", "env", "GOOS")
// fmt.Println(strings.Join(cmd.Args(), " "))
// // #string go env GOOS
func (c *Cmd) Args() []string {
args := make([]string, 0, len(c.args)+1)
args = append(args, c.name)
args = append(args, c.args...)
return args
}
// EnvList returns the environment list for execution.
// @group Environment
//
// Example: env list
//
// cmd := execx.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
// fmt.Println(strings.Join(cmd.EnvList(), ","))
// // #string A=1
func (c *Cmd) EnvList() []string {
return buildEnv(c.envMode, c.env)
}
// String returns a human-readable representation of the command.
// @group Debugging
//
// Example: string
//
// cmd := execx.Command("echo", "hello world", "it's")
// fmt.Println(cmd.String())
// // #string echo "hello world" it's
func (c *Cmd) String() string {
parts := make([]string, 0, len(c.args)+1)
parts = append(parts, c.name)
for _, arg := range c.args {
if strings.ContainsAny(arg, " \t\n\r") {
parts = append(parts, strconv.Quote(arg))
continue
}
parts = append(parts, arg)
}
return strings.Join(parts, " ")
}
// ShellEscaped returns a shell-escaped string for logging only.
// @group Debugging
//
// Example: shell escaped
//
// cmd := execx.Command("echo", "hello world", "it's")
// fmt.Println(cmd.ShellEscaped())
// // #string echo 'hello world' "it's"
func (c *Cmd) ShellEscaped() string {
parts := make([]string, 0, len(c.args)+1)
parts = append(parts, shellEscape(c.name))
for _, arg := range c.args {
parts = append(parts, shellEscape(arg))
}
return strings.Join(parts, " ")
}
// ShadowPrint configures shadow printing for this command chain.
// @group Shadow Print
//
// Example: shadow print
//
// _, _ = execx.Command("bash", "-c", `echo "hello world"`).
// ShadowPrint().
// OnStdout(func(line string) { fmt.Println(line) }).
// Run()
// // execx > bash -c 'echo "hello world"'
// //
// // hello world
// //
// // execx > bash -c 'echo "hello world"' (1ms)
//
// Example: shadow print options
//
// mask := func(cmd string) string {
// return strings.ReplaceAll(cmd, "token", "***")
// }
// formatter := func(ev execx.ShadowEvent) string {
// return fmt.Sprintf("shadow: %s %s", ev.Phase, ev.Command)
// }
// _, _ = execx.Command("bash", "-c", `echo "hello world"`).
// ShadowPrint(
// execx.WithPrefix("execx"),
// execx.WithMask(mask),
// execx.WithFormatter(formatter),
// ).
// OnStdout(func(line string) { fmt.Println(line) }).
// Run()
// // shadow: before bash -c 'echo "hello world"'
// // hello world
// // shadow: after bash -c 'echo "hello world"'
func (c *Cmd) ShadowPrint(opts ...ShadowOption) *Cmd {
root := c.rootCmd()
root.shadowConfig = defaultShadowConfig()
for _, opt := range opts {
opt(&root.shadowConfig)
}
root.shadowPrint = true
return c
}
// ShadowOff disables shadow printing for this command chain, preserving configuration.
// @group Shadow Print
//
// Example: shadow off
//
// _, _ = execx.Command("printf", "hi").ShadowPrint().ShadowOff().Run()
func (c *Cmd) ShadowOff() *Cmd {
root := c.rootCmd()
root.shadowPrint = false
return c
}
// ShadowOn enables shadow printing using the previously configured options.
// @group Shadow Print
//
// Example: shadow on
//
// cmd := execx.Command("printf", "hi").
// ShadowPrint(execx.WithPrefix("run"))
// cmd.ShadowOff()
// _, _ = cmd.ShadowOn().Run()
// // run > printf hi
// // run > printf hi (1ms)
func (c *Cmd) ShadowOn() *Cmd {
root := c.rootCmd()
if root.shadowConfig.prefix == "" {
root.shadowConfig = defaultShadowConfig()
}
root.shadowPrint = true
return c
}
// WithPrefix sets the shadow print prefix.
// @group Shadow Print
//
// Example: shadow prefix
//
// _, _ = execx.Command("printf", "hi").ShadowPrint(execx.WithPrefix("run")).Run()
// // run > printf hi
// // run > printf hi (1ms)
func WithPrefix(prefix string) ShadowOption {
return func(cfg *shadowConfig) {
cfg.prefix = prefix
}
}
// WithMask applies a masker to the shadow-printed command string.
// @group Shadow Print
//
// Example: shadow mask
//
// mask := func(cmd string) string {
// return strings.ReplaceAll(cmd, "secret", "***")
// }
// _, _ = execx.Command("printf", "secret").ShadowPrint(execx.WithMask(mask)).Run()
// // execx > printf ***
// // execx > printf *** (1ms)
func WithMask(fn func(string) string) ShadowOption {
return func(cfg *shadowConfig) {
cfg.mask = fn
}
}
// WithFormatter sets a formatter for ShadowPrint output.
// @group Shadow Print
//
// Example: shadow formatter
//
// formatter := func(ev execx.ShadowEvent) string {
// return fmt.Sprintf("shadow: %s %s", ev.Phase, ev.Command)
// }
// _, _ = execx.Command("printf", "hi").ShadowPrint(execx.WithFormatter(formatter)).Run()
// // shadow: before printf hi
// // shadow: after printf hi
func WithFormatter(fn func(ShadowEvent) string) ShadowOption {
return func(cfg *shadowConfig) {
cfg.formatter = fn
}
}
// Run executes the command and returns the result and any error.
// @group Execution
//
// Example: run
//
// res, _ := execx.Command("go", "env", "GOOS").Run()
// fmt.Println(res.ExitCode == 0)
// // #bool true
func (c *Cmd) Run() (Result, error) {
if err := c.validatePTY(); err != nil {
return Result{Err: err, ExitCode: -1}, err
}
shadow := c.shadowPrintStart(false)
pipe := c.newPipeline(false, shadow)
pipe.start()
pipe.wait()
result, _ := pipe.primaryResult(c.rootCmd().pipeMode)
shadow.finish()
return result, result.Err
}
// Output executes the command and returns stdout and any error.
// @group Execution
//
// Example: output
//
// out, _ := execx.Command("printf", "hello").Output()
// fmt.Print(out)
// // hello
func (c *Cmd) Output() (string, error) {
result, err := c.Run()
return result.Stdout, err
}
// OutputBytes executes the command and returns stdout bytes and any error.
// @group Execution
//
// Example: output bytes
//
// out, _ := execx.Command("printf", "hello").OutputBytes()
// fmt.Println(string(out))
// // #string hello
func (c *Cmd) OutputBytes() ([]byte, error) {
result, err := c.Run()
return []byte(result.Stdout), err
}
// OutputTrimmed executes the command and returns trimmed stdout and any error.
// @group Execution
//
// Example: output trimmed
//
// out, _ := execx.Command("printf", "hello\n").OutputTrimmed()
// fmt.Println(out)
// // #string hello
func (c *Cmd) OutputTrimmed() (string, error) {
result, err := c.Run()
return strings.TrimSpace(result.Stdout), err
}
// CombinedOutput executes the command and returns stdout+stderr and any error.
// @group Execution
//
// Example: combined output
//
// out, err := execx.Command("go", "env", "-badflag").CombinedOutput()
// fmt.Print(out)
// fmt.Println(err == nil)
// // flag provided but not defined: -badflag
// // usage: go env [-json] [-changed] [-u] [-w] [var ...]
// // Run 'go help env' for details.
// // false
func (c *Cmd) CombinedOutput() (string, error) {
if err := c.validatePTY(); err != nil {
return "", err
}
shadow := c.shadowPrintStart(false)
pipe := c.newPipeline(true, shadow)
pipe.start()
pipe.wait()
result, combined := pipe.primaryResult(c.rootCmd().pipeMode)
shadow.finish()
return combined, result.Err
}
// PipelineResults executes the command and returns per-stage results and any error.
// @group Pipelining
//
// Example: pipeline results
//
// results, _ := execx.Command("printf", "go").
// Pipe("tr", "a-z", "A-Z").
// PipelineResults()
// fmt.Printf("%+v", results)
// // [
// // {Stdout:go Stderr: ExitCode:0 Err:<nil> Duration:6.367208ms signal:<nil>}
// // {Stdout:GO Stderr: ExitCode:0 Err:<nil> Duration:4.976291ms signal:<nil>}
// // ]
func (c *Cmd) PipelineResults() ([]Result, error) {
if err := c.validatePTY(); err != nil {
return nil, err
}
shadow := c.shadowPrintStart(false)
pipe := c.newPipeline(false, shadow)
pipe.start()
pipe.wait()
results := pipe.results()
shadow.finish()
return results, firstResultErr(results)
}
// Start executes the command asynchronously.
// @group Execution
//
// Example: start
//
// proc := execx.Command("go", "env", "GOOS").Start()
// res, _ := proc.Wait()
// fmt.Println(res.ExitCode == 0)
// // #bool true
func (c *Cmd) Start() *Process {
if err := c.validatePTY(); err != nil {
proc := &Process{done: make(chan struct{})}
proc.finish(Result{Err: err, ExitCode: -1})
return proc
}
shadow := c.shadowPrintStart(true)
pipe := c.newPipeline(false, shadow)
pipe.start()
proc := &Process{
pipeline: pipe,
mode: c.rootCmd().pipeMode,
done: make(chan struct{}),
shadow: shadow,
}
go func() {
pipe.wait()
result, _ := pipe.primaryResult(proc.mode)
proc.finish(result)
}()
return proc
}
func (c *Cmd) ctxOrBackground() context.Context {
if c.ctx == nil {
return context.Background()
}
return c.ctx
}
func (c *Cmd) rootCmd() *Cmd {
if c.root != nil {
return c.root
}
return c
}
func (c *Cmd) execCmd() *exec.Cmd {
cmd := exec.CommandContext(c.ctxOrBackground(), c.name, c.args...)
if c.dir != "" {
cmd.Dir = c.dir
}
cmd.Env = buildEnv(c.envMode, c.env)
if c.sysProcAttr != nil {
cmd.SysProcAttr = c.sysProcAttr
}
if c.onExecCmd != nil {
c.onExecCmd(cmd)
}
return cmd
}
var isTerminalFunc = term.IsTerminal
var openPTYFunc = openPTY
var ptyCheckFunc = ptyCheck
func isTerminalWriter(w io.Writer) bool {
f, ok := w.(*os.File)
if !ok {
return false
}
return isTerminalFunc(int(f.Fd()))
}
func (c *Cmd) validatePTY() error {
root := c.rootCmd()
if !root.usePTY {
return nil
}
if root.next != nil {
return errors.New("execx: WithPTY is not supported with pipelines")
}
if err := ptyCheckFunc(); err != nil {
return err
}
return nil
}
func (c *Cmd) stdoutWriter(buf *bytes.Buffer, withCombined bool, combined *bytes.Buffer, shadow *shadowContext) io.Writer {
if c.stdoutW != nil && c.onStdout == nil && !withCombined {
if isTerminalWriter(c.stdoutW) {
return c.stdoutW
}
}
writers := []io.Writer{}
if c.stdoutW != nil {
writers = append(writers, c.stdoutW)
}
writers = append(writers, buf)
if withCombined {
writers = append(writers, combined)
}
if c.onStdout != nil {
writers = append(writers, &lineWriter{onLine: c.onStdout})
}
var out io.Writer = buf
if len(writers) > 1 {
out = io.MultiWriter(writers...)
}
return wrapShadowWriter(out, shadow)
}
func (c *Cmd) stderrWriter(buf *bytes.Buffer, withCombined bool, combined *bytes.Buffer, shadow *shadowContext) io.Writer {
if c.stderrW != nil && c.onStderr == nil && !withCombined {
if isTerminalWriter(c.stderrW) {
return c.stderrW
}
}
writers := []io.Writer{}
if c.stderrW != nil {
writers = append(writers, c.stderrW)
}
writers = append(writers, buf)
if withCombined {
writers = append(writers, combined)
}
if c.onStderr != nil {
writers = append(writers, &lineWriter{onLine: c.onStderr})
}
var out io.Writer = buf
if len(writers) > 1 {
out = io.MultiWriter(writers...)
}
return wrapShadowWriter(out, shadow)
}
func (c *Cmd) ptyWriter(buf *bytes.Buffer, withCombined bool, combined *bytes.Buffer, shadow *shadowContext) io.Writer {
writers := []io.Writer{}
if c.stdoutW != nil {
writers = append(writers, c.stdoutW)
}
if c.stderrW != nil && c.stderrW != c.stdoutW {
writers = append(writers, c.stderrW)
}
writers = append(writers, buf)
if withCombined {
writers = append(writers, combined)
}
if c.onStdout != nil || c.onStderr != nil {
writers = append(writers, &ptyLineWriter{onStdout: c.onStdout, onStderr: c.onStderr})
}
var out io.Writer = buf
if len(writers) > 1 {
out = io.MultiWriter(writers...)
}
return wrapShadowWriter(out, shadow)
}
type lineWriter struct {
onLine func(string)
buf bytes.Buffer
}
// Write buffers output and emits completed lines to the callback.
func (l *lineWriter) Write(p []byte) (int, error) {
if l.onLine == nil {
return len(p), nil
}
for _, b := range p {
if b == '\n' {
line := l.buf.String()
l.buf.Reset()
line = strings.TrimSuffix(line, "\r")
l.onLine(line)
continue
}
_ = l.buf.WriteByte(b)
}
return len(p), nil
}
type ptyLineWriter struct {
onStdout func(string)
onStderr func(string)
buf bytes.Buffer
}
// Write buffers output and emits completed lines to stdout/stderr callbacks.