github.com/google/osv-scalibr@v0.4.1/extractor/filesystem/language/java/purl/purl.go (about)

     1  // Copyright 2025 Google LLC
     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 purl converts a package to a Maven type PackageURL.
    16  package purl
    17  
    18  import (
    19  	"strings"
    20  
    21  	archivemeta "github.com/google/osv-scalibr/extractor/filesystem/language/java/archive/metadata"
    22  	"github.com/google/osv-scalibr/extractor/filesystem/language/java/javalockfile"
    23  	"github.com/google/osv-scalibr/purl"
    24  )
    25  
    26  // MakePackageURL returns a package URL from a version string and a Maven specific metadata struct
    27  // according to the Maven PURL spec:
    28  // - Group ID is lowercased and stored as the namespace
    29  // - Artifact ID is lowercased and stored as the name
    30  func MakePackageURL(version string, metadata any) *purl.PackageURL {
    31  	switch m := metadata.(type) {
    32  	case *archivemeta.Metadata:
    33  		return &purl.PackageURL{
    34  			Type:      purl.TypeMaven,
    35  			Namespace: strings.ToLower(m.GroupID),
    36  			Name:      strings.ToLower(m.ArtifactID),
    37  			Version:   version,
    38  		}
    39  	case *javalockfile.Metadata:
    40  		q := map[string]string{}
    41  		if m.Classifier != "" {
    42  			q[purl.Classifier] = m.Classifier
    43  		}
    44  		if m.Type != "" {
    45  			q[purl.Type] = m.Type
    46  		}
    47  		var qualifiers purl.Qualifiers
    48  		if len(q) > 0 {
    49  			qualifiers = purl.QualifiersFromMap(q)
    50  		}
    51  		return &purl.PackageURL{
    52  			Type:       purl.TypeMaven,
    53  			Namespace:  strings.ToLower(m.GroupID),
    54  			Name:       strings.ToLower(m.ArtifactID),
    55  			Version:    version,
    56  			Qualifiers: qualifiers,
    57  		}
    58  	default:
    59  		return nil
    60  	}
    61  }