Debian Codegraph @

interp/stdin_os.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 //go:build !js
5
6 package interp
7
8 import (
9 "io"
10 "os"
11
12 "golang.org/x/term"
13 )
14
15 // stdinFile is the runner's standard input. Outside of js/wasm it is
16 // always an [*os.File]: the only type that subprocesses can inherit,
17 // and one supporting cancellable reads via [os.File.SetReadDeadline].
18 type stdinFile = *os.File
19
20 // newPipe returns an OS pipe; both ends are [*os.File] so they can
21 // be inherited by subprocesses.
22 func newPipe() (stdinFile, *os.File, error) {
23 return os.Pipe()
24 }
25
26 // newStdinFile converts a reader into the runner's stdin. Readers
27 // other than [*os.File] require an [os.Pipe] and a copying goroutine,
28 // as an [os.File] is the only way to share a reader with subprocesses.
29 func newStdinFile(r io.Reader) (stdinFile, error) {
30 switch r := r.(type) {
31 case *os.File:
32 return r, nil
33 case nil:
34 return nil, nil
35 default:
36 pr, pw, err := os.Pipe()
37 if err != nil {
38 return nil, err
39 }
40 go func() {
41 io.Copy(pw, r)
42 pw.Close()
43 }()
44 return pr, nil
45 }
46 }
47
48 // stdinTerminal returns the file descriptor of the shell's stdin
49 // if it is a terminal.
50 // Note that we only call [os.File.Fd] on character devices,
51 // as it stops [os.File.SetReadDeadline] from working,
52 // which [Runner.readLine] needs to cancel blocking reads.
53 func stdinTerminal(stdin stdinFile) (int, bool) {
54 if stdin == nil {
55 return -1, false
56 }
57 fi, err := stdin.Stat()
58 if err != nil || fi.Mode()&os.ModeCharDevice == 0 {
59 return -1, false
60 }
61 fd := int(stdin.Fd())
62 return fd, term.IsTerminal(fd)
63 }