-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
308 lines (285 loc) · 8.95 KB
/
Copy pathmain.go
File metadata and controls
308 lines (285 loc) · 8.95 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime/debug"
"sort"
"strconv"
"strings"
"time"
"github.com/mevdschee/github-export/internal/config"
"github.com/mevdschee/github-export/internal/github"
"github.com/mevdschee/github-export/internal/hooks"
"github.com/mevdschee/github-export/internal/sync"
)
func main() {
maxAge := flag.String("max-age", "",
"only fetch issues/PRs/projects updated within this window (e.g. 2y, 6mo, 4w, 30d, 12h); useful for very large repos on first sync")
showVersion := flag.Bool("version", false, "print version and exit")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [flags] [owner/repo] [output-dir]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Exports GitHub issues, PRs, releases, labels, and milestones\n")
fmt.Fprintf(os.Stderr, "to a local directory in markdown format.\n\n")
fmt.Fprintf(os.Stderr, "Runs incrementally on subsequent invocations.\n\n")
fmt.Fprintf(os.Stderr, "If invoked with no arguments, owner/repo are read from ./repo.yml in the\n")
fmt.Fprintf(os.Stderr, "current directory, or detected from its origin git remote.\n\n")
fmt.Fprintf(os.Stderr, "Needs a GitHub token: set GITHUB_TOKEN, or just log in with the GitHub CLI\n('gh auth login') and it is picked up automatically.\n\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
}
flag.Parse()
args := flag.Args()
if *showVersion {
fmt.Println(resolveVersion())
return
}
token, note := resolveToken()
if token == "" {
fmt.Fprintln(os.Stderr, note)
os.Exit(1)
}
if note != "" {
log.Println(note)
}
var owner, repo, outDir string
switch {
case len(args) == 0:
// Deduce mode. owner/repo are filled in from cfg below (./repo.yml) or
// the origin git remote.
outDir = deduceOutDir()
case len(args) == 1:
if strings.Contains(args[0], "/") {
parts := strings.SplitN(args[0], "/", 2)
owner = parts[0]
repo = parts[1]
}
outDir = "github-data"
default:
if strings.Contains(args[0], "/") {
parts := strings.SplitN(args[0], "/", 2)
owner = parts[0]
repo = parts[1]
}
outDir = args[1]
}
cutoff := ""
if *maxAge != "" {
t, err := parseMaxAge(*maxAge)
if err != nil {
log.Fatalf("--max-age: %v", err)
}
cutoff = t.UTC().Format(time.RFC3339)
}
// Create output directories
os.MkdirAll(filepath.Join(outDir, "issues"), 0755)
os.MkdirAll(filepath.Join(outDir, "releases"), 0755)
// Read existing config for incremental sync
configPath := filepath.Join(outDir, "repo.yml")
cfg, err := config.ReadRepoConfig(configPath)
if err != nil {
log.Fatalf("Reading repo.yml: %v", err)
}
if cfg != nil && owner == "" {
owner = cfg.Owner
repo = cfg.Repo
}
if owner == "" || repo == "" {
if o, r, ok := detectRepoFromGit(); ok {
owner, repo = o, r
log.Printf("Detected %s/%s from git remote", owner, repo)
}
}
if owner == "" || repo == "" {
if len(args) == 0 {
log.Fatalf("no owner/repo given, no repo.yml in %s, and no GitHub origin remote; pass owner/repo (e.g., octocat/Hello-World) or run from a directory that already has an export or a GitHub checkout", outDir)
}
log.Fatal("owner/repo must be specified as first argument (e.g., octocat/Hello-World)")
}
since := ""
if cfg != nil {
since = cfg.SyncedAt
}
// Treat --max-age as a floor: if it's more recent than synced_at (or
// synced_at is empty), the cutoff drives the next fetch.
if cutoff != "" && cutoff > since {
since = cutoff
}
switch {
case since != "" && cutoff == since:
log.Printf("First sync limited to items updated since %s (--max-age=%s)", since, *maxAge)
case since != "":
log.Printf("Incremental sync since %s", since)
default:
log.Println("Full sync (first run)")
}
syncStart := time.Now().UTC().Format(time.RFC3339)
client := github.NewClient(token)
skip := sync.CheckScopes(client)
// Sync all entities
if err := sync.Labels(client, owner, repo, outDir); err != nil {
log.Printf("Warning: %v", err)
}
if err := sync.Milestones(client, owner, repo, outDir); err != nil {
log.Printf("Warning: %v", err)
}
var issueProjects map[int64][]string
var projectEvents []hooks.Event
if !skip["projects"] {
ip, pe, err := sync.Projects(client, owner, repo, outDir, since)
if err != nil {
log.Printf("Warning: %v", err)
}
issueProjects = ip
projectEvents = pe
}
events, err := sync.Issues(client, owner, repo, outDir, since, issueProjects)
if err != nil {
log.Printf("Warning: %v", err)
}
events = append(events, projectEvents...)
releaseEvents, err := sync.Releases(client, owner, repo, outDir)
if err != nil {
log.Printf("Warning: %v", err)
}
events = append(events, releaseEvents...)
discussionEvents, err := sync.Discussions(client, owner, repo, outDir, since)
if err != nil {
log.Printf("Warning: %v", err)
}
events = append(events, discussionEvents...)
if err := sync.Repo(client, owner, repo, outDir, syncStart); err != nil {
log.Fatalf("Writing repo.yml: %v", err)
}
log.Printf("Done. synced_at=%s", syncStart)
// Export events as markdown files for agents to pick up
if len(events) > 0 {
eventsDir := filepath.Join(outDir, "events")
log.Printf("Exporting %d events to %s — %s", len(events), eventsDir, summarizeEvents(events))
if err := hooks.Export(eventsDir, events); err != nil {
log.Printf("Warning: exporting events: %v", err)
}
}
}
// version is set at release time via -ldflags "-X main.version=vX.Y.Z". When
// empty (a plain `go build`/`go install`), resolveVersion falls back to the
// module version or VCS revision recorded in the build info.
var version string
// resolveVersion reports the build's version string. A release binary has it
// baked in; for `go install owner/repo@vX.Y.Z` it comes from the module
// version; for a local build it falls back to the commit revision.
func resolveVersion() string {
if version != "" {
return version
}
info, ok := debug.ReadBuildInfo()
if !ok {
return "dev"
}
if v := info.Main.Version; v != "" && v != "(devel)" {
return v
}
var rev, dirty string
for _, s := range info.Settings {
switch s.Key {
case "vcs.revision":
rev = s.Value
case "vcs.modified":
if s.Value == "true" {
dirty = "-dirty"
}
}
}
if rev != "" {
if len(rev) > 12 {
rev = rev[:12]
}
return "dev-" + rev + dirty
}
return "dev"
}
// deduceOutDir picks the output directory for a no-argument run. The current
// directory is used in place only when it is itself an export (already holds a
// repo.yml), which is the `cd path/to/github-data && github-export` update
// flow. Otherwise the export goes into a github-data/ subfolder — an existing
// one if present, or a fresh one when run inside a checked-out GitHub repo — so
// the checkout root is never polluted with issues/, releases/, repo.yml, etc.
func deduceOutDir() string {
if _, err := os.Stat("repo.yml"); err == nil {
return "."
}
return "github-data"
}
var gitRemoteRe = regexp.MustCompile(`github\.com[:/]([^/]+)/(.+?)(?:\.git)?$`)
// detectRepoFromGit parses owner/repo out of the origin remote URL, so the tool
// can be run with no arguments inside a checked-out GitHub repository.
func detectRepoFromGit() (owner, repo string, ok bool) {
out, err := exec.Command("git", "remote", "get-url", "origin").Output()
if err != nil {
return "", "", false
}
m := gitRemoteRe.FindStringSubmatch(strings.TrimSpace(string(out)))
if m == nil {
return "", "", false
}
return m[1], m[2], true
}
var maxAgeRe = regexp.MustCompile(`^(\d+)(h|d|w|mo|y)$`)
// parseMaxAge turns a human age like "2y", "6mo", "4w", "30d", "12h" into the
// UTC timestamp that age ago. Months are taken as 30 days and years as 365
// days — the cutoff is an approximate floor, not a calendar boundary.
func parseMaxAge(s string) (time.Time, error) {
m := maxAgeRe.FindStringSubmatch(s)
if m == nil {
return time.Time{}, fmt.Errorf("must be Nh, Nd, Nw, Nmo or Ny (got %q)", s)
}
n, err := strconv.Atoi(m[1])
if err != nil || n <= 0 {
return time.Time{}, fmt.Errorf("must be a positive integer (got %q)", m[1])
}
var d time.Duration
switch m[2] {
case "h":
d = time.Duration(n) * time.Hour
case "d":
d = time.Duration(n) * 24 * time.Hour
case "w":
d = time.Duration(n) * 7 * 24 * time.Hour
case "mo":
d = time.Duration(n) * 30 * 24 * time.Hour
case "y":
d = time.Duration(n) * 365 * 24 * time.Hour
}
return time.Now().Add(-d), nil
}
// summarizeEvents returns a stable "type=N, type=N, ..." breakdown of an event
// slice, sorted by descending count then ascending type name.
func summarizeEvents(events []hooks.Event) string {
counts := map[string]int{}
for _, ev := range events {
counts[ev.Type]++
}
type kv struct {
k string
n int
}
pairs := make([]kv, 0, len(counts))
for k, n := range counts {
pairs = append(pairs, kv{k, n})
}
sort.Slice(pairs, func(i, j int) bool {
if pairs[i].n != pairs[j].n {
return pairs[i].n > pairs[j].n
}
return pairs[i].k < pairs[j].k
})
parts := make([]string, len(pairs))
for i, p := range pairs {
parts[i] = fmt.Sprintf("%s=%d", p.k, p.n)
}
return strings.Join(parts, ", ")
}