github.com/gofunct/common@v0.0.0-20190131174352-fd058c7fbf22/pkg/temp/dir.go (about)

     1  package temp
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  	"path/filepath"
     9  )
    10  
    11  // Directory is an interface to a temporary directory, in which you can
    12  // create new files.
    13  type Directory interface {
    14  	// NewFile creates a new file in that directory. Calling NewFile
    15  	// with the same filename twice will result in an error.
    16  	NewFile(name string) (io.WriteCloser, error)
    17  	// Delete removes the directory and its content.
    18  	Delete() error
    19  }
    20  
    21  // Dir is wrapping an temporary directory on disk.
    22  type Dir struct {
    23  	// Name is the name (full path) of the created directory.
    24  	Name string
    25  }
    26  
    27  var _ Directory = &Dir{}
    28  
    29  // CreateTempDir returns a new Directory wrapping a temporary directory
    30  // on disk.
    31  func CreateTempDir(prefix string) (*Dir, error) {
    32  	name, err := ioutil.TempDir("", fmt.Sprintf("%s-", prefix))
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	return &Dir{
    38  		Name: name,
    39  	}, nil
    40  }
    41  
    42  // NewFile creates a new file in the specified directory.
    43  func (d *Dir) NewFile(name string) (io.WriteCloser, error) {
    44  	return os.OpenFile(
    45  		filepath.Join(d.Name, name),
    46  		os.O_WRONLY|os.O_CREATE|os.O_TRUNC|os.O_EXCL,
    47  		0700,
    48  	)
    49  }
    50  
    51  // Delete the underlying directory, and all of its content.
    52  func (d *Dir) Delete() error {
    53  	return os.RemoveAll(d.Name)
    54  }