github.com/rgonomic/rgo@v0.2.2-0.20220708095818-4747f0905d6e/internal/mod/license.go (about)

     1  // Copyright ©2019 The rgonomic 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 mod
     6  
     7  import (
     8  	"io/ioutil"
     9  	"log"
    10  	"os"
    11  	"path/filepath"
    12  	"regexp"
    13  	"strings"
    14  
    15  	"github.com/google/licensecheck"
    16  )
    17  
    18  // License holds a package's license information.
    19  type License struct {
    20  	// Path is the path to the license relative
    21  	// to the root of the repository.
    22  	Path string
    23  
    24  	// Text is the text of the license.
    25  	Text []byte
    26  
    27  	// Cover is the license check information
    28  	// for the license.
    29  	Cover licensecheck.Coverage
    30  }
    31  
    32  // Licenses returns all detected licenses under the specified
    33  // root path. If verbose is true, Licenses will log additional
    34  // information to os.Stderr.
    35  func Licenses(root string, candidate *regexp.Regexp, verbose bool) ([]License, error) {
    36  	var files []License
    37  	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    38  		if err != nil {
    39  			return nil
    40  		}
    41  		if info.IsDir() {
    42  			if strings.HasPrefix(info.Name(), ".") {
    43  				return filepath.SkipDir
    44  			}
    45  			return nil
    46  		}
    47  		if candidate != nil && !candidate.MatchString(info.Name()) {
    48  			return nil
    49  		}
    50  		b, err := ioutil.ReadFile(path)
    51  		if err != nil {
    52  			return err
    53  		}
    54  		cover, ok := licensecheck.Cover(b, licensecheck.Options{})
    55  		if ok {
    56  			files = append(files, License{Path: path, Cover: cover, Text: b})
    57  		} else if verbose {
    58  			log.Println("missed:", path)
    59  		}
    60  		return nil
    61  	})
    62  	return files, err
    63  }