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

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

Avoid parent folder structure when creating tar

问题

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

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

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

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

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

  1. func compress(src string, dst string) error {
  2. // 创建 tar 文件
  3. tarFile, err := os.Create(dst)
  4. if err != nil {
  5. return err
  6. }
  7. defer tarFile.Close()
  8. // 创建 tar.Writer
  9. tarWriter := tar.NewWriter(tarFile)
  10. defer tarWriter.Close()
  11. // 获取父文件夹路径
  12. parentDir := filepath.Dir(src)
  13. // 遍历源文件夹
  14. err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
  15. if err != nil {
  16. return err
  17. }
  18. // 检查路径是否包含父文件夹路径
  19. if strings.HasPrefix(path, parentDir) {
  20. // 去除父文件夹路径
  21. path = strings.TrimPrefix(path, parentDir)
  22. }
  23. // 创建 tar 文件中的文件或文件夹
  24. header, err := tar.FileInfoHeader(info, info.Name())
  25. if err != nil {
  26. return err
  27. }
  28. header.Name = path
  29. if err := tarWriter.WriteHeader(header); err != nil {
  30. return err
  31. }
  32. // 如果是文件夹,则不需要写入内容
  33. if !info.IsDir() {
  34. file, err := os.Open(path)
  35. if err != nil {
  36. return err
  37. }
  38. defer file.Close()
  39. if _, err := io.Copy(tarWriter, file); err != nil {
  40. return err
  41. }
  42. }
  43. return nil
  44. })
  45. return err
  46. }

你可以将以上代码片段替换原始代码中的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

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

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

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

  1. os.Chdir("/home/Documents/project")
  2. 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:

确定