copyright_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. ".sql": true,
  21. }
  22. // Directories to search
  23. var copyrightCheckDirs = []string{".", "../cmd", "../internal", "../lib", "../test", "../script"}
  24. // Valid copyright headers, searched for in the top five lines in each file.
  25. var copyrightRegexps = []string{
  26. `Copyright`,
  27. `package auto`,
  28. `automatically generated by genxdr`,
  29. `generated by protoc`,
  30. `^// Code generated .* DO NOT EDIT\.$`,
  31. }
  32. var copyrightRe = regexp.MustCompile(strings.Join(copyrightRegexps, "|"))
  33. func TestCheckCopyright(t *testing.T) {
  34. for _, dir := range copyrightCheckDirs {
  35. err := filepath.Walk(dir, checkCopyright)
  36. if err != nil {
  37. t.Error(err)
  38. }
  39. }
  40. }
  41. func checkCopyright(path string, info os.FileInfo, err error) error {
  42. if err != nil {
  43. return err
  44. }
  45. if !info.Mode().IsRegular() {
  46. return nil
  47. }
  48. if !copyrightCheckExts[filepath.Ext(path)] {
  49. return nil
  50. }
  51. fd, err := os.Open(path)
  52. if err != nil {
  53. return err
  54. }
  55. defer fd.Close()
  56. scanner := bufio.NewScanner(fd)
  57. for i := 0; scanner.Scan() && i < 5; i++ {
  58. if copyrightRe.MatchString(scanner.Text()) {
  59. return nil
  60. }
  61. }
  62. return fmt.Errorf("missing copyright in %s?", path)
  63. }