Skip to content

Instantly share code, notes, and snippets.

@Hunsin
Last active Jan 5, 2018
Embed
What would you like to do?
Tar and Un-tar Gzip files in Golang
package main
import (
"archive/tar"
"compress/gzip"
"io"
"io/ioutil"
"log"
"os"
"strings"
)
func walk(path, r string, tw *tar.Writer) error {
if tw == nil {
panic("tw must not be nil")
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
i, err := f.Stat()
if err != nil {
return err
}
h, err := tar.FileInfoHeader(i, "")
if err != nil {
return err
}
h.Name = strings.TrimPrefix(path, r)
if err = tw.WriteHeader(h); err != nil {
return err
}
if i.IsDir() {
fs, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for i := range fs {
p := path + "/" + fs[i].Name()
if err = walk(p, r, tw); err != nil {
return err
}
}
return nil
}
_, err = io.Copy(tw, f)
return err
}
func main() {
log.SetFlags(log.Lshortfile)
l := len(os.Args)
if l < 3 {
log.Fatal("Usage: zipper <source file>... <dist file>.tar.gz")
}
fs := os.Args[1 : l-1]
dist, err := os.Create(os.Args[l-1])
if err != nil {
log.Fatalln(err)
}
defer dist.Close()
gz := gzip.NewWriter(dist)
tw := tar.NewWriter(gz)
for i := range fs {
info, err := os.Stat(fs[i])
if err != nil {
log.Println(err)
continue
}
r := strings.TrimSuffix(fs[i], "/")
r = strings.TrimSuffix(r, info.Name())
err = walk(fs[i], r, tw)
if err != nil {
log.Print(err)
}
}
if err = tw.Close(); err != nil {
log.Print(err)
}
if err = gz.Close(); err != nil {
log.Print(err)
}
}
package main
import (
"archive/tar"
"compress/gzip"
"io"
"log"
"os"
)
func main() {
log.SetFlags(log.Lshortfile)
l := len(os.Args)
if l < 3 {
log.Fatal("Usage: zipper <source file>... <dist file>.tar.gz")
}
fs := os.Args[1 : l-1]
dist, err := os.Create(os.Args[l-1])
if err != nil {
log.Fatalln(err)
}
defer dist.Close()
gz := gzip.NewWriter(dist)
defer gz.Close()
tw := tar.NewWriter(gz)
defer tw.Close()
for i := range fs {
f, err := os.Open(fs[i])
if err != nil {
log.Println(err)
continue
}
defer f.Close()
info, err := f.Stat()
if err != nil {
log.Println(err)
continue
}
h, err := tar.FileInfoHeader(info, "")
if err != nil {
log.Println(err)
continue
}
if err = tw.WriteHeader(h); err != nil {
log.Println(err)
continue
}
if _, err = io.Copy(tw, f); err != nil {
log.Println(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment