github.com/thanos-io/thanos@v0.32.5/scripts/copyright/copyright.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package main
     5  
     6  import (
     7  	"bytes"
     8  	"log"
     9  	"os"
    10  	"path/filepath"
    11  	"strings"
    12  )
    13  
    14  type copyright []byte
    15  
    16  var (
    17  	// thanos compatible for Go and Proto files.
    18  	thanos copyright = []byte(`// Copyright (c) The Thanos Authors.
    19  // Licensed under the Apache License 2.0.
    20  
    21  `)
    22  	cortex copyright = []byte(`// Copyright (c) The Cortex Authors.
    23  // Licensed under the Apache License 2.0.
    24  
    25  `)
    26  )
    27  
    28  func applyLicenseToProtoAndGo() error {
    29  	return filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
    30  		if err != nil {
    31  			return err
    32  		}
    33  
    34  		// Filter out stuff that does not need copyright.
    35  		if info.IsDir() {
    36  			switch path {
    37  			case "vendor":
    38  				return filepath.SkipDir
    39  			}
    40  			return nil
    41  		}
    42  		if strings.HasSuffix(path, ".pb.go") {
    43  			return nil
    44  		}
    45  		if (filepath.Ext(path) != ".proto" && filepath.Ext(path) != ".go") ||
    46  			// We copied this file, and we want to maintain its license (MIT).
    47  			path == "pkg/testutil/testutil.go" ||
    48  			// Generated file.
    49  			path == "pkg/ui/bindata.go" {
    50  			return nil
    51  		}
    52  
    53  		b, err := os.ReadFile(filepath.Clean(path))
    54  		if err != nil {
    55  			return err
    56  		}
    57  
    58  		var cr copyright
    59  		if strings.HasPrefix(path, "internal/cortex") {
    60  			// We vendored in Cortex files, and we want to maintain its license
    61  			cr = cortex
    62  		} else {
    63  			cr = thanos
    64  		}
    65  		if err := writeLicence(cr, path, b); err != nil {
    66  			return err
    67  		}
    68  		return nil
    69  	})
    70  }
    71  
    72  func writeLicence(cr copyright, path string, b []byte) error {
    73  	if !strings.HasPrefix(string(b), string(cr)) {
    74  		log.Println("file", path, "is missing Copyright header. Adding.")
    75  
    76  		var bb bytes.Buffer
    77  		_, _ = bb.Write(cr)
    78  		_, _ = bb.Write(b)
    79  		if err := os.WriteFile(path, bb.Bytes(), 0600); err != nil {
    80  			return err
    81  		}
    82  	}
    83  	return nil
    84  }
    85  
    86  func main() {
    87  	if err := applyLicenseToProtoAndGo(); err != nil {
    88  		log.Fatal(err)
    89  	}
    90  }