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

     1  // Package godep provides functions for working with the godep tool.
     2  package godep
     3  
     4  import (
     5  	"errors"
     6  	"path/filepath"
     7  
     8  	"github.com/fossas/fossa-cli/buildtools"
     9  	"github.com/fossas/fossa-cli/files"
    10  	"github.com/fossas/fossa-cli/pkg"
    11  )
    12  
    13  // A Package is a single imported package within a godep project.
    14  type Package struct {
    15  	ImportPath string
    16  	Rev        string
    17  	Comment    string
    18  }
    19  
    20  // Lockfile contains the contents of a godep lockfile.
    21  type Lockfile struct {
    22  	ImportPath   string
    23  	GoVersion    string
    24  	GodepVersion string
    25  	Deps         []Package
    26  
    27  	normalized map[string]pkg.Import
    28  }
    29  
    30  // Resolve implements resolver.Resolver for godep.
    31  func (l Lockfile) Resolve(importpath string) (pkg.Import, error) {
    32  	rev, ok := l.normalized[importpath]
    33  	if !ok {
    34  		return pkg.Import{}, buildtools.ErrNoRevisionForPackage
    35  	}
    36  	return rev, nil
    37  }
    38  
    39  // New constructs a godep Lockfile while pre-computing the revision lookup.
    40  func New(dirname string) (Lockfile, error) {
    41  	ok, err := UsedIn(dirname)
    42  	if err != nil {
    43  		return Lockfile{}, err
    44  	}
    45  	if !ok {
    46  		return Lockfile{}, errors.New("directory does not use godep")
    47  	}
    48  	lockfile, err := FromFile(filepath.Join(dirname, "Godeps", "Godeps.json"))
    49  	if err != nil {
    50  		return Lockfile{}, err
    51  	}
    52  	normalized := make(map[string]pkg.Import)
    53  	for _, project := range lockfile.Deps {
    54  		normalized[project.ImportPath] = pkg.Import{
    55  			Target: project.Comment,
    56  			Resolved: pkg.ID{
    57  				Type:     pkg.Go,
    58  				Name:     project.ImportPath,
    59  				Revision: project.Rev,
    60  				Location: "",
    61  			},
    62  		}
    63  	}
    64  
    65  	lockfile.normalized = normalized
    66  	return lockfile, nil
    67  }
    68  
    69  // UsedIn checks whether godep is used correctly within a project folder.
    70  func UsedIn(dirname string) (bool, error) {
    71  	return files.Exists(dirname, "Godeps", "Godeps.json")
    72  }
    73  
    74  // FromFile reads a raw Lockfile from a Godeps/Godeps.json file.
    75  func FromFile(filename string) (Lockfile, error) {
    76  	var lockfile Lockfile
    77  	err := files.ReadJSON(&lockfile, filename)
    78  	if err != nil {
    79  		return Lockfile{}, err
    80  	}
    81  	return lockfile, nil
    82  }