zk/cmd/new.go

81 lines
2.1 KiB
Go
Raw Normal View History

package cmd
2020-12-25 19:25:52 +00:00
import (
"errors"
2020-12-25 19:25:52 +00:00
"fmt"
2021-04-04 13:31:54 +00:00
"github.com/mickael-menu/zk/adapter"
2020-12-28 15:00:48 +00:00
"github.com/mickael-menu/zk/core/note"
2020-12-25 19:25:52 +00:00
"github.com/mickael-menu/zk/core/zk"
2020-12-28 15:00:48 +00:00
"github.com/mickael-menu/zk/util/opt"
2021-01-02 17:01:30 +00:00
"github.com/mickael-menu/zk/util/os"
2020-12-25 19:25:52 +00:00
)
// New adds a new note to the notebook.
type New struct {
Directory string `arg optional default:"." help:"Directory in which to create the note."`
2021-02-07 18:03:27 +00:00
Title string `short:t placeholder:TITLE help:"Title of the new note."`
Group string `short:g placeholder:NAME help:"Name of the config group this note belongs to. Takes precedence over the config of the directory."`
Extra map[string]string ` help:"Extra variables passed to the templates." mapsep:","`
Template string `type:path placeholder:PATH help:"Custom template used to render the note."`
PrintPath bool `short:p help:"Print the path of the created note instead of editing it."`
}
2021-01-01 17:24:15 +00:00
func (cmd *New) ConfigOverrides() zk.ConfigOverrides {
return zk.ConfigOverrides{
Group: opt.NewNotEmptyString(cmd.Group),
2021-01-01 17:24:15 +00:00
BodyTemplatePath: opt.NewNotEmptyString(cmd.Template),
Extra: cmd.Extra,
}
}
2021-04-04 13:31:54 +00:00
func (cmd *New) Run(container *adapter.Container) error {
2021-03-17 17:04:27 +00:00
zk, err := container.Zk()
2020-12-28 15:00:48 +00:00
if err != nil {
return err
}
2021-01-01 17:24:15 +00:00
dir, err := zk.RequireDirAt(cmd.Directory, cmd.ConfigOverrides())
if err != nil {
return err
}
2021-01-02 17:01:30 +00:00
content, err := os.ReadStdinPipe()
2020-12-28 15:00:48 +00:00
if err != nil {
return err
}
opts := note.CreateOpts{
Config: container.Config,
2021-01-01 17:24:15 +00:00
Dir: *dir,
Title: opt.NewNotEmptyString(cmd.Title),
Content: content,
2020-12-28 15:00:48 +00:00
}
2021-02-13 21:16:11 +00:00
file, err := note.Create(opts, container.TemplateLoader(dir.Config.Note.Lang), container.Date)
2020-12-28 15:00:48 +00:00
if err != nil {
var noteExists note.ErrNoteExists
if !errors.As(err, &noteExists) {
return err
}
if confirmed, _ := container.Terminal.Confirm(
fmt.Sprintf("%s already exists, do you want to edit this note instead?", noteExists.Name),
true,
); !confirmed {
// abort...
return nil
}
file = noteExists.Path
2020-12-28 15:00:48 +00:00
}
2021-01-02 17:01:30 +00:00
if cmd.PrintPath {
fmt.Printf("%+v\n", file)
return nil
} else {
return note.Edit(zk, file)
}
}