/
main.go
81 lines (69 loc) · 1.9 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
package main
// Inspired by ChatGPT
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
)
const (
stylesSourceFile = "cmd/gendoc/styles.go"
styleListWebPage = "https://github.com/alecthomas/chroma/tree/master/styles"
)
func fetchPage() (string, error) {
// Fetch the webpage
resp, err := http.Get(styleListWebPage)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Read the body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func extractStyleNames(htmlContent string) []string {
// Use a regular expression to find all the links to XML files
re := regexp.MustCompile(`styles/.*\.xml`)
matches := re.FindAllString(htmlContent, -1)
// Extract the style names from the matches
styleNames := make([]string, len(matches))
for i, match := range matches {
// Find the last '/' and the last '.'
lastSlashIdx := strings.LastIndex(match, "/")
lastDotIdx := strings.LastIndex(match, ".")
// Extract the style name from the match
styleName := match[lastSlashIdx+1 : lastDotIdx]
// Remove everything after the last period
styleName = strings.TrimSuffix(styleName, styleName[strings.LastIndex(styleName, "."):])
styleNames[i] = styleName
}
return styleNames
}
func generateGoSourceCode(styles []string) string {
var buffer bytes.Buffer
buffer.WriteString("package main\n\nvar styles = []string{\n")
for _, style := range styles {
buffer.WriteString("\t\"")
buffer.WriteString(style)
buffer.WriteString("\",\n")
}
buffer.WriteString("}\n")
return buffer.String()
}
func main() {
pageHTML, err := fetchPage()
if err != nil {
log.Fatalf("error fetching page: %v", err)
}
styleNames := extractStyleNames(pageHTML)
sourceCode := generateGoSourceCode(styleNames)
err = ioutil.WriteFile(stylesSourceFile, []byte(sourceCode), 0644)
if err != nil {
log.Fatalf("error writing source code to file: %v", err)
}
}