copyright_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. // Checks for files missing copyright notice
  7. package meta
  8. import (
  9. "bufio"
  10. "fmt"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "testing"
  16. )
  17. // File extensions to check
  18. var copyrightCheckExts = map[string]bool{
  19. ".go": true,
  20. }
  21. // Directories to search
  22. var copyrightCheckDirs = []string{".", "../cmd", "../lib", "../test", "../script"}
  23. // Valid copyright headers, searched for in the top five lines in each file.
  24. var copyrightRegexps = []string{
  25. `Copyright`,
  26. `package auto`,
  27. `automatically generated by genxdr`,
  28. `generated by protoc`,
  29. }
  30. var copyrightRe = regexp.MustCompile(strings.Join(copyrightRegexps, "|"))
  31. func TestCheckCopyright(t *testing.T) {
  32. for _, dir := range copyrightCheckDirs {
  33. err := filepath.Walk(dir, checkCopyright)
  34. if err != nil {
  35. t.Error(err)
  36. }
  37. }
  38. }
  39. func checkCopyright(path string, info os.FileInfo, err error) error {
  40. if err != nil {
  41. return err
  42. }
  43. if !info.Mode().IsRegular() {
  44. return nil
  45. }
  46. if !copyrightCheckExts[filepath.Ext(path)] {
  47. return nil
  48. }
  49. fd, err := os.Open(path)
  50. if err != nil {
  51. return err
  52. }
  53. defer fd.Close()
  54. scanner := bufio.NewScanner(fd)
  55. for i := 0; scanner.Scan() && i < 5; i++ {
  56. if copyrightRe.MatchString(scanner.Text()) {
  57. return nil
  58. }
  59. }
  60. return fmt.Errorf("missing copyright in %s?", path)
  61. }