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.

107 lines
1.9 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. err error
  17. )
  18. // Create output file
  19. outFile, err = os.Create(target)
  20. if err != nil {
  21. return err
  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. err = addToArchive(tarWriter, file)
  31. if err != nil {
  32. return err
  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. err error
  43. )
  44. // Get FileInfo about our file providing file size, mode, etc.
  45. info, err = os.Lstat(filename)
  46. if err != nil {
  47. return err
  48. }
  49. // Create a tar Header from the FileInfo data
  50. header, err = tar.FileInfoHeader(info, info.Name())
  51. if err != nil {
  52. return err
  53. }
  54. isSymlink := info.Mode()&os.ModeSymlink != 0
  55. if isSymlink {
  56. header.Typeflag = tar.TypeSymlink
  57. }
  58. // Use full path as name (FileInfoHeader only takes the basename)
  59. // If we don't do this the directory strucuture would
  60. // not be preserved
  61. // https://golang.org/src/archive/tar/common.go?#L626
  62. header.Name = strings.TrimPrefix(
  63. strings.TrimPrefix(
  64. filename,
  65. Variables.RootDir,
  66. ),
  67. "/",
  68. )
  69. // Write file header to the tar archive
  70. err = tarWriter.WriteHeader(header)
  71. if err != nil {
  72. return err
  73. }
  74. // Do not write file if it is a symlink
  75. if isSymlink {
  76. return nil
  77. }
  78. // Open the file which will be written into the archive
  79. file, err = os.Open(filename)
  80. if err != nil {
  81. return err
  82. }
  83. defer file.Close()
  84. // Copy file content to tar archive
  85. _, err = io.Copy(tarWriter, file)
  86. if err != nil {
  87. return err
  88. }
  89. return nil
  90. }