github.com/google/osv-scalibr@v0.4.1/artifact/image/layerscanning/testing/fakelayerbuilder/extractor.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 fakelayerbuilder
    16  
    17  import (
    18  	"bufio"
    19  	"context"
    20  	"strings"
    21  
    22  	"github.com/google/osv-scalibr/extractor"
    23  	"github.com/google/osv-scalibr/extractor/filesystem"
    24  	"github.com/google/osv-scalibr/inventory"
    25  	"github.com/google/osv-scalibr/plugin"
    26  	"github.com/google/osv-scalibr/purl"
    27  )
    28  
    29  // FakeTestLayersExtractor extracts FakeTestLayers built from the FakeLayerBuilder
    30  type FakeTestLayersExtractor struct {
    31  }
    32  
    33  // Name of the extractor.
    34  func (e FakeTestLayersExtractor) Name() string { return "fake/layerextractor" }
    35  
    36  // Version of the extractor.
    37  func (e FakeTestLayersExtractor) Version() int { return 0 }
    38  
    39  // Requirements of the extractor.
    40  func (e FakeTestLayersExtractor) Requirements() *plugin.Capabilities {
    41  	return &plugin.Capabilities{}
    42  }
    43  
    44  // FileRequired always returns true, as this is for testing only
    45  func (e FakeTestLayersExtractor) FileRequired(_ filesystem.FileAPI) bool {
    46  	return true
    47  }
    48  
    49  // Extract extracts packages from yarn.lock files passed through the scan input.
    50  func (e FakeTestLayersExtractor) Extract(_ context.Context, input *filesystem.ScanInput) (inventory.Inventory, error) {
    51  	scanner := bufio.NewScanner(input.Reader)
    52  	pkgs := []*extractor.Package{}
    53  
    54  	for scanner.Scan() {
    55  		pkgline := scanner.Text()
    56  		// If no version found, just return "" as version
    57  		pkg, version, _ := strings.Cut(pkgline, "@")
    58  
    59  		pkgs = append(pkgs, &extractor.Package{
    60  			Name:      pkg,
    61  			Version:   version,
    62  			PURLType:  purl.TypeGeneric,
    63  			Locations: []string{input.Path},
    64  		})
    65  	}
    66  
    67  	if err := scanner.Err(); err != nil {
    68  		return inventory.Inventory{}, err
    69  	}
    70  
    71  	return inventory.Inventory{Packages: pkgs}, nil
    72  }
    73  
    74  var _ filesystem.Extractor = FakeTestLayersExtractor{}