func FollowFile(path string, cfg *tf.TfcatConfig) { if !FileExists(path) { fmt.Fprintf(os.Stderr, "input file '%s' does not exist.\n", path) os.Exit(1) } watcher, err := fsnotify.NewWatcher() panicOn(err) defer watcher.Close() f, err := os.Open(path) panicOn(err) // move to end for tailing _, err = f.Seek(0, 2) panicOn(err) err = watcher.Add(path) panicOn(err) fr := tf.NewFrameReader(f, 1024*1024) var frame tf.Frame i := int64(1) nextFrame: for { _, _, err, _ = fr.NextFrame(&frame) if err != nil { if err == io.EOF { select { case event := <-watcher.Events: if event.Op&fsnotify.Write == fsnotify.Write { continue nextFrame } } } fmt.Fprintf(os.Stderr, "tfcat error from fr.NextFrame(): '%v'\n", err) os.Exit(1) } frame.DisplayFrame(os.Stdout, i, cfg.PrettyPrint, cfg.SkipPayload, cfg.Rreadable) i++ } }
func main() { myflags := flag.NewFlagSet("tfcat", flag.ExitOnError) cfg := &tf.TfcatConfig{} cfg.DefineFlags(myflags) err := myflags.Parse(os.Args[1:]) err = cfg.ValidateConfig() if err != nil { usage(err, myflags) } leftover := myflags.Args() //Q("leftover = %v", leftover) if len(leftover) == 0 && cfg.ReadStdin == false { fmt.Fprintf(os.Stderr, "no input files given\n") showUse(myflags) os.Exit(1) } GlobalPrettyPrint = cfg.PrettyPrint if cfg.Follow { if len(leftover) != 1 { if cfg.ReadStdin { fmt.Fprintf(os.Stderr, "cannot follow stdin\n") showUse(myflags) os.Exit(1) } fmt.Fprintf(os.Stderr, "can only follow a single file\n") showUse(myflags) os.Exit(1) } FollowFile(leftover[0], cfg) return } if cfg.ReadStdin { if len(leftover) > 0 { fmt.Fprintf(os.Stderr, "if reading from stdin, cannot also read from files\n") showUse(myflags) os.Exit(1) } leftover = []string{"stdin"} } if cfg.RawCount > 0 || cfg.RawSkip > 0 { if len(leftover) != 1 { fmt.Fprintf(os.Stderr, "can only copy raw messages from one file\n") showUse(myflags) os.Exit(1) } SendRawBytes(leftover[0], cfg.RawCount, os.Stdout, cfg.RawSkip) return } i := int64(1) nextfile: for _, inputFile := range leftover { f := prepInput(inputFile) defer f.Close() //P("starting on inputFile '%s'", inputFile) fr := tf.NewFrameReader(f, 1024*1024) var frame tf.Frame for ; err == nil; i++ { _, _, err, _ = fr.NextFrame(&frame) if err != nil { if err == io.EOF { continue nextfile } fmt.Fprintf(os.Stderr, "tfcat error from fr.NextFrame() at i=%v: '%v'\n", i, err) os.Exit(1) } frame.DisplayFrame(os.Stdout, i, cfg.PrettyPrint, cfg.SkipPayload, cfg.Rreadable) } } }