-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
2408 lines (1995 loc) · 100 KB
/
coverage.html
File metadata and controls
2408 lines (1995 loc) · 100 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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>hpn: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/harpoon/hpn/cmd/hpn/main.go (0.0%)</option>
<option value="file1">github.com/harpoon/hpn/cmd/hpn/root.go (0.0%)</option>
<option value="file2">github.com/harpoon/hpn/internal/config/config.go (0.0%)</option>
<option value="file3">github.com/harpoon/hpn/internal/config/validation.go (0.0%)</option>
<option value="file4">github.com/harpoon/hpn/internal/logger/interface.go (0.0%)</option>
<option value="file5">github.com/harpoon/hpn/internal/runtime/detector.go (0.0%)</option>
<option value="file6">github.com/harpoon/hpn/internal/runtime/docker.go (0.0%)</option>
<option value="file7">github.com/harpoon/hpn/internal/runtime/nerdctl.go (0.0%)</option>
<option value="file8">github.com/harpoon/hpn/internal/runtime/podman.go (0.0%)</option>
<option value="file9">github.com/harpoon/hpn/internal/version/version.go (0.0%)</option>
<option value="file10">github.com/harpoon/hpn/pkg/errors/errors.go (0.0%)</option>
<option value="file11">github.com/harpoon/hpn/pkg/types/config.go (0.0%)</option>
<option value="file12">github.com/harpoon/hpn/pkg/types/image.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"fmt"
"os"
)
func main() <span class="cov0" title="0">{
if err := rootCmd.Execute(); err != nil </span><span class="cov0" title="0">{
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}</span>
}</pre>
<pre class="file" id="file1" style="display: none">package main
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/harpoon/hpn/internal/config"
containerruntime "github.com/harpoon/hpn/internal/runtime"
"github.com/harpoon/hpn/internal/version"
"github.com/harpoon/hpn/pkg/types"
)
// Legacy variables for backward compatibility
// These are now managed by the version package
var (
legacyVersion = version.GetVersion()
legacyCommit = version.GetShortCommit()
legacyDate = version.BuildDate
)
// Command line flags matching images.sh
var (
action string
imageFile string
registry string
project string
pushMode int
loadMode int
saveMode int
configFile string
runtimeName string
autoFallback bool
)
// Global configuration
var (
cfg *types.Config
configMgr *config.Manager
runtimeDetector *containerruntime.Detector
)
var rootCmd = &cobra.Command{
Use: "hpn",
Short: "Manage container images (pull/save/load/push) with flexible modes",
Long: `Manage container images (pull/save/load/push) with flexible modes`,
Version: version.GetFullVersion(),
RunE: runCommand,
SilenceUsage: true, // Don't show usage on errors
SilenceErrors: true, // Don't let Cobra print errors automatically
}
// Version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Show version information",
Long: "Display detailed version information including build details",
Run: func(cmd *cobra.Command, args []string) <span class="cov0" title="0">{
version.PrintDetailedVersion()
}</span>,
}
func init() <span class="cov0" title="0">{
// Initialize configuration manager
configMgr = config.NewManager()
// Initialize runtime detector
runtimeDetector = containerruntime.NewDetector()
// Required flags matching images.sh interface
rootCmd.Flags().StringVarP(&action, "action", "a", "", "Action (required): pull | save | load | push")
rootCmd.Flags().StringVarP(&imageFile, "file", "f", "", "Image list file (required for pull/save/push)")
rootCmd.Flags().StringVarP(&registry, "registry", "r", "", "Target registry")
rootCmd.Flags().StringVarP(&project, "project", "p", "", "Target project namespace")
// Mode flags
rootCmd.Flags().IntVar(&pushMode, "push-mode", 0, "Push mode (1|2|3)")
rootCmd.Flags().IntVar(&loadMode, "load-mode", 0, "Load mode (1|2|3)")
rootCmd.Flags().IntVar(&saveMode, "save-mode", 0, "Save mode (1|2|3)")
// Configuration flag
rootCmd.Flags().StringVarP(&configFile, "config", "c", "", "Config file (default is $HOME/.hpn/config.yaml)")
// Runtime flags
rootCmd.Flags().StringVar(&runtimeName, "runtime", "", "Container runtime to use (docker|podman|nerdctl)")
rootCmd.Flags().BoolVar(&autoFallback, "auto-fallback", false, "Automatically fallback to available runtime")
// Version flags (in addition to --version)
rootCmd.Flags().BoolP("version", "v", false, "Show version information")
rootCmd.Flags().BoolP("Version", "V", false, "Show version information")
// Add version subcommand
rootCmd.AddCommand(versionCmd)
// Custom usage template matching images.sh
rootCmd.SetUsageTemplate(usageTemplate)
}</span>
const usageTemplate = `Usage: {{.UseLine}} -a <action> -f <file> [options]
Actions:
pull Pull images from registry
save Save images to tar files
load Load images from tar files
push Push images to registry
Options:
-a, --action Action: pull | save | load | push
-f, --file Image list file
-r, --registry Target registry
-p, --project Target project namespace
-c, --config Config file path
--runtime Container runtime: docker | podman | nerdctl
--auto-fallback Auto fallback to available runtime
-v, --version Show version
-h, --help Show help
Modes:
--push-mode 1=registry/image:tag 2=registry/project/image:tag
--save-mode 1=current dir 2=./images/ 3=./images/<project>/
--load-mode 1=current dir 2=./images/ 3=recursive ./images/*/
Examples:
hpn -a pull -f images.txt
hpn -a save -f images.txt --save-mode 2
hpn -a push -f images.txt -r harbor.com -p prod --push-mode 2
hpn --runtime podman -a pull -f images.txt
`
func runCommand(cmd *cobra.Command, args []string) error <span class="cov0" title="0">{
// Check for version flags first
if versionFlag, _ := cmd.Flags().GetBool("version"); versionFlag </span><span class="cov0" title="0">{
printVersionInfo()
return nil
}</span>
<span class="cov0" title="0">if versionFlag, _ := cmd.Flags().GetBool("Version"); versionFlag </span><span class="cov0" title="0">{
printVersionInfo()
return nil
}</span>
// Load configuration
<span class="cov0" title="0">var err error
cfg, err = configMgr.Load(configFile)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load configuration: %v", err)
}</span>
// Apply configuration defaults if flags are not set
<span class="cov0" title="0">if registry == "" </span><span class="cov0" title="0">{
registry = cfg.Registry
}</span>
<span class="cov0" title="0">if project == "" </span><span class="cov0" title="0">{
project = cfg.Project
}</span>
<span class="cov0" title="0">if pushMode == 0 </span><span class="cov0" title="0">{
pushMode = int(cfg.Modes.PushMode)
}</span>
<span class="cov0" title="0">if loadMode == 0 </span><span class="cov0" title="0">{
loadMode = int(cfg.Modes.LoadMode)
}</span>
<span class="cov0" title="0">if saveMode == 0 </span><span class="cov0" title="0">{
saveMode = int(cfg.Modes.SaveMode)
}</span>
// Validate action (skip if empty, as it might be a version-only call)
<span class="cov0" title="0">if action != "" </span><span class="cov0" title="0">{
validActions := []string{"pull", "save", "load", "push"}
actionValid := false
for _, validAction := range validActions </span><span class="cov0" title="0">{
if action == validAction </span><span class="cov0" title="0">{
actionValid = true
break</span>
}
}
<span class="cov0" title="0">if !actionValid </span><span class="cov0" title="0">{
return fmt.Errorf("invalid action '%s'. Valid actions: %s", action, strings.Join(validActions, ", "))
}</span>
} else<span class="cov0" title="0"> {
// If no action provided and no version flags, show error
return fmt.Errorf("missing required -a <action> parameter. Use -h for help or -v for version")
}</span>
// Validate file parameter for actions that require it
<span class="cov0" title="0">if action != "load" && imageFile == "" </span><span class="cov0" title="0">{
return fmt.Errorf("missing required -f <image_list> parameter for action '%s'", action)
}</span>
// Validate mode compatibility with action
<span class="cov0" title="0">switch action </span>{
case "push":<span class="cov0" title="0">
// Check for incompatible modes
if cmd.Flags().Changed("save-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--save-mode cannot be used with push action")
}</span>
<span class="cov0" title="0">if cmd.Flags().Changed("load-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--load-mode cannot be used with push action")
}</span>
// Validate push mode range
<span class="cov0" title="0">if pushMode < 1 || pushMode > 2 </span><span class="cov0" title="0">{
return fmt.Errorf("invalid push-mode '%d'. Valid values: 1, 2", pushMode)
}</span>
case "save":<span class="cov0" title="0">
// Check for incompatible modes
if cmd.Flags().Changed("push-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--push-mode cannot be used with save action")
}</span>
<span class="cov0" title="0">if cmd.Flags().Changed("load-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--load-mode cannot be used with save action")
}</span>
// Validate save mode range
<span class="cov0" title="0">if saveMode < 1 || saveMode > 3 </span><span class="cov0" title="0">{
return fmt.Errorf("invalid save-mode '%d'. Valid values: 1, 2, 3", saveMode)
}</span>
case "load":<span class="cov0" title="0">
// Check for incompatible modes
if cmd.Flags().Changed("push-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--push-mode cannot be used with load action")
}</span>
<span class="cov0" title="0">if cmd.Flags().Changed("save-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--save-mode cannot be used with load action")
}</span>
// Validate load mode range
<span class="cov0" title="0">if loadMode < 1 || loadMode > 3 </span><span class="cov0" title="0">{
return fmt.Errorf("invalid load-mode '%d'. Valid values: 1, 2, 3", loadMode)
}</span>
case "pull":<span class="cov0" title="0">
// Pull doesn't use any modes, check for incompatible modes
if cmd.Flags().Changed("push-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--push-mode cannot be used with pull action")
}</span>
<span class="cov0" title="0">if cmd.Flags().Changed("save-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--save-mode cannot be used with pull action")
}</span>
<span class="cov0" title="0">if cmd.Flags().Changed("load-mode") </span><span class="cov0" title="0">{
return fmt.Errorf("--load-mode cannot be used with pull action")
}</span>
}
// Smart push mode adjustment: if user specifies project but uses default push mode 1,
// automatically switch to push mode 2 to include the project
<span class="cov0" title="0">if action == "push" && pushMode == 1 && project != "" </span><span class="cov0" title="0">{
// Check if project was explicitly specified by user (not just from config default)
projectExplicitlySet := cmd.Flags().Changed("project") ||
(cfg != nil && cfg.Project != project) // project differs from config default
if projectExplicitlySet </span><span class="cov0" title="0">{
pushMode = 2
fmt.Printf("Auto-adjusted to push mode 2 for project '%s'\n", project)
}</span>
}
// Execute the action
<span class="cov0" title="0">switch action </span>{
case "pull":<span class="cov0" title="0">
return executePull()</span>
case "save":<span class="cov0" title="0">
return executeSave()</span>
case "load":<span class="cov0" title="0">
return executeLoad()</span>
case "push":<span class="cov0" title="0">
return executePush(cmd)</span>
default:<span class="cov0" title="0">
return fmt.Errorf("unknown action: %s", action)</span>
}
}
func executePull() error <span class="cov0" title="0">{
fmt.Printf("Executing pull action with file: %s\n", imageFile)
// Select container runtime
selectedRuntime, err := selectContainerRuntime()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("container runtime selection failed: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Using container runtime: %s\n", selectedRuntime.Name())
// Read image list from file
images, err := readImageList(imageFile)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to read image list: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Found %d images to pull\n", len(images))
// Pull each image
successCount := 0
failedImages := []string{}
for i, image := range images </span><span class="cov0" title="0">{
fmt.Printf("[%d/%d] Pulling %s...\n", i+1, len(images), image)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
pullOptions := containerruntime.PullOptions{
Timeout: 5 * time.Minute,
}
if err := selectedRuntime.Pull(ctx, image, pullOptions); err != nil </span><span class="cov0" title="0">{
fmt.Printf("❌ Failed to pull %s: %v\n", image, err)
failedImages = append(failedImages, image)
}</span> else<span class="cov0" title="0"> {
fmt.Printf("✅ Successfully pulled %s\n", image)
successCount++
}</span>
<span class="cov0" title="0">cancel()</span>
}
// Print summary
<span class="cov0" title="0">fmt.Printf("\nSummary: %d successful, %d failed\n", successCount, len(failedImages))
if len(failedImages) > 0 </span><span class="cov0" title="0">{
fmt.Printf("\nFailed images:\n")
for _, img := range failedImages </span><span class="cov0" title="0">{
fmt.Printf(" - %s\n", img)
}</span>
<span class="cov0" title="0">return fmt.Errorf("failed to pull %d images", len(failedImages))</span>
}
<span class="cov0" title="0">return nil</span>
}
func executeSave() error <span class="cov0" title="0">{
fmt.Printf("Executing save action with file: %s, mode: %d\n", imageFile, saveMode)
// Select container runtime
selectedRuntime, err := selectContainerRuntime()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("container runtime selection failed: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Using container runtime: %s\n", selectedRuntime.Name())
// Read image list from file
images, err := readImageList(imageFile)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to read image list: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Found %d images to save\n", len(images))
// Determine save directory based on mode
var saveDir string
switch saveMode </span>{
case 1:<span class="cov0" title="0">
saveDir = "."</span> // Current directory
case 2:<span class="cov0" title="0">
saveDir = "./images"
if err := os.MkdirAll(saveDir, 0755); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create images directory: %v", err)
}</span>
case 3:<span class="cov0" title="0">
// Will create project-specific directories as needed
saveDir = "./images"
if err := os.MkdirAll(saveDir, 0755); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create images directory: %v", err)
}</span>
}
<span class="cov0" title="0">fmt.Printf("Save mode %d: saving to %s\n", saveMode, saveDir)
// Save each image
successCount := 0
failedImages := []string{}
for i, image := range images </span><span class="cov0" title="0">{
fmt.Printf("[%d/%d] Saving %s...\n", i+1, len(images), image)
if err := saveImage(selectedRuntime, image, saveDir, saveMode); err != nil </span><span class="cov0" title="0">{
fmt.Printf("❌ Failed to save %s: %v\n", image, err)
failedImages = append(failedImages, image)
}</span> else<span class="cov0" title="0"> {
fmt.Printf("✅ Successfully saved %s\n", image)
successCount++
}</span>
}
// Print summary
<span class="cov0" title="0">fmt.Printf("\nSummary: %d successful, %d failed\n", successCount, len(failedImages))
if len(failedImages) > 0 </span><span class="cov0" title="0">{
fmt.Printf("\nFailed images:\n")
for _, img := range failedImages </span><span class="cov0" title="0">{
fmt.Printf(" - %s\n", img)
}</span>
<span class="cov0" title="0">return fmt.Errorf("failed to save %d images", len(failedImages))</span>
}
<span class="cov0" title="0">return nil</span>
}
func executeLoad() error <span class="cov0" title="0">{
fmt.Printf("Executing load action with mode: %d\n", loadMode)
// Select container runtime
selectedRuntime, err := selectContainerRuntime()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("container runtime selection failed: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Using container runtime: %s\n", selectedRuntime.Name())
// Determine load directory based on mode
var loadDir string
var tarFiles []string
switch loadMode </span>{
case 1:<span class="cov0" title="0">
// Load from current directory
loadDir = "."
files, err := findTarFiles(loadDir, false)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to find tar files in current directory: %v", err)
}</span>
<span class="cov0" title="0">tarFiles = files</span>
case 2:<span class="cov0" title="0">
// Load from ./images/ directory
loadDir = "./images"
files, err := findTarFiles(loadDir, false)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to find tar files in images directory: %v", err)
}</span>
<span class="cov0" title="0">tarFiles = files</span>
case 3:<span class="cov0" title="0">
// Recursively load from ./images/*/ subdirectories
loadDir = "./images"
files, err := findTarFiles(loadDir, true)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to find tar files recursively: %v", err)
}</span>
<span class="cov0" title="0">tarFiles = files</span>
}
<span class="cov0" title="0">fmt.Printf("Found %d tar files to load\n", len(tarFiles))
// Load each tar file
successCount := 0
failedFiles := []string{}
for i, tarFile := range tarFiles </span><span class="cov0" title="0">{
fmt.Printf("[%d/%d] Loading %s...\n", i+1, len(tarFiles), tarFile)
if err := loadImage(selectedRuntime, tarFile); err != nil </span><span class="cov0" title="0">{
fmt.Printf("❌ Failed to load %s: %v\n", tarFile, err)
failedFiles = append(failedFiles, tarFile)
}</span> else<span class="cov0" title="0"> {
fmt.Printf("✅ Successfully loaded %s\n", tarFile)
successCount++
}</span>
}
// Print summary
<span class="cov0" title="0">fmt.Printf("\nSummary: %d successful, %d failed\n", successCount, len(failedFiles))
if len(failedFiles) > 0 </span><span class="cov0" title="0">{
fmt.Printf("\nFailed files:\n")
for _, file := range failedFiles </span><span class="cov0" title="0">{
fmt.Printf(" - %s\n", file)
}</span>
<span class="cov0" title="0">return fmt.Errorf("failed to load %d files", len(failedFiles))</span>
}
<span class="cov0" title="0">return nil</span>
}
func executePush(cmd *cobra.Command) error <span class="cov0" title="0">{
fmt.Printf("Executing push action with file: %s, mode: %d, registry: %s, project: %s\n",
imageFile, pushMode, registry, project)
// Detect container runtime
selectedRuntime, err := selectContainerRuntime()
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("container runtime selection failed: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Using container runtime: %s\n", selectedRuntime.Name())
// Read image list from file
images, err := readImageList(imageFile)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to read image list: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("Found %d images to push\n", len(images))
fmt.Printf("Target registry: %s\n", registry)
fmt.Printf("Target project: %s\n", project)
fmt.Printf("Push mode: %d\n", pushMode)
// Push each image
successCount := 0
failedImages := []string{}
for i, image := range images </span><span class="cov0" title="0">{
fmt.Printf("[%d/%d] Pushing %s...\n", i+1, len(images), image)
// Determine project name for this specific image based on push mode
var effectiveProject string
if pushMode == 2 </span><span class="cov0" title="0">{
// For mode 2, use smart project selection
if cmd.Flags().Changed("project") </span><span class="cov0" title="0">{
// User explicitly specified project via command line
effectiveProject = project
}</span> else<span class="cov0" title="0"> if cfg != nil && cfg.Project != "" && cfg.Project != "library" </span><span class="cov0" title="0">{
// Use config file project (if not default "library")
effectiveProject = cfg.Project
}</span> else<span class="cov0" title="0"> {
// Use original image project name
effectiveProject = extractProjectFromImage(image)
}</span>
} else<span class="cov0" title="0"> {
// For mode 1, use the project as-is (though it won't be used)
effectiveProject = project
}</span>
<span class="cov0" title="0">if err := pushImage(selectedRuntime, image, registry, effectiveProject, pushMode); err != nil </span><span class="cov0" title="0">{
fmt.Printf("❌ Failed to push %s: %v\n", image, err)
failedImages = append(failedImages, image)
}</span> else<span class="cov0" title="0"> {
fmt.Printf("✅ Successfully pushed %s\n", image)
successCount++
}</span>
}
// Print summary
<span class="cov0" title="0">fmt.Printf("\nSummary: %d successful, %d failed\n", successCount, len(failedImages))
if len(failedImages) > 0 </span><span class="cov0" title="0">{
fmt.Printf("\nFailed images:\n")
for _, img := range failedImages </span><span class="cov0" title="0">{
fmt.Printf(" - %s\n", img)
}</span>
<span class="cov0" title="0">return fmt.Errorf("failed to push %d images", len(failedImages))</span>
}
<span class="cov0" title="0">return nil</span>
}
// selectContainerRuntime selects the appropriate container runtime
func selectContainerRuntime() (containerruntime.ContainerRuntime, error) <span class="cov0" title="0">{
// If runtime is explicitly specified via flag
if runtimeName != "" </span><span class="cov0" title="0">{
selectedRuntime, err := runtimeDetector.GetByName(runtimeName)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("specified runtime '%s' is not available: %v", runtimeName, err)
}</span>
<span class="cov0" title="0">return selectedRuntime, nil</span>
}
// Check if runtime is specified in config
<span class="cov0" title="0">var configuredRuntime string
if cfg != nil && cfg.Runtime.Preferred != "" </span><span class="cov0" title="0">{
configuredRuntime = cfg.Runtime.Preferred
}</span>
// If configured runtime is specified, try to use it
<span class="cov0" title="0">if configuredRuntime != "" </span><span class="cov0" title="0">{
configuredRuntimeObj, err := runtimeDetector.GetByName(configuredRuntime)
if err == nil </span><span class="cov0" title="0">{
return configuredRuntimeObj, nil
}</span>
// Configured runtime is not available, check for alternatives
<span class="cov0" title="0">available := runtimeDetector.DetectAvailable()
if len(available) == 0 </span><span class="cov0" title="0">{
return nil, fmt.Errorf("no container runtime found. Please install docker, podman, or nerdctl")
}</span>
// Check if auto-fallback is enabled
<span class="cov0" title="0">if autoFallback || (cfg != nil && cfg.Runtime.AutoFallback) </span><span class="cov0" title="0">{
fmt.Printf("Runtime '%s' unavailable, using '%s'\n", configuredRuntime, available[0].Name())
return available[0], nil
}</span>
// Ask user for confirmation
<span class="cov0" title="0">fmt.Printf("Runtime '%s' is not available\n", configuredRuntime)
fmt.Printf("Found available runtime: %s\n", available[0].Name())
fmt.Printf("Use '%s' instead of '%s'? (y/N): ", available[0].Name(), configuredRuntime)
var response string
fmt.Scanln(&response)
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" </span><span class="cov0" title="0">{
fmt.Printf("Using '%s' runtime\n", available[0].Name())
return available[0], nil
}</span> else<span class="cov0" title="0"> {
return nil, fmt.Errorf("user declined runtime fallback. Please install '%s' or update config", configuredRuntime)
}</span>
}
// No specific runtime configured, use the preferred one
<span class="cov0" title="0">preferred := runtimeDetector.GetPreferred()
if preferred == nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("no container runtime found. Please install docker, podman, or nerdctl")
}</span>
<span class="cov0" title="0">return preferred, nil</span>
}
// readImageList reads image list from file
func readImageList(filename string) ([]string, error) <span class="cov0" title="0">{
file, err := os.Open(filename)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to open file %s: %v", filename, err)
}</span>
<span class="cov0" title="0">defer file.Close()
var images []string
scanner := bufio.NewScanner(file)
for scanner.Scan() </span><span class="cov0" title="0">{
line := strings.TrimSpace(scanner.Text())
// Skip empty lines and comments
if line != "" && !strings.HasPrefix(line, "#") </span><span class="cov0" title="0">{
images = append(images, line)
}</span>
}
<span class="cov0" title="0">if err := scanner.Err(); err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("error reading file: %v", err)
}</span>
<span class="cov0" title="0">if len(images) == 0 </span><span class="cov0" title="0">{
return nil, fmt.Errorf("no images found in file %s", filename)
}</span>
<span class="cov0" title="0">return images, nil</span>
}
// saveImage saves a single image to tar file
func saveImage(containerRuntime containerruntime.ContainerRuntime, image, baseDir string, mode int) error <span class="cov0" title="0">{
// Parse image name to generate tar filename
tarFilename := generateTarFilename(image)
var tarPath string
switch mode </span>{
case 1, 2:<span class="cov0" title="0">
// Mode 1: current directory, Mode 2: ./images/
tarPath = fmt.Sprintf("%s/%s", baseDir, tarFilename)</span>
case 3:<span class="cov0" title="0">
// Mode 3: ./images/<project>/
projectDir := extractProjectFromImage(image)
fullDir := fmt.Sprintf("%s/%s", baseDir, projectDir)
if err := os.MkdirAll(fullDir, 0755); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create project directory %s: %v", fullDir, err)
}</span>
<span class="cov0" title="0">tarPath = fmt.Sprintf("%s/%s", fullDir, tarFilename)</span>
}
// Execute save command using runtime interface
<span class="cov0" title="0">ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := containerRuntime.Save(ctx, image, tarPath); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to save image: %v", err)
}</span>
// Check if file was created successfully
<span class="cov0" title="0">if _, err := os.Stat(tarPath); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("tar file was not created: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf(" Saved: %s\n", tarPath)
return nil</span>
}
// generateTarFilename generates tar filename from image name
func generateTarFilename(image string) string <span class="cov0" title="0">{
// Replace problematic characters for filename
filename := strings.ReplaceAll(image, "/", "_")
filename = strings.ReplaceAll(filename, ":", "_")
// Add .tar extension
return filename + ".tar"
}</span>
// extractProjectFromImage extracts project name from image for mode 3
func extractProjectFromImage(image string) string <span class="cov0" title="0">{
parts := strings.Split(image, "/")
if len(parts) >= 3 </span><span class="cov0" title="0">{
// For images like registry.k8s.io/coredns/coredns:v1.11.1
return parts[len(parts)-2] // Return "coredns"
}</span> else<span class="cov0" title="0"> if len(parts) == 2 </span><span class="cov0" title="0">{
// For images like calico/node:v3.28.2
return parts[0] // Return "calico"
}</span> else<span class="cov0" title="0"> {
// For images like nginx:latest
return "library" // Default project name
}</span>
}
// findTarFiles finds all .tar files in the specified directory
func findTarFiles(dir string, recursive bool) ([]string, error) <span class="cov0" title="0">{
var tarFiles []string
if recursive </span><span class="cov0" title="0">{
// Recursively find tar files in subdirectories
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error </span><span class="cov0" title="0">{
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">if !info.IsDir() && strings.HasSuffix(strings.ToLower(info.Name()), ".tar") </span><span class="cov0" title="0">{
tarFiles = append(tarFiles, path)
}</span>
<span class="cov0" title="0">return nil</span>
})
<span class="cov0" title="0">if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
} else<span class="cov0" title="0"> {
// Find tar files only in the specified directory
files, err := filepath.Glob(filepath.Join(dir, "*.tar"))
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">tarFiles = files</span>
}
<span class="cov0" title="0">return tarFiles, nil</span>
}
// loadImage loads a single tar file using the specified runtime
func loadImage(containerRuntime containerruntime.ContainerRuntime, tarFile string) error <span class="cov0" title="0">{
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if err := containerRuntime.Load(ctx, tarFile); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to load image: %v", err)
}</span>
<span class="cov0" title="0">return nil</span>
}
// pushImage pushes a single image to registry with the specified mode
func pushImage(containerRuntime containerruntime.ContainerRuntime, image, targetRegistry, targetProject string, mode int) error <span class="cov0" title="0">{
var targetImage string
// Parse original image name and tag
imageName, imageTag := parseImageNameAndTag(image)
switch mode </span>{
case 1:<span class="cov0" title="0">
// Mode 1: registry/image:tag (不包含项目名称)
targetImage = fmt.Sprintf("%s/%s:%s", targetRegistry, imageName, imageTag)</span>
case 2:<span class="cov0" title="0">
// Mode 2: registry/project/image:tag
targetImage = fmt.Sprintf("%s/%s/%s:%s", targetRegistry, targetProject, imageName, imageTag)
fmt.Printf(" Project: %s\n", targetProject)</span>
}
<span class="cov0" title="0">fmt.Printf(" Tag: %s -> %s\n", image, targetImage)
// Tag the image
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if err := containerRuntime.Tag(ctx, image, targetImage); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to tag image: %v", err)
}</span>
// Push the image
<span class="cov0" title="0">pushOptions := containerruntime.PushOptions{
Timeout: 10 * time.Minute,
}
if err := containerRuntime.Push(ctx, targetImage, pushOptions); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to push image: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf(" Pushed: %s\n", targetImage)
return nil</span>
}
// parseImageNameAndTag parses image name and tag from full image string
func parseImageNameAndTag(image string) (string, string) <span class="cov0" title="0">{
parts := strings.Split(image, "/")
lastPart := parts[len(parts)-1]
if strings.Contains(lastPart, ":") </span><span class="cov0" title="0">{
tagParts := strings.Split(lastPart, ":")
return tagParts[0], tagParts[1]
}</span>
<span class="cov0" title="0">return lastPart, "latest"</span>
}
// printVersionInfo prints version information (legacy function)
func printVersionInfo() <span class="cov0" title="0">{
version.PrintVersion()
}</pre>
<pre class="file" id="file2" style="display: none">package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/viper"
"github.com/harpoon/hpn/pkg/errors"
"github.com/harpoon/hpn/pkg/types"
)
// Manager handles configuration loading and management
type Manager struct {
config *types.Config
viper *viper.Viper
}
// NewManager creates a new configuration manager
func NewManager() *Manager <span class="cov0" title="0">{
return &Manager{
viper: viper.New(),
}
}</span>
// Load loads configuration from various sources with proper priority
func (m *Manager) Load(configFile string) (*types.Config, error) <span class="cov0" title="0">{
// Start with default configuration
m.config = types.DefaultConfig()
// Set up viper
m.setupViper()
// Load configuration file if specified or found
if err := m.loadConfigFile(configFile); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
// Load environment variables
<span class="cov0" title="0">m.loadEnvironmentVariables()
// Unmarshal into config struct
if err := m.viper.Unmarshal(m.config); err != nil </span><span class="cov0" title="0">{
return nil, errors.Wrap(err, errors.ErrConfigParsing, "failed to parse configuration")
}</span>
// Validate configuration
<span class="cov0" title="0">if err := ValidateConfig(m.config); err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">return m.config, nil</span>
}
// setupViper configures viper settings
func (m *Manager) setupViper() <span class="cov0" title="0">{
m.viper.SetConfigName("config")
m.viper.SetConfigType("yaml")
// Add config search paths
m.viper.AddConfigPath(".")
m.viper.AddConfigPath("$HOME/.hpn")
m.viper.AddConfigPath("/etc/hpn")
// Set environment variable prefix
m.viper.SetEnvPrefix("HPN")
m.viper.AutomaticEnv()
// Replace dots and dashes with underscores for env vars
m.viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
}</span>
// loadConfigFile loads configuration from file
func (m *Manager) loadConfigFile(configFile string) error <span class="cov0" title="0">{
if configFile != "" </span><span class="cov0" title="0">{
// Use specified config file
m.viper.SetConfigFile(configFile)
if err := m.viper.ReadInConfig(); err != nil </span><span class="cov0" title="0">{
if os.IsNotExist(err) </span><span class="cov0" title="0">{
return errors.New(errors.ErrConfigNotFound, fmt.Sprintf("config file not found: %s", configFile))
}</span>
<span class="cov0" title="0">return errors.Wrap(err, errors.ErrConfigParsing, fmt.Sprintf("failed to read config file: %s", configFile))</span>
}
} else<span class="cov0" title="0"> {
// Try to find config file in search paths
if err := m.viper.ReadInConfig(); err != nil </span><span class="cov0" title="0">{
// It's okay if no config file is found, we'll use defaults
if _, ok := err.(viper.ConfigFileNotFoundError); !ok </span><span class="cov0" title="0">{
return errors.Wrap(err, errors.ErrConfigParsing, "failed to read config file")
}</span>