-
Notifications
You must be signed in to change notification settings - Fork 0
/
split.go
84 lines (68 loc) · 1.71 KB
/
split.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
package timecat
import (
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
)
var plainTextHeading = "##"
var heading = "^" + plainTextHeading
var nowISODate = func() string {
return now().Format(time.RFC3339)
}
func prependCurrentISODate(str string) string {
return nowISODate() + "-" + str
}
func Split(rpath string, dir string) []FileContent {
lines := getLines(rpath)
var result []FileContent
r := regexp.MustCompile(heading + " (.*)")
for _, line := range lines {
match := r.FindStringSubmatch(line)
// we have already found the first header and are now collecting lines
if len(result) > 0 && len(match) == 0 {
result[0].Content += line + "\n"
}
// we found a header on the current line
if len(match) > 1 {
// start a new header
result = append([]FileContent{newFileContent(match[1], dir)}, result...)
}
}
return pruneEmptyFileContents(result)
}
func pruneEmptyFileContents(fcs []FileContent) []FileContent {
var pruned []FileContent
r := regexp.MustCompile(".")
for _, fc := range fcs {
if match := r.FindStringSubmatch(fc.Content); len(match) > 0 {
pruned = append(pruned, fc)
} else {
os.Remove(filepath.Join(fc.Dir, fc.Name))
}
}
return pruned
}
func getLines(path string) []string {
absPath, _ := getAbs(path)
text, _ := readFile(absPath)
return strings.Split(text, "\n")
}
func newFileContent(name string, dir string) FileContent {
dir, _ = getAbs(dir)
if _, err := parseDateFileName(name); err != nil {
name = prependCurrentISODate(name)
}
return FileContent{
Dir: dir,
Name: path.Base(name),
Content: "",
}
}
func WriteSplits(fcs []FileContent) {
for _, fc := range fcs {
writeFile(path.Join(fc.Dir, fc.Name), []byte(fc.Content), 0644)
}
}