Skip to content

Instantly share code, notes, and snippets.

@mathyourlife
Created June 6, 2018 03:55
Show Gist options
  • Save mathyourlife/0ba7239e8b0a5185e8cb91751ef84f0f to your computer and use it in GitHub Desktop.
Save mathyourlife/0ba7239e8b0a5185e8cb91751ef84f0f to your computer and use it in GitHub Desktop.
create a tarball from a source directory including empty folders
// Sample script for generating a tarball from a source directory
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"os"
"path/filepath"
)
func main() {
var err error
var buf *bytes.Buffer
var gw *gzip.Writer
buf = new(bytes.Buffer)
gw, err = gzip.NewWriterLevel(buf, gzip.BestCompression)
if err != nil {
panic(err)
}
err = WriteTarball(buf, os.Args[1])
if err != nil {
panic(err)
}
// gzip writer needs to close before io.Copy to a file or get an unexpected
// EOF error on gunzip
err = gw.Close()
if err != nil {
panic(err)
}
fo, err := os.Create(os.Args[2])
if err != nil {
panic(err)
}
defer fo.Close()
_, err = io.Copy(fo, buf)
if err != nil {
panic(err)
}
}
func WriteTarball(w io.Writer, root string) error {
tw := tar.NewWriter(w)
defer tw.Close()
base := filepath.Base(root)
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
hdr, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
p, err := filepath.Rel(root, path)
if err != nil {
return err
}
hdr.Name = filepath.Join(base, p)
if err != nil {
return err
}
err = tw.WriteHeader(hdr)
if err != nil {
return err
}
if info.Mode().IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
return err
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment