File: catl.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 Single-file source-code for catl.
  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 catl.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "bufio"
  38     "bytes"
  39     "errors"
  40     "io"
  41     "os"
  42 )
  43 
  44 // Note: the code is avoiding using the fmt package to save hundreds of
  45 // kilobytes on the resulting executable, which is a noticeable difference.
  46 
  47 const info = `
  48 catl [options...] [file...]
  49 
  50 
  51 Unlike "cat", conCATenate Lines ensures lines across inputs are never joined
  52 by accident, when an input's last line doesn't end with a line-feed.
  53 
  54 Input is assumed to be UTF-8, and all CRLF byte-pairs are turned into line
  55 feeds. Leading BOM (byte-order marks) on first lines are also ignored.
  56 
  57 All (optional) leading options start with either single or double-dash:
  58 
  59     -h          show this help message
  60     -help       show this help message
  61 `
  62 
  63 // errNoMoreOutput is a dummy error whose message is ignored, and which
  64 // causes the app to quit immediately and successfully
  65 var errNoMoreOutput = errors.New(`no more output`)
  66 
  67 func main() {
  68     args := os.Args[1:]
  69 
  70     if len(args) > 0 {
  71         switch args[0] {
  72         case `-h`, `--h`, `-help`, `--help`:
  73             os.Stderr.WriteString(info[1:])
  74             return
  75 
  76         case `--`:
  77             args = args[1:]
  78         }
  79     }
  80 
  81     liveLines := true
  82     if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil {
  83         liveLines = false
  84     }
  85 
  86     if err := run(os.Stdout, args, liveLines); isActualError(err) {
  87         os.Stderr.WriteString(err.Error())
  88         os.Stderr.WriteString("\n")
  89         os.Exit(1)
  90     }
  91 }
  92 
  93 func run(w io.Writer, args []string, live bool) error {
  94     bw := bufio.NewWriter(w)
  95     defer bw.Flush()
  96 
  97     if len(args) == 0 {
  98         return catl(bw, os.Stdin, live)
  99     }
 100 
 101     for _, name := range args {
 102         if err := handleFile(bw, name, live); err != nil {
 103             return err
 104         }
 105     }
 106     return nil
 107 }
 108 
 109 func handleFile(w *bufio.Writer, name string, live bool) error {
 110     if name == `` || name == `-` {
 111         return catl(w, os.Stdin, live)
 112     }
 113 
 114     f, err := os.Open(name)
 115     if err != nil {
 116         return errors.New(`can't read from file named "` + name + `"`)
 117     }
 118     defer f.Close()
 119 
 120     return catl(w, f, live)
 121 }
 122 
 123 // isActualError is to figure out whether not to ignore an error, and thus
 124 // show it as an error message
 125 func isActualError(err error) bool {
 126     return err != nil && err != errNoMoreOutput
 127 }
 128 
 129 func catl(w *bufio.Writer, r io.Reader, live bool) error {
 130     const gb = 1024 * 1024 * 1024
 131     sc := bufio.NewScanner(r)
 132     sc.Buffer(nil, 8*gb)
 133 
 134     for i := 0; sc.Scan(); i++ {
 135         if i == 0 && bytes.HasPrefix(sc.Bytes(), []byte{0xef, 0xbb, 0xbf}) {
 136             w.Write(sc.Bytes()[3:])
 137         } else {
 138             w.Write(sc.Bytes())
 139         }
 140 
 141         if w.WriteByte('\n') != nil {
 142             return errNoMoreOutput
 143         }
 144 
 145         if !live {
 146             continue
 147         }
 148 
 149         if err := w.Flush(); err != nil {
 150             return errNoMoreOutput
 151         }
 152     }
 153 
 154     return sc.Err()
 155 }