-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathhelper.go
More file actions
713 lines (636 loc) · 19 KB
/
helper.go
File metadata and controls
713 lines (636 loc) · 19 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
package rpmutils
import (
"fmt"
"net/url"
"path/filepath"
"sort"
"strings"
"time"
"unicode"
"github.com/open-edge-platform/os-image-composer/internal/ospackage"
"github.com/open-edge-platform/os-image-composer/internal/utils/logger"
)
func resolveMultiCandidates(parentPkg ospackage.PackageInfo, candidates []ospackage.PackageInfo) (ospackage.PackageInfo, error) {
parentBase, err := extractRepoBase(parentPkg.URL)
if err != nil {
return ospackage.PackageInfo{}, fmt.Errorf("failed to extract repo base from parent package URL: %w", err)
}
/////////////////////////////////////
//A: if version is specified
/////////////////////////////////////
// All candidates have the same .Name, so just use candidates[0].Name for version extraction
op := ""
ver := ""
hasVersionConstraint := false
if len(candidates) > 0 {
op, ver, hasVersionConstraint = extractVersionRequirement(parentPkg.RequiresVer, extractBasePackageNameFromFile(candidates[0].Name))
}
if hasVersionConstraint {
// First pass: look for candidates from the same repo that meet version constraint
var sameRepoMatches []ospackage.PackageInfo
var otherRepoMatches []ospackage.PackageInfo
for _, candidate := range candidates {
candidateBase, err := extractRepoBase(candidate.URL)
if err != nil {
continue
}
// Check if version constraint is satisfied
cmp, err := comparePackageVersions(candidate.Version, ver)
if err != nil {
continue
}
versionMatches := false
switch op {
case "=":
versionMatches = (cmp == 0)
case "<<", "<":
versionMatches = (cmp < 0)
case "<=":
versionMatches = (cmp <= 0)
case ">>", ">":
versionMatches = (cmp > 0)
case ">=":
versionMatches = (cmp >= 0)
}
if versionMatches {
if candidateBase == parentBase {
sameRepoMatches = append(sameRepoMatches, candidate)
} else {
otherRepoMatches = append(otherRepoMatches, candidate)
}
}
}
// Priority 1: return first match from same repo
if len(sameRepoMatches) > 0 {
return sameRepoMatches[0], nil
}
// Priority 2: return first match from other repos
if len(otherRepoMatches) > 0 {
return otherRepoMatches[0], nil
}
return ospackage.PackageInfo{}, fmt.Errorf("no candidates satisfy version constraint = %s%s", op, ver)
}
/////////////////////////////////////
// B: if version is not specified
//////////////////////////////////////
// Check for empty candidates list
if len(candidates) == 0 {
return ospackage.PackageInfo{}, fmt.Errorf("no candidates provided for selection")
}
// If only one candidate, return it
if len(candidates) == 1 {
return candidates[0], nil
}
// Rule 1: find all candidates with the same base URL and return the latest version
var sameBaseCandidates []ospackage.PackageInfo
for _, candidate := range candidates {
candidateBase, err := extractRepoBase(candidate.URL)
if err != nil {
continue
}
if candidateBase == parentBase {
sameBaseCandidates = append(sameBaseCandidates, candidate)
}
}
// If we found candidates with the same base URL, return the one with the latest version
if len(sameBaseCandidates) > 0 {
if len(sameBaseCandidates) == 1 {
return sameBaseCandidates[0], nil
}
// Find the candidate with the latest version
latest := sameBaseCandidates[0]
for _, candidate := range sameBaseCandidates[1:] {
cmp := compareVersions(candidate.Version, latest.Version)
if cmp > 0 {
latest = candidate
}
}
return latest, nil
}
// Rule 2: If no candidate has the same repo, return the first candidate in other repos
return candidates[0], nil
}
func extractRepoBase(rawURL string) (string, error) {
log := logger.Logger()
u, err := url.Parse(rawURL)
if err != nil {
return "", err
}
path := u.Path
// For Debian repositories - split by "/pool/"
if strings.Contains(path, "/pool/") {
parts := strings.SplitN(path, "/pool/", 2)
base := fmt.Sprintf("%s://%s%s/pool/", u.Scheme, u.Host, parts[0])
return base, nil
}
// For RPM repositories - split by "/Packages/"
if strings.Contains(path, "/Packages/") {
parts := strings.SplitN(path, "/Packages/", 2)
base := fmt.Sprintf("%s://%s%s/Packages/", u.Scheme, u.Host, parts[0])
return base, nil
}
// For RPM repositories with RPMS structure - find the directory containing the RPM file
if strings.HasSuffix(path, ".rpm") {
// Remove the filename to get the directory
lastSlash := strings.LastIndex(path, "/")
if lastSlash > 0 {
dirPath := path[:lastSlash+1] // Keep the trailing slash
base := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, dirPath)
return base, nil
}
}
// For DEB repositories with .deb files
if strings.HasSuffix(path, ".deb") {
// Remove the filename to get the directory
lastSlash := strings.LastIndex(path, "/")
if lastSlash > 0 {
dirPath := path[:lastSlash+1] // Keep the trailing slash
base := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, dirPath)
return base, nil
}
}
// Fallback: if no specific pattern found, try to extract directory from any file
if strings.Contains(path, ".") { // Likely a file with extension
lastSlash := strings.LastIndex(path, "/")
if lastSlash > 0 {
dirPath := path[:lastSlash+1]
base := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, dirPath)
return base, nil
}
}
log.Errorf("Unable to extract repo base from URL: %s", rawURL)
return "", fmt.Errorf("unable to extract repo base from URL: %s", rawURL)
}
// compareVersions compares two Debian package versions
// Returns 1 if v1 > v2, -1 if v1 < v2, 0 if equal
func compareVersions(v1, v2 string) int {
// Extract version from Debian package names like "acct_6.6.4-5+b1_amd64.deb"
extractVersion := func(name string) string {
parts := strings.Split(name, "_")
if len(parts) >= 2 {
return parts[1]
}
return name
}
ver1 := extractVersion(v1)
ver2 := extractVersion(v2)
cmp, _ := comparePackageVersions(ver1, ver2)
return cmp
}
// extractBasePackageNameFromFile extracts the base package name from a full package filename
// e.g., "curl-8.8.0-2.azl3.x86_64.rpm" -> "curl"
// e.g., "curl-devel-8.8.0-1.azl3.x86_64.rpm" -> "curl-devel"
func extractBasePackageNameFromFile(fullName string) string {
// Remove .rpm suffix if present
name := strings.TrimSuffix(fullName, ".rpm")
// Split by '-' and find where the version starts
parts := strings.Split(name, "-")
if len(parts) < 2 {
return name
}
// Find the first part that looks like a version (starts with digit)
for i := 1; i < len(parts); i++ {
if len(parts[i]) > 0 && (parts[i][0] >= '0' && parts[i][0] <= '9') {
// get the name
maybe_name := strings.Join(parts[:i], "-")
// check if version is part of the name
// full name contains version, if package name has version,
// it will be repeated in the full name
for j := i + 1; j < len(parts); j++ {
if len(parts[j]) > 0 && strings.Contains(parts[j], parts[i]) {
maybe_name = strings.Join(parts[:j], "-")
break
}
}
// return name or name-version
return maybe_name
}
}
// If no version-like part found, return the whole name
return name
}
// extractBaseNameFromDep takes a potentially complex requirement string
// and returns only the base package/capability name.
func extractBaseNameFromDep(req string) string {
if strings.HasPrefix(req, "(") && strings.Contains(req, " ") {
trimmed := strings.TrimPrefix(req, "(")
parts := strings.Fields(trimmed)
if len(parts) > 0 {
req = parts[0]
}
}
finalParts := strings.Fields(req)
if len(finalParts) == 0 {
return ""
}
base := finalParts[0]
return base
}
func findAllCandidates(parent ospackage.PackageInfo, depName string, all []ospackage.PackageInfo) ([]ospackage.PackageInfo, error) {
// log := logger.Logger()
var candidates []ospackage.PackageInfo
// First pass: look for exact name (canonical name) matches
for _, pi := range all {
// Extract the base package name (everything before the first '-' that starts a version)
baseName := extractBasePackageNameFromFile(pi.Name)
if baseName == depName {
candidates = append(candidates, pi)
}
}
// If no direct matches found, search in Provides field
if len(candidates) == 0 {
for _, pi := range all {
for _, provided := range pi.Provides {
if provided == depName {
candidates = append(candidates, pi)
}
}
}
}
// If no direct matches found, search in Files field
if len(candidates) == 0 {
for _, pi := range all {
for _, file := range pi.Files {
if file == depName {
candidates = append(candidates, pi)
}
}
}
}
// Sort candidates by version (highest version first)
sort.Slice(candidates, func(i, j int) bool {
cmp, _ := comparePackageVersions(candidates[i].Version, candidates[j].Version)
return cmp > 0
})
return candidates, nil
}
// ResolvePackage finds the best matching package for a given package name
func ResolveTopPackageConflicts(want string, all []ospackage.PackageInfo) (ospackage.PackageInfo, bool) {
var candidates []ospackage.PackageInfo
for _, pi := range all {
// 1) exact name, e.g. acct-205-25.azl3.noarch.rpm
if pi.Name == want {
candidates = append(candidates, pi)
break
}
cleanName := extractBasePackageNameFromFile(pi.Name)
// 2) base name, e.g. acct
if cleanName == want {
candidates = append(candidates, pi)
continue
}
// 3) prefix by want-version ("acl-")
// expected pi.Name should look like openvino-2025.3.0-2025.3.0.19807-1.noarch.rpm
// want = openvino-2025.3.0
if strings.HasPrefix(pi.Name, want) {
// Extract string after "-" and compare with pi.Version
if dashIdx := strings.LastIndex(want, "-"); dashIdx != -1 {
verStr := want[dashIdx+1:]
if strings.Contains(pi.Version, verStr) {
candidates = append(candidates, pi)
continue
}
}
}
}
// If no candidates found, check Provides field
if len(candidates) == 0 {
for _, pi := range all {
for _, provided := range pi.Provides {
if provided == want {
candidates = append(candidates, pi)
break
}
}
}
}
if len(candidates) == 0 {
return ospackage.PackageInfo{}, false
}
// If we got an exact match in step (1), it's the only candidate
if len(candidates) == 1 && (candidates[0].Name == want || extractBasePackageNameFromFile(candidates[0].Name) == want) {
return candidates[0], true
}
// If multiple candidates, apply further filtering based on Dist
if Dist != "" {
// Filter candidates by release if any candidate matches Dist
distRelease := ""
for _, pi := range candidates {
if idx := strings.LastIndex(pi.Version, "-"); idx != -1 {
verPart := pi.Version[idx+1:]
if dotIdx := strings.Index(verPart, "."); dotIdx != -1 {
release := verPart[dotIdx+1:]
if release == Dist {
distRelease = release
break
}
}
}
}
if distRelease != "" {
filtered := candidates[:0]
for _, pi := range candidates {
if idx := strings.LastIndex(pi.Version, "-"); idx != -1 {
verPart := pi.Version[idx+1:]
if dotIdx := strings.Index(verPart, "."); dotIdx != -1 {
release := verPart[dotIdx+1:]
if release == distRelease {
filtered = append(filtered, pi)
}
}
}
}
candidates = filtered
}
}
// Sort by version (highest version first)
sort.Slice(candidates, func(i, j int) bool {
return compareVersions(candidates[i].Version, candidates[j].Version) > 0
})
return candidates[0], true
}
func extractVersionRequirement(reqVers []string, depName string) (op string, ver string, found bool) {
for _, reqVer := range reqVers {
reqVer = strings.TrimSpace(reqVer)
// Handle alternatives (|) - check if our depName is in any of the alternatives
alternatives := strings.Split(reqVer, "|")
for _, alt := range alternatives {
alt = strings.TrimSpace(alt)
// Extract the base package name from the requirement
var baseName string
if idx := strings.Index(alt, " ("); idx != -1 {
// Case: "systemd (= 0:255-29.emt3)"
baseName = strings.TrimSpace(alt[:idx])
} else if idx := strings.Index(alt, "("); idx != -1 {
// Case: "python3dist(cryptography)"
baseName = strings.TrimSpace(alt[:idx])
} else {
// Case: no parentheses, just the package name
baseName = alt
}
// Check if this matches our dependency name
if baseName != depName {
continue // Skip to next alternative
}
// Found our dependency, now extract version constraint
// Look for version constraint in format: "packagename (operator version)"
if idx := strings.Index(alt, " ("); idx != -1 {
verConstraint := alt[idx+2:] // Skip " ("
if idx2 := strings.Index(verConstraint, ")"); idx2 != -1 {
verConstraint = verConstraint[:idx2]
}
// Split into operator and version
parts := strings.Fields(verConstraint)
if len(parts) >= 2 {
op := parts[0]
ver := strings.Join(parts[1:], " ") // Join in case version has spaces
// DO NOT strip epoch - keep the full version including epoch
// The epoch (e.g., "1:" in "1:3.0.0-9.emt3") is crucial for version comparison
return op, ver, true
}
}
// If we found the dependency but no version constraint, return found=false
return "", "", false
}
}
return "", "", false
}
func comparePackageVersions(a, b string) (int, error) {
// Empty-version handling: empty < any non-empty
if a == "" && b == "" {
return 0, nil
}
if a == "" {
return -1, nil
}
if b == "" {
return 1, nil
}
// Helper to split epoch
splitEpoch := func(ver string) (epoch int, rest string) {
parts := strings.SplitN(ver, ":", 2)
if len(parts) == 2 {
if _, err := fmt.Sscanf(parts[0], "%d", &epoch); err != nil {
epoch = 0
}
rest = parts[1]
} else {
epoch = 0
rest = ver
}
return
}
// Handle epoch first
epochA, restA := splitEpoch(a)
epochB, restB := splitEpoch(b)
if epochA < epochB {
return -1, nil
}
if epochA > epochB {
return 1, nil
}
// After epoch comparison, check if one is a prefix of the other
// This handles cases like "1.19-1.emt3" vs "1.19"
if strings.HasPrefix(restA, restB) {
if restA == restB {
return 0, nil // exact match
}
// restA is longer, check if the next character is a separator
if len(restA) > len(restB) {
nextChar := restA[len(restB)]
if nextChar == '-' || nextChar == '.' || nextChar == '+' || nextChar == '~' {
return 0, nil // treat as equal since restB is a valid prefix
}
}
}
if strings.HasPrefix(restB, restA) {
if restA == restB {
return 0, nil // exact match
}
// restB is longer, check if the next character is a separator
if len(restB) > len(restA) {
nextChar := restB[len(restA)]
if nextChar == '-' || nextChar == '.' || nextChar == '+' || nextChar == '~' {
return 0, nil // treat as equal since restA is a valid prefix
}
}
}
// If no prefix match, fall back to detailed comparison
// Split version string into upstream version and release for RPMat last hyphen
splitRevision := func(ver string) (upstream string, revision string) {
if i := strings.LastIndex(ver, "-"); i >= 0 {
return ver[:i], ver[i+1:]
}
return ver, ""
}
// nextSegment returns the next contiguous numeric or non-numeric segment.
nextSegment := func(s string) (seg string, rest string, numeric bool) {
if s == "" {
return "", "", false
}
// numeric segment
if s[0] >= '0' && s[0] <= '9' {
i := 0
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
i++
}
return s[:i], s[i:], true
}
// non-numeric segment
i := 0
for i < len(s) && (s[i] < '0' || s[i] > '9') {
i++
}
return s[:i], s[i:], false
}
// Character ordering per Debian: '~' < end-of-string < letters < other characters.
// This ordering is crucial for correct Debian version comparison, as defined in
// Debian Policy Manual section 5.6.12 ("Version"). See:
// https://www.debian.org/doc/debian-policy/ch-controlfields.html#version
charOrder := func(r rune) int {
if r == '~' {
return -2
}
if r == 0 {
return -1
}
if unicode.IsLetter(r) {
return int(r)
}
return 0x100 + int(r)
}
// Compare two non-digit segments using Debian ordering
compareNonDigitSegments := func(aSeg, bSeg string) int {
ai, bi := 0, 0
for {
var ra, rb rune
if ai < len(aSeg) {
ra = rune(aSeg[ai])
} else {
ra = 0
}
if bi < len(bSeg) {
rb = rune(bSeg[bi])
} else {
rb = 0
}
// both ended
if ra == 0 && rb == 0 {
return 0
}
if ra != rb {
oa := charOrder(ra)
ob := charOrder(rb)
if oa < ob {
return -1
}
return 1
}
ai++
bi++
}
}
// Compare numeric segments (as dpkg: strip leading zeros, compare length, then lexicographically)
compareNumericSegments := func(aSeg, bSeg string) int {
aTrim := strings.TrimLeft(aSeg, "0")
bTrim := strings.TrimLeft(bSeg, "0")
// treat empty as zero
if aTrim == "" && bTrim == "" {
return 0
}
if aTrim == "" {
return -1
}
if bTrim == "" {
return 1
}
// longer numeric (more digits) is greater
if len(aTrim) > len(bTrim) {
return 1
}
if len(aTrim) < len(bTrim) {
return -1
}
// same length -> lexical compare works
if aTrim > bTrim {
return 1
}
if aTrim < bTrim {
return -1
}
return 0
}
// Split upstream and debian revisions
upA, debA := splitRevision(restA)
upB, debB := splitRevision(restB)
// Compare iterative parts (used for upstream version and debian revision)
compareParts := func(sa, sb string) int {
for sa != "" || sb != "" {
// Handle tilde first: '~' sorts before everything (including end-of-string)
if (len(sa) > 0 && sa[0] == '~') || (len(sb) > 0 && sb[0] == '~') {
if len(sa) > 0 && sa[0] == '~' && !(len(sb) > 0 && sb[0] == '~') {
return -1
}
if len(sb) > 0 && sb[0] == '~' && !(len(sa) > 0 && sa[0] == '~') {
return 1
}
// both have tilde: consume and continue
if len(sa) > 0 && sa[0] == '~' && len(sb) > 0 && sb[0] == '~' {
sa = sa[1:]
sb = sb[1:]
continue
}
}
// After tilde handling, if either side is exhausted, the exhausted side is less
if sa == "" && sb == "" {
break
}
if sa == "" {
return -1
}
if sb == "" {
return 1
}
segA, restASeg, numA := nextSegment(sa)
segB, restBSeg, numB := nextSegment(sb)
// both empty segments -> continue
if segA == "" && segB == "" {
sa, sb = restASeg, restBSeg
continue
}
// numeric vs non-numeric: numeric < non-numeric
if numA != numB {
if numA {
return -1
}
return 1
}
// both numeric
if numA && numB {
if cmp := compareNumericSegments(segA, segB); cmp != 0 {
return cmp
}
} else { // both non-numeric
if cmp := compareNonDigitSegments(segA, segB); cmp != 0 {
return cmp
}
}
sa, sb = restASeg, restBSeg
}
return 0
}
// Compare upstream versions first, then debian revisions
if cmp := compareParts(upA, upB); cmp != 0 {
return cmp, nil
}
if cmp := compareParts(debA, debB); cmp != 0 {
return cmp, nil
}
return 0, nil
}
// GenerateSPDXFileName creates a SPDX manifest filename based on repository configuration
func GenerateSPDXFileName(repoNm string) string {
timestamp := time.Now().Format("20060102_150405")
SPDXFileNm := filepath.Join("spdx_manifest_rpm_" + strings.ReplaceAll(repoNm, " ", "_") + "_" + timestamp + ".json")
return SPDXFileNm
}