-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
71 lines (64 loc) · 1.54 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/spf13/pflag"
"github.com/xdg-go/go-rewrap-errors/internal/rewriter"
)
func printHelp(exitCode int) {
fmt.Fprint(os.Stderr, "usage: go-rewrap-errors [options] [input-filename]\n\n")
fmt.Fprint(os.Stderr, "If no input filename is provided, it will read from stdin.\n\n")
pflag.PrintDefaults()
os.Exit(exitCode)
}
func main() {
// Setup options
optWrite := pflag.BoolP("write", "w", false, "overwrite source file instead of writing to stdout")
optHelp := pflag.BoolP("help", "h", false, "show this help text")
pflag.Parse()
if *optHelp {
printHelp(0)
}
// Read original source
var oldSource []byte
var filename string
var fromStdin bool
var err error
switch len(pflag.Args()) {
case 0:
fromStdin = true
filename = "stdin"
oldSource, err = ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("couldn't read from stdin: %v", err)
os.Exit(1)
}
case 1:
filename = pflag.Args()[0]
oldSource, err = ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("couldn't read from %s: %v", filename, err)
os.Exit(1)
}
default:
log.Print("Error: too many command line arguments\n\n")
printHelp(1)
}
// Rewrite the original source
newSource, err := rewriter.Rewrite(filename, oldSource)
if err != nil {
log.Fatal(err)
}
// Overwrite or print the new source
if !fromStdin && *optWrite {
fi, err := os.Stat(filename)
if err != nil {
log.Fatal(err)
}
ioutil.WriteFile(filename, newSource, fi.Mode())
} else {
fmt.Print(string(newSource))
}
}