supriya
supriya

Reputation: 965

How can I put a tar file inside tar file in golang

I want to create a tar file and inside that tar file I want to put other tar files.Hierarchy is something like

TopLevelTar.tar.gz
    |-->primary/primary.tar
    |-->secondary/secondaty.tar
    |-->tertiary/tertiary.tar

How can I do it in golag?

Upvotes: 1

Views: 1558

Answers (2)

shivendra pratap singh
shivendra pratap singh

Reputation: 1398

I think this might help you. Basically, this solution is creating a tarball from multiple files. You have to simply give path of your files in place of a.go and b.go etc.

package main

import (
    "archive/tar"
    "compress/gzip"
    "io"
    "log"
    "os"
)

func addFile(tw *tar.Writer, path string) error {
    file, err := os.Open(path)
    if err != nil {
        return err
    }
    defer file.Close()
    if stat, err := file.Stat(); err == nil {
        // now lets create the header as needed for this file within the tarball
        header := new(tar.Header)
        header.Name = path
        header.Size = stat.Size()
        header.Mode = int64(stat.Mode())
        header.ModTime = stat.ModTime()
        // write the header to the tarball archive
        if err := tw.WriteHeader(header); err != nil {
            return err
        }
        // copy the file data to the tarball
        if _, err := io.Copy(tw, file); err != nil {
            return err
        }
    }
    return nil
}

func main() {
    // set up the output file
    file, err := os.Create("output.tar.gz")
    if err != nil {
        log.Fatalln(err)
    }
    defer file.Close()
    // set up the gzip writer
    gw := gzip.NewWriter(file)
    defer gw.Close()
    tw := tar.NewWriter(gw)
    defer tw.Close()
    // grab the paths that need to be added in
    paths := []string{
        "a.go",
        "b.go",
    }
    // add each file as needed into the current tar archive
    for i := range paths {
        if err := addFile(tw, paths[i]); err != nil {
            log.Fatalln(err)
        }
    }
}

Upvotes: 3

lofcek
lofcek

Reputation: 1233

I think it won't work this way. Gzip contains just one file, and tar is utility that serialize many file into one. Therefore those two util are used together. Usually you can put all files into one:

tar cvf file.tar primary/primary.txt secondary/second.wtf etc/other.file

And than you compress this file with gzip

gzip file.tar

It is okey. But gzipped could be just one file. Of course is possible to create many archives like primary/primary.tar and again tar archives together and gzip after it, but would be a bit confusing.

Upvotes: 0

Related Questions