62 lines
1.1 KiB
Go
Executable File
62 lines
1.1 KiB
Go
Executable File
package extract
|
|
|
|
import (
|
|
"archive/tar"
|
|
"compress/bzip2"
|
|
"compress/gzip"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
func extractTar(archivePath string, archiveFormat format, writer *entryWriter) error {
|
|
file, err := os.Open(archivePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
if archiveFormat == formatTar {
|
|
if info, err := file.Stat(); err == nil {
|
|
writer.progress.SetTotal(info.Size())
|
|
}
|
|
}
|
|
|
|
source, err := decompress(file, archiveFormat)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
reader := tar.NewReader(source)
|
|
for {
|
|
header, err := reader.Next()
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
switch header.Typeflag {
|
|
case tar.TypeDir:
|
|
err = writer.writeDirectory(header.Name)
|
|
case tar.TypeReg:
|
|
err = writer.writeFile(header.Name, reader)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
func decompress(file *os.File, archiveFormat format) (io.Reader, error) {
|
|
switch archiveFormat {
|
|
case formatTarGzip:
|
|
return gzip.NewReader(file)
|
|
case formatTarBzip2:
|
|
return bzip2.NewReader(file), nil
|
|
default:
|
|
return file, nil
|
|
}
|
|
}
|