2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2019-01-02 15:12:07 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package fpath
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2019-01-08 14:05:14 +00:00
|
|
|
"strings"
|
2019-01-02 15:12:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//EditFile opens the best OS-specific text editor we can find
|
|
|
|
func EditFile(fileToEdit string) error {
|
|
|
|
editorPath := getEditorPath()
|
|
|
|
if editorPath == "" {
|
2019-11-14 08:31:30 +00:00
|
|
|
return fmt.Errorf("unable to find suitable editor for file %s", fileToEdit)
|
2019-01-02 15:12:07 +00:00
|
|
|
}
|
|
|
|
cmd := exec.Command(editorPath, fileToEdit)
|
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
cmd.Stdin = os.Stdin
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
return cmd.Run()
|
|
|
|
}
|
|
|
|
|
|
|
|
func getEditorPath() string {
|
|
|
|
// we currently only attempt to open TTY-friendly editors here
|
|
|
|
// we could consider using https://github.com/mattn/go-isatty
|
|
|
|
// alongside "start" / "open" / "xdg-open"
|
|
|
|
|
|
|
|
//look for a preference in environment variables
|
|
|
|
for _, eVar := range [...]string{"EDITOR", "VISUAL", "GIT_EDITOR"} {
|
|
|
|
path := os.Getenv(eVar)
|
2019-03-25 15:57:54 +00:00
|
|
|
_, err := os.Stat(path)
|
|
|
|
if len(path) > 0 && err == nil {
|
2019-01-02 15:12:07 +00:00
|
|
|
return path
|
|
|
|
}
|
|
|
|
}
|
|
|
|
//look for a preference via 'git config'
|
|
|
|
git, err := exec.LookPath("git")
|
|
|
|
if err == nil {
|
|
|
|
out, err := exec.Command(git, "config", "core.editor").Output()
|
2019-03-25 15:57:54 +00:00
|
|
|
if err == nil {
|
|
|
|
cmd := strings.TrimSpace(string(out))
|
|
|
|
_, err := os.Stat(cmd)
|
|
|
|
if len(cmd) > 0 && err == nil {
|
|
|
|
return cmd
|
|
|
|
}
|
2019-01-02 15:12:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
//heck, just try a bunch of options
|
|
|
|
for _, exe := range [...]string{"nvim", "vim", "vi", "emacs", "nano", "pico"} {
|
|
|
|
path, err := exec.LookPath(exe)
|
|
|
|
if err == nil {
|
|
|
|
return path
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|