-
Notifications
You must be signed in to change notification settings - Fork 0
/
package-collector.go
498 lines (410 loc) · 11.7 KB
/
package-collector.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type FetchConfig struct {
github bool
astrolabe bool
ziglibs bool
aquila_red bool
}
func main() {
fetch_github := flag.Bool("github", true, "fetches from github")
fetch_astrolabe := flag.Bool("astrolabe", true, "fetches from astrolabe.pm")
fetch_ziglibs := flag.Bool("ziglibs", true, "fetches from ziglibs/repository")
fetch_aquila := flag.Bool("aquila", true, "fetches from aquila.red")
tags_file := flag.String("tags", "tags.json", "Output file for tags.")
pkgs_file := flag.String("packages", "packages.json", "Output file for packages.")
ziglibs_repo := flag.String("repository", "repository", "Defines the location of the ziglibs repository.")
flag.Parse()
fetch_config := FetchConfig{
github: *fetch_github,
astrolabe: *fetch_astrolabe,
ziglibs: *fetch_ziglibs,
aquila_red: *fetch_aquila,
}
if fetch_config.ziglibs {
log.Print("Updating the ziglibs repository...")
git_executable, err := exec.LookPath("git")
if err != nil {
log.Fatalln(err)
}
_, err = (&exec.Cmd{
Path: git_executable,
Args: []string{"git", "submodule", "update", "--init", "--recursive"},
Dir: ".",
}).Output()
if err != nil {
log.Fatalln(err)
}
_, err = (&exec.Cmd{
Path: git_executable,
Args: []string{"git", "pull"},
Dir: *ziglibs_repo,
}).Output()
if err != nil {
log.Fatalln(err)
}
}
raw_packages := make([]Package, 0)
if fetch_config.ziglibs {
log.Print("Fetching packages from ziglibs/repository...")
err := filepath.Walk((*ziglibs_repo)+"/packages", func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
// log.Printf("loading %s...\n", path)
bytes, err := os.ReadFile(path)
if err != nil {
return err
}
var pkg = ZigPackageDef{}
err = json.Unmarshal(bytes, &pkg)
if err != nil {
return err
}
raw_packages = append(raw_packages, Package{
GitRepo: pkg.Git,
DisplayName: strings.TrimSuffix(filepath.Base(path), ".json"),
Tags: filterAndSortTags(pkg.Tags),
Author: pkg.Author,
Source: SRC_ZIGLIBS,
Links: Links{
Github: heapify(pkg.Git),
},
Description: pkg.Description,
RootFile: heapify(pkg.RootFile),
})
return nil
})
if err != nil {
log.Fatalln(err)
}
}
if fetch_config.github {
log.Print("Fetching packages from github...")
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_API_TOKEN")},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// fmt.Printf("%d %d %d %v\n", count, repos.GetTotal(), len(repos.Repositories), repos.GetIncompleteResults())
raw_packages = loadGithubTopic(client, raw_packages, "zig-package")
raw_packages = loadGithubTopic(client, raw_packages, "zig-library")
}
// astrolabe and aquila must be fetched later as they might disturb the original author of the package
if fetch_config.astrolabe {
log.Print("Fetching packages from astrolabe.pm...")
response, err := http.Get("https://astrolabe.pm/pkgs")
if err != nil {
log.Fatalln(err)
}
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalln(err)
}
var astro_pkgs []AstroPackage
err = json.Unmarshal(bytes, &astro_pkgs)
for _, pkg := range astro_pkgs {
raw_packages = append(raw_packages, Package{
GitRepo: pkg.SourceUrl,
DisplayName: pkg.Name,
Tags: filterAndSortTags(pkg.Tags),
Author: pkg.User,
Source: SRC_ASTROLABE,
Links: Links{
Astrolabe: heapify(fmt.Sprintf("https://astrolabe.pm/#/package/%s/%s/%s", pkg.User, pkg.Name, pkg.Version)),
},
Description: pkg.Description,
})
}
}
if fetch_config.aquila_red {
log.Print("Fetching packages from aquila.red...")
client := &http.Client{}
req, err := http.NewRequest("GET", "https://aquila.red/all/packages", nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("Accept", "application/json")
response, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalln(err)
}
var aquila_pkgs AquilaList
err = json.Unmarshal(bytes, &aquila_pkgs)
for _, pkg := range aquila_pkgs.List {
author := strings.Split(pkg.RemoteName, "/")[0]
raw_packages = append(raw_packages, Package{
GitRepo: fmt.Sprintf("https://github.com/%s", pkg.RemoteName),
DisplayName: pkg.Name,
Tags: make([]string, 0),
Author: author,
Source: SRC_AQUILA,
Links: Links{
Aquila: heapify(fmt.Sprintf("https://aquila.red/%d/%s/%s", pkg.Remote, author, pkg.Name)),
},
Description: pkg.Description,
})
}
}
log.Printf("Collected %d source packages, merging...", len(raw_packages))
packages := make(map[string]Package)
for _, pkg := range raw_packages {
unique_path := strings.ToLower(uniqueGitPath(pkg.GitRepo))
stored := packages[unique_path]
if stored.GitRepo != "" {
// log.Printf("duplicate repo: %s\n", stored.GitRepo)
stored.Tags = append(stored.Tags, pkg.Tags...)
stored.Source |= pkg.Source // we got the package from several sources
if stored.Links.Aquila == nil {
stored.Links.Aquila = pkg.Links.Aquila
}
if stored.Links.Astrolabe == nil {
stored.Links.Astrolabe = pkg.Links.Astrolabe
}
if stored.Links.Github == nil {
stored.Links.Github = pkg.Links.Github
}
} else {
stored = pkg
}
packages[unique_path] = stored
}
log.Printf("Loaded %d packages, with %d packages merged.", len(packages), len(raw_packages)-len(packages))
package_list := make([]Package, 0)
for _, pkg := range packages {
pkg.Tags = mergeTags(pkg.Tags)
package_list = append(package_list, pkg)
}
sort.Slice(package_list, func(i, j int) bool {
return strings.ToLower(package_list[i].DisplayName) < strings.ToLower(package_list[j].DisplayName)
})
final, err := json.MarshalIndent(package_list, "", " ")
if err != nil {
log.Fatalln(err)
}
os.WriteFile(*pkgs_file, final, 0666)
all_tags := make(map[string]Tag, 0)
if fetch_config.ziglibs {
log.Print("Fetching tags from ziglibs/repository...")
err = filepath.Walk((*ziglibs_repo)+"/tags", func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
// log.Printf("loading %s...\n", path)
bytes, err := os.ReadFile(path)
if err != nil {
return err
}
var tag = ZigTagDef{}
err = json.Unmarshal(bytes, &tag)
if err != nil {
return err
}
name := strings.TrimSuffix(filepath.Base(path), ".json")
all_tags[name] = Tag{
Name: name,
Description: tag.Description,
}
return nil
})
if err != nil {
log.Fatalln(err)
}
}
for _, pkg := range package_list {
for _, tag := range pkg.Tags {
if all_tags[tag].Name == "" {
all_tags[tag] = Tag{
Name: tag,
Description: "",
}
}
}
}
tag_list := make([]Tag, 0)
for _, tag := range all_tags {
tag_list = append(tag_list, tag)
}
sort.Slice(tag_list, func(i, j int) bool {
return strings.ToLower(tag_list[i].Name) < strings.ToLower(tag_list[j].Name)
})
final_tags, err := json.MarshalIndent(tag_list, "", " ")
if err != nil {
log.Fatalln(err)
}
os.WriteFile(*tags_file, final_tags, 0666)
}
func loadGithubTopic(client *github.Client, raw_packages []Package, topic string) []Package {
page := 1
count := 0
for {
repos, _, err := client.Search.Repositories(
context.Background(),
"topic:"+topic,
&github.SearchOptions{
Sort: "stars",
Order: "desc",
ListOptions: github.ListOptions{
Page: page,
PerPage: 100,
},
},
)
if err != nil {
log.Fatalf("failed to query repositories: %s", err)
}
for _, repo := range repos.Repositories {
raw_packages = append(raw_packages, Package{
GitRepo: *repo.CloneURL,
DisplayName: *repo.Name,
Tags: filterAndSortTags(repo.Topics),
Author: *repo.Owner.Login,
Source: SRC_GITHUB,
Links: Links{
Github: repo.HTMLURL,
},
Description: repo.GetDescription(),
})
}
count += len(repos.Repositories)
if len(repos.Repositories) == 0 || count >= repos.GetTotal() {
break
}
page += 1
}
return raw_packages
}
func uniqueGitPath(uri string) string {
if strings.HasPrefix(uri, "https://github.com") && strings.HasSuffix(uri, ".git") {
return uri[0 : len(uri)-4]
}
return uri
}
func mergeTags(tags_list ...[]string) []string {
set := make(map[string]bool)
res := make([]string, 0)
for _, tags := range tags_list {
for _, tag := range tags {
if !set[tag] {
res = append(res, tag)
set[tag] = true
}
}
}
sort.Strings(res)
return res
}
type Package struct {
Author string `json:"author"` // first come, first serve
DisplayName string `json:"name"`
Tags []string `json:"tags"`
GitRepo string `json:"git"` // used for deduplication
RootFile *string `json:"root_file"`
Description string `json:"description"`
Source int `json:"source"`
Links Links `json:"links"`
}
type Links struct {
Github *string `json:"github"`
Astrolabe *string `json:"astrolabe"`
Aquila *string `json:"aquila"`
}
const (
SRC_GITHUB = 1 << iota // https://github.com/topics/zig-package
SRC_AQUILA = 1 << iota // https://aquila.red/
SRC_ASTROLABE = 1 << iota // https://astrolabe.pm/
SRC_ZIGLIBS = 1 << iota // https://github.com/ziglibs/repository
)
var filtered_tags []string = []string{
"zig",
"zig-package",
"ziglang",
"zig-programming-language",
"zig-library",
"zig-lang",
}
func filterAndSortTags(tags []string) []string {
res := []string{}
for _, tag := range tags {
tag = strings.ToLower(tag)
if !contains(filtered_tags, tag) {
res = append(res, tag)
}
}
return res
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
type ZigPackageDef struct {
Author string `json:"author"`
Tags []string `json:"tags"`
Git string `json:"git"`
RootFile string `json:"root_file"`
Description string `json:"description"`
}
type AstroPackage struct {
User string `json:"user"`
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
License string `json:"license"`
SourceUrl string `json:"source_url"`
Downloads int `json:"downloads"`
Tags []string `json:"tags"`
// Deps string `json:"deps"`
// BuildDeps string `json:"build_deps"`
}
type AquilaList struct {
List []AquilaPkg `json:"list"`
}
type AquilaPkg struct {
Uuid string `json:"uuid"` // : "001ZFTQN5BK6P7235W2YY7TKP1",
Owner string `json:"owner"` // : "0015KMZ1NDDFP4WRWSVA31N0CD",
Name string `json:"name"` // : "pcre-8.45",
CreatedOn string `json:"created_on"` // : "Mon, 28 Feb 2022 02:04:49 UTC",
Remote int `json:"remote"` // : 1,
RemoteId string `json:"remote_id"` // : "462170122",
RemoteName string `json:"remote_name"` // : "nektro/pcre-8.45",
Description string `json:"description"` // : "Perl Compatible Regular Expressions",
License string `json:"license"` // : "BSD-3-Clause",
LatestVersion string `json:"latest_version"` // : "v0.1",
StarCount string `json:"star_count"` // : 0
}
func heapify(str string) *string {
ptr := new(string)
*ptr = str
return ptr
}
type Tag struct {
Name string `json:"name"`
Description string `json:"description"`
}
type ZigTagDef struct {
Description string `json:"description"`
}