|
|
- package Archive
-
- import (
- "archive/tar"
- "compress/gzip"
- "io"
- "io/fs"
- "os"
- "path/filepath"
- "strings"
- )
-
- func UnGzip(source, target string) error {
- var (
- reader, writer *os.File
- archive *gzip.Reader
- e error
- )
-
- reader, e = os.Open(source)
- if e != nil {
- return e
- }
- defer reader.Close()
-
- archive, e = gzip.NewReader(reader)
- if e != nil {
- return e
- }
- defer archive.Close()
-
- target = filepath.Join(target, archive.Name)
-
- writer, e = os.Create(target)
- if e != nil {
- return e
- }
- defer writer.Close()
-
- _, e = io.Copy(writer, archive)
- return e
- }
-
- func Untar(tarball, target string) error {
- var (
- reader *os.File
- tarReader *tar.Reader
- header *tar.Header
- info fs.FileInfo
- file *os.File
- path string
- e error
- )
-
- reader, e = os.Open(tarball)
- if e != nil {
- return e
- }
-
- defer reader.Close()
- tarReader = tar.NewReader(reader)
-
- for {
- header, e = tarReader.Next()
- if e == io.EOF {
- break
- }
- if e != nil {
- return e
- }
-
- path = "/" + strings.Join(strings.Split(header.Name, "/")[1:], "/")
-
- info = header.FileInfo()
- if info.IsDir() {
- e = os.MkdirAll(path, info.Mode())
- if e != nil {
- return e
- }
- continue
- }
-
- file, e = os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
- if e != nil {
- return e
- }
-
- defer file.Close()
-
- _, e = io.Copy(file, tarReader)
- if e != nil {
- return e
- }
- }
-
- return nil
- }
-
- func UntarGzip(source, target string) error {
- var (
- tarPath string = strings.ReplaceAll(source, ".gz", "")
- e error
- )
-
- e = UnGzip(source, tarPath)
- if e != nil {
- return e
- }
-
- return Untar(tarPath, target)
- }
|