github.com/SpiderOak/wwhrd@v0.2.2-0.20181011170608-77c9537cbd49/cli.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/jessevdk/go-flags"
     9  	log "github.com/sirupsen/logrus"
    10  )
    11  
    12  type cliOpts struct {
    13  	List        `command:"list" alias:"ls" description:"List licenses"`
    14  	Check       `command:"check" alias:"chk" description:"Check licenses against config file"`
    15  	VersionFlag func() error `long:"version" short:"v" description:"Show CLI version"`
    16  
    17  	Quiet func() error `short:"q" long:"quiet" description:"quiet mode, do not log accepted packages"`
    18  }
    19  
    20  type List struct {
    21  	NoColor bool `long:"no-color" description:"disable colored output"`
    22  }
    23  
    24  type Check struct {
    25  	File      string `short:"f" long:"file" description:"input file" default:".wwhrd.yml"`
    26  	ReportOut string `short:"r" long:"report-out" description:"report of all licenses found" default:""`
    27  	NoColor   bool   `long:"no-color" description:"disable colored output"`
    28  }
    29  
    30  const VersionHelp flags.ErrorType = 1961
    31  
    32  var (
    33  	version = "dev"
    34  	commit  = "1961213"
    35  	date    = "1961-02-13T20:06:35Z"
    36  )
    37  
    38  func setQuiet() error {
    39  	log.SetLevel(log.ErrorLevel)
    40  	return nil
    41  }
    42  
    43  func newCli() *flags.Parser {
    44  	opts := cliOpts{
    45  		VersionFlag: func() error {
    46  			return &flags.Error{
    47  				Type:    VersionHelp,
    48  				Message: fmt.Sprintf("version %s\ncommit %s\ndate %s\n", version, commit, date),
    49  			}
    50  		},
    51  		Quiet: setQuiet,
    52  	}
    53  	parser := flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash)
    54  	parser.LongDescription = "What would Henry Rollins do?"
    55  
    56  	return parser
    57  }
    58  
    59  func (l *List) Execute(args []string) error {
    60  
    61  	if l.NoColor {
    62  		log.SetFormatter(&log.TextFormatter{DisableColors: true})
    63  	} else {
    64  		log.SetFormatter(&log.TextFormatter{ForceColors: true})
    65  	}
    66  
    67  	root, err := rootDir()
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	pkgs, err := WalkImports(root)
    73  	if err != nil {
    74  		return err
    75  	}
    76  	lics := GetLicenses(root, pkgs)
    77  
    78  	for k, v := range lics {
    79  		if v.Recognized() {
    80  			log.WithFields(log.Fields{
    81  				"package": k,
    82  				"license": v.Type,
    83  			}).Info("Found License")
    84  		} else {
    85  			log.WithFields(log.Fields{
    86  				"package": k,
    87  			}).Warning("Did not find recognized license!")
    88  		}
    89  	}
    90  
    91  	return nil
    92  }
    93  
    94  const licenseReportHeader = `THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED IN PORTIONS OF THE FLOW PROJECT`
    95  const licenseReportTemplate = `
    96  
    97  ---
    98  
    99  The following software may be included in this product: %s. This software contains the following license and notice below:
   100  
   101  %s
   102  `
   103  
   104  func (c *Check) Execute(args []string) error {
   105  
   106  	if c.NoColor {
   107  		log.SetFormatter(&log.TextFormatter{DisableColors: true})
   108  	} else {
   109  		log.SetFormatter(&log.TextFormatter{ForceColors: true})
   110  	}
   111  
   112  	t, err := ReadConfig(c.File)
   113  	if err != nil {
   114  		err = fmt.Errorf("Can't read config file: %s", err)
   115  		return err
   116  	}
   117  
   118  	root, err := rootDir()
   119  	if err != nil {
   120  		return err
   121  	}
   122  
   123  	pkgs, err := WalkImports(root)
   124  	if err != nil {
   125  		return err
   126  	}
   127  	lics := GetLicenses(root, pkgs)
   128  
   129  	// Make a map out of the blacklist
   130  	blacklist := make(map[string]bool)
   131  	for _, v := range t.Blacklist {
   132  		blacklist[v] = true
   133  	}
   134  
   135  	// Make a map out of the whitelist
   136  	whitelist := make(map[string]bool)
   137  	for _, v := range t.Whitelist {
   138  		whitelist[v] = true
   139  	}
   140  
   141  	// Make a map out of the exceptions list
   142  	exceptions := make(map[string]bool)
   143  	exceptionsWildcard := make(map[string]bool)
   144  	for _, v := range t.Exceptions {
   145  		if strings.HasSuffix(v, "/...") {
   146  			exceptionsWildcard[strings.TrimRight(v, "/...")] = true
   147  		} else {
   148  			exceptions[v] = true
   149  		}
   150  	}
   151  
   152  	var report *os.File
   153  
   154  	if c.ReportOut != "" {
   155  		report, err = os.Create(c.ReportOut)
   156  		if err != nil {
   157  			return err
   158  		}
   159  		defer report.Close()
   160  
   161  		_, err = report.WriteString(licenseReportHeader)
   162  		if err != nil {
   163  			return err
   164  		}
   165  	}
   166  
   167  PackageList:
   168  	for pkg, lic := range lics {
   169  
   170  		if report != nil {
   171  			_, err = report.WriteString(fmt.Sprintf(licenseReportTemplate, pkg, lic.Text))
   172  			if err != nil {
   173  				return err
   174  			}
   175  		}
   176  
   177  		contextLogger := log.WithFields(log.Fields{
   178  			"package": pkg,
   179  			"license": lic.Type,
   180  		})
   181  
   182  		// License is whitelisted and not specified in blacklist
   183  		if whitelist[lic.Type] && !blacklist[lic.Type] {
   184  			contextLogger.Info("Found Approved license")
   185  			continue PackageList
   186  		}
   187  
   188  		// if we have exceptions wildcards, let's run through them
   189  		if len(exceptionsWildcard) > 0 {
   190  			for wc, _ := range exceptionsWildcard {
   191  				if strings.HasPrefix(pkg, wc) {
   192  					// we have a match
   193  					contextLogger.Warn("Found exceptioned package")
   194  					continue PackageList
   195  				}
   196  			}
   197  		}
   198  
   199  		// match single-package exceptions
   200  		if _, exists := exceptions[pkg]; exists {
   201  			contextLogger.Warn("Found exceptioned package")
   202  			continue PackageList
   203  		}
   204  
   205  		// no matches, it's a non-approved license
   206  		contextLogger.Error("Found Non-Approved license")
   207  		err = fmt.Errorf("Non-Approved license found")
   208  
   209  	}
   210  
   211  	return err
   212  }
   213  
   214  func rootDir() (string, error) {
   215  	root, err := os.Getwd()
   216  	if err != nil {
   217  		return "", err
   218  	}
   219  
   220  	info, err := os.Lstat(root)
   221  	if err != nil {
   222  		return "", err
   223  	}
   224  	if info.Mode()&os.ModeSymlink != 0 {
   225  		root, err = os.Readlink(root)
   226  		if err != nil {
   227  			return "", err
   228  		}
   229  	}
   230  	return root, nil
   231  }