I have been using this code to write to a tar file. I am calling it like
err = retarIt(dirTopDebug, path)
, where dirTopDebug
is the path to my tar file (/tmp/abc.tar
), and path
is the path of files I want to add (/tmp/xyz/...
). When I am untarring the generated tar file, I find that inside abc.tar
files are put in /tmp/xyz/..
format. But I want them inside tar like xyz/...
, i.e. without the tmp
folder.
How can I do that?
func TarGzWrite(_path string, tw *tar.Writer, fi os.FileInfo) {
fr, _ := os.Open(_path)
//handleError(err)
defer fr.Close()
h := new(tar.Header)
h.Name = _path
h.Size = fi.Size()
h.Mode = int64(fi.Mode())
h.ModTime = fi.ModTime()
err := tw.WriteHeader(h)
if err != nil {
panic(err)
}
_, _ = io.Copy(tw, fr)
//handleError( err )
}
func IterDirectory(dirPath string, tw *tar.Writer) {
dir, _ := os.Open(dirPath)
//handleError( err )
defer dir.Close()
fis, _ := dir.Readdir(0)
//handleError( err )
for _, fi := range fis {
fmt.Println(dirPath)
curPath := dirPath + "/" + fi.Name()
if fi.IsDir() {
//TarGzWrite( curPath, tw, fi )
IterDirectory(curPath, tw)
} else {
fmt.Printf("adding... %s
", curPath)
TarGzWrite(curPath, tw, fi)
}
}
}
func retarIt(outFilePath, inPath string) error {
fw, err := os.Create(outFilePath)
if err != nil {
return err
}
defer fw.Close()
gw := gzip.NewWriter(fw)
defer gw.Close()
// tar write
tw := tar.NewWriter(gw)
defer tw.Close()
IterDirectory(inPath, tw)
fmt.Println("tar.gz ok")
return nil
}