@@ -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,65 @@ 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
+ source , err := os .Open (src )
27
+ if err != nil {
28
+ return err
29
+ }
30
+ defer source .Close ()
31
+ if err := os .MkdirAll (filepath .Dir (dst ), 0o660 ); err != nil {
32
+ return err
33
+ }
34
+ destination , err := os .Create (dst )
35
+ if err != nil {
36
+ return err
37
+ }
38
+ defer destination .Close ()
39
+ _ , err = io .Copy (destination , source )
40
+ return err
41
+ }
42
+
43
+ func GetFileSHA256 (filePath string ) (string , error ) {
44
+ file , err := os .Open (filePath )
45
+ if err != nil {
46
+ return "" , err
47
+ }
48
+ defer file .Close ()
49
+ hash := sha256 .New ()
50
+ if _ , err := io .Copy (hash , file ); err != nil {
51
+ return "" , err
52
+ }
53
+ return fmt .Sprintf ("sha256:%x" , hash .Sum (nil )), nil
54
+ }
55
+
21
56
// 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 ) {
57
+ func DownloadFile (ctx context.Context , dest string , f limayaml.File , decompress bool , description string , expectedArch limayaml.Arch ) (_ string , reterr error ) {
23
58
if f .Arch != expectedArch {
24
59
return "" , fmt .Errorf ("%w: %q: unsupported arch: %q" , ErrSkipped , f .Location , f .Arch )
25
60
}
26
- fields := logrus.Fields {"location" : f .Location , "arch" : f .Arch , "digest" : f .Digest }
61
+ fields := logrus.Fields {"location" : f .Location , "arch" : f .Arch , "digest" : f .Digest , "LocalPath" : f .LocalPath }
62
+ if f .LocalPath != "" {
63
+ if _ , err := os .Stat (f .LocalPath ); err != nil {
64
+ return "" , err
65
+ }
66
+ logrus .WithFields (fields ).Infof ("Attempting to copy local file %s" , description )
67
+ if reterr != nil {
68
+ defer os .Remove (dest )
69
+ }
70
+ if err := CopyFile (f .LocalPath , dest ); err != nil {
71
+ return "" , fmt .Errorf ("failed to copy file: %w" , err )
72
+ }
73
+ sha256Sum , err := GetFileSHA256 (dest )
74
+ if err != nil {
75
+ return "" , fmt .Errorf ("failed to getsha256: %w" , err )
76
+ }
77
+
78
+ if sha256Sum != f .Digest .String () {
79
+ return "" , fmt .Errorf ("wrong sha256 for %s" , dest )
80
+ }
81
+ return f .LocalPath , nil
82
+ }
83
+
27
84
logrus .WithFields (fields ).Infof ("Attempting to download %s" , description )
28
85
res , err := downloader .Download (ctx , dest , f .Location ,
29
86
downloader .WithCache (),
0 commit comments