|
13 | 13 | package main |
14 | 14 |
|
15 | 15 | import ( |
| 16 | + "flag" |
16 | 17 | "fmt" |
17 | 18 | "go/ast" |
18 | 19 | "go/parser" |
|
43 | 44 | excludes = []string{ |
44 | 45 | "test/conformance", |
45 | 46 | } |
| 47 | + addFlag = flag.Bool("add", false, "automatically add copyright headers to files that are missing them") |
46 | 48 | ) |
47 | 49 |
|
48 | 50 | func checkCopyright() ([]string, error) { |
@@ -136,15 +138,44 @@ func isGenerated(fset *token.FileSet, file *ast.File) bool { |
136 | 138 | return false |
137 | 139 | } |
138 | 140 |
|
| 141 | +func addCopyright(filename string) error { |
| 142 | + content, err := os.ReadFile(filename) |
| 143 | + if err != nil { |
| 144 | + return err |
| 145 | + } |
| 146 | + |
| 147 | + // Prepare the copyright header with proper comment formatting |
| 148 | + header := "// " + strings.ReplaceAll(copyright, "\n", "\n// ") + "\n\n" |
| 149 | + |
| 150 | + // Add the header to the beginning of the file |
| 151 | + newContent := header + string(content) |
| 152 | + |
| 153 | + return os.WriteFile(filename, []byte(newContent), 0644) |
| 154 | +} |
| 155 | + |
139 | 156 | func main() { |
| 157 | + flag.Parse() |
| 158 | + |
140 | 159 | files, err := checkCopyright() |
141 | 160 | if err != nil { |
142 | 161 | log.Fatal(err) |
143 | 162 | } |
144 | 163 | if len(files) > 0 { |
145 | | - fmt.Printf("[ERROR] invalid copyright files (%d):\n", len(files)) |
146 | | - fmt.Println(strings.Join(files, "\n")) |
147 | | - os.Exit(1) |
| 164 | + if *addFlag { |
| 165 | + fmt.Printf("Adding copyright headers to %d files:\n", len(files)) |
| 166 | + for _, file := range files { |
| 167 | + fmt.Printf(" %s\n", file) |
| 168 | + if err := addCopyright(file); err != nil { |
| 169 | + log.Printf("Failed to add copyright to %s: %v", file, err) |
| 170 | + continue |
| 171 | + } |
| 172 | + } |
| 173 | + fmt.Printf("Successfully added copyright headers to %d files!\n", len(files)) |
| 174 | + } else { |
| 175 | + fmt.Printf("[ERROR] invalid copyright files (%d):\n", len(files)) |
| 176 | + fmt.Println(strings.Join(files, "\n")) |
| 177 | + os.Exit(1) |
| 178 | + } |
148 | 179 | return |
149 | 180 | } |
150 | 181 | fmt.Println("Good files !") |
|
0 commit comments