-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathroot.go
More file actions
1936 lines (1720 loc) · 61.3 KB
/
root.go
File metadata and controls
1936 lines (1720 loc) · 61.3 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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the cpackget project. */
package installer
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
errs "github.com/open-cmsis-pack/cpackget/cmd/errors"
"github.com/open-cmsis-pack/cpackget/cmd/ui"
"github.com/open-cmsis-pack/cpackget/cmd/utils"
"github.com/open-cmsis-pack/cpackget/cmd/xml"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"golang.org/x/mod/semver"
"golang.org/x/sync/semaphore"
)
const PublicIndex = "index.pidx"
const KeilDefaultPackRoot = "https://www.keil.com/pack/"
// DefaultPublicIndex is the public index to use in "default mode"
const DefaultPublicIndex = KeilDefaultPackRoot + PublicIndex
// GetDefaultCmsisPackRoot provides a default location
// for the pack root if not provided. This is to enable
// a "default mode", where the public index will be
// automatically initiated if not ready yet.
func GetDefaultCmsisPackRoot() string {
var root string
// Workaround to fake default mode in tests,
// by avoiding writing in any of the default locations,
// and using the generated testing pack dirs.
if root = os.Getenv("CPACKGET_DEFAULT_MODE_PATH"); root != "" {
return filepath.Clean(root)
}
if runtime.GOOS == "windows" {
root = os.Getenv("LOCALAPPDATA")
if root == "" {
root = os.Getenv("USERPROFILE")
if root != "" {
root = root + "\\AppData\\Local"
}
}
if root != "" {
root = root + "\\Arm\\Packs"
}
} else {
root = os.Getenv("XDG_CACHE_HOME")
if root == "" {
root = os.Getenv("HOME")
if root != "" {
root = root + "/.cache"
}
}
if root != "" {
root = root + "/arm/packs"
}
}
return filepath.Clean(root)
}
// AddPack adds a pack to the pack installation directory structure
// AddPack installs a pack from the given packPath. It handles various scenarios such as
// checking and extracting EULA, force reinstalling, and handling dependencies.
//
// Parameters:
// - packPath: The path to the pack to be installed.
// - checkEula: If true, the EULA will be checked before installation.
// - extractEula: If true, the EULA will be extracted.
// - forceReinstall: If true, the pack will be reinstalled even if it is already installed.
// - noRequirements: If true, the requirements check and installation will be skipped.
// - timeout: The timeout duration for fetching the pack.
//
// Returns:
// - error: An error if the installation fails, otherwise nil.
func AddPack(packPath string, checkEula, extractEula, forceReinstall, noRequirements, testing bool, timeout int) error {
isDep := false
// tag dependency packs with $ for correct logging output
if strings.TrimPrefix(packPath, "$") != packPath {
isDep = true
packPath = packPath[1:]
}
pack, err := preparePack(packPath, false, false, false, true, timeout)
if err != nil {
return err
}
if !isDep {
if !testing {
if pack.isPackID || !pack.IsLocallySourced {
if err := UpdatePublicIndexIfOnline(); err != nil {
return err
}
}
if err := ReadIndexFiles(); err != nil {
return err
}
// prepare again after update public files
pack, err = preparePack(packPath, false, false, false, true, timeout)
if err != nil {
return err
}
}
log.Infof("Adding pack \"%s\"", packPath)
}
dropPreInstalled := false
fullPackPath := ""
backupPackPath := ""
if !extractEula && pack.isInstalled {
if forceReinstall {
log.Debugf("Making temporary backup of pack \"%s\"", packPath)
// Get target pack's full path and move it to a temporary "_tmp" directory
fullPackPath = filepath.Join(Installation.PackRoot, pack.Vendor, pack.Name, pack.GetVersionNoMeta())
backupPackPath = fullPackPath + "_tmp"
if err := utils.MoveFile(fullPackPath, backupPackPath); err != nil {
return err
}
log.Debugf("Moved pack to temporary path \"%s\"", backupPackPath)
dropPreInstalled = true
} else {
log.Errorf("Pack \"%s\" is already installed here: \"%s\", use the --force-reinstall (-F) flag to force installation", packPath, filepath.Join(Installation.PackRoot, pack.Vendor, pack.Name, pack.GetVersionNoMeta()))
return nil
}
}
if pack.isPackID {
pack.path, err = FindPackURL(pack)
if err != nil {
return err
}
}
if err = pack.fetch(timeout); err != nil {
return err
}
// Since we only get the target version here, can only
// print the message now for dependencies
if isDep {
log.Infof("Adding pack %s", pack.Vendor+"."+pack.Name+"."+pack.targetVersion)
}
// Tells the UI to return right away with the [E]xtract option selected
ui.Extract = extractEula
// Unlock the pack (to enable reinstalling) and lock it afterwards
pack.Unlock()
defer pack.Lock()
if err = pack.install(Installation, checkEula || extractEula); err != nil {
// Just for internal purposes, is not presented as an error to the user
if err == errs.ErrEula {
return nil
}
if dropPreInstalled {
log.Error("Error installing pack, reverting temporary pack to original state")
// Make sure the original directory doesn't exist to avoid moving errors
if err := os.RemoveAll(fullPackPath); err != nil {
return err
}
if err := utils.MoveFile(backupPackPath, fullPackPath); err != nil {
return err
}
}
return err
}
// Remove the original "temporary" pack
// Manual removal via os.RemoveAll as "_tmp" is an invalid packPath for RemovePack
if dropPreInstalled {
utils.UnsetReadOnlyR(backupPackPath)
if err := os.RemoveAll(backupPackPath); err != nil {
return err
}
log.Debugf("Successfully deleted temporary pack \"%s\"", backupPackPath)
}
if !noRequirements {
log.Debug("installing package requirements")
err := pack.loadDependencies(true)
if err != nil {
return err
}
if !pack.RequirementsSatisfied() {
// Print all dependencies info on one message
msg := ""
for _, p := range pack.Requirements.packages {
if !p.installed {
msg += utils.FormatPackVersion(p.info) + " "
}
}
if msg != "" {
log.Infof("Package requirements not satisfied - installing %s", msg)
}
for _, req := range pack.Requirements.packages {
// Recursively install dependencies
path := req.info[1] + "." + req.info[0] + "." + req.info[2]
pack, err := preparePack(path, false, false, false, true, timeout)
if err != nil {
return err
}
if !pack.isInstalled {
log.Debug("pack has dependencies, installing")
err := AddPack("$"+path, checkEula, extractEula, forceReinstall, false, false, timeout)
if err != nil {
return err
}
} else {
log.Debugf("required pack %s already installed - skipping", path)
}
}
} else {
log.Debugf("pack has all required dependencies installed (%d packs)", len(pack.Requirements.packages))
}
} else {
log.Debug("skipping requirements checking and installation")
}
return Installation.touchPackIdx()
}
// RemovePack removes a specified pack from the installation.
// If the pack is installed, it will be uninstalled. If the purge option is enabled,
// the pack will be completely removed from the system.
//
// Parameters:
// - packPath: The path to the pack to be removed.
// - purge: A boolean indicating whether to completely remove the pack.
// - timeout: An integer specifying the timeout duration for the operation.
//
// Returns:
// - error: An error if the removal process fails, or nil if successful.
func RemovePack(packPath string, purge, testing bool, timeout int) error {
log.Debugf("Removing pack \"%v\"", packPath)
if !testing {
if err := ReadIndexFiles(); err != nil {
return err
}
}
// TODO: by default, remove latest version first
// if no version is given
pack, err := preparePack(packPath, true, false, false, true, timeout)
if err != nil {
return err
}
if pack.isInstalled {
// TODO: If removing-all is enabled, get rid of the version
// pack.Version = ""
pack.Unlock()
if err = pack.uninstall(Installation); err != nil {
return err
}
if purge {
if err = pack.purge(); err != nil {
return err
}
}
return Installation.touchPackIdx()
} else if purge {
pack.Unlock()
return pack.purge()
}
log.Errorf("Pack \"%v\" is not installed", packPath)
return errs.ErrPackNotInstalled
}
// AddPdsc adds a PDSC (Pack Description) file to the installation.
// It prepares the PDSC file and installs it. If the PDSC entry already exists,
// it logs the information and returns nil. After installation, it writes the
// local PIDX (Pack Index) and updates the pack index.
//
// Parameters:
// - pdscPath: The file path to the PDSC file.
//
// Returns:
// - error: An error if any step fails, otherwise nil.
func AddPdsc(pdscPath string) error {
log.Infof("Adding pdsc \"%v\"", pdscPath)
if err := ReadIndexFiles(); err != nil {
return err
}
pdsc, err := preparePdsc(pdscPath)
if err != nil {
return err
}
if err := pdsc.install(Installation); err != nil {
if err == errs.ErrPdscEntryExists {
log.Info(err)
return nil
}
return err
}
if err := Installation.LocalPidx.Write(); err != nil {
return err
}
return Installation.touchPackIdx()
}
// RemovePdsc removes a PDSC (Pack Description) file from the installation.
//
// Parameters:
// - pdscPath: The file path to the PDSC file to be removed.
//
// Returns:
// - error: An error if the removal process fails, otherwise nil.
//
// The function performs the following steps:
// 1. Logs the removal action.
// 2. Prepares the PDSC file for removal by calling preparePdsc.
// 3. Clears the URL field of the PDSC file as it is not needed for removal.
// 4. Uninstalls the PDSC file from the installation.
// 5. Writes the updated local Pidx (Pack Index) to disk.
// 6. Touches the Pack Index to update its timestamp.
func RemovePdsc(pdscPath string) error {
log.Debugf("Removing pdsc \"%v\"", pdscPath)
pdsc, err := preparePdsc(pdscPath)
if err != nil {
return err
}
// preparePdsc will fill in the full path for this PDSC file path
// in the URL field, that is not needed for removing
pdsc.URL = ""
if err = pdsc.uninstall(Installation); err != nil {
return err
}
if err := Installation.LocalPidx.Write(); err != nil {
return err
}
return Installation.touchPackIdx()
}
// massDownloadPdscFiles downloads PDSC files based on the provided PDSC tag.
// It calls downloadPdscFile for each PDSC file in the tag and logs errors if they occur.
// If skipInstalledPdscFiles is true, already installed PDSC files will be skipped.
// The timeout parameter specifies the maximum duration (in seconds) for the download operation.
//
// Parameters:
// - pdscTag: The PDSC tag containing information about the files to be downloaded.
// - skipInstalledPdscFiles: A boolean flag indicating whether to skip already installed PDSC files.
// - timeout: An integer specifying the timeout duration in seconds.
//
// Example:
//
// massDownloadPdscFiles(pdscTag, true, 30)
func massDownloadPdscFiles(pdscTag xml.PdscTag, skipInstalledPdscFiles bool, timeout int) {
if err := Installation.downloadPdscFile(pdscTag, skipInstalledPdscFiles, timeout); err != nil {
log.Error(err)
}
}
// UpdatePack updates the specified pack or all installed packs if packPath is empty.
// It checks for EULA acceptance and installs any required dependencies unless noRequirements is true.
//
// Parameters:
// - packPath: The path or identifier of the pack to update. If empty, all installed packs are updated.
// - checkEula: A boolean indicating whether to check for EULA acceptance.
// - noRequirements: A boolean indicating whether to skip checking and installing dependencies.
// - timeout: An integer specifying the timeout duration for operations.
//
// Returns:
// - error: An error if the update process fails, otherwise nil.
func UpdatePack(packPath string, checkEula, noRequirements bool, timeout int) error {
if packPath == "" {
installedPacks, err := findInstalledPacks(false, true)
if err != nil {
return err
}
for _, installedPack := range installedPacks {
err = UpdatePack(installedPack.Vendor+"."+installedPack.Name, checkEula, noRequirements, timeout)
if err != nil {
log.Error(err)
}
}
return nil
}
pack, err := preparePack(packPath, false, true, true, true, timeout)
if err != nil {
return err
}
if !pack.IsPublic || pack.isInstalled {
if !pack.isInstalled {
log.Infof("Pack \"%s\" is not installed", packPath)
}
return nil
}
log.Infof("Updating pack \"%s\"", packPath)
if pack.isPackID {
pack.path, err = FindPackURL(pack)
if err != nil {
return err
}
}
if err = pack.fetch(timeout); err != nil {
return err
}
// Unlock the pack (to enable reinstalling) and lock it afterwards
pack.Unlock()
defer pack.Lock()
if err = pack.install(Installation, checkEula); err != nil {
// Just for internal purposes, is not presented as an error to the user
if err == errs.ErrEula {
return nil
}
return err
}
if !noRequirements {
log.Debug("installing package requirements")
err := pack.loadDependencies(true)
if err != nil {
return err
}
if !pack.RequirementsSatisfied() {
// Print all dependencies info on one message
msg := ""
for _, p := range pack.Requirements.packages {
if !p.installed {
msg += utils.FormatPackVersion(p.info) + " "
}
}
if msg != "" {
log.Infof("Package requirements not satisfied - installing %s", msg)
}
for _, req := range pack.Requirements.packages {
// Recursively install dependencies
path := req.info[1] + "." + req.info[0] + "." + req.info[2]
pack, err := preparePack(path, false, false, false, true, timeout)
if err != nil {
return err
}
if !pack.isInstalled {
log.Debug("pack has dependencies, installing")
err := AddPack("$"+path, checkEula, false, false, false, false, timeout)
if err != nil {
return err
}
} else {
log.Debugf("required pack %s already installed - skipping", path)
}
}
} else {
log.Debugf("pack has all required dependencies installed (%d packs)", len(pack.Requirements.packages))
}
} else {
log.Debug("skipping requirements checking and installation")
}
return Installation.touchPackIdx()
}
// CheckConcurrency adjusts the given concurrency level based on the maximum
// number of CPU cores available. If the provided concurrency is greater than
// 1, it ensures that it does not exceed the maximum number of CPU cores. If
// the provided concurrency is less than or equal to 1, it sets the concurrency
// to 0.
//
// Parameters:
//
// concurrency - The desired level of concurrency.
//
// Returns:
//
// The adjusted level of concurrency, which will be between 0 and the maximum
// number of CPU cores.
func CheckConcurrency(concurrency int) int {
maxWorkers := runtime.GOMAXPROCS(0)
if concurrency > 1 {
if concurrency > maxWorkers {
concurrency = maxWorkers
}
} else {
concurrency = 0
}
return concurrency
}
// DownloadPDSCFiles downloads all PDSC files available on the public index.
// It reads the public index XML and lists all PDSC tags. If there are no packs
// in the public index, it logs this information and returns nil.
//
// If progress encoding is enabled, it logs the number of PDSC files and the
// public index.
//
// The function supports concurrent downloads, controlled by the `concurrency`
// parameter. If `concurrency` is 0, downloads are performed sequentially.
// Otherwise, a semaphore is used to limit the number of concurrent downloads.
//
// Parameters:
// - skipInstalledPdscFiles: If true, skips downloading PDSC files that are already installed.
// - concurrency: The number of concurrent downloads to allow. If 0, downloads are sequential.
// - timeout: The timeout for each download operation.
//
// Returns:
// - An error if there is an issue reading the public index XML or acquiring the semaphore.
func DownloadPDSCFiles(skipInstalledPdscFiles bool, concurrency int, timeout int) error {
log.Info("Downloading all PDSC files available on the public index")
if err := Installation.PublicIndexXML.Read(); err != nil {
return err
}
pdscTags := Installation.PublicIndexXML.ListPdscTags()
numPdsc := len(pdscTags)
if numPdsc == 0 {
log.Info("(no packs in public index)")
return nil
}
if utils.GetEncodedProgress() {
log.Infof("[J%d:F\"%s\"]", numPdsc, Installation.PublicIndex)
}
ctx := context.TODO()
concurrency = CheckConcurrency(concurrency)
sem := semaphore.NewWeighted(int64(concurrency))
for _, pdscTag := range pdscTags {
if concurrency == 0 {
massDownloadPdscFiles(pdscTag, skipInstalledPdscFiles, timeout)
} else {
if err := sem.Acquire(ctx, 1); err != nil {
log.Errorf("Failed to acquire semaphore: %v", err)
break
}
go func(pdscTag xml.PdscTag) {
defer sem.Release(1)
massDownloadPdscFiles(pdscTag, skipInstalledPdscFiles, timeout)
}(pdscTag)
}
}
if concurrency > 1 {
if err := sem.Acquire(ctx, int64(concurrency)); err != nil {
log.Errorf("Failed to acquire semaphore: %v", err)
}
}
return nil
}
// UpdateInstalledPDSCFiles updates the PDSC files of installed packs referenced in the public index.
// It checks if the PDSC files need updating and downloads the latest versions if necessary.
//
// Parameters:
// - pidxXML: A pointer to the PidxXML structure containing the public index data.
// - concurrency: The number of concurrent downloads allowed. If set to 0, downloads are performed sequentially.
// - timeout: The timeout duration for downloading PDSC files.
//
// Returns:
// - error: An error if any issue occurs during the update process.
//
// The function performs the following steps:
// 1. Lists all PDSC files in the installation web directory.
// 2. For each PDSC file, it reads the file and checks if the pack is still present in the public index.
// 3. If the pack is no longer present, it deletes the PDSC file.
// 4. If the pack is present but has a newer version in the public index, it downloads the latest version.
// 5. Lists all PDSC files in the local directory and repeats the update process for these files.
func UpdateInstalledPDSCFiles(pidxXML *xml.PidxXML, concurrency int, timeout int) error {
log.Info("Updating PDSC files of installed packs referenced in " + PublicIndex)
pdscFiles, err := utils.ListDir(Installation.WebDir, ".pdsc$")
if err != nil {
return err
}
numPdsc := len(pdscFiles)
if utils.GetEncodedProgress() {
log.Infof("[J%d:F\"%s\"]", numPdsc, Installation.PublicIndex)
}
ctx := context.TODO()
concurrency = CheckConcurrency(concurrency)
sem := semaphore.NewWeighted(int64(concurrency))
for _, pdscFile := range pdscFiles {
log.Debugf("Checking if \"%s\" needs updating", pdscFile)
pdscXML := xml.NewPdscXML(pdscFile)
err := pdscXML.Read()
if err != nil {
log.Errorf("%s: %v", pdscFile, err)
utils.UnsetReadOnly(pdscFile)
os.Remove(pdscFile)
continue
}
searchTag := xml.PdscTag{
Vendor: pdscXML.Vendor,
Name: pdscXML.Name,
}
// Warn the user if the pack is no longer present in index.pidx
tags := pidxXML.FindPdscTags(searchTag)
if len(tags) == 0 {
log.Warnf("The pack %s::%s is no longer present in the updated \"%s\", deleting PDSC file \"%v\"", pdscXML.Vendor, pdscXML.Name, PublicIndex, pdscFile)
utils.UnsetReadOnly(pdscFile)
os.Remove(pdscFile)
continue
}
versionInIndex := tags[0].Version
latestVersion := pdscXML.LatestVersion()
if versionInIndex != latestVersion {
log.Infof("%s::%s can be upgraded from \"%s\" to \"%s\"", pdscXML.Vendor, pdscXML.Name, latestVersion, versionInIndex)
if concurrency == 0 {
massDownloadPdscFiles(tags[0], false, timeout)
} else {
if err := sem.Acquire(ctx, 1); err != nil {
log.Errorf("Failed to acquire semaphore: %v", err)
break
}
pdscTag := tags[0]
go func(pdscTag xml.PdscTag) {
defer sem.Release(1)
massDownloadPdscFiles(pdscTag, false, timeout)
}(pdscTag)
}
}
}
if concurrency > 1 {
if err := sem.Acquire(ctx, int64(concurrency)); err != nil {
log.Errorf("Failed to acquire semaphore: %v", err)
}
}
pdscFiles, err = utils.ListDir(Installation.LocalDir, ".pdsc$")
if err != nil {
return err
}
numPdsc = len(pdscFiles)
if utils.GetEncodedProgress() {
log.Infof("[J%d:F\"%s\"]", numPdsc, Installation.LocalDir)
}
for _, pdscFile := range pdscFiles {
log.Debugf("Checking if \"%s\" needs updating", pdscFile)
pdscXML := xml.NewPdscXML(pdscFile)
err := pdscXML.Read()
if err != nil {
log.Errorf("%s: %v", pdscFile, err)
utils.UnsetReadOnly(pdscFile)
os.Remove(pdscFile)
continue
}
if pdscXML.URL == "" {
continue
}
originalLatestVersion := pdscXML.LatestVersion()
var pdscTag xml.PdscTag
pdscTag.Name = pdscXML.Name
pdscTag.Vendor = pdscXML.Vendor
pdscTag.URL = pdscXML.URL
if err := Installation.loadPdscFile(pdscTag, timeout); err != nil {
log.Error(err)
}
pdscXML = xml.NewPdscXML(pdscFile)
err = pdscXML.Read()
if err != nil {
log.Errorf("%s: %v", pdscFile, err)
utils.UnsetReadOnly(pdscFile)
os.Remove(pdscFile)
continue
}
latestVersion := pdscXML.LatestVersion()
if originalLatestVersion != latestVersion {
log.Infof("%s::%s can be upgraded from \"%s\" to \"%s\"", pdscXML.Vendor, pdscXML.Name, originalLatestVersion, latestVersion)
}
}
return nil
}
// GetIndexPath returns the index path based on the provided indexPath argument.
// If indexPath is empty, it defaults to the public index XML URL from the Installation configuration.
// Logs the index path if encoded progress is not enabled.
// Warns if the index path uses a non-HTTPS URL.
//
// Parameters:
// - indexPath: The initial index path to be processed.
//
// Returns:
// - string: The final index path.
// - error: An error if any occurred during processing.
func GetIndexPath(indexPath string) (string, error) {
if indexPath == "" {
indexPath = strings.TrimSuffix(Installation.PublicIndexXML.URL, "/")
}
if !utils.GetEncodedProgress() {
log.Infof("Using path: \"%v\"", indexPath)
}
var err error
if strings.HasPrefix(indexPath, "http://") || strings.HasPrefix(indexPath, "https://") {
if !strings.HasPrefix(indexPath, "https://") {
log.Warnf("Non-HTTPS url: \"%s\"", indexPath)
}
}
return indexPath, err
}
func UpdatePublicIndexIfOnline() error {
// If public index already exists then first check if online, then its timestamp
// if we are online and it is too old then download a current version
if utils.FileExists(Installation.PublicIndex) {
err := utils.CheckConnection(DefaultPublicIndex, 0)
if err != nil && errors.Unwrap(err) != errs.ErrOffline {
return err
}
if errors.Unwrap(err) != errs.ErrOffline {
v := viper.New()
var updateConf updateCfg
err = Installation.checkUpdateCfg(v, &updateConf)
if err != nil {
UnlockPackRoot()
err1 := UpdatePublicIndex(DefaultPublicIndex, true, false, false, false, 0, 0)
if err1 != nil {
return err1
}
_ = Installation.updateUpdateCfg(v, &updateConf)
}
} else {
log.Debug("Offline mode: Skipping public index update")
}
}
// if public index does not or not yet exist then download without check
if !utils.FileExists(Installation.PublicIndex) {
UnlockPackRoot()
err1 := UpdatePublicIndex(DefaultPublicIndex, true, false, false, false, 0, 0)
if err1 != nil {
return err1
}
v := viper.New()
var updateConf updateCfg
updateConf.Default.Auto = true
_ = Installation.updateUpdateCfg(v, &updateConf) // create the update config file
}
return nil
}
// UpdatePublicIndex updates the public index file from a given path or URL.
//
// Parameters:
// - indexPath: The path or URL to the public index file. If empty, the default public index URL is used.
// - overwrite: A boolean flag to indicate whether to overwrite the existing public index. This will be removed in future versions.
// - sparse: A boolean flag to indicate whether to perform a sparse update.
// - downloadPdsc: A boolean flag to indicate whether to download PDSC files.
// - downloadRemainingPdscFiles: A boolean flag to indicate whether to download remaining PDSC files.
// - concurrency: The number of concurrent operations allowed.
// - timeout: The timeout duration for network operations.
//
// Returns:
// - error: An error if the update fails, otherwise nil.
func UpdatePublicIndex(indexPath string, overwrite bool, sparse bool, downloadPdsc bool, downloadRemainingPdscFiles bool, concurrency int, timeout int) error {
// TODO: Remove overwrite when cpackget v1 gets released
if !overwrite {
return errs.ErrCannotOverwritePublicIndex
}
// For backwards compatibility, allow indexPath to be a file, but ideally it should be empty
if indexPath == "" {
indexPath = strings.TrimSuffix(Installation.PublicIndexXML.URL, "/") + "/" + PublicIndex
}
var err error
if strings.HasPrefix(indexPath, "http://") || strings.HasPrefix(indexPath, "https://") {
if !strings.HasPrefix(indexPath, "https://127.0.0.1") {
err = utils.CheckConnection(indexPath, 0)
if err != nil && errors.Unwrap(err) == errs.ErrOffline {
return err
}
}
}
log.Infof("Updating public index")
log.Debugf("Updating public index with \"%v\"", indexPath)
if strings.HasPrefix(indexPath, "http://") || strings.HasPrefix(indexPath, "https://") {
if !strings.HasPrefix(indexPath, "https://") {
log.Warnf("Non-HTTPS url: \"%s\"", indexPath)
}
indexPath, err = utils.DownloadFile(indexPath, timeout)
if err != nil {
return err
}
defer os.Remove(indexPath)
} else {
if indexPath != "" {
if !utils.FileExists(indexPath) && !utils.DirExists(indexPath) {
return errs.ErrFileNotFoundUseInit
}
fileInfo, err := os.Stat(indexPath)
if err != nil {
return err
}
if fileInfo.IsDir() {
return errs.ErrInvalidPublicIndexReference
}
}
}
pidxXML := xml.NewPidxXML(indexPath)
if err := pidxXML.Read(); err != nil {
return err
}
utils.UnsetReadOnly(Installation.PublicIndex)
if err := utils.CopyFile(indexPath, Installation.PublicIndex); err != nil {
return err
}
utils.SetReadOnly(Installation.PublicIndex)
if downloadPdsc {
err = DownloadPDSCFiles(false, concurrency, timeout)
if err != nil {
return err
}
}
if !sparse {
err = UpdateInstalledPDSCFiles(pidxXML, concurrency, timeout)
if err != nil {
return err
}
}
if downloadRemainingPdscFiles {
err = DownloadPDSCFiles(true, concurrency, timeout)
if err != nil {
return err
}
}
return Installation.touchPackIdx()
}
// installedPack represents a package that has been installed.
// It embeds xml.PdscTag and includes additional fields to track
// the PDSC file path, installation status, and any errors encountered.
type installedPack struct {
xml.PdscTag
pdscPath string
isPdscInstalled bool
err error
}
// findInstalledPacks retrieves a list of installed packs based on the provided options.
// It searches for installed packs in the specified directory and optionally includes
// local packs and removes duplicates.
//
// Parameters:
// - addLocalPacks: If true, includes packs listed in the local repository index.
// - removeDuplicates: If true, removes duplicate packs from the list.
//
// Returns:
// - A slice of installedPack containing the details of the installed packs.
// - An error if any issues occur during the retrieval process.
func findInstalledPacks(addLocalPacks, removeDuplicates bool) ([]installedPack, error) {
installedPacks := []installedPack{}
// First, get installed packs from *.pack files
pattern := filepath.Join(Installation.PackRoot, "*", "*", "*", "*.pdsc")
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range matches {
pdscPath := strings.ReplaceAll(match, Installation.PackRoot, "")
packName, _ := filepath.Split(pdscPath)
packName = strings.ReplaceAll(packName, "/", " ")
packName = strings.ReplaceAll(packName, "\\", " ")
packName = strings.Trim(packName, " ")
packName = strings.ReplaceAll(packName, " ", ".")
packNameBits := strings.SplitN(packName, ".", 3)
pack := installedPack{pdscPath: match}
pack.Vendor = packNameBits[0]
pack.Name = packNameBits[1]
pack.Version = packNameBits[2]
installedPacks = append(installedPacks, pack)
}
if addLocalPacks {
// Add packs listed in .Local/local_repository.pidx to the list
if err := Installation.LocalPidx.Read(); err != nil {
log.Error(err)
} else {
installedPdscs := Installation.LocalPidx.ListPdscTags()
for _, pdsc := range installedPdscs {
pack := installedPack{PdscTag: pdsc, isPdscInstalled: true}
pack.pdscPath = pdsc.URL + pack.Vendor + "/" + pack.Name + ".pdsc"
parsedURL, err := url.ParseRequestURI(pdsc.URL)
pack.err = err
if pack.err != nil {
installedPacks = append(installedPacks, pack)
continue
}
pack.pdscPath = filepath.Join(utils.CleanPath(parsedURL.Path), pack.Vendor+"."+pack.Name+".pdsc")
pdscXML := xml.NewPdscXML(pack.pdscPath)
pack.err = pdscXML.Read()
if pack.err == nil {
pack.Version = pdscXML.LatestVersion()
}
installedPacks = append(installedPacks, pack)
}
}
}
if removeDuplicates {
sort.Slice(installedPacks, func(i, j int) bool {
vi := strings.ToLower(installedPacks[i].Vendor)
vj := strings.ToLower(installedPacks[j].Vendor)
if vi == vj {
ai := strings.ToLower(installedPacks[i].Name)
aj := strings.ToLower(installedPacks[j].Name)
if ai == aj {
return installedPacks[i].Version > installedPacks[j].Version
}
return ai < aj
}
return vi < vj
})
noDupInstalledPacks := []installedPack{}
if len(installedPacks) > 0 {
last := 0
noDupInstalledPacks = append(noDupInstalledPacks, installedPacks[0])
for i, installedPack := range installedPacks {
if i > 0 {
//nolint:staticcheck // intentional logic for clarity
if !(installedPacks[last].Vendor == installedPack.Vendor && installedPacks[last].Name == installedPack.Name) {
noDupInstalledPacks = append(noDupInstalledPacks, installedPack)
last = i
}
}
}
}
return noDupInstalledPacks, nil
}
return installedPacks, nil
}
// ListInstalledPacks lists the installed packs based on the provided filters.
// It can list packs from the public index, cached packs, installed packs with updates,
// and installed packs with dependencies.
//
// Parameters:
// - listCached: If true, lists the cached packs.
// - listPublic: If true, lists the packs from the public index.