Skip to content

Commit eb0c01d

Browse files
feat: automatically detect and extract tar files
1 parent a99c38e commit eb0c01d

File tree

1 file changed

+59
-4
lines changed

1 file changed

+59
-4
lines changed

pkg/plugin/discovery/download.go

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
package discovery
22

33
import (
4+
"archive/tar"
5+
"compress/gzip"
46
"crypto/sha256"
57
"encoding/hex"
8+
"fmt"
9+
"io"
610
"os"
711
"path"
12+
"regexp"
13+
"strings"
814
"time"
915

1016
"github.com/cavaliergopher/grab/v3"
@@ -44,9 +50,49 @@ func showDownloadProgressBar(name string, res *grab.Response) {
4450
<-done
4551
}
4652

53+
func extractFileFromTarGz(name, inputFile, outputFile string) error {
54+
compressedFile, err := os.Open(inputFile)
55+
if err != nil {
56+
return err
57+
}
58+
defer compressedFile.Close()
59+
60+
decompressedFile, err := gzip.NewReader(compressedFile)
61+
if err != nil {
62+
return err
63+
}
64+
defer decompressedFile.Close()
65+
66+
tarReader := tar.NewReader(decompressedFile)
67+
for {
68+
header, err := tarReader.Next()
69+
if err == io.EOF {
70+
return fmt.Errorf("could not extract file")
71+
}
72+
if err != nil {
73+
return err
74+
}
75+
if header.Typeflag == tar.TypeReg && strings.HasPrefix(header.Name, name) {
76+
outFile, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY, 0755)
77+
if err != nil {
78+
return err
79+
}
80+
_, err = io.Copy(outFile, tarReader)
81+
outFile.Close()
82+
if err != nil {
83+
return err
84+
}
85+
return nil
86+
}
87+
}
88+
}
89+
90+
var tgzRegexp = regexp.MustCompile(`^(.*)\.(tgz|tar\.gz)$`)
91+
4792
func downloadPlugin(pluginInfo *plugin.PluginInfo, downloadInfo *resolver.PluginDownloadInfo, showProgress bool) (string, error) {
48-
targetPath := path.Join(pluginInfo.PluginPath, downloadInfo.Version, downloadInfo.FileName)
49-
req, err := grab.NewRequest(targetPath, downloadInfo.URL)
93+
versionDir := path.Join(pluginInfo.PluginPath, downloadInfo.Version)
94+
targetFile := path.Join(versionDir, downloadInfo.FileName)
95+
req, err := grab.NewRequest(targetFile, downloadInfo.URL)
5096
if err != nil {
5197
return "", err
5298
}
@@ -65,8 +111,17 @@ func downloadPlugin(pluginInfo *plugin.PluginInfo, downloadInfo *resolver.Plugin
65111
if err := res.Err(); err != nil {
66112
return "", err
67113
}
68-
if err := os.Chmod(res.Filename, 0755); err != nil {
114+
115+
tgzMatch := tgzRegexp.FindStringSubmatch(downloadInfo.FileName)
116+
if len(tgzMatch) > 2 {
117+
outFile := path.Join(versionDir, tgzMatch[1])
118+
if err = extractFileFromTarGz(pluginInfo.Name, targetFile, outFile); err != nil {
119+
return "", err
120+
}
121+
targetFile = outFile
122+
}
123+
if err := os.Chmod(targetFile, 0755); err != nil {
69124
return "", err
70125
}
71-
return res.Filename, nil
126+
return targetFile, nil
72127
}

0 commit comments

Comments
 (0)