@@ -5,9 +5,13 @@ package fileutils
5
5
6
6
import (
7
7
"context"
8
+ "crypto/sha256"
8
9
"errors"
9
10
"fmt"
11
+ "io"
12
+ "os"
10
13
"path"
14
+ "path/filepath"
11
15
12
16
"github.com/sirupsen/logrus"
13
17
@@ -18,12 +22,67 @@ import (
18
22
// ErrSkipped is returned when the downloader did not attempt to download the specified file.
19
23
var ErrSkipped = errors .New ("skipped to download" )
20
24
25
+ func CopyFile (src , dst string ) error {
26
+
27
+ source , err := os .Open (src )
28
+ if err != nil {
29
+ return err
30
+ }
31
+ defer source .Close ()
32
+ if err := os .MkdirAll (filepath .Dir (dst ), 0660 ); err != nil {
33
+ return err
34
+ }
35
+
36
+ destination , err := os .Create (dst )
37
+ if err != nil {
38
+ return err
39
+ }
40
+ defer destination .Close ()
41
+ _ , err = io .Copy (destination , source )
42
+ return err
43
+ }
44
+
45
+ func GetFileSHA256 (filePath string ) (string , error ) {
46
+ file , err := os .Open (filePath )
47
+ if err != nil {
48
+ return "" , err
49
+ }
50
+ defer file .Close ()
51
+ hash := sha256 .New ()
52
+ if _ , err := io .Copy (hash , file ); err != nil {
53
+ return "" , err
54
+ }
55
+ return fmt .Sprintf ("sha256:%x" , hash .Sum (nil )), nil
56
+ }
57
+
21
58
// DownloadFile downloads a file to the cache, optionally copying it to the destination. Returns path in cache.
22
- func DownloadFile (ctx context.Context , dest string , f limayaml.File , decompress bool , description string , expectedArch limayaml.Arch ) (string , error ) {
59
+ func DownloadFile (ctx context.Context , dest string , f limayaml.File , decompress bool , description string , expectedArch limayaml.Arch ) (_ string , reterr error ) {
23
60
if f .Arch != expectedArch {
24
61
return "" , fmt .Errorf ("%w: %q: unsupported arch: %q" , ErrSkipped , f .Location , f .Arch )
25
62
}
26
- fields := logrus.Fields {"location" : f .Location , "arch" : f .Arch , "digest" : f .Digest }
63
+ fields := logrus.Fields {"location" : f .Location , "arch" : f .Arch , "digest" : f .Digest , "LocalPath" : f .LocalPath }
64
+ if f .LocalPath != "" {
65
+ if _ , err := os .Stat (f .LocalPath ); err != nil {
66
+ return "" , err
67
+ }
68
+ logrus .WithFields (fields ).Infof ("Attempting to copy local file %s" , description )
69
+ if reterr != nil {
70
+ defer os .Remove (dest )
71
+ }
72
+ if err := CopyFile (f .LocalPath , dest ); err != nil {
73
+ return "" , fmt .Errorf ("failed to copy file: %w" , err )
74
+ }
75
+ sha256Sum , err := GetFileSHA256 (dest )
76
+ if err != nil {
77
+ return "" , fmt .Errorf ("failed to getsha256: %w" , err )
78
+ }
79
+
80
+ if sha256Sum != f .Digest .String () {
81
+ return "" , fmt .Errorf ("wrong sha256 for %s" , dest )
82
+ }
83
+ return f .LocalPath , nil
84
+ }
85
+
27
86
logrus .WithFields (fields ).Infof ("Attempting to download %s" , description )
28
87
res , err := downloader .Download (ctx , dest , f .Location ,
29
88
downloader .WithCache (),
0 commit comments