创建tar文件时避免使用父文件夹结构。

huangapple go评论80阅读模式
英文:

Avoid parent folder structure when creating tar

问题

你可以按照以下方式修改该方法来实现你的需求:

在给定的链接中,找到并打开folders.go文件。在该文件中,你可以找到compress方法的实现。

在该方法中,你可以看到它使用了filepath.Walk函数来遍历源文件夹中的所有文件和子文件夹。在每次遍历时,它会将文件或文件夹的路径添加到tar文件中。

要避免父文件夹结构,你可以在每次遍历时检查当前文件或文件夹的路径是否包含父文件夹的路径。如果包含,则将其添加到tar文件中时去除父文件夹路径。

以下是一个示例修改的代码片段:

func compress(src string, dst string) error {
    // 创建 tar 文件
    tarFile, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer tarFile.Close()

    // 创建 tar.Writer
    tarWriter := tar.NewWriter(tarFile)
    defer tarWriter.Close()

    // 获取父文件夹路径
    parentDir := filepath.Dir(src)

    // 遍历源文件夹
    err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        // 检查路径是否包含父文件夹路径
        if strings.HasPrefix(path, parentDir) {
            // 去除父文件夹路径
            path = strings.TrimPrefix(path, parentDir)
        }

        // 创建 tar 文件中的文件或文件夹
        header, err := tar.FileInfoHeader(info, info.Name())
        if err != nil {
            return err
        }
        header.Name = path

        if err := tarWriter.WriteHeader(header); err != nil {
            return err
        }

        // 如果是文件夹,则不需要写入内容
        if !info.IsDir() {
            file, err := os.Open(path)
            if err != nil {
                return err
            }
            defer file.Close()

            if _, err := io.Copy(tarWriter, file); err != nil {
                return err
            }
        }

        return nil
    })

    return err
}

你可以将以上代码片段替换原始代码中的compress方法实现。这样修改后的方法将在创建tar文件时避免父文件夹结构,直接包含文件。

希望对你有帮助!

英文:

https://github.com/mimoo/eureka/blob/master/folders.go

I am using the compress method given in the above link for creating Tar with recursive folder structure in Golang.

Now, say if I give /home/Documents/project as src

Then, the created tar also contains /home/Documents/project/files
I want to avoid the parent folder structure here.

Ex. tar should directly contain : files

How can I modify this method to achieve this ?

Thanks in advance.

答案1

得分: 2

一个不修改代码的巧妙方法,如果你的程序没有并发逻辑,你可以这样做:

os.Chdir("/home/Documents/project")
compress("./", output)
英文:

A tricky method without modifying the code, If your program does not have concurrent logic, you can do this:

os.Chdir("/home/Documents/project")
compress("./", output)

huangapple
  • 本文由 发表于 2021年10月10日 13:09:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/69512481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定