Source file src/internal/copyright/copyright_test.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package copyright
     6  
     7  import (
     8  	"bytes"
     9  	"internal/testenv"
    10  	"io"
    11  	"io/fs"
    12  	"os"
    13  	"path/filepath"
    14  	"testing"
    15  )
    16  
    17  var copyright = []byte("Copyright")
    18  
    19  var permitted = [][]byte{
    20  	[]byte("// Code generated by "),
    21  	[]byte("// Code generated from "),
    22  	[]byte("// Created by cgo -cdefs"),
    23  	[]byte("// DO NOT EDIT\n// generated by:"),
    24  	[]byte("// Empty assembly file"),
    25  	[]byte("// Generated using cgo"),
    26  	[]byte("// Original source:\n//\thttp://www.zorinaq.com/papers/md5-amd64.html"), // public domain crypto/md5
    27  	[]byte("// created by cgo -cdefs"),
    28  	[]byte("// go run mkasm.go"),
    29  	[]byte("// mkerrors"),
    30  	[]byte("// mksys"),
    31  	[]byte("// run\n// Code generated by"), // cmd/compile/internal/test/constFold_test.go
    32  	[]byte("//go:build !nethttpomithttp2"), // hack to pacify h2_bundle, which drops copyright header
    33  }
    34  
    35  func TestCopyright(t *testing.T) {
    36  	buf := make([]byte, 2048)
    37  	filepath.WalkDir(filepath.Join(testenv.GOROOT(t), "src"), func(path string, d fs.DirEntry, err error) error {
    38  		if d.IsDir() && (d.Name() == "testdata" || d.Name() == "vendor") {
    39  			return filepath.SkipDir
    40  		}
    41  		switch filepath.Ext(d.Name()) {
    42  		default:
    43  			return nil
    44  		case ".s", ".go":
    45  			// check
    46  		}
    47  
    48  		f, err := os.Open(path)
    49  		if err != nil {
    50  			t.Error(err)
    51  			return nil
    52  		}
    53  		defer f.Close()
    54  		n, err := f.Read(buf)
    55  		if err != nil && err != io.EOF {
    56  			t.Error(err)
    57  			return nil
    58  		}
    59  		b := buf[:n]
    60  		if bytes.Contains(b, copyright) {
    61  			return nil
    62  		}
    63  		for _, ok := range permitted {
    64  			if bytes.HasPrefix(b, ok) {
    65  				return nil
    66  			}
    67  		}
    68  		t.Logf("%.100s %s", b, path)
    69  		t.Errorf("%s: missing copyright notice", path)
    70  		return nil
    71  	})
    72  }
    73  

View as plain text