1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
package cmd
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
// CmdEdit is `direnv edit [PATH_TO_RC]`
var CmdEdit = &Cmd{
Name: "edit",
Desc: `Opens PATH_TO_RC or the current .envrc or .env into an $EDITOR and allow
the file to be loaded afterwards.`,
Args: []string{"[PATH_TO_RC]"},
Action: actionWithConfig(cmdEditAction),
}
func cmdEditAction(env Env, args []string, config *Config) (err error) {
var rcPath string
var times *FileTimes
var foundRC *RC
defer log.SetPrefix(log.Prefix())
log.SetPrefix(log.Prefix() + "cmd_edit: ")
foundRC, err = config.FindRC()
if err != nil {
return err
}
if foundRC != nil {
times = &foundRC.times
}
if len(args) > 1 {
rcPath = args[1]
fi, _ := os.Stat(rcPath)
if fi != nil && fi.IsDir() {
rcPath = filepath.Join(rcPath, ".envrc")
}
} else {
if foundRC == nil {
return fmt.Errorf(".envrc or .env not found. Use `direnv edit .` to create a new .envrc in the current directory")
}
rcPath = foundRC.path
}
editor := env["EDITOR"]
if editor == "" {
logError(config, "$EDITOR not found.")
editor = detectEditor(env["PATH"])
if editor == "" {
err = fmt.Errorf("could not find a default editor in the PATH")
return
}
}
run := fmt.Sprintf("%s %s", editor, BashEscape(rcPath))
// G204: Subprocess launched with function call as argument or cmd arguments
// #nosec
cmd := exec.Command(config.BashPath, "-c", run)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return
}
foundRC, err = FindRC(rcPath, config)
logDebug("foundRC: %#v", foundRC)
logDebug("times: %#v", times)
if times != nil {
logDebug("times.Check(): %#v", times.Check())
}
if err == nil && foundRC != nil && (times == nil || times.Check() != nil) {
err = foundRC.Allow()
}
return
}
// Utils
// Editors contains a list of known editors and how to start them.
var Editors = [][]string{
{"editor"},
{"subl", "-w"},
{"mate", "-w"},
{"open", "-t", "-W"}, // Opens with the default text editor on mac
{"nano"},
{"vim"},
{"emacs"},
}
func detectEditor(pathenv string) string {
for _, editor := range Editors {
if _, err := lookPath(editor[0], pathenv); err == nil {
return strings.Join(editor, " ")
}
}
return ""
}
|