Start refactor of code into what I think is a more modular way of working

This commit is contained in:
2020-01-26 12:16:37 +00:00
parent eadbe9e743
commit 3e6bcbc5a8
8 changed files with 236 additions and 72 deletions
+71
View File
@@ -0,0 +1,71 @@
package evelogs
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strings"
)
type LogDir struct {
Path string
}
func NewLogDir(path string) (*LogDir, error) {
// do a unix like expansion if the path starts like `~/`
if strings.HasPrefix(path, "~/") {
userName, _ := user.Current()
path = filepath.Join(userName.HomeDir, path[2:])
}
ld := &LogDir{Path: path}
if !ld.DExists() {
return nil, fmt.Errorf("Path %s does not exist or is a regular file", ld.Path)
}
return ld, nil
}
func (ld *LogDir) DExists() bool {
info, err := os.Stat(ld.Path)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
func (ld *LogDir) GetLogFiles() ([]*LogFile, error) {
//TODO: iterate through the directory looking for logs
files, err := ioutil.ReadDir(ld.Path)
var paths []string
if err != nil {
log.Fatal(err)
return nil, err
}
for _, f := range files {
if !f.IsDir() {
paths = append(paths, ld.Path+string(os.PathSeparator)+f.Name())
}
}
logfiles, err := PathsToLogFiles(paths)
if err != nil {
log.Fatal(err)
return nil, err
}
return logfiles, nil
}
// Generate logDir instances from log dir paths
func DirsToLogDirs(paths []string) ([]*LogDir, error) {
var logDirs []*LogDir
for _, dirpath := range paths {
newLogDir, err := NewLogDir(dirpath)
if err != nil {
return nil, err
}
logDirs = append(logDirs, newLogDir)
}
return logDirs, nil
}
+48
View File
@@ -0,0 +1,48 @@
package evelogs
import (
"fmt"
"log"
"os"
)
type LogFile struct {
Path string
}
// create a lofFile instance, if it's a file.
func NewLogFile(path string) (*LogFile, error) {
lf := &LogFile{Path: path}
exists := lf.FileExists()
if !exists {
return nil, fmt.Errorf("File %s not found or is directory", lf.Path)
}
return lf, nil
}
func (lf *LogFile) FileExists() bool {
info, err := os.Stat(lf.Path)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func (lf *LogFile) TailFile() error {
//lets start a goroutine to tail the file here
return nil
}
//create logFile instances from a list of paths
func PathsToLogFiles(paths []string) ([]*LogFile, error) {
var logFiles []*LogFile
for _, f := range paths {
nLogFile, err := NewLogFile(f)
if err != nil {
log.Printf("Error with %s: %s", f, err)
return nil, err
}
logFiles = append(logFiles, nLogFile)
}
return logFiles, nil
}