Drop command

This commit is contained in:
Dan Jones 2024-02-11 13:50:27 -06:00
commit cc9e8f6167
6 changed files with 214 additions and 23 deletions

42
files/append.go Normal file
View file

@ -0,0 +1,42 @@
package files
import (
"fmt"
"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
}
filename := fmt.Sprintf("%s.%s", strings.ReplaceAll(l.Name, ".", string(os.PathSeparator)), conf.Input.Ext)
path := fp.Join(conf.Input.Path, filename)
dir := fp.Dir(path)
err = os.MkdirAll(dir, 0750)
if err != nil {
return err
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
if err != nil {
return err
}
defer f.Close()
for _, e := range l.Entries {
by, err := e.MarshalText()
if err != nil {
continue
}
f.Write(by)
}
return nil
}

91
files/append_test.go Normal file
View file

@ -0,0 +1,91 @@
package files
import (
"fmt"
"os"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
"github.com/stretchr/testify/suite"
)
func TestAppend(t *testing.T) {
suite.Run(t, new(AppendTestSuite))
}
type AppendTestSuite struct {
suite.Suite
dir string
}
func (s *AppendTestSuite) SetupSuite() {
s.dir, _ = os.MkdirTemp("", "append-test")
config.Overrides["input.path"] = s.dir
config.Overrides["input.ext"] = "log"
}
func (s *AppendTestSuite) TearDownSuite() {
os.RemoveAll(s.dir)
delete(config.Overrides, "input.path")
delete(config.Overrides, "input.ext")
}
func (s *AppendTestSuite) TestSuccess() {
when := time.Now().Local()
e := models.Entry{
Title: "Jimmy",
Date: when,
Fields: []models.Meta{
{"foo", 42},
{"bar", true},
},
}
l := models.Log{
Name: "test",
Entries: []models.Entry{e},
}
err := Append(l)
s.Require().NoError(err)
s.Require().FileExists(s.dir + "/test.log")
// @todo test file contents
}
func (s *AppendTestSuite) TestConfLoadErr() {
currConf := config.ConfigPath
tmp, _ := os.CreateTemp("", "app-conf-*.toml")
fname := tmp.Name()
defer tmp.Close()
defer os.Remove(fname)
fmt.Fprintln(tmp, `{"not":"toml"}`)
config.ConfigPath = fname
defer func(path string) {
config.ConfigPath = path
}(currConf)
err := Append(models.Log{})
s.Assert().ErrorContains(err, "toml")
}
func (s *AppendTestSuite) TestMkdirErr() {
// Don't run this test as root
config.Overrides["input.path"] = "/root/my-logs-test"
defer func(path string) {
config.Overrides["input.path"] = path
}(s.dir)
err := Append(models.Log{})
s.Assert().ErrorContains(err, "permission denied")
}
func (s *AppendTestSuite) TestOpenErr() {
l := models.Log{
Name: "test-open-err",
}
fname := s.dir + "/test-open-err.log"
os.MkdirAll(s.dir, 0750)
f, _ := os.Create(fname)
f.Close()
os.Chmod(fname, 0400) // read only
err := Append(l)
s.Assert().ErrorContains(err, "permission denied")
}