my-log/files/append.go
Dan Jones 9f05f933dd ♲ Refactor configuration to use viper with context propagation
- Replace global ConfigPath and Overrides with viper-based configuration
- Add viper.New() to create configurable viper instances
- Store viper and unmarshaled Config struct in context for testability
- Add RetrieveFromContext and AddToContext helper functions
- Update files.Append to accept context and retrieve config from it
- Update formatters.Preferred and formatters.New to accept context
- Add PersistentPreRunE in CLI to create and configure viper instance
- Support -c flag for custom config file path
- Support -v flag for config value overrides
- Update all test files to create viper and add to context
- Remove unused config types and load functions
- Add viper as dependency with automatic env var support (MYLOG_*)
2026-03-09 13:46:01 -05:00

62 lines
1.1 KiB
Go

package files
import (
"context"
"fmt"
"io"
"os"
fp "path/filepath"
"strings"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
)
func Append(ctx context.Context, l models.Log) error {
_, conf := config.RetrieveFromContext(ctx)
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)
}
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_RDWR, 0640)
if err != nil {
return err
}
defer f.Close()
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})
}
}
for _, e := range l.Entries {
by, err := e.MarshalText()
if err != nil {
continue
}
f.Write(by)
f.Write([]byte{10})
}
return nil
}