/* The MIT License (MIT) Copyright © 2025 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. */ /* 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 ( // gap has the spaces between current timer value and current date/time gap = ` ` // clear has enough spaces in it to cover any chronograph output clear = "\r" + ` ` + "\r" dateTimeFormat = `2006-01-02 15:04:05 Jan Mon` forceQuitCode = 255 ) const ( // every = 100 * time.Millisecond // chronoFormat = `15:04:05.0` // every = 500 * time.Millisecond // chronoFormat = `15:04:05` every = 1000 * time.Millisecond chronoFormat = `15:04:05` ) const info = ` timer [options...] [command...] [args...] Run a live timer/chronograph on stderr, always showing below all lines from stdin, which update stdout as they come. When stdin (or the command run) is over, this app 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 or giving it any command to run, acting as a simple live clock until you force-quit it, via Control+C, or end the stdin stream via Control+D. 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 stdout and stderr lines show without ever being mixed up. Note: by default this app assumes command output is plain-text lines, so a command's non-empty binary stdout may be corrupted in subtle ways; use the binary option to avoid that. The options are, available both in single and double-dash versions -b treat stdin or a command's stdout as generic binary data -bin treat stdin or a command's stdout as generic binary data -binary treat stdin or a command's stdout as generic binary data -h show this help message -help show this help message ` func main() { bin := false args := os.Args[1:] if len(args) > 0 { switch args[0] { case `-h`, `--h`, `-help`, `--help`: os.Stdout.WriteString(info[1:]) return case `-b`, `--b`, `-bin`, `--bin`, `-binary`, `--binary`: bin = true args = args[1:] } } if len(args) > 0 && args[0] == `--` { args = args[1:] } if len(args) > 0 { os.Exit(runTask(args[0], args[1:], bin)) } err := chronograph(os.Stdin, nil, bin) if quit, ok := err.(justQuit); ok { os.Exit(quit.exitCode) } if err != nil { showError(err) os.Exit(1) } } // justQuit is a custom error-type which isn't for showing, but for 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, bin bool) (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, bin) 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() } func showError(err error) { if err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") } } // readBytes is the binary-mode alternative to func readLines for a command's // standard output func readBytes(r io.Reader, chunks chan []byte) error { defer close(chunks) if r == nil { return nil } var buf [16 * 1024]byte for { n, err := r.Read(buf[:]) if err == io.EOF { if n > 0 { chunks <- buf[:n] } return nil } if err != nil { return err } if n < 1 { continue } chunks <- buf[: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() { 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, bin bool) error { start := time.Now() t := time.NewTicker(every) // s is a buffer used to minimize actual writes to final stdout/stderr s := make([]byte, 0, 1024) // start showing the timer right away s = startChronoLine(s[:0], start, start) os.Stderr.Write(s) // stopped is a special event to handle force-quitting the app stopped := make(chan os.Signal, 1) defer close(stopped) signal.Notify(stopped, os.Interrupt) // errors will no longer travel when both input streams are over errors := make(chan error) var waitAllOutput sync.WaitGroup waitAllOutput.Add(2) // binary-mode only concerns stdin or stdout, and never stderr readOutput := readLines if bin { readOutput = readBytes } // relay stdout data asynchronously outChunks := make(chan []byte) go func() { defer waitAllOutput.Done() if stdout != nil { errors <- readOutput(stdout, outChunks) } }() // relay stderr data asynchronously errLines := make(chan []byte) go func() { defer waitAllOutput.Done() if stderr != nil { errors <- readLines(stderr, errLines) } }() // quit is a special event which happens when both input streams are over quit := make(chan struct{}) defer close(quit) go func() { waitAllOutput.Wait() close(errors) quit <- struct{}{} }() for { select { case now := <-t.C: s = append(s[:0], clear...) s = startChronoLine(s, start, now) os.Stderr.Write(s) case chunk := <-outChunks: if chunk == 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, if // not handled correctly os.Stderr.WriteString(clear) s = append(s[:0], chunk...) // add an extra line-feed byte only when in plain-text mode if !bin { s = append(s, '\n') } // assume (final) stdout write errors are due to a closed pipe, // so quit this app successfully right away if _, err := os.Stdout.Write(s); err != nil { t.Stop() s = startChronoLine(s[:0], start, time.Now()) s = endChronoLine(s, start) os.Stderr.Write(s) return nil } s = startChronoLine(s[:0], start, time.Now()) os.Stderr.Write(s) case line := <-errLines: if line == nil { // filter out junk for needlessly-chatty pipes, while still // keeping actual empty lines continue } s = append(append(append(s[:0], clear...), line...), '\n') s = startChronoLine(s, start, time.Now()) s = endChronoLine(s, start) os.Stderr.Write(s) case err := <-errors: if err == nil { continue } os.Stderr.WriteString(clear) showError(err) s = startChronoLine(s[:0], start, time.Now()) os.Stderr.Write(s) case <-quit: os.Stderr.Write(endChronoLine(s[:0], start)) return justQuit{0} case <-stopped: t.Stop() os.Stderr.Write(endChronoLine(s[:0], start)) return justQuit{forceQuitCode} } } } func startChronoLine(buf []byte, start, now time.Time) []byte { dt := now.Sub(start) buf = time.Time{}.Add(dt).AppendFormat(buf, chronoFormat) buf = append(buf, gap...) buf = now.AppendFormat(buf, dateTimeFormat) return buf } func endChronoLine(buf []byte, start time.Time) []byte { secs := time.Since(start).Seconds() buf = append(buf, gap...) buf = strconv.AppendFloat(buf, secs, 'f', 4, 64) buf = append(buf, " seconds\n"...) return buf }