Debian Codegraph @

utils/read.go

raw symbols SCIP
1 package utils
2
3 import (
4 "bufio"
5 "bytes"
6 "io"
7 "io/ioutil"
8 "os"
9 "strings"
10 "unicode"
11
12 "github.com/pkg/errors"
13 "github.com/smallstep/cli/errs"
14 "github.com/smallstep/cli/ui"
15 )
16
17 // In command line utilities, it is a de facto standard that a hyphen "-"
18 // indicates STDIN as a file to be read.
19 const stdinFilename = "-"
20
21 // stdin points to os.Stdin.
22 var stdin = os.Stdin
23
24 // FileExists is a wrapper on os.Stat that returns false if os.Stat returns an
25 // error, it returns true otherwise. This method does not care if os.Stat
26 // returns any other kind of errors.
27 func FileExists(path string) bool {
28 if path == "" {
29 return false
30 }
31 _, err := os.Stat(path)
32 return err == nil
33 }
34
35 // ReadAll returns a slice of bytes with the content of the given reader.
36 func ReadAll(r io.Reader) ([]byte, error) {
37 b, err := ioutil.ReadAll(r)
38 return b, errors.Wrap(err, "error reading data")
39 }
40
41 // ReadString reads one line from the given io.Reader.
42 func ReadString(r io.Reader) (string, error) {
43 br := bufio.NewReader(r)
44 str, err := br.ReadString('\n')
45 if err != nil && err != io.EOF {
46 return "", errors.Wrap(err, "error reading string")
47 }
48 return strings.TrimSpace(str), nil
49 }
50
51 // ReadPasswordFromFile reads and returns the password from the given filename.
52 // The contents of the file will be trimmed at the right.
53 func ReadPasswordFromFile(filename string) ([]byte, error) {
54 password, err := ioutil.ReadFile(filename)
55 if err != nil {
56 return nil, errs.FileError(err, filename)
57 }
58 password = bytes.TrimRightFunc(password, unicode.IsSpace)
59 return password, nil
60 }
61
62 // ReadStringPasswordFromFile reads and returns the password from the given filename.
63 // The contents of the file will be trimmed at the right.
64 func ReadStringPasswordFromFile(filename string) (string, error) {
65 b, err := ReadPasswordFromFile(filename)
66 if err != nil {
67 return "", err
68 }
69 return string(b), nil
70 }
71
72 // ReadInput from stdin if something is detected or ask the user for an input
73 // using the given prompt.
74 func ReadInput(prompt string) ([]byte, error) {
75 st, err := stdin.Stat()
76 if err != nil {
77 return nil, errors.Wrap(err, "error reading data")
78 }
79
80 if st.Size() == 0 && st.Mode()&os.ModeNamedPipe == 0 {
81 return ui.PromptPassword(prompt)
82 }
83
84 return ReadAll(stdin)
85 }
86
87 // ReadFile returns the contents of the file identified by name. It reads from
88 // STDIN if name is a hyphen ("-").
89 func ReadFile(name string) (b []byte, err error) {
90 if name == stdinFilename {
91 name = "/dev/stdin"
92 b, err = ioutil.ReadAll(stdin)
93 } else {
94 b, err = ioutil.ReadFile(name)
95 }
96 if err != nil {
97 return nil, errs.FileError(err, name)
98 }
99 return b, nil
100 }