zk/cmd/new.go

61 lines
1.5 KiB
Go
Raw Normal View History

package cmd
2020-12-25 19:25:52 +00:00
import (
"fmt"
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
)
2020-12-28 15:00:48 +00:00
// New adds a new note to the slip box.
type New struct {
2020-12-28 15:00:48 +00:00
Directory string `arg optional type:"path" default:"." help:"Directory in which to create the note"`
2021-01-02 17:01:30 +00:00
PrintPath bool `help:"Prints the path of the created note to stdin instead of editing it"`
2020-12-28 15:00:48 +00:00
Title string `short:"t" help:"Title of the new note" placeholder:"TITLE"`
Template string `type:"path" help:"Custom template to use to render the note" placeholder:"PATH"`
Extra map[string]string `help:"Extra variables passed to the templates"`
}
2021-01-01 17:24:15 +00:00
func (cmd *New) ConfigOverrides() zk.ConfigOverrides {
return zk.ConfigOverrides{
BodyTemplatePath: opt.NewNotEmptyString(cmd.Template),
Extra: cmd.Extra,
}
}
2020-12-28 15:00:48 +00:00
func (cmd *New) Run(container *Container) error {
zk, err := zk.Open(".")
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{
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
}
file, err := note.Create(opts, container.TemplateLoader(dir.Config.Lang), container.Date)
2020-12-28 15:00:48 +00:00
if err != nil {
return err
}
2021-01-02 17:01:30 +00:00
if cmd.PrintPath {
fmt.Printf("%+v\n", file)
return nil
} else {
return note.Edit(zk, file)
}
}