github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/review/git-codereview/editor.go (about)

     1  // Copyright 2015 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 main
     6  
     7  import (
     8  	"io"
     9  	"io/ioutil"
    10  	"os"
    11  	"os/exec"
    12  )
    13  
    14  // editor invokes an interactive editor on a temporary file containing
    15  // initial, blocks until the editor exits, and returns the (possibly
    16  // edited) contents of the temporary file. It follows the conventions
    17  // of git for selecting and invoking the editor (see git-var(1)).
    18  func editor(initial string) string {
    19  	// Query the git editor command.
    20  	gitEditor := trim(cmdOutput("git", "var", "GIT_EDITOR"))
    21  
    22  	// Create temporary file.
    23  	temp, err := ioutil.TempFile("", "git-codereview")
    24  	if err != nil {
    25  		dief("creating temp file: %v", err)
    26  	}
    27  	tempName := temp.Name()
    28  	defer os.Remove(tempName)
    29  	if _, err := io.WriteString(temp, initial); err != nil {
    30  		dief("%v", err)
    31  	}
    32  	if err := temp.Close(); err != nil {
    33  		dief("%v", err)
    34  	}
    35  
    36  	// Invoke the editor. See git's prepare_shell_cmd.
    37  	cmd := exec.Command("sh", "-c", gitEditor+" \"$@\"", gitEditor, tempName)
    38  	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
    39  	if err := cmd.Run(); err != nil {
    40  		os.Remove(tempName)
    41  		dief("editor exited with: %v", err)
    42  	}
    43  
    44  	// Read the edited file.
    45  	b, err := ioutil.ReadFile(tempName)
    46  	if err != nil {
    47  		dief("%v", err)
    48  	}
    49  	return string(b)
    50  }