File: plain.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 plain.
  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 plain.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 plain [options...] [file...]
  49 
  50 
  51 Turn potentially ANSI-styled plain-text into actual plain-text.
  52 
  53 Input is assumed to be UTF-8, and all CRLF byte-pairs are turned into line
  54 feeds.
  55 
  56 All (optional) leading options start with either single or double-dash:
  57 
  58     -h          show this help message
  59     -help       show this help message
  60 `
  61 
  62 const errorStyle = "\x1b[31m"
  63 
  64 // errNoMoreOutput is a dummy error whose message is ignored, and which
  65 // causes the app to quit immediately and successfully
  66 var errNoMoreOutput = errors.New(`no more output`)
  67 
  68 func main() {
  69     if len(os.Args) > 1 {
  70         switch os.Args[1] {
  71         case `-h`, `--h`, `-help`, `--help`:
  72             os.Stderr.WriteString(info[1:])
  73             return
  74         }
  75     }
  76 
  77     if err := run(os.Stdout, os.Args[1:]); isActualError(err) {
  78         os.Stderr.WriteString(errorStyle)
  79         os.Stderr.WriteString(err.Error())
  80         os.Stderr.WriteString("\x1b[0m\n")
  81         os.Exit(1)
  82     }
  83 }
  84 
  85 func run(w io.Writer, args []string) error {
  86     bw := bufio.NewWriter(w)
  87     defer bw.Flush()
  88 
  89     if len(args) == 0 {
  90         return plain(bw, os.Stdin)
  91     }
  92 
  93     for _, name := range args {
  94         if err := handleFile(bw, name); err != nil {
  95             return err
  96         }
  97     }
  98     return nil
  99 }
 100 
 101 func handleFile(w *bufio.Writer, name string) error {
 102     if name == `` || name == `-` {
 103         return plain(w, os.Stdin)
 104     }
 105 
 106     f, err := os.Open(name)
 107     if err != nil {
 108         return errors.New(`can't read from file named "` + name + `"`)
 109     }
 110     defer f.Close()
 111 
 112     return plain(w, f)
 113 }
 114 
 115 // isActualError is to figure out whether not to ignore an error, and thus
 116 // show it as an error message
 117 func isActualError(err error) bool {
 118     return err != nil && err != io.EOF && err != errNoMoreOutput
 119 }
 120 
 121 // indexEscapeSequence finds the first ANSI-style escape-sequence, which is
 122 // either the alert/bell byte, or the multi-byte sequences starting either
 123 // with ESC[ or ESC]; either returned index can be negative
 124 func indexEscapeSequence(s []byte) (int, int) {
 125     var prev byte
 126 
 127     for i, b := range s {
 128         if b == '\a' {
 129             return i, i + 1
 130         }
 131 
 132         if prev == '\x1b' && b == '[' {
 133             j := indexLetter(s[i+1:])
 134             if j < 0 {
 135                 return i, -1
 136             }
 137             return i - 1, i + 1 + j + 1
 138         }
 139 
 140         if prev == '\x1b' && b == ']' {
 141             j := bytes.IndexByte(s[i+1:], ':')
 142             if j < 0 {
 143                 return i, -1
 144             }
 145             return i - 1, i + 1 + j + 1
 146         }
 147 
 148         if prev == '\x1b' && b == '\\' {
 149             return i - 1, i + 1
 150         }
 151 
 152         prev = b
 153     }
 154 
 155     return -1, -1
 156 }
 157 
 158 func indexLetter(s []byte) int {
 159     for i, b := range s {
 160         if 'A' <= b && b <= 'Z' {
 161             return i
 162         }
 163         if 'a' <= b && b <= 'z' {
 164             return i
 165         }
 166     }
 167 
 168     return -1
 169 }
 170 
 171 func plain(w *bufio.Writer, r io.Reader) error {
 172     const gb = 1024 * 1024 * 1024
 173     sc := bufio.NewScanner(r)
 174     sc.Buffer(nil, 8*gb)
 175 
 176     for sc.Scan() {
 177         line := sc.Bytes()
 178 
 179         for len(line) > 0 {
 180             i, j := indexEscapeSequence(line)
 181             if i < 0 {
 182                 w.Write(line)
 183                 break
 184             }
 185 
 186             w.Write(line[:i])
 187 
 188             if j < 0 {
 189                 break
 190             }
 191             line = line[j:]
 192         }
 193 
 194         w.WriteByte('\n')
 195         if err := w.Flush(); err != nil {
 196             // a write error may be the consequence of stdout being closed,
 197             // perhaps by another app along a pipe
 198             return errNoMoreOutput
 199         }
 200     }
 201 
 202     return sc.Err()
 203 }