github.com/jonsyu1/godel@v0.0.0-20171017211503-64567a0cf169/apps/okgo/checks/checker.go (about)

     1  // Copyright 2016 Palantir Technologies, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package checks
    16  
    17  import (
    18  	"os/exec"
    19  	"path/filepath"
    20  	"strings"
    21  
    22  	"github.com/palantir/amalgomate/amalgomated"
    23  	"github.com/palantir/pkg/pkgpath"
    24  	"github.com/pkg/errors"
    25  
    26  	"github.com/palantir/godel/apps/okgo/checkoutput"
    27  	"github.com/palantir/godel/apps/okgo/params"
    28  )
    29  
    30  type Checker interface {
    31  	// Cmd returns the command represented by this checker
    32  	Cmd() amalgomated.Cmd
    33  
    34  	// Check runs the current checker on "all" packages using the provided configuration and returns the output. The
    35  	// provided Cmder is used to invoke the check. "rootDir" is used as the root directory to determine the packages
    36  	// that the checker is run on. Conceptually, this method uses "config" and "rootDir" to generate the arguments
    37  	// required to check "all" packages (excluding any that the config specifies should be excluded), invokes the
    38  	// Cmder using those arguments in the given working directory, and returns the filtered output.
    39  	Check(runner amalgomated.Cmder, rootDir string, config params.OKGo) ([]checkoutput.Issue, error)
    40  
    41  	// CheckPackages runs the current checker on the specified packages using the provided configuration and returns
    42  	// the output. The provided Cmder is used to invoke the check. The root directory contained in the "packages"
    43  	// parameter is used as the working directory of the Cmder. Conceptually, this method uses "config" and
    44  	// "packages" to generate the arguments required to check the specified packages (excluding any that the config
    45  	// specifies should be excluded), invokes the Cmder using those arguments in the given working directory, and
    46  	// returns the filtered output.
    47  	CheckPackages(runner amalgomated.Cmder, packages pkgpath.Packages, config params.OKGo) ([]checkoutput.Issue, error)
    48  }
    49  
    50  const (
    51  	packages = allArgType("")
    52  	rootDir  = allArgType(".")
    53  	splat    = allArgType("./...")
    54  )
    55  
    56  type checkerDefinition struct {
    57  	cmd           amalgomated.Cmd
    58  	lineParser    checkoutput.LineParser
    59  	rawLineFilter func(line string) bool
    60  	allArg        allArgType
    61  	globalCheck   bool // true indicates that per-package checks are not supported (must be run on a root directory)
    62  }
    63  
    64  func (c *checkerDefinition) Cmd() amalgomated.Cmd {
    65  	return c.cmd
    66  }
    67  
    68  func (c *checkerDefinition) GetParser(rootDir string) checkoutput.IssueParser {
    69  	return &checkoutput.SingleLineIssueParser{
    70  		LineParser: c.lineParser,
    71  		RootDir:    rootDir,
    72  	}
    73  }
    74  
    75  func (c *checkerDefinition) Check(cmder amalgomated.Cmder, rootDir string, config params.OKGo) ([]checkoutput.Issue, error) {
    76  	if c.allArg == packages {
    77  		// this Checker should handle "all" by calling "CheckPackages" with "all" packages
    78  		packages, err := pkgpath.PackagesInDir(rootDir, config.Exclude)
    79  		if err != nil {
    80  			return nil, errors.Wrapf(err, "failed to get all packages in directory %s", rootDir)
    81  		}
    82  		return c.CheckPackages(cmder, packages, config)
    83  	}
    84  
    85  	checkArgsFromConfig, _ := config.ArgsForCheck(c.cmd)
    86  	allArg := string(c.allArg)
    87  	return c.checkWithFilters(cmder, append(checkArgsFromConfig, allArg), rootDir, config.FiltersForCheck(c.cmd))
    88  }
    89  
    90  func (c *checkerDefinition) CheckPackages(cmder amalgomated.Cmder, packages pkgpath.Packages, config params.OKGo) ([]checkoutput.Issue, error) {
    91  	if c.globalCheck {
    92  		// this check does not support package-specific checks
    93  		return nil, errors.Errorf("checker %s does not support specifying packages", c.cmd.Name())
    94  	}
    95  
    96  	// exclude packages specified to be excluded in config
    97  	filteredPackages, err := packages.Filter(config.Exclude)
    98  	if err != nil {
    99  		return nil, errors.Wrapf(err, "failed to filter packages %v specified in exclude configuration %v", packages, config.Exclude)
   100  	}
   101  
   102  	checkArgsFromConfig, _ := config.ArgsForCheck(c.cmd)
   103  
   104  	// translate packages into proper argument format for this runner
   105  	pkgArgs, err := filteredPackages.Paths(pkgpath.Relative)
   106  	if err != nil {
   107  		return nil, errors.Wrapf(err, "failed to get paths for packages")
   108  	}
   109  	return c.checkWithFilters(cmder, append(checkArgsFromConfig, pkgArgs...), packages.RootDir(), config.FiltersForCheck(c.cmd))
   110  }
   111  
   112  func (c *checkerDefinition) checkWithFilters(cmder amalgomated.Cmder, runnerArgs []string, cmdDir string, filters []checkoutput.Filterer) ([]checkoutput.Issue, error) {
   113  	output, err := c.check(cmder, runnerArgs, cmdDir)
   114  	if err != nil {
   115  		return nil, err
   116  	}
   117  	filteredOutput, err := checkoutput.ApplyFilters(output, filters)
   118  	if err != nil {
   119  		return nil, errors.Wrapf(err, "failed to apply filters to output %v", output)
   120  	}
   121  	return filteredOutput, nil
   122  }
   123  
   124  func (c *checkerDefinition) check(cmder amalgomated.Cmder, runnerArgs []string, cmdDir string) ([]checkoutput.Issue, error) {
   125  	var err error
   126  	if !filepath.IsAbs(cmdDir) {
   127  		cmdDir, err = filepath.Abs(cmdDir)
   128  		if err != nil {
   129  			return nil, errors.Wrapf(err, "failed to convert %s to an absolute path", cmdDir)
   130  		}
   131  	}
   132  
   133  	cmd := cmder.Cmd(runnerArgs, cmdDir)
   134  	rawOutput, err := cmd.CombinedOutput()
   135  	if _, ok := err.(*exec.ExitError); err != nil && !ok {
   136  		// only propagate error returned from runner if it is not an exec.ExitError -- ExitErrors are ignored
   137  		// because many check programs will return a non-zero exit code if any violations are found even if the
   138  		// check program itself ran successfully.
   139  		return nil, errors.Wrapf(err, "running check with args %v in directory %s failed", runnerArgs, cmdDir)
   140  	}
   141  
   142  	reader := strings.NewReader(string(rawOutput))
   143  	parser := c.GetParser(cmdDir)
   144  	return checkoutput.ParseIssues(reader, parser, c.rawLineFilter)
   145  }