copyright_test.go 1.5 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. }
  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. `^// Code generated .* DO NOT EDIT\.$`,
  30. }
  31. var copyrightRe = regexp.MustCompile(strings.Join(copyrightRegexps, "|"))
  32. func TestCheckCopyright(t *testing.T) {
  33. for _, dir := range copyrightCheckDirs {
  34. err := filepath.Walk(dir, checkCopyright)
  35. if err != nil {
  36. t.Error(err)
  37. }
  38. }
  39. }
  40. func checkCopyright(path string, info os.FileInfo, err error) error {
  41. if err != nil {
  42. return err
  43. }
  44. if !info.Mode().IsRegular() {
  45. return nil
  46. }
  47. if !copyrightCheckExts[filepath.Ext(path)] {
  48. return nil
  49. }
  50. fd, err := os.Open(path)
  51. if err != nil {
  52. return err
  53. }
  54. defer fd.Close()
  55. scanner := bufio.NewScanner(fd)
  56. for i := 0; scanner.Scan() && i < 5; i++ {
  57. if copyrightRe.MatchString(scanner.Text()) {
  58. return nil
  59. }
  60. }
  61. return fmt.Errorf("missing copyright in %s?", path)
  62. }