github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/pkg/extrafs/extrafs.go (about)

     1  package extrafs
     2  
     3  import (
     4  	"io/fs"
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  /*
    10     Go does not currently support symlinks in io/fs.
    11     We work around this by wrapping the fs.FS returned by os.DirFS with our own type which bolts on the ReadLinkFS
    12  */
    13  
    14  type OSFS interface {
    15  	fs.FS
    16  	fs.StatFS
    17  }
    18  
    19  type ReadLinkFS interface {
    20  	ResolveSymlink(name, dir string) (string, error)
    21  }
    22  
    23  type FS interface {
    24  	OSFS
    25  	ReadLinkFS
    26  }
    27  
    28  type filesystem struct {
    29  	root       string
    30  	underlying OSFS
    31  }
    32  
    33  func OSDir(path string) FS {
    34  	return &filesystem{
    35  		root:       path,
    36  		underlying: os.DirFS(path).(OSFS),
    37  	}
    38  }
    39  
    40  func (f *filesystem) Open(name string) (fs.File, error) {
    41  	return f.underlying.Open(name)
    42  }
    43  
    44  func (f *filesystem) Stat(name string) (fs.FileInfo, error) {
    45  	return f.underlying.Stat(name)
    46  }
    47  
    48  func (f *filesystem) ResolveSymlink(name, dir string) (string, error) {
    49  	link, err := os.Readlink(filepath.Join(f.root, dir, name))
    50  	if err == nil {
    51  		return filepath.Join(dir, link), nil
    52  	}
    53  	return name, nil
    54  }