chore: Add simple parsers for journald and tail files

This commit is contained in:
2026-06-11 21:42:25 +03:00
parent be42840c64
commit fca7d8bbc9
8 changed files with 111 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
package parser
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
)
func ParseJournald(unit string) (Parser, error) {
if unit == "" {
return Parser{}, errors.New("unit name cannot be empty")
}
validUnitName := regexp.MustCompile(`^[a-zA-Z0-9:_\.\-@]+$`)
if !validUnitName.MatchString(unit) {
return Parser{}, fmt.Errorf("invalid systemd unit name: %s", unit)
}
cmd := exec.Command("journalctl", "-u", unit, "-f", "-n", "0", "-o", "short", "--no-pager")
stdout, err := cmd.StdoutPipe()
if err != nil {
return Parser{}, fmt.Errorf("stdout pipe error: %w", err)
}
if err := cmd.Start(); err != nil {
return Parser{}, fmt.Errorf("failed to start journalctl: %w", err)
}
p := Parser{
parser: bufio.NewScanner(stdout),
ch: make(chan string, 100),
cmd: cmd,
file: nil,
}
return p, nil
}
+31
View File
@@ -0,0 +1,31 @@
package parser
import (
"bufio"
"os/exec"
)
type Parser struct {
parser *bufio.Scanner
ch chan string
cmd *exec.Cmd
file *string
}
func (p *Parser) Start() {
go func() {
for p.parser.Scan() {
p.ch <- p.parser.Text()
}
}()
}
func (p *Parser) Stop() {
if p.cmd != nil && p.cmd.Process != nil {
p.cmd.Process.Kill()
}
}
func (p *Parser) Channel() <-chan string {
return p.ch
}
+39
View File
@@ -0,0 +1,39 @@
package parser
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
)
func ParseFile(path string) (Parser, error) {
if path == "" {
return Parser{}, errors.New("path cannot be empty")
}
if _, err := os.Stat(path); os.IsNotExist(err) {
return Parser{}, fmt.Errorf("file does not exist: %s", path)
}
cmd := exec.Command("tail", "-F", "-n", "10", path)
stdout, err := cmd.StdoutPipe()
if err != nil {
return Parser{}, fmt.Errorf("stdout pipe error: %w", err)
}
if err := cmd.Start(); err != nil {
return Parser{}, fmt.Errorf("failed to start tail parser: %w", err)
}
p := Parser{
parser: bufio.NewScanner(stdout),
ch: make(chan string, 100),
cmd: cmd,
file: &path,
}
return p, nil
}