d715b053e7
Enables request-scoped cancellation, timeouts, and graceful shutdown for all database operations across API handlers, CLI commands, and TUI.
84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
|
|
"github.com/lerko/nib/internal/db"
|
|
"github.com/lerko/nib/internal/display"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var editCmd = &cobra.Command{
|
|
Use: "edit <id>",
|
|
Short: "edit entity body in $EDITOR",
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: runEdit,
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(editCmd)
|
|
}
|
|
|
|
func runEdit(cmd *cobra.Command, args []string) error {
|
|
store, err := openStore()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer store.Close()
|
|
|
|
id, err := store.Resolve(cmd.Context(), args[0])
|
|
if err != nil {
|
|
return fmt.Errorf("not_found — no entity with id %s", args[0])
|
|
}
|
|
|
|
e, err := store.Get(cmd.Context(), id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
tmpfile, err := os.CreateTemp("", "nib-*.md")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(tmpfile.Name())
|
|
|
|
if _, err := tmpfile.WriteString(e.Body); err != nil {
|
|
tmpfile.Close()
|
|
return err
|
|
}
|
|
tmpfile.Close()
|
|
|
|
editor := os.Getenv("EDITOR")
|
|
if editor == "" {
|
|
editor = "vi"
|
|
}
|
|
|
|
editorCmd := exec.Command(editor, tmpfile.Name())
|
|
editorCmd.Stdin = os.Stdin
|
|
editorCmd.Stdout = os.Stdout
|
|
editorCmd.Stderr = os.Stderr
|
|
if err := editorCmd.Run(); err != nil {
|
|
return fmt.Errorf("editor: %w", err)
|
|
}
|
|
|
|
newBody, err := os.ReadFile(tmpfile.Name())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
body := string(newBody)
|
|
if body == e.Body {
|
|
fmt.Println("(no changes)")
|
|
return nil
|
|
}
|
|
|
|
if err := store.Update(cmd.Context(), id, &db.EntityUpdate{Body: &body}); err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Printf("updated %s\n", display.FormatID(id))
|
|
return nil
|
|
}
|