6
6
7
7
"github.com/pkg/errors"
8
8
orderedmap "github.com/wk8/go-ordered-map/v2"
9
+ "golang.org/x/exp/slices"
9
10
)
10
11
11
12
type jsonKind int
@@ -33,7 +34,7 @@ type Packages struct {
33
34
// example:
34
35
// ["package1", "package2@latest", "[email protected] "]
35
36
func (pkgs * Packages ) VersionedNames () []string {
36
- result := []string {}
37
+ result := make ( []string , 0 , len ( pkgs . Collection ))
37
38
for _ , p := range pkgs .Collection {
38
39
name := p .name
39
40
if p .Version != "" {
@@ -51,15 +52,11 @@ func (pkgs *Packages) Add(versionedName string) {
51
52
}
52
53
53
54
// Remove removes a package from the list of packages
54
- func (pkgs * Packages ) Remove (versionedName string ) error {
55
+ func (pkgs * Packages ) Remove (versionedName string ) {
55
56
name , version := parseVersionedName (versionedName )
56
- for idx , pkg := range pkgs .Collection {
57
- if pkg .name == name && pkg .Version == version {
58
- pkgs .Collection = append (pkgs .Collection [:idx ], pkgs .Collection [idx + 1 :]... )
59
- return nil
60
- }
61
- }
62
- return errors .Errorf ("package %s not found" , versionedName )
57
+ pkgs .Collection = slices .DeleteFunc (pkgs .Collection , func (pkg Package ) bool {
58
+ return pkg .name == name && pkg .Version == version
59
+ })
63
60
}
64
61
65
62
func (pkgs * Packages ) UnmarshalJSON (data []byte ) error {
@@ -97,7 +94,7 @@ func (pkgs *Packages) UnmarshalJSON(data []byte) error {
97
94
98
95
func (pkgs * Packages ) MarshalJSON () ([]byte , error ) {
99
96
if pkgs .jsonKind == jsonList {
100
- packagesList := []string {}
97
+ packagesList := make ( []string , 0 , len ( pkgs . Collection ))
101
98
for _ , p := range pkgs .Collection {
102
99
103
100
// Version may be empty for unversioned packages
@@ -167,15 +164,14 @@ func (p *Package) UnmarshalJSON(data []byte) error {
167
164
}
168
165
169
166
// Second, attempt to unmarshal as a Package struct
170
- type Alias Package // Use an alias-type to avoid infinite recursion
171
- alias := & Alias {}
167
+ type packageAlias Package // Use an alias-type to avoid infinite recursion
168
+ alias := & packageAlias {}
172
169
if err := json .Unmarshal (data , alias ); err != nil {
173
170
return errors .WithStack (err )
174
171
}
175
172
176
- // more robust way to copy all fields from alias?
173
+ * p = Package ( * alias )
177
174
p .kind = regular
178
- p .Version = alias .Version
179
175
return nil
180
176
}
181
177
@@ -185,8 +181,8 @@ func (p Package) MarshalJSON() ([]byte, error) {
185
181
}
186
182
187
183
// If we have a regular package, we want to marshal the entire struct:
188
- type Alias Package // Use an alias-type to avoid infinite recursion
189
- return json .Marshal ((Alias )(p ))
184
+ type packageAlias Package // Use an alias-type to avoid infinite recursion
185
+ return json .Marshal ((packageAlias )(p ))
190
186
}
191
187
192
188
// parseVersionedName parses the name and version from package@version representation
0 commit comments