/* The MIT License (MIT) Copyright © 2024 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Single-file source-code for timer, where the unit-tests from the original app are omitted. To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath timer.go */ package main import ( "bufio" "io" "os" "os/exec" "os/signal" "strconv" "sync" "time" ) // Note: the code is avoiding using the fmt package to save hundreds of // kilobytes on the resulting executable, which is a noticeable difference. const ( spaces = ` ` // clear has enough spaces in it to cover any chronograph output clear = "\r" + spaces + spaces + spaces + "\r" ) const info = ` timer [command...] [args...] Run a live timer/chronograph on stderr, always showing below all lines from stdin, which update stdout as they come. When stdin is over, it simply quits showing how long it ran, by extending its last visible timer line on stderr. You can also use this app without piping anything to its stdin, acting as a simple live clock until you force-quit it. To ensure any stderr lines don't clash with the chronograph output line, you can also run this app with arguments to have it run a command, thus guaranteeing the subtask's stderr lines show without interference. ` func main() { if len(os.Args) > 1 { switch os.Args[1] { case `-h`, `--h`, `-help`, `--help`: os.Stderr.WriteString(info[1:]) return } } if len(os.Args) > 1 { os.Exit(runTask(os.Args[1], os.Args[2:])) } err := chronograph(os.Stdin, nil) if quit, ok := err.(justQuit); ok { os.Exit(quit.exitCode) } } // justQuit is a custom error-type which isn't for showing, but quitting the // app right away instead type justQuit struct { exitCode int } // Error is only to satisfy the error interface, and not for showing func (justQuit) Error() string { return `quitting right away` } // runTask handles running the app in `subtask-mode` func runTask(name string, args []string) (exitCode int) { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin stdout, err := cmd.StdoutPipe() if err != nil { showError(err) return 1 } defer stdout.Close() stderr, err := cmd.StderrPipe() if err != nil { showError(err) return 1 } defer stderr.Close() if err := cmd.Start(); err != nil { showError(err) return 1 } err = chronograph(stdout, stderr) if quit, ok := err.(justQuit); ok { return quit.exitCode } if err != nil { showError(err) } if err := cmd.Wait(); err != nil { showError(err) } return cmd.ProcessState.ExitCode() } // showError gives a consistent style/look to any of the app's own errors func showError(err error) { if err == nil { return } os.Stderr.WriteString("\x1b[31m") os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\x1b[0m\n") } // readLines is run twice asynchronously, so that both stdin and stderr lines // are handled independently, which matters when running a subtask func readLines(r io.Reader, lines chan []byte) error { defer close(lines) // when not handling a subtask, this func will be called with a nil // reader, since without a subtask, there's no stderr to read from if r == nil { return nil } const gb = 1024 * 1024 * 1024 sc := bufio.NewScanner(r) sc.Buffer(nil, 8*gb) for sc.Scan() { // interesting: trying to filter out needlessly-chatty pipes // doesn't work as intended when done here, but is fine when // done at both receiving ends in the big select statement lines <- sc.Bytes() } return sc.Err() } // chronograph runs a live chronograph, showing the time elapsed: 2 input // sources for lines are handled concurrently, one destined for the app's // stdout, the other for the app's stderr, without interfering with the // chronograph lines, which also show on stderr func chronograph(stdout io.Reader, stderr io.Reader) error { start := time.Now() t := time.NewTicker(100 * time.Millisecond) startChronoLine(start, start) stopped := make(chan os.Signal, 1) defer close(stopped) signal.Notify(stopped, os.Interrupt) errors := make(chan error) var waitAllLines sync.WaitGroup waitAllLines.Add(2) outLines := make(chan []byte) go func() { defer waitAllLines.Done() errors <- readLines(stdout, outLines) }() errLines := make(chan []byte) go func() { defer waitAllLines.Done() errors <- readLines(stderr, errLines) }() quit := make(chan struct{}) defer close(quit) go func() { waitAllLines.Wait() close(errors) quit <- struct{}{} }() for { select { case now := <-t.C: os.Stderr.WriteString(clear) startChronoLine(start, now) case line := <-outLines: if line == nil { // filter out junk for needlessly-chatty pipes, while still // keeping actual empty lines continue } // write-order of the next 3 steps matters, to avoid mixing // up lines since stdout and stderr lines can show up together os.Stderr.WriteString(clear) os.Stdout.Write(line) _, err := os.Stdout.WriteString("\n") startChronoLine(start, time.Now()) if err != nil { endChronoLine(start) return err } case line := <-errLines: if line == nil { // filter out junk for needlessly-chatty pipes, while still // keeping actual empty lines continue } // write-order of the next 3 steps matters, to avoid mixing // up lines since stdout and stderr lines can show up together os.Stderr.WriteString(clear) os.Stderr.Write(line) _, err := os.Stderr.WriteString("\n") startChronoLine(start, time.Now()) if err != nil { endChronoLine(start) return err } case err := <-errors: if err == nil { continue } os.Stderr.WriteString(clear) showError(err) startChronoLine(start, time.Now()) case <-quit: endChronoLine(start) return justQuit{0} case <-stopped: t.Stop() endChronoLine(start) return justQuit{255} } } } func startChronoLine(start, now time.Time) { var buf [64]byte dt := now.Sub(start) os.Stderr.Write(time.Time{}.Add(dt).AppendFormat(buf[:0], `15:04:05`)) os.Stderr.Write([]byte(` `)) os.Stderr.Write(now.AppendFormat(buf[:0], `2006-01-02 15:04:05 Jan Mon`)) } func endChronoLine(start time.Time) { var buf [64]byte secs := time.Since(start).Seconds() os.Stderr.Write([]byte(` `)) os.Stderr.Write(strconv.AppendFloat(buf[:0], secs, 'f', 4, 64)) os.Stderr.Write([]byte(" seconds\n")) }