Skip to content

Commit

Permalink
feat: x/editor (#15)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <[email protected]>
  • Loading branch information
caarlos0 authored Nov 16, 2023
1 parent 4a717d4 commit 450eedb
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
31 changes: 31 additions & 0 deletions editor/editor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package editor

import (
"fmt"
"os"
"os/exec"
"strings"
)

const defaultEditor = "nano"

// Cmd returns a *exec.Cmd editing the given path with $EDITOR or nano if no
// $EDITOR is set.
func Cmd(app, path string) (*exec.Cmd, error) {
if os.Getenv("SNAP_REVISION") != "" {
return nil, fmt.Errorf("Did you install with Snap? %[1]s is sandboxed and unable to open an editor. Please install %[1]s with Go or another package manager to enable editing.", app)
}
editor, args := getEditor()
return exec.Command(editor, append(args, path)...), nil
}

func getEditor() (string, []string) {
editor := strings.Fields(os.Getenv("EDITOR"))
if len(editor) > 1 {
return editor[0], editor[1:]
}
if len(editor) == 1 {
return editor[0], []string{}
}
return defaultEditor, []string{}
}
37 changes: 37 additions & 0 deletions editor/editor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package editor

import (
"reflect"
"testing"
)

func TestEditor(t *testing.T) {
filename := "README.md"
for k, v := range map[string][]string{
"": {"nano", filename},
"nvim": {"nvim", filename},
"vim": {"vim", filename},
"vscode --foo": {"vscode", "--foo", filename},
"nvim -a -b": {"nvim", "-a", "-b", filename},
} {
t.Run(k, func(t *testing.T) {
t.Setenv("EDITOR", k)
cmd, _ := Cmd("X", "README.md")
got := cmd.Args
if !reflect.DeepEqual(got, v) {
t.Fatalf("expected %v; got %v", v, got)
}
})
}

t.Run("inside snap", func(t *testing.T) {
t.Setenv("SNAP_REVISION", "10")
got, err := Cmd("X", "foo")
if err == nil {
t.Fatalf("expected an error, got nil")
}
if got != nil {
t.Fatalf("should have returned nil, got %v", got)
}
})
}
3 changes: 3 additions & 0 deletions editor/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/charmbracelet/x/editor

go 1.20
1 change: 1 addition & 0 deletions go.work
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
go 1.20

use (
./editor
./exp/higherorder
./exp/ordered
./exp/slice
Expand Down

0 comments on commit 450eedb

Please sign in to comment.