-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
178 lines (150 loc) · 4.97 KB
/
main.go
File metadata and controls
178 lines (150 loc) · 4.97 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Package main provides the core functionality for updating GitHub star counts in Markdown and AsciiDoc files.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/google/go-github/v68/github"
"golang.org/x/oauth2"
)
const githubURLPrefix = "https://github.com/"
var version = "dev"
func main() {
outPath := flag.String("out", "", "output file path (defaults to input file)")
dryRun := flag.Bool("dry-run", false, "print updated markdown to stdout")
showVersion := flag.Bool("version", false, "show version info and exit")
flag.Parse()
if *showVersion {
fmt.Printf("markdown-github-stars-updater version %s\n", version)
return
}
if flag.NArg() < 1 {
fmt.Fprintln(os.Stderr, "Usage: markdown-github-stars-updater [flags] <path_to_file>")
flag.PrintDefaults()
os.Exit(1)
}
filePath := flag.Arg(0)
contentBytes, err := os.ReadFile(filepath.Clean(filePath))
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading the file:", err)
os.Exit(1)
}
content := string(contentBytes)
token, err := getAccessToken()
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
client := newGitHubClient(token)
// Select Updater based on extension
ext := strings.ToLower(filepath.Ext(filePath))
var updater LinkUpdater
switch ext {
case ".md", ".markdown":
updater = &MarkdownUpdater{}
case ".adoc", ".asciidoc":
updater = &ASCIIDocUpdater{}
default:
// Default to Markdown for backward compatibility if no extension matches, or error out?
// Spec says "Tool automatically detects file type or applies appropriate parsing".
// Let's assume Markdown if unknown for now, or maybe print a warning?
// Given the project name is "markdown-github-stars-updater", defaulting to markdown seems safe,
// but explicit support for asciidoc is added.
// Let's print a warning and default to markdown for now, or just fail.
// Failing is safer to avoid corrupting other files.
fmt.Fprintf(os.Stderr, "Unsupported file extension: %s. Supported: .md, .markdown, .adoc, .asciidoc\n", ext)
os.Exit(1)
}
// 1. Find Repos
repos, err := updater.FindRepos(content)
if err != nil {
fmt.Fprintln(os.Stderr, "Error finding repositories:", err)
os.Exit(1)
}
// 2. Fetch Stars
stars := make(map[string]int)
ctx := context.Background()
for _, repoURL := range repos {
if _, exists := stars[repoURL]; exists {
continue
}
count, fetchErr := getStarsCount(ctx, client, repoURL)
if fetchErr != nil {
fmt.Fprintf(os.Stderr, "Warning: Could not fetch stars for %s: %v\n", repoURL, fetchErr)
continue
}
stars[repoURL] = count
}
// 3. Update Content
updatedContent, err := updater.UpdateContent(content, stars)
if err != nil {
fmt.Fprintln(os.Stderr, "Error updating content:", err)
os.Exit(1)
}
if *dryRun {
fmt.Println(updatedContent)
return
}
output := filePath
if *outPath != "" {
output = *outPath
}
// G306: Expect WriteFile permissions to be 0600 or less (gosec)
// We use 0644 because this is a documentation tool and the files are usually public/shared.
err = os.WriteFile(output, []byte(updatedContent), 0o644) //nolint:gosec
if err != nil {
fmt.Fprintln(os.Stderr, "Error writing updated file:", err)
os.Exit(1)
}
fmt.Println("File updated successfully.")
}
// getStarsCount takes a GitHub repository URL and returns the current number of stars.
func getStarsCount(ctx context.Context, client *github.Client, repoURL string) (int, error) {
if !strings.HasPrefix(repoURL, githubURLPrefix) {
return 0, fmt.Errorf("invalid GitHub URL: %s", repoURL)
}
owner, repo, err := parseRepoName(repoURL[len(githubURLPrefix):])
if err != nil {
return 0, err
}
repository, _, err := client.Repositories.Get(ctx, owner, repo)
if err != nil {
return 0, err
}
return repository.GetStargazersCount(), nil
}
// parseRepoName takes a path like "owner/repo" (possibly with trailing segments, query strings, or fragments)
// and returns the owner and repo parts.
func parseRepoName(repoPath string) (string, string, error) {
// Use net/url to correctly parse query parameters and fragments
u, err := url.Parse(repoPath)
if err != nil {
return "", "", fmt.Errorf("failed to parse repository path: %w", err)
}
// We only care about the path part of the URL
path := strings.TrimPrefix(u.Path, "/")
parts := strings.SplitN(path, "/", 3) //nolint:mnd
if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
return "", "", fmt.Errorf("invalid repository path: %q", path)
}
return parts[0], parts[1], nil
}
// getAccessToken retrieves the GitHub access token from the environment variable
func getAccessToken() (string, error) {
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
return "", errors.New("missing GITHUB_TOKEN; set a GitHub personal access token")
}
return token, nil
}
func newGitHubClient(token string) *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
return github.NewClient(tc)
}