File: dessv.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright (c) 2026 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 dessv.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "bytes"
  37     "errors"
  38     "io"
  39     "os"
  40 )
  41 
  42 const info = `
  43 dessv [filenames...]
  44 
  45 Turn Space(s)-Separated Values (SSV) into Tab-Separated Values (TSV), where
  46 both leading and trailing spaces from input lines are ignored.
  47 `
  48 
  49 func main() {
  50     buffered := false
  51     args := os.Args[1:]
  52 
  53     if len(args) > 0 {
  54         switch args[0] {
  55         case `-b`, `--b`, `-buffered`, `--buffered`:
  56             buffered = true
  57             args = args[1:]
  58 
  59         case `-h`, `--h`, `-help`, `--help`:
  60             os.Stdout.WriteString(info[1:])
  61             return
  62         }
  63     }
  64 
  65     if len(args) > 0 && args[0] == `--` {
  66         args = args[1:]
  67     }
  68 
  69     liveLines := !buffered
  70     if !buffered {
  71         if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil {
  72             liveLines = false
  73         }
  74     }
  75 
  76     if err := run(os.Stdout, args, liveLines); err != nil && err != io.EOF {
  77         os.Stderr.WriteString(err.Error())
  78         os.Stderr.WriteString("\n")
  79         os.Exit(1)
  80     }
  81 }
  82 
  83 func run(w io.Writer, args []string, live bool) error {
  84     bw := bufio.NewWriter(w)
  85     defer bw.Flush()
  86 
  87     if len(args) == 0 {
  88         return dessv(bw, os.Stdin, live)
  89     }
  90 
  91     for _, name := range args {
  92         if err := handleFile(bw, name, live); err != nil {
  93             return err
  94         }
  95     }
  96     return nil
  97 }
  98 
  99 func handleFile(w *bufio.Writer, name string, live bool) error {
 100     if name == `` || name == `-` {
 101         return dessv(w, os.Stdin, live)
 102     }
 103 
 104     f, err := os.Open(name)
 105     if err != nil {
 106         return errors.New(`can't read from file named "` + name + `"`)
 107     }
 108     defer f.Close()
 109 
 110     return dessv(w, f, live)
 111 }
 112 
 113 func dessv(w *bufio.Writer, r io.Reader, live bool) error {
 114     const gb = 1024 * 1024 * 1024
 115     sc := bufio.NewScanner(r)
 116     sc.Buffer(nil, 8*gb)
 117     handleRow := handleRowSSV
 118     numTabs := ^0
 119 
 120     for i := 0; sc.Scan(); i++ {
 121         s := sc.Bytes()
 122         if i == 0 {
 123             if bytes.HasPrefix(s, []byte{0xef, 0xbb, 0xbf}) {
 124                 s = s[3:]
 125             }
 126 
 127             for _, b := range s {
 128                 if b == '\t' {
 129                     handleRow = handleRowTSV
 130                     break
 131                 }
 132             }
 133             numTabs = handleRow(w, s, numTabs)
 134         } else {
 135             handleRow(w, s, numTabs)
 136         }
 137 
 138         if w.WriteByte('\n') != nil {
 139             return io.EOF
 140         }
 141 
 142         if !live {
 143             continue
 144         }
 145 
 146         if err := w.Flush(); err != nil {
 147             return io.EOF
 148         }
 149     }
 150 
 151     return sc.Err()
 152 }
 153 
 154 func handleRowSSV(w *bufio.Writer, s []byte, n int) int {
 155     for len(s) > 0 && s[0] == ' ' {
 156         s = s[1:]
 157     }
 158     for len(s) > 0 && s[len(s)-1] == ' ' {
 159         s = s[:len(s)-1]
 160     }
 161 
 162     got := 0
 163 
 164     for got = 0; len(s) > 0; got++ {
 165         if got > 0 {
 166             w.WriteByte('\t')
 167         }
 168 
 169         i := bytes.IndexByte(s, ' ')
 170         if i < 0 {
 171             w.Write(s)
 172             s = nil
 173             n--
 174             break
 175         }
 176 
 177         w.Write(s[:i])
 178         s = s[i+1:]
 179         for len(s) > 0 && s[0] == ' ' {
 180             s = s[1:]
 181         }
 182         n--
 183     }
 184 
 185     w.Write(s)
 186     writeTabs(w, n)
 187     return got
 188 }
 189 
 190 func handleRowTSV(w *bufio.Writer, s []byte, n int) int {
 191     got := 0
 192     for _, b := range s {
 193         if b == '\t' {
 194             got++
 195         }
 196     }
 197 
 198     w.Write(s)
 199     writeTabs(w, n-got)
 200     return got
 201 }
 202 
 203 func writeTabs(w *bufio.Writer, n int) {
 204     for n > 0 {
 205         w.WriteByte('\t')
 206         n--
 207     }
 208 }