64 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			64 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package files
 | |
| 
 | |
| import (
 | |
| 	"fmt"
 | |
| 	"io"
 | |
| 	"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 := 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
 | |
| }
 |