github.com/lineaje-labs/syft@v0.98.1-0.20231227153149-9e393f60ff1b/syft/pkg/cataloger/java/parse_gradle_lockfile.go (about)

     1  package java
     2  
     3  import (
     4  	"bufio"
     5  	"strings"
     6  
     7  	"github.com/anchore/syft/syft/artifact"
     8  	"github.com/anchore/syft/syft/file"
     9  	"github.com/anchore/syft/syft/pkg"
    10  	"github.com/anchore/syft/syft/pkg/cataloger/generic"
    11  )
    12  
    13  const gradleLockfileGlob = "**/gradle.lockfile*"
    14  
    15  // Dependency represents a single dependency in the gradle.lockfile file
    16  type LockfileDependency struct {
    17  	Group   string
    18  	Name    string
    19  	Version string
    20  }
    21  
    22  func parseGradleLockfile(_ file.Resolver, _ *generic.Environment, reader file.LocationReadCloser) ([]pkg.Package, []artifact.Relationship, error) {
    23  	var pkgs []pkg.Package
    24  
    25  	// Create a new scanner to read the file
    26  	scanner := bufio.NewScanner(reader)
    27  
    28  	// Create slices to hold the dependencies and plugins
    29  	dependencies := []LockfileDependency{}
    30  
    31  	// Loop over all lines in the file
    32  	for scanner.Scan() {
    33  		line := scanner.Text()
    34  
    35  		// Trim leading and trailing whitespace from the line
    36  		line = strings.TrimSpace(line)
    37  
    38  		groupNameVersion := line
    39  		groupNameVersion = strings.Split(groupNameVersion, "=")[0]
    40  		parts := strings.Split(groupNameVersion, ":")
    41  
    42  		// we have a version directly specified
    43  		if len(parts) == 3 {
    44  			// Create a new Dependency struct and add it to the dependencies slice
    45  			dep := LockfileDependency{Group: parts[0], Name: parts[1], Version: parts[2]}
    46  			dependencies = append(dependencies, dep)
    47  		}
    48  	}
    49  
    50  	// map the dependencies
    51  	for _, dep := range dependencies {
    52  		archive := pkg.JavaArchive{
    53  			PomProject: &pkg.JavaPomProject{
    54  				GroupID:    dep.Group,
    55  				ArtifactID: dep.Name,
    56  				Version:    dep.Version,
    57  				Name:       dep.Name,
    58  			},
    59  		}
    60  
    61  		mappedPkg := pkg.Package{
    62  			Name:    dep.Name,
    63  			Version: dep.Version,
    64  			Locations: file.NewLocationSet(
    65  				reader.Location.WithAnnotation(pkg.EvidenceAnnotationKey, pkg.PrimaryEvidenceAnnotation),
    66  			),
    67  			Language: pkg.Java,
    68  			Type:     pkg.JavaPkg,
    69  			PURL:     packageURL(dep.Name, dep.Version, archive),
    70  			Metadata: archive,
    71  		}
    72  		mappedPkg.SetID()
    73  		pkgs = append(pkgs, mappedPkg)
    74  	}
    75  
    76  	return pkgs, nil, nil
    77  }