Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support reading compressed files through exec #15

Merged
merged 2 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions pkg/analyze/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package analyze

import (
"fmt"
"io"
"log"
"net/netip"
"os"
Expand Down Expand Up @@ -143,11 +144,13 @@ func (a *Analyzer) RunLoop(iter fileiter.Iterator) error {
}

func (a *Analyzer) AnalyzeFile(filename string) error {
f, err := os.Open(filename)
f, err := OpenFile(filename)
if err != nil {
return err
}
defer f.Close()
if closer, ok := f.(io.Closer); ok {
defer closer.Close()
}
return a.RunLoop(fileiter.NewWithScanner(f))
}

Expand Down
46 changes: 46 additions & 0 deletions pkg/analyze/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,59 @@ package analyze
import (
"io"
"os"
"os/exec"
"path/filepath"

"github.com/nxadm/tail"
"github.com/taoky/ayano/pkg/fileiter"
)

const oneMiB = 1024 * 1024

func filterByCommand(r io.Reader, args []string) (io.ReadCloser, error) {
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = r
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
go func() {
cmd.Wait()
if closer, ok := r.(io.Closer); ok {
closer.Close()
}
}()
return stdout, err
}

type filterFunc func(r io.Reader) (io.Reader, error)

var fileTypes = map[string]filterFunc{
".gz": func(r io.Reader) (io.Reader, error) {
return filterByCommand(r, []string{"gzip", "-cd"})
},
".xz": func(r io.Reader) (io.Reader, error) {
return filterByCommand(r, []string{"xz", "-cd", "-T", "0"})
taoky marked this conversation as resolved.
Show resolved Hide resolved
},
".zst": func(r io.Reader) (io.Reader, error) {
return filterByCommand(r, []string{"zstd", "-cd", "-T0"})
},
}

func OpenFile(filename string) (io.Reader, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
if filter, ok := fileTypes[filepath.Ext(filename)]; ok {
return filter(f)
}
return f, nil
}

func (a *Analyzer) OpenTailIterator(filename string) (fileiter.Iterator, error) {
var seekInfo *tail.SeekInfo
if a.Config.Whole {
Expand Down
Loading