Skip to content

Commit f5cf19d

Browse files
authored
Merge pull request #360 from zong-zhe/add-tmp-path
feat: add a tmp dir for adding dependency to reduce the impact of failed downloads
2 parents c5c5085 + 1e80f0e commit f5cf19d

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

pkg/client/client.go

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io"
77
"os"
88
"path/filepath"
9+
"runtime"
910
"strings"
1011

1112
"github.com/BurntSushi/toml"
@@ -976,19 +977,56 @@ func (c *KpmClient) Download(dep *pkg.Dependency, homePath, localPath string) (*
976977
}
977978
}
978979

979-
err := c.DepDownloader.Download(*downloader.NewDownloadOptions(
980-
downloader.WithLocalPath(localPath),
980+
// create a tmp dir to download the oci package.
981+
tmpDir, err := os.MkdirTemp("", "")
982+
if err != nil {
983+
return nil, reporter.NewErrorEvent(reporter.Bug, err, fmt.Sprintf("failed to create temp dir '%s'.", tmpDir))
984+
}
985+
// clean the temp dir.
986+
defer os.RemoveAll(tmpDir)
987+
988+
err = c.DepDownloader.Download(*downloader.NewDownloadOptions(
989+
downloader.WithLocalPath(tmpDir),
981990
downloader.WithSource(dep.Source),
982991
downloader.WithLogWriter(c.logWriter),
983992
downloader.WithSettings(c.settings),
984993
))
985994
if err != nil {
986995
return nil, err
987996
}
988-
dpkg, err := pkg.FindFirstKclPkgFrom(localPath)
997+
998+
// check the package in tmp dir is a valid kcl package.
999+
_, err = pkg.FindFirstKclPkgFrom(tmpDir)
9891000
if err != nil {
9901001
return nil, err
9911002
}
1003+
1004+
// rename the tmp dir to the local path.
1005+
if utils.DirExists(localPath) {
1006+
err := os.RemoveAll(localPath)
1007+
if err != nil {
1008+
return nil, err
1009+
}
1010+
}
1011+
1012+
if runtime.GOOS != "windows" {
1013+
err = os.Rename(tmpDir, localPath)
1014+
if err != nil {
1015+
return nil, err
1016+
}
1017+
} else {
1018+
err = copy.Copy(tmpDir, localPath)
1019+
if err != nil {
1020+
return nil, err
1021+
}
1022+
}
1023+
1024+
// load the package from the local path.
1025+
dpkg, err := c.LoadPkgFromPath(localPath)
1026+
if err != nil {
1027+
return nil, err
1028+
}
1029+
9921030
dep.FromKclPkg(dpkg)
9931031
dep.Sum, err = c.AcquireDepSum(*dep)
9941032
if err != nil {

0 commit comments

Comments
 (0)