File: gobble.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 gobble. 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 gobble.go 32 */ 33 34 package main 35 36 import ( 37 "bytes" 38 "io" 39 "os" 40 "os/exec" 41 ) 42 43 const info = ` 44 gobble [command...] [args...] 45 46 Read all bytes from standard input, and only then emit them out, or run 47 the command given, sending those bytes to its standard input. 48 ` 49 50 func main() { 51 if len(os.Args) > 1 { 52 switch os.Args[1] { 53 case `-h`, `--h`, `-help`, `--help`: 54 os.Stderr.WriteString(info[1:]) 55 return 56 } 57 } 58 59 // wait until the last byte is read 60 input, err := io.ReadAll(os.Stdin) 61 if err != nil { 62 showError(err) 63 os.Exit(1) 64 } 65 66 // emit data just read and quit, if no command was given 67 if len(os.Args) == 1 { 68 os.Stdout.Write(input) 69 return 70 } 71 72 // run a command, using the data just read for its stdin 73 name := os.Args[1] 74 args := os.Args[2:] 75 cmd := exec.Command(name, args...) 76 cmd.Stdin = bytes.NewReader(input) 77 cmd.Stdout = os.Stdout 78 cmd.Stderr = os.Stderr 79 80 if err := cmd.Start(); err != nil { 81 showError(err) 82 } 83 84 if err := cmd.Wait(); err != nil { 85 showError(err) 86 } 87 88 os.Exit(cmd.ProcessState.ExitCode()) 89 } 90 91 // showError gives a consistent style/look to any of the app's own errors 92 func showError(err error) { 93 os.Stderr.WriteString("\x1b[31m") 94 os.Stderr.WriteString(err.Error()) 95 os.Stderr.WriteString("\x1b[0m\n") 96 }