forked from elastic/package-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexer.go
86 lines (68 loc) · 1.93 KB
/
indexer.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"context"
"sort"
"github.com/Masterminds/semver/v3"
"github.com/elastic/package-registry/packages"
)
type Indexer interface {
Init(context.Context) error
Get(context.Context, *packages.GetOptions) (packages.Packages, error)
}
type CombinedIndexer []Indexer
func NewCombinedIndexer(indexers ...Indexer) CombinedIndexer {
return indexers
}
func (c CombinedIndexer) Init(ctx context.Context) error {
for _, indexer := range c {
err := indexer.Init(ctx)
if err != nil {
return err
}
}
return nil
}
func (c CombinedIndexer) Get(ctx context.Context, opts *packages.GetOptions) (packages.Packages, error) {
var packages packages.Packages
for _, indexer := range c {
p, err := indexer.Get(ctx, opts)
if err != nil {
return nil, err
}
packages = packages.Join(p)
}
if opts != nil && opts.Filter != nil && !opts.Filter.AllVersions {
return latestPackagesVersion(packages), nil
}
return packages, nil
}
func latestPackagesVersion(source packages.Packages) (result packages.Packages) {
sort.Sort(byNameVersion(source))
current := ""
for _, p := range source {
if p.Name == current {
continue
}
current = p.Name
result = append(result, p)
}
return result
}
type byNameVersion packages.Packages
func (p byNameVersion) Len() int { return len(p) }
func (p byNameVersion) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byNameVersion) Less(i, j int) bool {
if p[i].Name != p[j].Name {
return p[i].Name < p[j].Name
}
// Newer versions first.
iSemVer, _ := semver.NewVersion(p[i].Version)
jSemVer, _ := semver.NewVersion(p[j].Version)
if iSemVer != nil && jSemVer != nil {
return jSemVer.LessThan(iSemVer)
}
return p[j].Version < p[i].Version
}