github.com/abhinav/git-pr@v0.6.1-0.20171029234004-54218d68c11b/editor/temp.go (about)

     1  package editor
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  )
     9  
    10  // tempFileWithContents creates a new temporary file with the given contents
    11  // and returns a path to it. The caller is responsible for deleting it.
    12  func tempFileWithContents(contents string) (string, error) {
    13  	f, err := ioutil.TempFile("", "git-stack-edit-string")
    14  	if err != nil {
    15  		return "", fmt.Errorf("could not open a temporary file: %v", err)
    16  	}
    17  
    18  	if _, err := io.WriteString(f, contents); err != nil {
    19  		// TODO: combine errors
    20  		f.Close()
    21  		os.Remove(f.Name())
    22  		return "", err
    23  	}
    24  
    25  	if err := f.Close(); err != nil {
    26  		os.Remove(f.Name())
    27  		return "", err
    28  	}
    29  
    30  	return f.Name(), nil
    31  }