continued refactoring, added more tests, better error handling

This commit is contained in:
2022-10-02 14:22:31 +02:00
parent 66c4b68036
commit e6723a6951
9 changed files with 244 additions and 41 deletions

View File

@@ -19,34 +19,48 @@ package lib
import (
"errors"
"github.com/alecthomas/repr"
"io"
"os"
)
func ProcessFiles(args []string) error {
var pattern string
havefiles := false
fds, pattern, err := determineIO(args)
//prepareColumns()
if err != nil {
return err
}
for _, fd := range fds {
printData(parseFile(fd, pattern))
}
return nil
}
func determineIO(args []string) ([]io.Reader, string, error) {
var pattern string
var fds []io.Reader
var havefiles bool
if len(args) > 0 {
// threre were args left, take a look
if _, err := os.Stat(args[0]); err != nil {
// first one is not a file, consider it as regexp and
// shift arg list
pattern = args[0]
args = args[1:]
}
if len(args) > 0 {
// only files
for _, file := range args {
fd, err := os.OpenFile(file, os.O_RDONLY, 0755)
if err != nil {
die(err)
return nil, "", err
}
data := parseFile(fd, pattern)
if Debug {
repr.Print(data)
}
printData(data)
fds = append(fds, fd)
}
havefiles = true
}
@@ -55,15 +69,11 @@ func ProcessFiles(args []string) error {
if !havefiles {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
data := parseFile(os.Stdin, pattern)
if Debug {
repr.Print(data)
}
printData(data)
fds = append(fds, os.Stdin)
} else {
return errors.New("No file specified and nothing to read on stdin!")
return nil, "", errors.New("No file specified and nothing to read on stdin!")
}
}
return nil
return fds, pattern, nil
}