From 731e991f1f15182ff48db22365e513a3702f68a6 Mon Sep 17 00:00:00 2001 From: Parnic Date: Fri, 10 Jun 2022 09:38:50 -0500 Subject: [PATCH] Support piping data in This allows using someone else's data to compare runtimes, behavior, etc. without having to recompile. Since it's patched into the function that all days use to read, it's incompatible with running all days, which I feel is a reasonable compromise and behavior expectation. The Mode() check is how the internet says you can test if you should even try to look at stdin, and the Size() check ensures that there's actually data to be read instead of just an open stdin handle (running in VSCode with a debugger seems to keep the stdin handle open, for example, so it passes the Mode() check and then hangs when trying to read since there's nothing to actually read). --- utilities/parsing.go | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/utilities/parsing.go b/utilities/parsing.go index 1c81540..7746483 100644 --- a/utilities/parsing.go +++ b/utilities/parsing.go @@ -3,18 +3,33 @@ package utilities import ( "bufio" "fmt" + "io" + "os" "strconv" "parnic.com/aoc2019/inputs" ) func getData(filename string, lineHandler func(line string)) { - file, err := inputs.Sets.Open(fmt.Sprintf("%s.txt", filename)) - // version that doesn't use embedded files: - // file, err := os.Open(fmt.Sprintf("inputs/%s.txt", filename)) + var err error + stdinStat, err := os.Stdin.Stat() if err != nil { panic(err) } + + var file io.ReadCloser + if (stdinStat.Mode()&os.ModeCharDevice) == 0 && stdinStat.Size() > 0 { + file = os.Stdin + } else { + file, err = inputs.Sets.Open(fmt.Sprintf("%s.txt", filename)) + // version that doesn't use embedded files: + // file, err := os.Open(fmt.Sprintf("inputs/%s.txt", filename)) + + if err != nil { + panic(err) + } + } + defer file.Close() scanner := bufio.NewScanner(file)