-
Notifications
You must be signed in to change notification settings - Fork 1
/
add.go
executable file
·168 lines (136 loc) · 3.8 KB
/
add.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/*
Copyright © 2020 Raphael Pour <info@raphaelpour.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/RaphaelPour/blogctl/pkg/metadata"
"github.com/fatih/color"
shellquote "github.com/kballard/go-shellquote"
)
const CONTENT_FILE = "content.md"
func GetContentFile(postPath string) string {
return filepath.Join(postPath, CONTENT_FILE)
}
var addCmd = &cobra.Command{
Use: "add",
Short: "Add a new post",
RunE: func(cmd *cobra.Command, args []string) error {
if Title == "" {
return fmt.Errorf("Title missing")
}
/* Generate slug */
slug := slug(Title)
postPath := filepath.Join(BlogPath, slug)
/* Check if slug already exists */
/* Ask user for input */
content := fmt.Sprintf("# %s\n\n", Title)
/* Abort if file already exist to prevent data loss when checking
* it afterwards.
*/
if _, err := os.Stat(postPath); err == nil {
return fmt.Errorf("Error adding new post '%s': File already exists", slug)
}
if Interactive {
err := Open(&content)
if err != nil {
return fmt.Errorf("Error getting content from user: %s", err)
}
}
/* Save post at the right place */
if err := os.Mkdir(postPath, os.ModeDir|os.ModePerm); err != nil {
rescuePost(content)
return fmt.Errorf("Error creating post dir: %s", err)
}
if err := ioutil.WriteFile(GetContentFile(postPath), []byte(content), os.ModePerm); err != nil {
rescuePost(content)
return fmt.Errorf("Error writing post: %s", err)
}
/* Store metadata info */
metadata := &metadata.Metadata{
Title: Title,
CreatedAt: time.Now().Unix(),
}
if err := metadata.Save(postPath); err != nil {
rescuePost(content)
return err
}
color.Green(GetContentFile(postPath))
return nil
},
}
var (
Title string
Interactive bool
SlugRegex = regexp.MustCompile(`[^A-Za-z0-9-]`)
)
func init() {
postCmd.AddCommand(addCmd)
addCmd.Flags().StringVarP(&Title, "title", "t", "", "Title of the post (required)")
addCmd.Flags().BoolVarP(&Interactive, "interactive", "i", false, "Opens default editor with new post.")
}
func slug(s string) string {
return SlugRegex.ReplaceAllString(strings.ReplaceAll(strings.ToLower(s), " ", "-"), "")
}
func rescuePost(content string) {
fmt.Printf("<<< POST\n%s\n>>> POST\n", content)
}
func Open(initialValue *string) error {
var editor string
if val, ok := os.LookupEnv("EDITOR"); ok {
editor = val
}
if val, ok := os.LookupEnv("VISUAL"); ok {
editor = val
}
if editor == "" {
return fmt.Errorf("set EDITOR or VISUAL variable")
}
file, err := ioutil.TempFile("", "new-post*.md")
if err != nil {
return err
}
defer os.Remove(file.Name())
if _, err := file.WriteString(*initialValue); err != nil {
return err
}
if err := file.Close(); err != nil {
return err
}
args, err := shellquote.Split(editor)
if err != nil {
return err
}
args = append(args, file.Name())
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
raw, err := ioutil.ReadFile(file.Name())
if err != nil {
return err
}
*initialValue = string(raw)
return nil
}