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