github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/syft/pkg/cataloger/java/parse_gradle_lockfile.go (about)

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