This commit is contained in:
bel
2023-10-29 09:05:39 -06:00
parent c75bd74823
commit ce5bf71f6b
2 changed files with 119 additions and 0 deletions

View File

@@ -1,6 +1,8 @@
package ledger
import (
"bufio"
"bytes"
"fmt"
"io"
"io/fs"
@@ -20,6 +22,41 @@ func NewFiles(p string, q ...string) (Files, error) {
return f, err
}
func (files Files) TempGetLastNLines(n int) ([]string, error) {
p := files.paths()[0]
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
return peekLastNLines(io.Discard, bufio.NewReader(f), n)
}
func (files Files) TempSetLastNLines(n int, lines []string) error {
panic("e")
}
func peekLastNLines(w io.Writer, r *bufio.Reader, n int) ([]string, error) {
lastNLines := make([]string, 0, n)
for {
line, err := r.ReadBytes('\n')
if len(line) > 0 {
lastNLines = append(lastNLines, string(bytes.TrimRight(line, "\n")))
for i := 0; i < len(lastNLines)-n; i++ {
fmt.Fprintln(w, lastNLines[i])
}
lastNLines = lastNLines[max(0, len(lastNLines)-n):]
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return lastNLines, nil
}
func (files Files) paths() []string {
result := make([]string, 0, len(files))
for i := range files {