From ca56b4b550e1f193fccaa0b162c1bc4f24b336b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mickae=CC=88l=20Menu?= Date: Sat, 20 Feb 2021 19:25:11 +0100 Subject: [PATCH] Ask to open any existing note with `zk new` --- cmd/new.go | 17 ++++++++++++++++- core/note/create.go | 20 ++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/cmd/new.go b/cmd/new.go index 854717b..6fef3ae 100644 --- a/cmd/new.go +++ b/cmd/new.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "github.com/mickael-menu/zk/core/note" @@ -49,9 +50,23 @@ func (cmd *New) Run(container *Container) error { Title: opt.NewNotEmptyString(cmd.Title), Content: content, } + file, err := note.Create(opts, container.TemplateLoader(dir.Config.Note.Lang), container.Date) if err != nil { - return err + var noteExists note.ErrNoteExists + if !errors.As(err, ¬eExists) { + 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 } if cmd.PrintPath { diff --git a/core/note/create.go b/core/note/create.go index 589ae7d..dbf746e 100644 --- a/core/note/create.go +++ b/core/note/create.go @@ -24,6 +24,17 @@ type CreateOpts struct { Content opt.String } +// ErrNoteExists is an error returned when a note already exists with the +// filename generated by Create(). +type ErrNoteExists struct { + Name string + Path string +} + +func (e ErrNoteExists) Error() string { + return fmt.Sprintf("%s: note already exists", e.Path) +} + // Create generates a new note from the given options. // Returns the path of the newly created note. func Create( @@ -125,11 +136,13 @@ func genPath( dir zk.Dir, deps createDeps, ) (string, renderContext, error) { + var err error + var filename string var path string for i := 0; i < 50; i++ { context.ID = deps.genId() - filename, err := deps.filenameTemplate.Render(context) + filename, err = deps.filenameTemplate.Render(context) if err != nil { return "", context, err } @@ -146,5 +159,8 @@ func genPath( } } - return "", context, fmt.Errorf("%v: note already exists", path) + return "", context, ErrNoteExists{ + Name: filepath.Join(dir.Name, filename), + Path: path, + } }