-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathdocupdater.go
More file actions
96 lines (81 loc) · 2.17 KB
/
Copy pathdocupdater.go
File metadata and controls
96 lines (81 loc) · 2.17 KB
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
package main
import (
"fmt"
"io"
"net/http"
"os"
"regexp"
"strings"
)
type DocOpDefinition struct {
ProjectName string
SourceDocUrl string
SourceDocSectionRegex string
TargetDocURL string
TargetDocSectionRegex string
}
var DocOpDefinitions = []DocOpDefinition{
{
ProjectName: "subfinder",
SourceDocUrl: "https://raw.githubusercontent.com/projectdiscovery/subfinder/main/README.md",
SourceDocSectionRegex: `(?s)##?\s+Usage\n(.*?)(\n##?|\z)`,
TargetDocURL: "tools/subfinder/usage.mdx",
TargetDocSectionRegex: `(?s)##?\s+Subfinder help options\n(.*?)(\n##?|\z)`,
},
}
func main() {
updateDoc()
}
func updateDoc() {
for _, def := range DocOpDefinitions {
sourceDoc, err := fetchDoc(def.SourceDocUrl)
if err != nil {
fmt.Println("Error fetching source doc:", err)
return
}
targetDoc, err := readDoc(def.TargetDocURL)
if err != nil {
fmt.Println("Error fetching target doc:", err)
return
}
updatedDoc := replaceSection(sourceDoc, def.SourceDocSectionRegex, targetDoc, def.TargetDocSectionRegex)
_ = writeDoc(def.TargetDocURL, updatedDoc)
}
}
func fetchDoc(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch file: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func readDoc(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(data), nil
}
func writeDoc(path, data string) error {
return os.WriteFile(path, []byte(data), 0644)
}
func replaceSection(sourceDoc, sourceDocSectionRegex, targetDoc, targetDocSectionRegex string) string {
sourceRe := regexp.MustCompile(sourceDocSectionRegex)
targetRe := regexp.MustCompile(targetDocSectionRegex)
sourceMatch := sourceRe.FindStringSubmatch(sourceDoc)
targetMatch := targetRe.FindStringSubmatch(targetDoc)
if len(sourceMatch) == 0 || len(targetMatch) == 0 {
return targetDoc
}
return strings.Replace(targetDoc, targetMatch[1], sourceMatch[1], 1)
}