File: catl.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 catl.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 catl [options...] [file...]
  47 
  48 
  49 Unlike "cat", conCATenate Lines ensures lines across inputs are never joined
  50 by accident, when an input's last line doesn't end with a line-feed.
  51 
  52 Input is assumed to be UTF-8, and all CRLF byte-pairs are turned into line
  53 feeds. Leading BOM (byte-order marks) on first lines are also ignored.
  54 
  55 All (optional) leading options start with either single or double-dash:
  56 
  57     -h          show this help message
  58     -help       show this help message
  59 `
  60 
  61 func main() {
  62     buffered := false
  63     args := os.Args[1:]
  64 
  65     if len(args) > 0 {
  66         switch args[0] {
  67         case `-b`, `--b`, `-buffered`, `--buffered`:
  68             buffered = true
  69             args = args[1:]
  70 
  71         case `-h`, `--h`, `-help`, `--help`:
  72             os.Stdout.WriteString(info[1:])
  73             return
  74         }
  75     }
  76 
  77     if len(args) > 0 && args[0] == `--` {
  78         args = args[1:]
  79     }
  80 
  81     liveLines := !buffered
  82     if !buffered {
  83         if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil {
  84             liveLines = false
  85         }
  86     }
  87 
  88     if err := run(os.Stdout, args, liveLines); err != nil && err != io.EOF {
  89         os.Stderr.WriteString(err.Error())
  90         os.Stderr.WriteString("\n")
  91         os.Exit(1)
  92     }
  93 }
  94 
  95 func run(w io.Writer, args []string, live bool) error {
  96     bw := bufio.NewWriter(w)
  97     defer bw.Flush()
  98 
  99     dashes := 0
 100     for _, name := range args {
 101         if name == `-` {
 102             dashes++
 103         }
 104         if dashes > 1 {
 105             break
 106         }
 107     }
 108 
 109     if len(args) == 0 {
 110         return catl(bw, os.Stdin, live)
 111     }
 112 
 113     var stdin []byte
 114     gotStdin := false
 115 
 116     for _, name := range args {
 117         if name == `-` {
 118             if dashes == 1 {
 119                 if err := catl(bw, os.Stdin, live); err != nil {
 120                     return err
 121                 }
 122                 continue
 123             }
 124 
 125             if !gotStdin {
 126                 data, err := io.ReadAll(os.Stdin)
 127                 if err != nil {
 128                     return err
 129                 }
 130                 stdin = data
 131                 gotStdin = true
 132             }
 133 
 134             bw.Write(stdin)
 135             if len(stdin) > 0 && stdin[len(stdin)-1] != '\n' {
 136                 bw.WriteByte('\n')
 137             }
 138 
 139             if !live {
 140                 continue
 141             }
 142 
 143             if err := bw.Flush(); err != nil {
 144                 return io.EOF
 145             }
 146 
 147             continue
 148         }
 149 
 150         if err := handleFile(bw, name, live); err != nil {
 151             return err
 152         }
 153     }
 154     return nil
 155 }
 156 
 157 func handleFile(w *bufio.Writer, name string, live bool) error {
 158     if name == `` || name == `-` {
 159         return catl(w, os.Stdin, live)
 160     }
 161 
 162     f, err := os.Open(name)
 163     if err != nil {
 164         return errors.New(`can't read from file named "` + name + `"`)
 165     }
 166     defer f.Close()
 167 
 168     return catl(w, f, live)
 169 }
 170 
 171 func catl(w *bufio.Writer, r io.Reader, live bool) error {
 172     if !live {
 173         return catlFast(w, r)
 174     }
 175 
 176     const gb = 1024 * 1024 * 1024
 177     sc := bufio.NewScanner(r)
 178     sc.Buffer(nil, 8*gb)
 179 
 180     for i := 0; sc.Scan(); i++ {
 181         s := sc.Bytes()
 182         if i == 0 && bytes.HasPrefix(s, []byte{0xef, 0xbb, 0xbf}) {
 183             s = s[3:]
 184         }
 185 
 186         w.Write(s)
 187         if w.WriteByte('\n') != nil {
 188             return io.EOF
 189         }
 190 
 191         if err := w.Flush(); err != nil {
 192             return io.EOF
 193         }
 194     }
 195 
 196     return sc.Err()
 197 }
 198 
 199 func catlFast(w *bufio.Writer, r io.Reader) error {
 200     var buf [32 * 1024]byte
 201     var last byte = '\n'
 202 
 203     for i := 0; true; i++ {
 204         n, err := r.Read(buf[:])
 205         if n > 0 && err == io.EOF {
 206             err = nil
 207         }
 208         if err == io.EOF {
 209             if last != '\n' {
 210                 w.WriteByte('\n')
 211             }
 212             return nil
 213         }
 214 
 215         if err != nil {
 216             return err
 217         }
 218 
 219         chunk := buf[:n]
 220         if i == 0 && bytes.HasPrefix(chunk, []byte{0xef, 0xbb, 0xbf}) {
 221             chunk = chunk[3:]
 222         }
 223 
 224         if len(chunk) >= 1 {
 225             w.Write(chunk)
 226             last = chunk[len(chunk)-1]
 227         }
 228     }
 229 
 230     return nil
 231 }