github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/buildtools/govendor/govendor.go (about)

     1  // Package govendor provides tools for working with govendor.
     2  package govendor
     3  
     4  import (
     5  	"errors"
     6  	"path"
     7  	"path/filepath"
     8  	"time"
     9  
    10  	"github.com/apex/log"
    11  	"github.com/fossas/fossa-cli/buildtools"
    12  	"github.com/fossas/fossa-cli/files"
    13  	"github.com/fossas/fossa-cli/pkg"
    14  )
    15  
    16  // A Package is a single imported package within a govendor project.
    17  type Package struct {
    18  	Path         string
    19  	ChecksumSHA1 string
    20  	Revision     string
    21  	RevisionTime time.Time
    22  	Version      string
    23  	VersionExact string
    24  }
    25  
    26  // Lockfile contains the contents of a govendor lockfile.
    27  type Lockfile struct {
    28  	Comment string
    29  	Ignore  string
    30  	Package []Package
    31  
    32  	normalized map[string]pkg.Import
    33  }
    34  
    35  func (l Lockfile) Resolve(importpath string) (pkg.Import, error) {
    36  	log.Debugf("%#v", importpath)
    37  	for p := importpath; p != "." && p != "/"; p = path.Dir(p) {
    38  		log.Debugf("Trying: %#v", p)
    39  		rev, ok := l.normalized[p]
    40  		if ok {
    41  			rev.Resolved.Name = importpath
    42  			return rev, nil
    43  		}
    44  	}
    45  	return pkg.Import{}, buildtools.ErrNoRevisionForPackage
    46  }
    47  
    48  func New(dirname string) (Lockfile, error) {
    49  	ok, err := UsedIn(dirname)
    50  	if err != nil {
    51  		return Lockfile{}, err
    52  	}
    53  	if !ok {
    54  		return Lockfile{}, errors.New("directory does not use govendor")
    55  	}
    56  	lockfile, err := FromFile(filepath.Join(dirname, "vendor", "vendor.json"))
    57  	if err != nil {
    58  		return Lockfile{}, err
    59  	}
    60  	normalized := make(map[string]pkg.Import)
    61  	for _, project := range lockfile.Package {
    62  		normalized[project.Path] = pkg.Import{
    63  			Target: project.Version,
    64  			Resolved: pkg.ID{
    65  				Type:     pkg.Go,
    66  				Name:     project.Path,
    67  				Revision: project.Revision,
    68  				Location: "",
    69  			},
    70  		}
    71  	}
    72  
    73  	lockfile.normalized = normalized
    74  	return lockfile, nil
    75  }
    76  
    77  // UsedIn checks whether govendor is used correctly within a project folder.
    78  func UsedIn(dirname string) (bool, error) {
    79  	return files.Exists(dirname, "vendor", "vendor.json")
    80  }
    81  
    82  // FromFile reads a raw Lockfile from a vendor/vendor.json file.
    83  func FromFile(filename string) (Lockfile, error) {
    84  	var lockfile Lockfile
    85  	err := files.ReadJSON(&lockfile, filename)
    86  	if err != nil {
    87  		return Lockfile{}, err
    88  	}
    89  	return lockfile, nil
    90  }