File: countdown.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright (c) 2026 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     // every = 100 * time.Millisecond
  51     // chronoFormat = `15:04:05.0`
  52 
  53     every = 1000 * time.Millisecond
  54 
  55     chronoFormat   = `15:04:05`
  56     durationFormat = `15:04:05`
  57     dateTimeFormat = `2006-01-02 15:04:05 Jan Mon`
  58 )
  59 
  60 const info = `
  61 countdown [period]
  62 
  63 Run a live countdown timer on stderr, until the time-period given ends,
  64 or the app is force-quit.
  65 
  66 The time-period is either a simple integer number (of seconds), or an
  67 integer followed by any of
  68   - "s" (for seconds)
  69   - "m" (for minutes)
  70   - "h" (for hours)
  71 without spaces, or a combination of those time-units without spaces.
  72 `
  73 
  74 func main() {
  75     if len(os.Args) == 1 {
  76         os.Stderr.WriteString(info[1:])
  77         return
  78     }
  79 
  80     if len(os.Args) != 2 {
  81         os.Stderr.WriteString(info[1:])
  82         os.Exit(1)
  83     }
  84 
  85     switch os.Args[1] {
  86     case `-h`, `--h`, `-help`, `--help`:
  87         os.Stdout.WriteString(info[1:])
  88         return
  89     }
  90 
  91     period, err := parseDuration(os.Args[1])
  92     if err != nil {
  93         os.Stderr.WriteString(err.Error())
  94         os.Stderr.WriteString("\n")
  95         os.Exit(1)
  96     }
  97 
  98     os.Stderr.WriteString(`Countdown lasting `)
  99     os.Stderr.WriteString(time.Time{}.Add(period).Format(durationFormat))
 100     os.Stderr.WriteString(" started\n")
 101     countdown(period)
 102 }
 103 
 104 func parseDuration(s string) (time.Duration, error) {
 105     if n, err := strconv.Atoi(s); err == nil {
 106         return time.Duration(n) * time.Second, nil
 107     }
 108     return time.ParseDuration(s)
 109 }
 110 
 111 func countdown(period time.Duration) {
 112     start := time.Now()
 113     end := start.Add(period)
 114     t := time.NewTicker(every)
 115     startChronoLine(end, start)
 116 
 117     stopped := make(chan os.Signal, 1)
 118     defer close(stopped)
 119     signal.Notify(stopped, os.Interrupt)
 120 
 121     for {
 122         select {
 123         case now := <-t.C:
 124             if now.Sub(end) < 0 {
 125                 startChronoLine(end, now)
 126                 continue
 127             }
 128 
 129             t.Stop()
 130             startChronoLine(now, now)
 131             endChronoLine(start)
 132             return
 133 
 134         case <-stopped:
 135             t.Stop()
 136             endChronoLine(start)
 137             return
 138         }
 139     }
 140 }
 141 
 142 func startChronoLine(end, now time.Time) {
 143     dt := end.Sub(now)
 144 
 145     var buf [128]byte
 146     s := buf[:0]
 147     s = append(s, clear...)
 148     s = time.Time{}.Add(dt).AppendFormat(s, chronoFormat)
 149     s = append(s, `    `...)
 150     s = now.AppendFormat(s, dateTimeFormat)
 151 
 152     os.Stderr.Write(s)
 153 }
 154 
 155 func endChronoLine(start time.Time) {
 156     secs := time.Since(start).Seconds()
 157 
 158     var buf [64]byte
 159     s := buf[:0]
 160     s = append(s, `    `...)
 161     s = strconv.AppendFloat(s, secs, 'f', 4, 64)
 162     s = append(s, " seconds\n"...)
 163 
 164     os.Stderr.Write(s)
 165 }