forked from NollGo/Noll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
82 lines (71 loc) · 2.05 KB
/
export.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
package main
import (
"fmt"
"os"
"path/filepath"
"text/template"
)
const exportTemplate = `---
title: {{ .Title }}
createAt: {{ .CreatedAt }}
updateAt: {{ .UpdatedAt }}
tags: {{ .LabelsString }}
categories: {{ .Category }}
---
{{ .Body }}
`
func export(config Config) (err error) {
var data *GithubData
if data, err = getRepository(config.Owner, config.Name, config.Token); err != nil {
return err
}
discussions := data.Repository.Discussions
if discussions == nil || discussions.TotalCount == 0 {
return fmt.Errorf("no discussions")
}
discussionsMap := groupByCategory(discussions.Nodes)
tmpl, err := parseTemplate(exportTemplate)
if err != nil {
return err
}
for category, discussions := range discussionsMap {
_ = os.MkdirAll(filepath.Join(config.Export, category), os.ModePerm)
for _, discussion := range discussions {
if err = exportDiscussion(config.Export, discussion, tmpl); err != nil {
return err
}
}
}
return err
}
func exportDiscussion(dir string, discussion *Discussion, tmpl *template.Template) error {
filePath := filepath.Join(dir, discussion.Category.Name, fmt.Sprintf("%v.md", discussion.Number))
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
err = tmpl.Execute(file, map[string]interface{}{
"Title": discussion.Title,
"CreatedAt": discussion.CreatedAt.Format("2006-01-02 15:04:05"),
"UpdatedAt": discussion.UpdatedAt.Format("2006-01-02 15:04:05"),
"LabelsString": discussion.Labels.String(),
"Labels": discussion.Labels,
"Category": discussion.Category.Name,
"Body": discussion.Body,
})
if err != nil {
return err
}
return nil
}
func groupByCategory(discussions []*Discussion) map[string][]*Discussion {
group := make(map[string][]*Discussion)
for i := range discussions {
discussion := discussions[i]
group[discussion.Category.Name] = append(group[discussion.Category.Name], discussion)
}
return group
}
func parseTemplate(tmp string) (*template.Template, error) {
return template.New("export").Parse(tmp)
}