storj/internal/fpath/editor.go

60 lines
1.4 KiB
Go
Raw Normal View History

2019-01-24 20:15:10 +00:00
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package fpath
import (
"fmt"
"os"
"os/exec"
2019-01-08 14:05:14 +00:00
"strings"
)
//EditFile opens the best OS-specific text editor we can find
func EditFile(fileToEdit string) error {
editorPath := getEditorPath()
if editorPath == "" {
return fmt.Errorf("unable to find suitable editor for file %s", fileToEdit)
}
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 {
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
}
}
}
//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 ""
}