/
new.go
68 lines (55 loc) · 1.34 KB
/
new.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"errors"
"os"
"path/filepath"
"strings"
"github.com/urfave/cli/v2"
)
// NewPost initializes git repo and copies a sample config
func (hub *Hub) NewPost() *cli.Command {
return &cli.Command{
Name: "new",
Aliases: []string{"n"},
Usage: "Create a new post.",
Action: hub.MustHaveConfig(hub.newPost),
ArgsUsage: "[TITLE]",
Before: func(c *cli.Context) error {
if c.Args().First() == "" {
return errors.New("title is missing")
}
return nil
},
}
}
func (hub *Hub) newPost(cliCtx *cli.Context) error {
title := cliCtx.Args().First()
// fill basic metadata
var cfg = map[string]interface{}{
"Title": title,
}
// clean up title
sanitizedTitle := strings.ToLower(title)
sanitizedTitle = strings.ReplaceAll(sanitizedTitle, " ", "-")
if len(sanitizedTitle) > maxTitleLength {
sanitizedTitle = sanitizedTitle[:maxTitleLength]
}
sanitizedTitle = sanitizedTitle + ".md"
// persist the new post
currentDir, err := os.Getwd()
if err != nil {
return err
}
path := filepath.Join(currentDir, defaultPostDir, sanitizedTitle)
post, err := os.Create(path)
if err != nil {
return err
}
// render post template
err = saveResource("index", []string{"templates/post.tmpl"}, post, cfg, hub.Fs)
if err != nil {
return err
}
hub.Logger.Infof("New post created! %s", path)
return nil
}