From 5d04342b42210bab5053baba03c30a6e2d478307 Mon Sep 17 00:00:00 2001 From: gutmet Date: Mon, 5 Dec 2022 21:28:19 +0100 Subject: [PATCH] newpost command: accept --date flag for past or future dates --- post/post.go | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/post/post.go b/post/post.go index 5113e05..b65390b 100644 --- a/post/post.go +++ b/post/post.go @@ -2,16 +2,18 @@ package post import ( "bytes" + "errors" "flag" "fmt" - goutil "git.gutmet.org/goutil.git/misc" - "git.gutmet.org/wombat.git/blog" - gen "git.gutmet.org/wombat.git/generate" "io/ioutil" "os" "path/filepath" "text/template" "time" + + goutil "git.gutmet.org/goutil.git/misc" + "git.gutmet.org/wombat.git/blog" + gen "git.gutmet.org/wombat.git/generate" ) const dateformat string = "2006-01-02" @@ -42,8 +44,7 @@ func ensureDirectory(file string) { } } -func makePostFile(dirsuffix string, title string, content string) string { - now := time.Now().UTC() +func makePostFile(now time.Time, dirsuffix string, title string, content string) string { file := filename(dirsuffix, title, now) ensureDirectory(file) post := post{} @@ -72,7 +73,13 @@ func postNew(fl postFlags) error { tmpcontent, _ := ioutil.ReadAll(os.Stdin) content = string(tmpcontent) } - f := makePostFile(fl.blog, fl.title, content) + var t time.Time + if fl.datetime.val != nil { + t = *fl.datetime.val + } else { + t = time.Now().UTC() + } + f := makePostFile(t, fl.blog, fl.title, content) fmt.Println(f) if content == "" { wait := true @@ -89,11 +96,35 @@ func postNew(fl postFlags) error { return gen.Generate(gen.GenerateFlags{Noserve: fl.noserve}) } +type DateFlag struct { + val *time.Time +} + +func (d DateFlag) String() string { + if d.val == nil { + return "" + } else { + return time.Time(*d.val).Format(blog.TimeFormat) + } +} + +func (d *DateFlag) Set(s string) error { + if d == nil { + return errors.New("func (d *DateFlag) Set(s string): d is nil") + } + val, err := time.Parse(blog.TimeFormat, s) + if err == nil { + d.val = &val + } + return err +} + type postFlags struct { blog string title string category string noserve bool + datetime DateFlag } func Command() (goutil.CommandFlagsInit, goutil.CommandFunc) { @@ -103,6 +134,7 @@ func Command() (goutil.CommandFlagsInit, goutil.CommandFunc) { s.StringVar(&f.title, "title", "", "if title and category are set: read content from stdin") s.StringVar(&f.category, "category", "", "if title and category are set: read content from stdin") s.BoolVar(&f.noserve, "noserve", false, "don't generate and serve afterwards") + s.Var(&f.datetime, "date", "use date and time other than now (yyyy-mm-dd HH:MM)") } return flagsInit, func([]string) error { return postNew(f) } }