Skip to content

Instantly share code, notes, and snippets.

@mislav
Created October 24, 2017 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mislav/ca62231f776526729b5d4ddd74ad6657 to your computer and use it in GitHub Desktop.
Save mislav/ca62231f776526729b5d4ddd74ad6657 to your computer and use it in GitHub Desktop.
Go program to untar multiple gzipped tarballs listed on the command line
package main
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
)
// https://gist.github.com/sdomino/635a5ed4f32c93aad131#file-untargz-go
func Untar(dst string, r io.Reader) error {
gzr, err := gzip.NewReader(r)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
switch {
// if no more files are found return
case err == io.EOF:
return nil
// return any other error
case err != nil:
return err
// if the header is nil, just skip it (not sure how this happens)
case header == nil:
continue
}
// the target location where the dir/file should be created
target := filepath.Join(dst, header.Name)
// the following switch could also be done using fi.Mode(), not sure if there
// a benefit of using one vs. the other.
// fi := header.FileInfo()
// check the file type
switch header.Typeflag {
// if its a dir and it doesn't exist create it
case tar.TypeDir:
if _, err := os.Stat(target); err != nil {
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
}
// if it's a file create it
case tar.TypeReg:
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return err
}
// copy over contents
_, err = io.Copy(f, tr)
f.Close()
if err != nil {
return err
}
}
}
}
func abort(err error) {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
abort(fmt.Errorf("insufficient arguments"))
} else {
destination, _ := os.Getwd()
for _, tarfile := range os.Args[1:] {
tar, err := os.Open(tarfile)
if err != nil {
abort(err)
}
err = Untar(destination, tar)
tar.Close()
if err != nil {
abort(err)
}
fmt.Println(tarfile)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment