Files
ax/cmd/edit.go

64 lines
1.4 KiB
Go

package cmd
import (
"axolotl/output"
"axolotl/service"
"fmt"
"os"
"os/exec"
"github.com/spf13/cobra"
)
var editCmd = &cobra.Command{
Use: "edit <id>", Short: "Edit node content in $EDITOR", Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
svc, err := service.GetNodeService(cfg)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
n, err := svc.GetByID(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, "node not found:", args[0])
return
}
tmp, err := os.CreateTemp("", "ax-*.md")
if err != nil {
fmt.Fprintln(os.Stderr, "failed to create temp file:", err)
return
}
tmp.WriteString(n.Content)
tmp.Close()
defer os.Remove(tmp.Name())
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vi"
}
c := exec.Command(editor, tmp.Name())
c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr
if err := c.Run(); err != nil {
fmt.Fprintln(os.Stderr, "editor failed:", err)
return
}
if content, err := os.ReadFile(tmp.Name()); err == nil {
n.Content = string(content)
if err := svc.Update(n); err != nil {
fmt.Fprintln(os.Stderr, "failed to update:", err)
return
}
n, _ = svc.GetByID(args[0])
output.PrintNode(cmd.OutOrStdout(), svc, n, jsonFlag)
} else {
fmt.Fprintln(os.Stderr, "failed to read temp file:", err)
}
},
}
func init() {
rootCmd.AddCommand(editCmd)
}