PackageManager just because
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
1.7 KiB

  1. package Archive
  2. import (
  3. "PackageManager/Variables"
  4. "archive/tar"
  5. "compress/gzip"
  6. "io"
  7. "os"
  8. "strings"
  9. )
  10. func CreateArchive(files []string, target string) error {
  11. var (
  12. outFile *os.File
  13. gzipWriter *gzip.Writer
  14. tarWriter *tar.Writer
  15. file string
  16. e error
  17. )
  18. // Create output file
  19. outFile, e = os.Create(target)
  20. if e != nil {
  21. return e
  22. }
  23. defer outFile.Close()
  24. gzipWriter = gzip.NewWriter(outFile)
  25. defer gzipWriter.Close()
  26. tarWriter = tar.NewWriter(gzipWriter)
  27. defer tarWriter.Close()
  28. // Iterate over files and add them to the tar archive
  29. for _, file = range files {
  30. e = addToArchive(tarWriter, file)
  31. if e != nil {
  32. return e
  33. }
  34. }
  35. return nil
  36. }
  37. func addToArchive(tarWriter *tar.Writer, filename string) error {
  38. var (
  39. file *os.File
  40. info os.FileInfo
  41. header *tar.Header
  42. e error
  43. )
  44. // Open the file which will be written into the archive
  45. file, e = os.Open(filename)
  46. if e != nil {
  47. return e
  48. }
  49. defer file.Close()
  50. // Get FileInfo about our file providing file size, mode, etc.
  51. info, e = file.Stat()
  52. if e != nil {
  53. return e
  54. }
  55. // Create a tar Header from the FileInfo data
  56. header, e = tar.FileInfoHeader(info, info.Name())
  57. if e != nil {
  58. return e
  59. }
  60. // Use full path as name (FileInfoHeader only takes the basename)
  61. // If we don't do this the directory strucuture would
  62. // not be preserved
  63. // https://golang.org/src/archive/tar/common.go?#L626
  64. header.Name = strings.TrimPrefix(
  65. strings.TrimPrefix(
  66. filename,
  67. Variables.RootDir,
  68. ),
  69. "/",
  70. )
  71. // Write file header to the tar archive
  72. e = tarWriter.WriteHeader(header)
  73. if e != nil {
  74. return e
  75. }
  76. // Copy file content to tar archive
  77. _, e = io.Copy(tarWriter, file)
  78. if e != nil {
  79. return e
  80. }
  81. return nil
  82. }