forked from imskr/readme-update-actions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (84 loc) · 1.83 KB
/
main.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/mmcdole/gofeed"
)
func main() {
// get the rss list from the actions env
rss_url := os.Getenv("INPUT_RSS_LIST")
// get the number of posts or stories to commit
max_post, err := strconv.Atoi(os.Getenv("INPUT_MAX_POST"))
if err != nil || max_post == 0 {
max_post = 5
}
// get readme path from the actions env
readme_path := os.Getenv("INPUT_README_PATH")
// if path not provided default to root readme
if readme_path == "" {
readme_path = "./README.md"
}
fp := gofeed.NewParser()
feed, _ := fp.ParseURL(rss_url)
// store the posts
var items []string
// get the posts
// format it according to readme links format
if feed != nil && len(feed.Items) > 0 {
for i := 0; i < max_post; i++ {
if i < len(feed.Items) {
item := fmt.Sprintf("- [%s](%s)", feed.Items[i].Title, feed.Items[i].Link)
items = append(items, item)
} else {
break
}
}
}
// find readme and replace with our result
WriteToFile(readme_path, items)
}
func WriteToFile(path string, items []string) {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
var lines []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err = scanner.Err(); err != nil {
log.Fatal(err)
}
f.Close()
f, err = os.Create(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
stop := false
w := bufio.NewWriter(f)
for _, line := range lines {
line = strings.TrimSpace(line)
if !stop && line == "<!-- BLOG-POST-LIST:START -->" {
fmt.Fprintln(w, line)
stop = true
}
if line == "<!-- BLOG-POST-LIST:END -->" {
stop = false
for _, item := range items {
fmt.Fprintln(w, item)
}
}
if !stop {
fmt.Fprintln(w, line)
}
}
if err = w.Flush(); err != nil {
log.Fatal(err)
}
}