File size: 1,338 Bytes
1e92f2d |
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 |
package main
import (
"archive/tar"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
// extractFromTar will extract a file matching `glob` to `out`.
// If `exec` is set, the file will be marked executable.
func extractFromTar(r *tar.Reader, glob, out string, exec bool) error {
err := os.MkdirAll(filepath.Dir(out), 0755)
if err != nil {
return fmt.Errorf("make output dir '%s': %w", filepath.Dir(out), err)
}
tmpFile := out + ".tmp"
mode := fs.FileMode(0666)
if exec {
mode = 0755
}
outFile, err := os.OpenFile(tmpFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return fmt.Errorf("create temp file '%s': %w", tmpFile, err)
}
defer outFile.Close()
var name string
for {
hdr, err := r.Next()
if err != nil {
return fmt.Errorf("find '%s' in tgz: %w", glob, err)
}
ok, err := filepath.Match(glob, hdr.Name)
if err != nil {
return fmt.Errorf("invalid pattern '%s': %w", glob, err)
}
if !ok {
continue
}
name = hdr.Name
break
}
_, err = io.Copy(outFile, r)
if err != nil {
return fmt.Errorf("extract '%s' to '%s': %w", name, tmpFile, err)
}
err = outFile.Close()
if err != nil {
return fmt.Errorf("close '%s': %w", tmpFile, err)
}
err = os.Rename(tmpFile, out)
if err != nil {
return fmt.Errorf("rename '%s' to '%s': %w", tmpFile, out, err)
}
return nil
}
|