|
| 1 | +package gogit |
| 2 | + |
| 3 | +import ( |
| 4 | + "archive/tar" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | +) |
| 11 | + |
| 12 | +// Untar writes a tar stream to a filesystem. |
| 13 | +func Untar(in io.Reader, dir string) error { |
| 14 | + tr := tar.NewReader(in) |
| 15 | + for { |
| 16 | + header, err := tr.Next() |
| 17 | + if err != nil { |
| 18 | + if errors.Is(err, io.EOF) { |
| 19 | + return nil |
| 20 | + } |
| 21 | + return err |
| 22 | + } |
| 23 | + |
| 24 | + abs := filepath.Join(dir, header.Name) |
| 25 | + |
| 26 | + switch header.Typeflag { |
| 27 | + case tar.TypeDir: |
| 28 | + if err := os.MkdirAll(abs, os.FileMode(header.Mode)); err != nil { |
| 29 | + return fmt.Errorf("unable to create directory %s: %w", header.Name, err) |
| 30 | + } |
| 31 | + case tar.TypeReg: |
| 32 | + file, err := os.OpenFile(abs, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode)) |
| 33 | + if err != nil { |
| 34 | + return fmt.Errorf("unable to open file %s: %w", header.Name, err) |
| 35 | + } |
| 36 | + //nolint:gosec // We don't know what size limit we could set, the tar |
| 37 | + // archive can be an image layer and that can even reach the gigabyte range. |
| 38 | + // For now, we acknowledge the risk. |
| 39 | + // |
| 40 | + // We checked other softwares and tried to figure out how they manage this, |
| 41 | + // but it's handled the same way. |
| 42 | + if _, err := io.Copy(file, tr); err != nil { |
| 43 | + return fmt.Errorf("unable to copy tar file to filesystem: %w", err) |
| 44 | + } |
| 45 | + if err := file.Close(); err != nil { |
| 46 | + return fmt.Errorf("unable to close file %s: %w", header.Name, err) |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments