2024-02-11 13:50:27 -06:00
|
|
|
package files
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2024-03-09 15:38:34 -06:00
|
|
|
"io"
|
2024-02-11 13:50:27 -06:00
|
|
|
"os"
|
|
|
|
|
fp "path/filepath"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"codeberg.org/danjones000/my-log/config"
|
|
|
|
|
"codeberg.org/danjones000/my-log/models"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func Append(l models.Log) error {
|
|
|
|
|
conf, err := config.Load()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-26 19:30:32 -06:00
|
|
|
filename := l.Name
|
|
|
|
|
if conf.Input.DotFolder {
|
|
|
|
|
filename = strings.ReplaceAll(filename, ".", string(os.PathSeparator))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if conf.Input.Ext != "" {
|
|
|
|
|
filename = fmt.Sprintf("%s.%s", filename, conf.Input.Ext)
|
|
|
|
|
}
|
2024-02-11 13:50:27 -06:00
|
|
|
path := fp.Join(conf.Input.Path, filename)
|
|
|
|
|
dir := fp.Dir(path)
|
|
|
|
|
err = os.MkdirAll(dir, 0750)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-09 15:38:34 -06:00
|
|
|
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0640)
|
2024-02-11 13:50:27 -06:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer f.Close()
|
|
|
|
|
|
2024-03-09 15:38:34 -06:00
|
|
|
f.Seek(-1, os.SEEK_END)
|
|
|
|
|
last := make([]byte, 1, 1)
|
|
|
|
|
n, err := f.Read(last)
|
|
|
|
|
if err != nil && err != io.EOF {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err == nil && n > 0 {
|
|
|
|
|
if last[0] != 10 {
|
|
|
|
|
f.Write([]byte{10})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-11 13:50:27 -06:00
|
|
|
for _, e := range l.Entries {
|
|
|
|
|
by, err := e.MarshalText()
|
|
|
|
|
if err != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
f.Write(by)
|
2024-03-09 15:38:34 -06:00
|
|
|
f.Write([]byte{10})
|
2024-02-11 13:50:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|