github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/syft/source/filesource/file_source_provider.go (about)

     1  package filesource
     2  
     3  import (
     4  	"context"
     5  	"crypto"
     6  	"fmt"
     7  
     8  	"github.com/mitchellh/go-homedir"
     9  	"github.com/spf13/afero"
    10  
    11  	"github.com/anchore/syft/syft/source"
    12  )
    13  
    14  func NewSourceProvider(path string, exclude source.ExcludeConfig, digestAlgorithms []crypto.Hash, alias source.Alias) source.Provider {
    15  	return &fileSourceProvider{
    16  		path:             path,
    17  		exclude:          exclude,
    18  		digestAlgorithms: digestAlgorithms,
    19  		alias:            alias,
    20  	}
    21  }
    22  
    23  type fileSourceProvider struct {
    24  	path             string
    25  	exclude          source.ExcludeConfig
    26  	digestAlgorithms []crypto.Hash
    27  	alias            source.Alias
    28  }
    29  
    30  func (p fileSourceProvider) Name() string {
    31  	return "local-file"
    32  }
    33  
    34  func (p fileSourceProvider) Provide(_ context.Context) (source.Source, error) {
    35  	location, err := homedir.Expand(p.path)
    36  	if err != nil {
    37  		return nil, fmt.Errorf("unable to expand potential directory path: %w", err)
    38  	}
    39  
    40  	fs := afero.NewOsFs()
    41  	fileMeta, err := fs.Stat(location)
    42  	if err != nil {
    43  		return nil, fmt.Errorf("unable to stat location: %w", err)
    44  	}
    45  
    46  	if fileMeta.IsDir() {
    47  		return nil, fmt.Errorf("not a file source: %s", p.path)
    48  	}
    49  
    50  	return New(
    51  		Config{
    52  			Path:             location,
    53  			Exclude:          p.exclude,
    54  			DigestAlgorithms: p.digestAlgorithms,
    55  			Alias:            p.alias,
    56  		},
    57  	)
    58  }