File: jsons.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 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 jsons.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "io"
  37     "os"
  38     "strings"
  39 )
  40 
  41 const info = `
  42 jsons [options...] [filenames...]
  43 
  44 JSON Strings turns TSV (tab-separated values) data into a JSON array of
  45 objects whose values are strings or nulls, the latter being used for
  46 missing trailing values.
  47 `
  48 
  49 // noMoreOutput is a custom error-type meant to be deliberately ignored
  50 type noMoreOutput struct{}
  51 
  52 func (nmo noMoreOutput) Error() string {
  53     return `no more output`
  54 }
  55 
  56 func main() {
  57     if len(os.Args) > 1 {
  58         switch os.Args[1] {
  59         case `-h`, `--h`, `-help`, `--help`:
  60             os.Stdout.WriteString(info[1:])
  61             return
  62         }
  63     }
  64 
  65     err := run(os.Args[1:])
  66     if _, ok := err.(noMoreOutput); ok {
  67         err = nil
  68     }
  69 
  70     if err != nil {
  71         os.Stderr.WriteString("\x1b[31m")
  72         os.Stderr.WriteString(err.Error())
  73         os.Stderr.WriteString("\x1b[0m\n")
  74         os.Exit(1)
  75     }
  76 }
  77 
  78 type runConfig struct {
  79     lines int
  80     keys  []string
  81 }
  82 
  83 func run(paths []string) error {
  84     bw := bufio.NewWriter(os.Stdout)
  85     defer bw.Flush()
  86 
  87     dashes := 0
  88     var cfg runConfig
  89 
  90     for _, path := range paths {
  91         if path == `-` {
  92             dashes++
  93             if dashes > 1 {
  94                 continue
  95             }
  96 
  97             if err := handleInput(bw, os.Stdin, &cfg); err != nil {
  98                 return err
  99             }
 100 
 101             continue
 102         }
 103 
 104         if err := handleFile(bw, path, &cfg); err != nil {
 105             return err
 106         }
 107     }
 108 
 109     if len(paths) == 0 {
 110         if err := handleInput(bw, os.Stdin, &cfg); err != nil {
 111             return err
 112         }
 113     }
 114 
 115     if cfg.lines > 1 {
 116         bw.WriteString("\n]\n")
 117     } else {
 118         bw.WriteString("[]\n")
 119     }
 120     return nil
 121 }
 122 
 123 func handleFile(w *bufio.Writer, path string, cfg *runConfig) error {
 124     f, err := os.Open(path)
 125     if err != nil {
 126         return err
 127     }
 128     defer f.Close()
 129     return handleInput(w, f, cfg)
 130 }
 131 
 132 func escapeKeys(line string) []string {
 133     var keys []string
 134     var sb strings.Builder
 135 
 136     loopTSV(line, func(i int, s string) {
 137         sb.WriteByte('"')
 138         for _, r := range s {
 139             if r == '\\' || r == '"' {
 140                 sb.WriteByte('\\')
 141             }
 142             sb.WriteRune(r)
 143         }
 144         sb.WriteByte('"')
 145 
 146         keys = append(keys, sb.String())
 147         sb.Reset()
 148     })
 149 
 150     return keys
 151 }
 152 
 153 func emitRow(w *bufio.Writer, line string, keys []string) {
 154     j := 0
 155     w.WriteByte('{')
 156 
 157     loopTSV(line, func(i int, s string) {
 158         j = i
 159         if i > 0 {
 160             w.WriteString(", ")
 161         }
 162 
 163         w.WriteString(keys[i])
 164         w.WriteString(": \"")
 165 
 166         for _, r := range s {
 167             if r == '\\' || r == '"' {
 168                 w.WriteByte('\\')
 169             }
 170             w.WriteRune(r)
 171         }
 172         w.WriteByte('"')
 173     })
 174 
 175     for i := j + 1; i < len(keys); i++ {
 176         if i > 0 {
 177             w.WriteString(", ")
 178         }
 179         w.WriteString(keys[i])
 180         w.WriteString(": null")
 181     }
 182     w.WriteByte('}')
 183 }
 184 
 185 func loopTSV(line string, f func(i int, s string)) {
 186     for i := 0; len(line) > 0; i++ {
 187         pos := strings.IndexByte(line, '\t')
 188         if pos < 0 {
 189             f(i, line)
 190             return
 191         }
 192 
 193         f(i, line[:pos])
 194         line = line[pos+1:]
 195     }
 196 }
 197 
 198 func handleInput(w *bufio.Writer, r io.Reader, cfg *runConfig) error {
 199     const gb = 1024 * 1024 * 1024
 200     sc := bufio.NewScanner(r)
 201     sc.Buffer(nil, 8*gb)
 202 
 203     for sc.Scan() {
 204         if cfg.lines == 0 {
 205             cfg.keys = escapeKeys(sc.Text())
 206             w.WriteByte('[')
 207             cfg.lines++
 208             continue
 209         }
 210 
 211         if cfg.lines == 1 {
 212             w.WriteString("\n  ")
 213         } else {
 214             if _, err := w.WriteString(",\n  "); err != nil {
 215                 return noMoreOutput{}
 216             }
 217         }
 218 
 219         emitRow(w, sc.Text(), cfg.keys)
 220         cfg.lines++
 221     }
 222 
 223     return sc.Err()
 224 }