supriya
supriya

Reputation: 965

How to get desired path for the files inside tar while tarring them up

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\n", 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
}

Upvotes: 0

Views: 79

Answers (1)

Ravi R
Ravi R

Reputation: 1782

Whatever name is specified in the tar header, is used. Use the strings.LastIndex (or strings.Index) function of the strings package to separate the part till /tmp.

So if the code in TarGzWrite function above is modified as follows it works the way you want (note: you may want to replace strings.LastIndex below with strings.Index).

//TarGzWrite function same as above....
h := new(tar.Header)
//New code after this..
lastIndex := strings.LastIndex(_path, "/tmp")
fmt.Println("String is ", _path, "Last index is", lastIndex)
var name string
if lastIndex > 0 {
    name = _path[lastIndex+len("/tmp")+1:]
    fmt.Println("Got name:", name)
} else {
    //This would not be needed, but was there just for testing my code
    name = _path
}
// h.Name = _path
h.Name = name
h.Size = fi.Size()
h.Mode = int64(fi.Mode())

Upvotes: 1

Related Questions