CheckNewFiles checks that all new files contain the required file header with the correct year.
()
| 224 | |
| 225 | // CheckNewFiles checks that all new files contain the required file header with the correct year. |
| 226 | func (h Headers) CheckNewFiles() error { |
| 227 | mg.Deps(Headers.loadFile) |
| 228 | base := "origin/" + os.Getenv("GITHUB_BASE_REF") |
| 229 | |
| 230 | currentYear := time.Now().Year() |
| 231 | correctHeader := fmt.Sprintf("// Copyright © %d ", currentYear) |
| 232 | |
| 233 | cmd := exec.Command("git", "diff", "--name-only", "--diff-filter=A", base) |
| 234 | output, err := cmd.Output() |
| 235 | if err != nil { |
| 236 | return fmt.Errorf("failed to get list of new files: %w", err) |
| 237 | } |
| 238 | |
| 239 | var checkErrs errorSlice |
| 240 | for _, path := range strings.Split(strings.TrimSpace(string(output)), "\n") { |
| 241 | // Check if the file matches the HeaderRule before checking its header. |
| 242 | if rule := headerConfig.get(path); rule == nil { |
| 243 | continue // Skip files that do not match any HeaderRule. |
| 244 | } |
| 245 | |
| 246 | fileContent, err := os.ReadFile(path) |
| 247 | if err != nil { |
| 248 | return fmt.Errorf("failed to read file %s: %w", path, err) |
| 249 | } |
| 250 | |
| 251 | // Check if the first line of the file contains the correct copyright header. |
| 252 | scanner := bufio.NewScanner(bytes.NewReader(fileContent)) |
| 253 | if scanner.Scan() { |
| 254 | firstLine := scanner.Text() |
| 255 | if !strings.Contains(firstLine, correctHeader) { |
| 256 | checkErrs = append(checkErrs, &checkErr{Path: path, Reason: "incorrect year in copyright header; should be " + strconv.Itoa(currentYear)}) |
| 257 | } |
| 258 | } else { |
| 259 | checkErrs = append(checkErrs, &checkErr{Path: path, Reason: "empty file or missing header"}) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | if len(checkErrs) > 0 { |
| 264 | return checkErrs |
| 265 | } |
| 266 | return nil |
| 267 | } |
| 268 | |
| 269 | func init() { |
| 270 | preCommitChecks = append(preCommitChecks, Headers.Check) |