File: countdown.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2025 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath countdown.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "os"
  36     "os/signal"
  37     "strconv"
  38     "time"
  39 )
  40 
  41 // Note: the code is avoiding using the fmt package to save hundreds of
  42 // kilobytes on the resulting executable, which is a noticeable difference.
  43 
  44 const (
  45     spaces = `                `
  46 
  47     // clear has enough spaces in it to cover any chronograph output
  48     clear = "\r" + spaces + spaces + spaces + "\r"
  49 )
  50 
  51 const info = `
  52 countdown [period]
  53 
  54 Run a live countdown timer on stderr, until the time-period given ends,
  55 or the app is force-quit.
  56 
  57 The time-period is either a simple integer number (of seconds), or an
  58 integer followed by any of
  59   - "s" (for seconds)
  60   - "m" (for minutes)
  61   - "h" (for hours)
  62 without spaces, or a combination of those time-units without spaces.
  63 `
  64 
  65 func main() {
  66     if len(os.Args) == 1 {
  67         os.Stderr.WriteString(info[1:])
  68         return
  69     }
  70 
  71     if len(os.Args) == 2 {
  72         switch os.Args[1] {
  73         case `-h`, `--h`, `-help`, `--help`:
  74             os.Stderr.WriteString(info[1:])
  75             return
  76         }
  77 
  78         period, err := parseDuration(os.Args[1])
  79         if err != nil {
  80             os.Stderr.WriteString("\x1b[31m")
  81             os.Stderr.WriteString(err.Error())
  82             os.Stderr.WriteString("\x1b[0m\n")
  83             os.Exit(1)
  84         }
  85 
  86         os.Stderr.WriteString("Countdown lasting ")
  87         os.Stderr.WriteString(time.Time{}.Add(period).Format(`15:04:05`))
  88         os.Stderr.WriteString(" started\n")
  89         countdown(period)
  90         return
  91     }
  92 
  93     os.Stderr.WriteString(info[1:])
  94     os.Exit(1)
  95 }
  96 
  97 func parseDuration(s string) (time.Duration, error) {
  98     if n, err := strconv.Atoi(s); err == nil {
  99         return time.Duration(n) * time.Second, err
 100     }
 101     return time.ParseDuration(s)
 102 }
 103 
 104 func countdown(period time.Duration) {
 105     start := time.Now()
 106     end := start.Add(period)
 107     t := time.NewTicker(100 * time.Millisecond)
 108     startChronoLine(end, start)
 109 
 110     stopped := make(chan os.Signal, 1)
 111     defer close(stopped)
 112     signal.Notify(stopped, os.Interrupt)
 113 
 114     for {
 115         select {
 116         case now := <-t.C:
 117             os.Stderr.WriteString(clear)
 118             if now.Sub(end) < 0 {
 119                 startChronoLine(end, now)
 120                 continue
 121             }
 122 
 123             t.Stop()
 124             startChronoLine(now, now)
 125             endChronoLine(start)
 126             return
 127 
 128         case <-stopped:
 129             t.Stop()
 130             endChronoLine(start)
 131             return
 132         }
 133     }
 134 }
 135 
 136 // func startChronoLine(end, now time.Time) {
 137 //  var buf [64]byte
 138 //  dt := end.Sub(now)
 139 //
 140 //  os.Stderr.Write(time.Time{}.Add(dt).AppendFormat(buf[:0], `15:04:05.0`))
 141 //  os.Stderr.WriteString(`    `)
 142 //  os.Stderr.Write(now.AppendFormat(buf[:0], `2006-01-02 15:04:05 Jan Mon`))
 143 // }
 144 
 145 func startChronoLine(end, now time.Time) {
 146     var buf [64]byte
 147     dt := end.Sub(now)
 148 
 149     s := buf[:0]
 150     s = time.Time{}.Add(dt).AppendFormat(s, `15:04:05.0`)
 151     s = append(s, `    `...)
 152     s = now.AppendFormat(s, `2006-01-02 15:04:05 Jan Mon`)
 153     os.Stderr.Write(s)
 154 }
 155 
 156 func endChronoLine(start time.Time) {
 157     var buf [64]byte
 158     secs := time.Since(start).Seconds()
 159 
 160     os.Stderr.WriteString(`    `)
 161     os.Stderr.Write(strconv.AppendFloat(buf[:0], secs, 'f', 4, 64))
 162     os.Stderr.WriteString(" seconds\n")
 163 }