File: countdown.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2020-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 Single-file source-code for countdown.
  27 
  28 To compile a smaller-sized command-line app, you can use the `go` command as
  29 follows:
  30 
  31 go build -ldflags "-s -w" -trimpath countdown.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "os"
  38     "os/signal"
  39     "strconv"
  40     "time"
  41 )
  42 
  43 // Note: the code is avoiding using the fmt package to save hundreds of
  44 // kilobytes on the resulting executable, which is a noticeable difference.
  45 
  46 const (
  47     spaces = `                `
  48 
  49     // clear has enough spaces in it to cover any chronograph output
  50     clear = "\r" + spaces + spaces + spaces + "\r"
  51 )
  52 
  53 const info = `
  54 countdown [period]
  55 
  56 Run a live countdown timer on stderr, until the time-period given ends,
  57 or the app is force-quit.
  58 
  59 The time-period is either a simple integer number (of seconds), or an
  60 integer followed by any of
  61   - "s" (for seconds)
  62   - "m" (for minutes)
  63   - "h" (for hours)
  64 without spaces, or a combination of those time-units without spaces.
  65 `
  66 
  67 func main() {
  68     if len(os.Args) == 1 {
  69         os.Stderr.WriteString(info[1:])
  70         return
  71     }
  72 
  73     if len(os.Args) == 2 {
  74         switch os.Args[1] {
  75         case `-h`, `--h`, `-help`, `--help`:
  76             os.Stderr.WriteString(info[1:])
  77             return
  78         }
  79 
  80         period, err := parseDuration(os.Args[1])
  81         if err != nil {
  82             os.Stderr.WriteString("\x1b[31m")
  83             os.Stderr.WriteString(err.Error())
  84             os.Stderr.WriteString("\x1b[0m\n")
  85             os.Exit(1)
  86         }
  87 
  88         os.Stderr.WriteString("Countdown lasting ")
  89         os.Stderr.WriteString(time.Time{}.Add(period).Format(`15:04:05`))
  90         os.Stderr.WriteString(" started\n")
  91         countdown(period)
  92         return
  93     }
  94 
  95     os.Stderr.WriteString(info[1:])
  96     os.Exit(1)
  97 }
  98 
  99 func parseDuration(s string) (time.Duration, error) {
 100     if n, err := strconv.Atoi(s); err == nil {
 101         return time.Duration(n) * time.Second, err
 102     }
 103     return time.ParseDuration(s)
 104 }
 105 
 106 func countdown(period time.Duration) {
 107     start := time.Now()
 108     end := start.Add(period)
 109     t := time.NewTicker(100 * time.Millisecond)
 110     startChronoLine(end, start)
 111 
 112     stopped := make(chan os.Signal, 1)
 113     defer close(stopped)
 114     signal.Notify(stopped, os.Interrupt)
 115 
 116     for {
 117         select {
 118         case now := <-t.C:
 119             os.Stderr.WriteString(clear)
 120             startChronoLine(end, now)
 121             if now.Sub(end) >= 0 {
 122                 t.Stop()
 123                 endChronoLine(start)
 124                 return
 125             }
 126 
 127         case <-stopped:
 128             t.Stop()
 129             endChronoLine(start)
 130             return
 131         }
 132     }
 133 }
 134 
 135 // func startChronoLine(end, now time.Time) {
 136 //  var buf [64]byte
 137 //  dt := end.Sub(now)
 138 //
 139 //  os.Stderr.Write(time.Time{}.Add(dt).AppendFormat(buf[:0], `15:04:05.0`))
 140 //  os.Stderr.WriteString(`    `)
 141 //  os.Stderr.Write(now.AppendFormat(buf[:0], `2006-01-02 15:04:05 Jan Mon`))
 142 // }
 143 
 144 func startChronoLine(end, now time.Time) {
 145     var buf [64]byte
 146     dt := end.Sub(now)
 147 
 148     s := buf[:0]
 149     s = time.Time{}.Add(dt).AppendFormat(s, `15:04:05.0`)
 150     s = append(s, `    `...)
 151     s = now.AppendFormat(s, `2006-01-02 15:04:05 Jan Mon`)
 152     os.Stderr.Write(s)
 153 }
 154 
 155 func endChronoLine(start time.Time) {
 156     var buf [64]byte
 157     secs := time.Since(start).Seconds()
 158 
 159     os.Stderr.WriteString(`    `)
 160     os.Stderr.Write(strconv.AppendFloat(buf[:0], secs, 'f', 4, 64))
 161     os.Stderr.WriteString(" seconds\n")
 162 }