diff options
Diffstat (limited to 'utils.go')
| -rw-r--r-- | utils.go | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -5,6 +5,7 @@ import ( "fmt" "math" "os" + "io" "os/exec" "runtime" "strconv" @@ -12,6 +13,8 @@ import ( "unicode/utf8" "math/rand" "time" + "path/filepath" + "archive/tar" ) const ( @@ -304,3 +307,58 @@ func IsStrElement(some string, group []string) bool { return false } +func Tar(src string, writers ...io.Writer) error { + // ensure the src actually exists before trying to tar it + if _, err := os.Stat(src); err != nil { + return fmt.Errorf("Unable to tar files - %v", err.Error()) + } + mw := io.MultiWriter(writers...) + + //gzw := gzip.NewWriter(mw) + //defer gzw.Close() + + tw := tar.NewWriter(mw) + defer tw.Close() + + // walk path + return filepath.Walk(src, func(file string, fi os.FileInfo, err error) error { + // return on any error + if err != nil { + return err + } + // create a new dir/file header + header, err := tar.FileInfoHeader(fi, fi.Name()) + if err != nil { + return err + } + // update the name to correctly reflect the desired destination when untaring + header.Name = strings.TrimPrefix(strings.Replace(file, src, "", -1), string(filepath.Separator)) + + // write the header + if err := tw.WriteHeader(header); err != nil { + return err + } + + // return on non-regular files (thanks to [kumo](https://medium.com/@komuw/just-like-you-did-fbdd7df829d3) for this suggested update) + if !fi.Mode().IsRegular() { + return nil + } + + // open files for taring + f, err := os.Open(file) + if err != nil { + return err + } + // copy file data into tar writer + if _, err := io.Copy(tw, f); err != nil { + return err + } + + // manually close here after each file operation; defering would cause each file close + // to wait until all operations have completed. + f.Close() + + return nil + }) +} + |
