github.com/jgbaldwinbrown/perf@v0.1.1/storage/fs/local/local.go (about)

     1  // Copyright 2017 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package local implements the fs.FS interface using local files.
     6  // Metadata is not stored separately; the header of each file should
     7  // contain metadata as written by storage/app.
     8  package local
     9  
    10  import (
    11  	"os"
    12  	"path/filepath"
    13  
    14  	"golang.org/x/net/context"
    15  	"golang.org/x/perf/storage/fs"
    16  )
    17  
    18  // impl is an fs.FS backed by local disk.
    19  type impl struct {
    20  	root string
    21  }
    22  
    23  // NewFS constructs an FS that writes to the provided directory.
    24  func NewFS(root string) fs.FS {
    25  	return &impl{root}
    26  }
    27  
    28  // NewWriter creates a file and assigns metadata as extended filesystem attributes.
    29  func (fs *impl) NewWriter(ctx context.Context, name string, metadata map[string]string) (fs.Writer, error) {
    30  	if err := os.MkdirAll(filepath.Join(fs.root, filepath.Dir(name)), 0777); err != nil {
    31  		return nil, err
    32  	}
    33  	f, err := os.Create(filepath.Join(fs.root, name))
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	return &wrapper{f}, nil
    38  }
    39  
    40  type wrapper struct {
    41  	*os.File
    42  }
    43  
    44  // CloseWithError closes the file and attempts to unlink it.
    45  func (w *wrapper) CloseWithError(error) error {
    46  	w.Close()
    47  	return os.Remove(w.Name())
    48  }