File: squeeze.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 squeeze.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "bytes"
  37     "errors"
  38     "io"
  39     "os"
  40 )
  41 
  42 // Note: the code is avoiding using the fmt package to save hundreds of
  43 // kilobytes on the resulting executable, which is a noticeable difference.
  44 
  45 const info = `
  46 squeeze [filenames...]
  47 
  48 Ignore leading/trailing spaces (and carriage-returns) on lines, also turning
  49 all runs of multiple consecutive spaces into single spaces. Spaces around
  50 tabs are ignored as well.
  51 `
  52 
  53 // errNoMoreOutput is a dummy error whose message is ignored, and which
  54 // causes the app to quit immediately and successfully
  55 var errNoMoreOutput = errors.New(`no more output`)
  56 
  57 func main() {
  58     buffered := false
  59     args := os.Args[1:]
  60 
  61     if len(args) > 0 {
  62         switch args[0] {
  63         case `-b`, `--b`, `-buffered`, `--buffered`:
  64             buffered = true
  65             args = args[1:]
  66 
  67         case `-h`, `--h`, `-help`, `--help`:
  68             os.Stdout.WriteString(info[1:])
  69             return
  70         }
  71     }
  72 
  73     if len(args) > 0 && args[0] == `--` {
  74         args = args[1:]
  75     }
  76 
  77     liveLines := !buffered
  78     if !buffered {
  79         if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil {
  80             liveLines = false
  81         }
  82     }
  83 
  84     if err := run(os.Stdout, args, liveLines); isActualError(err) {
  85         os.Stderr.WriteString(err.Error())
  86         os.Stderr.WriteString("\n")
  87         os.Exit(1)
  88     }
  89 }
  90 
  91 func run(w io.Writer, args []string, live bool) error {
  92     bw := bufio.NewWriter(w)
  93     defer bw.Flush()
  94 
  95     if len(args) == 0 {
  96         return squeeze(bw, os.Stdin, live)
  97     }
  98 
  99     for _, name := range args {
 100         if err := handleFile(bw, name, live); err != nil {
 101             return err
 102         }
 103     }
 104     return nil
 105 }
 106 
 107 func handleFile(w *bufio.Writer, name string, live bool) error {
 108     if name == `` || name == `-` {
 109         return squeeze(w, os.Stdin, live)
 110     }
 111 
 112     f, err := os.Open(name)
 113     if err != nil {
 114         return errors.New(`can't read from file named "` + name + `"`)
 115     }
 116     defer f.Close()
 117 
 118     return squeeze(w, f, live)
 119 }
 120 
 121 // isActualError is to figure out whether not to ignore an error, and thus
 122 // show it as an error message
 123 func isActualError(err error) bool {
 124     return err != nil && err != errNoMoreOutput
 125 }
 126 
 127 func squeeze(w *bufio.Writer, r io.Reader, live bool) error {
 128     const gb = 1024 * 1024 * 1024
 129     sc := bufio.NewScanner(r)
 130     sc.Buffer(nil, 8*gb)
 131 
 132     for i := 0; sc.Scan(); i++ {
 133         s := sc.Bytes()
 134         if i == 0 && bytes.HasPrefix(s, []byte{0xef, 0xbb, 0xbf}) {
 135             s = s[3:]
 136         }
 137 
 138         writeSqueezed(w, s)
 139         if w.WriteByte('\n') != nil {
 140             return errNoMoreOutput
 141         }
 142 
 143         if !live {
 144             continue
 145         }
 146 
 147         if err := w.Flush(); err != nil {
 148             return errNoMoreOutput
 149         }
 150     }
 151 
 152     return sc.Err()
 153 }
 154 
 155 func writeSqueezed(w *bufio.Writer, s []byte) {
 156     // ignore leading spaces
 157     for len(s) > 0 && s[0] == ' ' {
 158         s = s[1:]
 159     }
 160 
 161     // ignore trailing spaces
 162     for len(s) > 0 && s[len(s)-1] == ' ' {
 163         s = s[:len(s)-1]
 164     }
 165 
 166     i := 0
 167     space := false
 168 
 169     for i < len(s) {
 170         switch b := s[i]; b {
 171         case ' ':
 172             space = true
 173             i++
 174 
 175         case '\t':
 176             space = false
 177             i++
 178             for i < len(s) && s[i] == ' ' {
 179                 i++
 180             }
 181             w.WriteByte('\t')
 182 
 183         default:
 184             if space {
 185                 w.WriteByte(' ')
 186                 space = false
 187             }
 188             w.WriteByte(b)
 189         }
 190     }
 191 }