-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
71 lines (64 loc) · 1.49 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
65
66
67
68
69
70
71
package main
import (
"bufio"
"errors"
"io"
"nglog/config"
debug "nglog/debugPrint"
"nglog/nginxErrorLogFormatter"
"os"
)
func LoadData() error {
if isInputFromPipe() {
debug.Println("Reading data from pipe")
return processData(os.Stdin, os.Stdout)
} else {
debug.Println("Loading data from file: " + config.Flags.FilePath)
file, e := getFile()
if e != nil {
return e
}
defer file.Close()
return processData(file, os.Stdout)
}
}
func processData(r io.Reader, w io.Writer) error {
formatter := nginxErrorLogFormatter.New(w)
scanner := bufio.NewScanner(bufio.NewReader(r))
rowCounter := 0
for scanner.Scan() {
rowCounter++
e := formatter.ReadBufferLine(scanner.Text())
if e != nil {
return e
}
if config.Flags.DebugMode && config.Flags.DebugMaxLines > 0 && rowCounter >= config.Flags.DebugMaxLines {
return nil
}
}
return nil
}
func isInputFromPipe() bool {
fi, _ := os.Stdin.Stat()
return fi.Mode()&os.ModeCharDevice == 0
}
func getFile() (*os.File, error) {
if config.Flags.FilePath == "" {
return nil, errors.New("please input a file path")
}
if !fileExists(config.Flags.FilePath) {
return nil, errors.New("the file provided does not exist")
}
file, e := os.Open(config.Flags.FilePath)
if e != nil {
return nil, errors.New("unable to read the file " + config.Flags.FilePath + " : " + e.Error())
}
return file, nil
}
func fileExists(filepath string) bool {
info, e := os.Stat(filepath)
if os.IsNotExist(e) {
return false
}
return !info.IsDir()
}