MCPcopy Create free account
hub / github.com/cli/cli / runInTerminal

Function runInTerminal

script/ghmock/terminal.go:25–81  ·  view source on GitHub ↗

runInTerminal starts cmd in a pseudo-terminal, so gh can prompt as it does for a user, and types each keys entry once the screen settles. It returns cmd.Wait's error. The terminal answers gh's queries, such as where the cursor is, which survey's prompts need.

(ctx context.Context, cmd *exec.Cmd, keys []string)

Source from the content-addressed store, hash-verified

23// cmd.Wait's error. The terminal answers gh's queries, such as where the
24// cursor is, which survey's prompts need.
25func runInTerminal(ctx context.Context, cmd *exec.Cmd, keys []string) (terminalRun, error) {
26 ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: terminalCols, Rows: terminalRows})
27 if err != nil {
28 return terminalRun{}, fmt.Errorf("starting a terminal: %w", err)
29 }
30 defer ptmx.Close()
31
32 keyboard := &lockedWriter{w: ptmx}
33 term := vt10x.New(vt10x.WithSize(terminalCols, terminalRows), vt10x.WithWriter(keyboard))
34 var output terminalOutput
35 output.lastOutput.Store(time.Now().UnixNano())
36 readDone := make(chan struct{})
37 go func() {
38 defer close(readDone)
39 reader := bufio.NewReader(io.TeeReader(ptmx, &output))
40 for {
41 if err := term.Parse(reader); err != nil {
42 return
43 }
44 }
45 }()
46 exited := make(chan error, 1)
47 go func() { exited <- cmd.Wait() }()
48
49 quietFor := func(d time.Duration) bool {
50 return time.Since(time.Unix(0, output.lastOutput.Load())) >= d
51 }
52 var run terminalRun
53 var waitErr error
54 done := false
55 for i, entry := range keys {
56 seq, err := parseKeys(entry)
57 if err != nil {
58 return terminalRun{}, err
59 }
60 if done = waitFor(ctx, exited, &waitErr, func() bool { return output.sawOutput.Load() && quietFor(settleTime) }); done {
61 run.unused = len(keys) - i
62 break
63 }
64 run.steps = append(run.steps, terminalStep{Keys: entry, Screen: screenText(term)})
65 output.lastOutput.Store(time.Now().UnixNano())
66 if _, err := keyboard.Write([]byte(seq)); err != nil {
67 return terminalRun{}, err
68 }
69 }
70 if !done {
71 waitFor(ctx, exited, &waitErr, func() bool { return false })
72 }
73 // Let the last output reach the screen.
74 select {
75 case <-readDone:
76 case <-time.After(time.Second):
77 }
78 run.screen = screenText(term)
79 run.output = output.String()
80 return run, waitErr
81}
82

Callers 1

runBinaryFunction · 0.70

Calls 7

WriteMethod · 0.95
StringMethod · 0.95
parseKeysFunction · 0.85
waitForFunction · 0.85
screenTextFunction · 0.85
ErrorfMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected