File: nj.go 1 /* 2 The MIT License (MIT) 3 4 Copyright © 2024 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 nj: this version has no http(s) support. Even 27 the unit-tests from the original nj are omitted. 28 29 To compile a smaller-sized command-line app, you can use the `go` command as 30 follows: 31 32 go build -ldflags "-s -w" -trimpath nj.go 33 */ 34 35 package main 36 37 import ( 38 "bufio" 39 "encoding/json" 40 "errors" 41 "io" 42 "os" 43 ) 44 45 const info = ` 46 nj [filepath...] 47 48 Nice Json reads JSON, and emits it back as ANSI-styled indented lines, using 49 2 spaces for each indentation level. 50 ` 51 52 // indent is how many spaces each indentation level uses 53 const indent = 2 54 55 const ( 56 // boolStyle is bluish, and very distinct from all other colors used 57 boolStyle = "\x1b[38;5;74m" 58 59 // keyStyle is magenta, and very distinct from normal strings 60 keyStyle = "\x1b[38;5;99m" 61 62 // nullStyle is a light-gray, just like syntax elements, but the word 63 // `null` is wide enough to stand out from syntax items at a glance 64 nullStyle = syntaxStyle 65 66 // numberStyle is a nice green 67 numberStyle = "\x1b[38;5;29m" 68 69 // stringStyle used to be bluish, but it's better to keep it plain, 70 // which also minimizes how many different colors the output can show 71 stringStyle = "" 72 73 // stringStyle is bluish, but clearly darker than boolStyle 74 // stringStyle = "\x1b[38;5;24m" 75 76 // syntaxStyle is a light-gray, not too light, not too dark 77 syntaxStyle = "\x1b[38;5;248m" 78 ) 79 80 // errNoMoreOutput is a way to successfully quit the app right away, its 81 // message never shown 82 var errNoMoreOutput = errors.New(`no more output`) 83 84 func main() { 85 if len(os.Args) > 1 { 86 switch os.Args[1] { 87 case `-h`, `--h`, `-help`, `--help`: 88 os.Stderr.WriteString(info[1:]) 89 return 90 } 91 } 92 93 if len(os.Args) > 2 { 94 showError(errors.New(`multiple inputs not allowed`)) 95 os.Exit(1) 96 } 97 98 var err error 99 if len(os.Args) == 1 || (len(os.Args) == 2 && os.Args[1] == `-`) { 100 // handle lack of filepath arg, or `-` as the filepath 101 err = niceJSON(os.Stdout, os.Stdin) 102 } else { 103 // handle being given a normal filepath 104 err = handleFile(os.Stdout, os.Args[1]) 105 } 106 107 if err != nil && err != errNoMoreOutput { 108 showError(err) 109 os.Exit(1) 110 } 111 } 112 113 // showError standardizes how errors look in this app 114 func showError(err error) { 115 os.Stderr.WriteString("\x1b[31m") 116 os.Stderr.WriteString(err.Error()) 117 os.Stderr.WriteString("\x1b[0m\n") 118 } 119 120 // writeSpaces does what it says, minimizing calls to write-like funcs 121 func writeSpaces(w *bufio.Writer, n int) { 122 const spaces = ` ` 123 for n >= len(spaces) { 124 w.WriteString(spaces) 125 n -= len(spaces) 126 } 127 if n > 0 { 128 w.WriteString(spaces[:n]) 129 } 130 } 131 132 func handleFile(w io.Writer, path string) error { 133 // if f := strings.HasPrefix; f(path, `https://`) || f(path, `http://`) { 134 // resp, err := http.Get(path) 135 // if err != nil { 136 // return err 137 // } 138 // defer resp.Body.Close() 139 // return niceJSON(w, resp.Body) 140 // } 141 142 f, err := os.Open(path) 143 if err != nil { 144 // on windows, file-not-found error messages may mention `CreateFile`, 145 // even when trying to open files in read-only mode 146 return errors.New(`can't open file named ` + path) 147 } 148 defer f.Close() 149 150 return niceJSON(w, f) 151 } 152 153 func niceJSON(w io.Writer, r io.Reader) error { 154 bw := bufio.NewWriter(w) 155 defer bw.Flush() 156 157 dec := json.NewDecoder(r) 158 // using string-like json.Number values instead of float64 ones avoids 159 // unneeded reformatting of numbers; reformatting parsed float64 values 160 // can potentially even drop/change decimals, causing the output not to 161 // match the input digits exactly, which is best to avoid 162 dec.UseNumber() 163 164 t, err := dec.Token() 165 if err == io.EOF { 166 return errors.New(`empty input isn't valid JSON`) 167 } 168 if err != nil { 169 return err 170 } 171 172 if err := handleToken(bw, dec, t, 0, 0); err != nil { 173 return err 174 } 175 // don't forget to end the last output line 176 bw.WriteByte('\n') 177 178 if _, err := dec.Token(); err != io.EOF { 179 return errors.New(`unexpected trailing JSON data`) 180 } 181 return nil 182 } 183 184 func handleToken(w *bufio.Writer, d *json.Decoder, t json.Token, pre, level int) error { 185 switch t := t.(type) { 186 case json.Delim: 187 switch t { 188 case json.Delim('['): 189 return handleArray(w, d, pre, level) 190 191 case json.Delim('{'): 192 return handleObject(w, d, pre, level) 193 194 default: 195 // return fmt.Errorf(`unsupported JSON delimiter %v`, t) 196 return errors.New(`unsupported JSON delimiter`) 197 } 198 199 case nil: 200 return handleNull(w, pre) 201 202 case bool: 203 return handleBoolean(w, t, pre) 204 205 case string: 206 return handleString(w, t, pre) 207 208 case json.Number: 209 return handleNumber(w, t, pre) 210 211 default: 212 // return fmt.Errorf(`unsupported token type %T`, t) 213 return errors.New(`unsupported token type`) 214 } 215 } 216 217 func handleArray(w *bufio.Writer, d *json.Decoder, pre, level int) error { 218 for i := 0; true; i++ { 219 t, err := d.Token() 220 if err != nil { 221 return err 222 } 223 224 if t == json.Delim(']') { 225 if i == 0 { 226 writeSpaces(w, indent*pre) 227 w.WriteString(syntaxStyle + "[]\x1b[0m") 228 } else { 229 w.WriteString("\n") 230 writeSpaces(w, indent*level) 231 w.WriteString(syntaxStyle + "]\x1b[0m") 232 } 233 return nil 234 } 235 236 if i == 0 { 237 writeSpaces(w, indent*pre) 238 w.WriteString(syntaxStyle + "[\x1b[0m\n") 239 } else { 240 // this is a good spot to check for early-quit opportunities 241 _, err = w.WriteString(syntaxStyle + ",\x1b[0m\n") 242 if err != nil { 243 return errNoMoreOutput 244 } 245 } 246 247 writeSpaces(w, indent*(level+1)) 248 if err := handleToken(w, d, t, level, level+1); err != nil { 249 return err 250 } 251 } 252 253 // make the compiler happy 254 return nil 255 } 256 257 func handleBoolean(w *bufio.Writer, b bool, pre int) error { 258 writeSpaces(w, indent*pre) 259 if b { 260 w.WriteString(boolStyle + "true\x1b[0m") 261 } else { 262 w.WriteString(boolStyle + "false\x1b[0m") 263 } 264 return nil 265 } 266 267 func handleKey(w *bufio.Writer, s string, pre int) error { 268 writeSpaces(w, indent*pre) 269 w.WriteString(syntaxStyle + "\"\x1b[0m" + keyStyle) 270 w.WriteString(s) 271 w.WriteString(syntaxStyle + "\":\x1b[0m ") 272 return nil 273 } 274 275 func handleNull(w *bufio.Writer, pre int) error { 276 writeSpaces(w, indent*pre) 277 w.WriteString(nullStyle + "null\x1b[0m") 278 return nil 279 } 280 281 func handleNumber(w *bufio.Writer, n json.Number, pre int) error { 282 writeSpaces(w, indent*pre) 283 w.WriteString(numberStyle) 284 w.WriteString(n.String()) 285 w.WriteString("\x1b[0m") 286 return nil 287 } 288 289 func handleObject(w *bufio.Writer, d *json.Decoder, pre, level int) error { 290 for i := 0; true; i++ { 291 t, err := d.Token() 292 if err != nil { 293 return err 294 } 295 296 if t == json.Delim('}') { 297 if i == 0 { 298 writeSpaces(w, indent*pre) 299 w.WriteString(syntaxStyle + "{}\x1b[0m") 300 } else { 301 w.WriteString("\n") 302 writeSpaces(w, indent*level) 303 w.WriteString(syntaxStyle + "}\x1b[0m") 304 } 305 return nil 306 } 307 308 if i == 0 { 309 writeSpaces(w, indent*pre) 310 w.WriteString(syntaxStyle + "{\x1b[0m\n") 311 } else { 312 // this is a good spot to check for early-quit opportunities 313 _, err = w.WriteString(syntaxStyle + ",\x1b[0m\n") 314 if err != nil { 315 return errNoMoreOutput 316 } 317 } 318 319 // the stdlib's JSON parser is supposed to complain about non-string 320 // keys anyway, but make sure just in case 321 k, ok := t.(string) 322 if !ok { 323 return errors.New(`expected key to be a string`) 324 } 325 if err := handleKey(w, k, level+1); err != nil { 326 return err 327 } 328 329 // handle value 330 t, err = d.Token() 331 if err != nil { 332 return err 333 } 334 if err := handleToken(w, d, t, 0, level+1); err != nil { 335 return err 336 } 337 } 338 339 // make the compiler happy 340 return nil 341 } 342 343 func handleString(w *bufio.Writer, s string, pre int) error { 344 writeSpaces(w, indent*pre) 345 w.WriteString(syntaxStyle + "\"\x1b[0m" + stringStyle) 346 w.WriteString(s) 347 w.WriteString(syntaxStyle + "\"\x1b[0m") 348 return nil 349 }