| 1 | /* |
| 2 | Copyright The containerd Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "flag" |
| 21 | "fmt" |
| 22 | "go/format" |
| 23 | "go/parser" |
| 24 | "go/token" |
| 25 | "io" |
| 26 | "io/ioutil" |
| 27 | "os" |
| 28 | "regexp" |
| 29 | "strings" |
| 30 | ) |
| 31 | |
| 32 | const name = "go-fix-acronym" |
| 33 | |
| 34 | type stringArray []string |
| 35 | |
| 36 | func (w *stringArray) String() string { |
| 37 | return strings.Join(*w, ",") |
| 38 | } |
| 39 | |
| 40 | func (w *stringArray) Set(value string) error { |
| 41 | *w = append(*w, value) |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | type config struct { |
| 46 | overwrite bool |
| 47 | acronyms stringArray |
| 48 | } |
| 49 | |
| 50 | func rewriteFile(c config, pattern *regexp.Regexp, path string) error { |
| 51 | content, err := ioutil.ReadFile(path) |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | |
| 56 | fset := token.NewFileSet() |
| 57 | tree, err := parser.ParseFile(fset, path, content, parser.ParseComments) |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | |
| 62 | rewriteNode(pattern, tree) |
| 63 | |
| 64 | var out io.Writer |
| 65 | if c.overwrite { |
| 66 | f, err := os.OpenFile(path, os.O_WRONLY, 0) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | out = f |
| 71 | defer f.Close() |
| 72 | } else { |
| 73 | out = os.Stdout |
| 74 | } |
| 75 | format.Node(out, fset, tree) |
| 76 | |
| 77 | return nil |
| 78 | } |
| 79 | |
| 80 | func realMain(c config, args []string) error { |
| 81 | pattern, err := compilePattern(c) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | for _, path := range args { |
| 86 | err := rewriteFile(c, pattern, path) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | } |
| 91 | return nil |
| 92 | } |
| 93 | |
| 94 | func main() { |
| 95 | var c config |
| 96 | flag.BoolVar(&c.overwrite, "w", false, "write result to (source) file instead of stdout") |
| 97 | flag.Var(&c.acronyms, "a", "acronym to capitalize") |
| 98 | flag.Parse() |
| 99 | |
| 100 | err := realMain(c, flag.Args()) |
| 101 | if err != nil { |
| 102 | fmt.Fprintf(os.Stderr, "%s: %s\n", name, err) |
| 103 | os.Exit(1) |
| 104 | } |
| 105 | } |