如何在 tar 中获取文件所需的路径,同时 tar 将它们调出

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

我一直在使用此代码写入 tar 文件。我称它为 err = retarIt(dirTopDebug, path),其中 dirTopDebug 是我的 tar 文件的路径 (/tmp/abc.tar),path 是我要添加的文件的路径 (/tmp/xyz/...).当我 untarring 生成的 tar 文件时,我发现 abc.tar 文件以 /tmp/xyz/.. 格式放置。但我希望它们像 xyz/... 一样在 tar 中,即没有 tmp 文件夹。

我该怎么做?

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
}

使用 tar header 中指定的任何名称。使用strings包的strings.LastIndex(或strings.Index)函数将部分分隔到/tmp.

因此,如果将上面的 TarGzWrite 函数中的代码修改如下,它将按照您想要的方式工作(注意:您可能希望将下面的 strings.LastIndex 替换为 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())