Created
October 31, 2014 16:53
-
-
Save maximilien/328c9ac19ab0a158a8df to your computer and use it in GitHub Desktop.
Creating tarball in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tar_helper | |
import ( | |
"archive/tar" | |
"compress/gzip" | |
"errors" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"os" | |
) | |
func CreateTarball(tarballFilePath string, filePaths []string) error { | |
file, err := os.Create(tarballFilePath) | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not create tarball file '%s', got error '%s'", tarballFilePath, err.Error())) | |
} | |
defer file.Close() | |
gzipWriter := gzip.NewWriter(file) | |
defer gzipWriter.Close() | |
tarWriter := tar.NewWriter(gzipWriter) | |
defer tarWriter.Close() | |
for _, filePath := range filePaths { | |
err := addFileToTarWriter(filePath, tarWriter) | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not add file '%s', to tarball, got error '%s'", filePath, err.Error())) | |
} | |
} | |
return nil | |
} | |
// Private methods | |
func addFileToTarWriter(filePath string, tarWriter *tar.Writer) error { | |
file, err := os.Open(filePath) | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not open file '%s', got error '%s'", filePath, err.Error())) | |
} | |
defer file.Close() | |
stat, err := file.Stat() | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not get stat for file '%s', got error '%s'", filePath, err.Error())) | |
} | |
header := &tar.Header{ | |
Name: filePath, | |
Size: stat.Size(), | |
Mode: int64(stat.Mode()), | |
ModTime: stat.ModTime(), | |
} | |
err = tarWriter.WriteHeader(header) | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not write header for file '%s', got error '%s'", filePath, err.Error())) | |
} | |
_, err = io.Copy(tarWriter, file) | |
if err != nil { | |
return errors.New(fmt.Sprintf("Could not copy the file '%s' data to the tarball, got error '%s'", filePath, err.Error())) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the sample. There is also a library https://github.com/walle/targz