This repository has been archived by the owner on Mar 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.go
78 lines (68 loc) · 2.05 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
package cmd
import (
"errors"
"fmt"
"io"
"os"
homedir "github.com/mitchellh/go-homedir"
toml "github.com/pelletier/go-toml"
"github.com/spf13/cobra"
"github.com/taylorskalyo/stno/datastore"
)
var addCmd = &cobra.Command{
Use: "add path",
Short: "Add an entry to your stno notebook",
Long: `Add an entry to your stno notebook
New entries will be opened in your default editor (specified by the EDITOR
environment variable). If the entry is not valid TOML, you will be prompted to
revise the entry. This command takes a path. This path is relative to the stno
directory (defaults to ~/.stno). `,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("add requires a path")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
// Open entry for writing
dir, err := homedir.Expand(stnoDir)
if err != nil {
fmt.Printf("Could not expand path %s: %s.\n", stnoDir, err.Error())
os.Exit(1)
}
ds := datastore.FileStore{Dir: dir}
entry, err := ds.NewEntryWriteCloser(args[0])
if err != nil {
fmt.Printf("Failed to create entry %s: %s.\n", args[0], err.Error())
os.Exit(1)
}
// Edit entry contents in temporary location
contents := ""
for {
contents, err = editString(contents)
if _, err = toml.Load(contents); err != nil {
fmt.Printf("Could not parse TOML: %s. Try again? ", err.Error())
if !confirm() {
break
}
} else {
break
}
}
// Write contents to entry
if _, err = io.WriteString(entry, contents); err != nil {
fmt.Printf("Failed to save notebook entry: %s.\n", err.Error())
os.Exit(1)
}
},
}
func init() {
RootCmd.AddCommand(addCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// addCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}