...

Source file src/oss.terrastruct.com/util-go/mapfs/mapfs.go

Documentation: oss.terrastruct.com/util-go/mapfs

     1  // Package mapfs takes in a description of a filesystem as a map[string]string
     2  // and writes it to a temp directory so that it may be used as an io/fs.FS.
     3  package mapfs
     4  
     5  import (
     6  	"errors"
     7  	"fmt"
     8  	"io/fs"
     9  	"os"
    10  	"path"
    11  )
    12  
    13  type FS struct {
    14  	dir string
    15  	fs.FS
    16  }
    17  
    18  func New(m map[string]string) (*FS, error) {
    19  	tempDir, err := os.MkdirTemp("", "mapfs-*")
    20  	if err != nil {
    21  		return nil, fmt.Errorf("failed to create root mapfs dir: %w", err)
    22  	}
    23  	for p, s := range m {
    24  		p = path.Join(tempDir, p)
    25  		err = os.MkdirAll(path.Dir(p), 0755)
    26  		if err != nil {
    27  			return nil, fmt.Errorf("failed to create mapfs dir %q: %w", path.Dir(p), err)
    28  		}
    29  		err = os.WriteFile(p, []byte(s), 0644)
    30  		if err != nil {
    31  			return nil, fmt.Errorf("failed to write mapfs file %q: %w", p, err)
    32  		}
    33  	}
    34  	return &FS{
    35  		dir: tempDir,
    36  		FS:  os.DirFS(tempDir),
    37  	}, nil
    38  }
    39  
    40  func (fs *FS) Close() error {
    41  	err := os.RemoveAll(fs.dir)
    42  	if errors.Is(err, os.ErrNotExist) {
    43  		return nil
    44  	}
    45  	if err != nil {
    46  		return fmt.Errorf("failed to close mapfs.FS: %w", err)
    47  	}
    48  	return nil
    49  }
    50  

View as plain text