11package main
22
33import (
4- "bytes "
4+ "context "
55 "flag"
66 "fmt"
7- "io/fs"
87 "os"
98 "path"
109
1110 tea "github.com/charmbracelet/bubbletea"
1211
1312 "github.com/hedhyw/json-log-viewer/internal/app"
1413 "github.com/hedhyw/json-log-viewer/internal/pkg/config"
14+ "github.com/hedhyw/json-log-viewer/internal/pkg/events"
1515 "github.com/hedhyw/json-log-viewer/internal/pkg/source"
16- "github.com/hedhyw/json-log-viewer/internal/pkg/source/fileinput"
17- "github.com/hedhyw/json-log-viewer/internal/pkg/source/readerinput"
1816)
1917
2018// version will be set on build.
@@ -39,41 +37,54 @@ func main() {
3937 fatalf ("Error reading config: %s\n " , err )
4038 }
4139
42- var sourceInput source.Input
40+ fileName := ""
41+ var inputSource * source.Source
4342
4443 switch flag .NArg () {
4544 case 0 :
46- sourceInput , err = getStdinSource (cfg , os .Stdin )
45+ // Tee stdin to a temp file, so that we can
46+ // lazy load the log entries using random access.
47+ fileName = "-"
48+
49+ stdIn , err := getStdinReader (os .Stdin )
4750 if err != nil {
4851 fatalf ("Stdin: %s\n " , err )
4952 }
53+
54+ inputSource , err = source .Reader (stdIn , cfg )
55+ if err != nil {
56+ fatalf ("Could not create temp flie: %s\n " , err )
57+ }
58+ defer inputSource .Close ()
59+
5060 case 1 :
51- sourceInput = fileinput .New (flag .Arg (0 ))
61+ fileName = flag .Arg (0 )
62+ inputSource , err = source .File (fileName , cfg )
63+ if err != nil {
64+ fatalf ("Could not create temp flie: %s\n " , err )
65+ }
66+ defer inputSource .Close ()
67+
5268 default :
5369 fatalf ("Invalid arguments, usage: %s file.log\n " , os .Args [0 ])
5470 }
5571
56- appModel := app .NewModel (sourceInput , cfg , version )
72+ appModel := app .NewModel (fileName , cfg , version )
5773 program := tea .NewProgram (appModel , tea .WithInputTTY (), tea .WithAltScreen ())
5874
75+ inputSource .StartStreaming (context .Background (), func (entries source.LazyLogEntries , err error ) {
76+ if err != nil {
77+ program .Send (events.ErrorOccuredMsg {Err : err })
78+ } else {
79+ program .Send (events .LogEntriesUpdateMsg (entries ))
80+ }
81+ })
82+
5983 if _ , err := program .Run (); err != nil {
6084 fatalf ("Error running program: %s\n " , err )
6185 }
6286}
6387
64- func getStdinSource (cfg * config.Config , defaultInput fs.File ) (source.Input , error ) {
65- stat , err := defaultInput .Stat ()
66- if err != nil {
67- return nil , fmt .Errorf ("stat: %w" , err )
68- }
69-
70- if stat .Mode ()& os .ModeCharDevice != 0 {
71- return readerinput .New (bytes .NewReader (nil ), cfg .StdinReadTimeout ), nil
72- }
73-
74- return readerinput .New (defaultInput , cfg .StdinReadTimeout ), nil
75- }
76-
7788func fatalf (message string , args ... any ) {
7889 fmt .Fprintf (os .Stderr , message , args ... )
7990 os .Exit (1 )
0 commit comments