package post import ( "bytes" "flag" "fmt" goutil "git.gutmet.org/goutil.git/misc" "git.gutmet.org/wombat.git/blog" gen "git.gutmet.org/wombat.git/generate" "git.gutmet.org/wombat.git/initer" "io/ioutil" "os" "path/filepath" "text/template" "time" ) const dateformat string = "2006-01-02" const stub string = `--- title: "{{.Title}}" date: {{.Date}} categories: --- ` type post struct { Title string Date string } func filename(dirsuffix string, title string, now time.Time) string { date := now.Format(dateformat) asciiTitle := blog.ConvASCII(title) return filepath.Join("stage0", "blog"+dirsuffix, fmt.Sprintf("%s-%s.md", date, asciiTitle)) } func ensureDirectory(file string) { dir := filepath.Dir(file) err := os.MkdirAll(dir, 0755) if err != nil { panic(err) } } func makePostFile(dirsuffix string, title string, content string) string { now := time.Now().UTC() file := filename(dirsuffix, title, now) ensureDirectory(file) post := post{} post.Title = title post.Date = now.Format(blog.TimeFormat) t := template.Must(template.New("Poststub").Parse(stub)) buf := new(bytes.Buffer) t.Execute(buf, post) err := goutil.WriteFile(file, buf.String()+content) if err != nil { fmt.Println(err) } return file } func postNew(fl postFlags) error { var err error initer.InitializedOrDie() if fl.title == "" { fl.title, err = goutil.AskFor("Title") if err != nil { return err } } var content string if fl.category != "" && fl.title != "" { tmpcontent, _ := ioutil.ReadAll(os.Stdin) content = string(tmpcontent) } f := makePostFile(fl.blog, fl.title, content) fmt.Println(f) if content == "" { wait := true err = goutil.OpenInEditor(f, wait) if err != nil { fmt.Println(err) fmt.Println("trying default application...") err = goutil.OpenInDefaultApp(f, wait) } } if err != nil { return err } noserve := (content != "") return gen.Generate(gen.GenerateFlags{Noserve: noserve}) } type postFlags struct { blog string title string category string } func Command() (goutil.CommandFlagsInit, goutil.CommandFunc) { f := postFlags{} flagsInit := func(s *flag.FlagSet) { s.StringVar(&f.blog, "blog", "", "which blog folder to post to, e.g. -blog=foo for 'blogfoo' (default \"blog\")") 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") } return flagsInit, func([]string) error { return postNew(f) } }