-
Notifications
You must be signed in to change notification settings - Fork 4
/
cmd.go
64 lines (58 loc) · 1.15 KB
/
cmd.go
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
package main
import (
"bufio"
"fmt"
"github.com/pkg/errors"
"io"
"os"
"strings"
)
func runCommand() error {
if isInputFromPipe() {
print("data is from pipe")
return toUppercase(os.Stdin, os.Stdout)
} else {
file, e := getFile()
if e != nil {
return e
}
defer file.Close()
return toUppercase(file, os.Stdout)
}
}
func isInputFromPipe() bool {
fi, _ := os.Stdin.Stat()
return fi.Mode() & os.ModeCharDevice == 0
}
func getFile() (*os.File, error){
if flags.filepath == "" {
return nil, errors.New("please input a file")
}
if !fileExists(flags.filepath) {
return nil, errors.New("the file provided does not exist")
}
file, e := os.Open(flags.filepath)
if e != nil {
return nil, errors.Wrapf(e,
"unable to read the file %s", flags.filepath)
}
return file, nil
}
func toUppercase(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(bufio.NewReader(r))
for scanner.Scan() {
_, e := fmt.Fprintln(
w, strings.ToUpper(scanner.Text()))
if e != nil {
return e
}
}
return nil
}
func fileExists(filepath string) bool {
info, e := os.Stat(filepath)
if os.IsNotExist(e) {
return false
}
return !info.IsDir()
}