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

     1  package editor
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"os/exec"
     8  )
     9  
    10  // Basic is an editor without special abilities. We can't detect whether the
    11  // user saved the file or not.
    12  type Basic struct {
    13  	name string
    14  	path string
    15  }
    16  
    17  // NewBasic builds a new basic editor.
    18  func NewBasic(name string) (*Basic, error) {
    19  	path, err := exec.LookPath(name)
    20  	if err != nil {
    21  		return nil, fmt.Errorf("could not resolve editor %q: %v", name, err)
    22  	}
    23  
    24  	return &Basic{name: name, path: path}, nil
    25  }
    26  
    27  // Name returns the name of the editor.
    28  func (e *Basic) Name() string {
    29  	return e.name
    30  }
    31  
    32  // EditString asks the user to edit the given string inside the editor.
    33  func (e *Basic) EditString(s string) (string, error) {
    34  	file, err := tempFileWithContents(s)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  	defer os.Remove(file)
    39  
    40  	cmd := exec.Command(e.path, file)
    41  	cmd.Stdout = os.Stdout
    42  	cmd.Stdin = os.Stdin
    43  	cmd.Stderr = os.Stderr
    44  	if err := cmd.Run(); err != nil {
    45  		return "", fmt.Errorf("editor %q failed: %v", e.name, err)
    46  	}
    47  
    48  	contents, err := ioutil.ReadFile(file)
    49  	if err != nil {
    50  		return "", fmt.Errorf("could not read temporary file: %v", err)
    51  	}
    52  
    53  	return string(contents), nil
    54  }