zip.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Package zip enables you to transparently read or write ZIP compressed archives and the files inside them.
  2. package zip
  3. import (
  4. "archive/zip"
  5. "errors"
  6. "io"
  7. "os"
  8. "path"
  9. "strings"
  10. "gitlab.com/yoginth/cae"
  11. )
  12. // A File represents a file or directory entry in archive.
  13. type File struct {
  14. *zip.FileHeader
  15. oldName string // NOTE: unused, for future change name feature.
  16. oldComment string // NOTE: unused, for future change comment feature.
  17. absPath string // Absolute path of local file system.
  18. tmpPath string
  19. }
  20. // A ZipArchive represents a file archive, compressed with Zip.
  21. type ZipArchive struct {
  22. *zip.ReadCloser
  23. FileName string
  24. Comment string
  25. NumFiles int
  26. Flag int
  27. Permission os.FileMode
  28. files []*File
  29. isHasChanged bool
  30. // For supporting flushing to io.Writer.
  31. writer io.Writer
  32. isHasWriter bool
  33. }
  34. // OpenFile is the generalized open call; most users will use Open
  35. // instead. It opens the named zip file with specified flag
  36. // (O_RDONLY etc.) if applicable. If successful,
  37. // methods on the returned ZipArchive can be used for I/O.
  38. // If there is an error, it will be of type *PathError.
  39. func OpenFile(name string, flag int, perm os.FileMode) (*ZipArchive, error) {
  40. z := new(ZipArchive)
  41. err := z.Open(name, flag, perm)
  42. return z, err
  43. }
  44. // Create creates the named zip file, truncating
  45. // it if it already exists. If successful, methods on the returned
  46. // ZipArchive can be used for I/O; the associated file descriptor has mode
  47. // O_RDWR.
  48. // If there is an error, it will be of type *PathError.
  49. func Create(name string) (*ZipArchive, error) {
  50. os.MkdirAll(path.Dir(name), os.ModePerm)
  51. return OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  52. }
  53. // Open opens the named zip file for reading. If successful, methods on
  54. // the returned ZipArchive can be used for reading; the associated file
  55. // descriptor has mode O_RDONLY.
  56. // If there is an error, it will be of type *PathError.
  57. func Open(name string) (*ZipArchive, error) {
  58. return OpenFile(name, os.O_RDONLY, 0)
  59. }
  60. // New accepts a variable that implemented interface io.Writer
  61. // for write-only purpose operations.
  62. func New(w io.Writer) *ZipArchive {
  63. return &ZipArchive{
  64. writer: w,
  65. isHasWriter: true,
  66. }
  67. }
  68. // List returns a string slice of files' name in ZipArchive.
  69. // Specify prefixes will be used as filters.
  70. func (z *ZipArchive) List(prefixes ...string) []string {
  71. isHasPrefix := len(prefixes) > 0
  72. names := make([]string, 0, z.NumFiles)
  73. for _, f := range z.files {
  74. if isHasPrefix && !cae.HasPrefix(f.Name, prefixes) {
  75. continue
  76. }
  77. names = append(names, f.Name)
  78. }
  79. return names
  80. }
  81. // AddEmptyDir adds a raw directory entry to ZipArchive,
  82. // it returns false if same directory enry already existed.
  83. func (z *ZipArchive) AddEmptyDir(dirPath string) bool {
  84. dirPath = strings.Replace(dirPath, "\\", "/", -1)
  85. if !strings.HasSuffix(dirPath, "/") {
  86. dirPath += "/"
  87. }
  88. for _, f := range z.files {
  89. if dirPath == f.Name {
  90. return false
  91. }
  92. }
  93. dirPath = strings.TrimSuffix(dirPath, "/")
  94. if strings.Contains(dirPath, "/") {
  95. // Auto add all upper level directories.
  96. z.AddEmptyDir(path.Dir(dirPath))
  97. }
  98. z.files = append(z.files, &File{
  99. FileHeader: &zip.FileHeader{
  100. Name: dirPath + "/",
  101. UncompressedSize: 0,
  102. },
  103. })
  104. z.updateStat()
  105. return true
  106. }
  107. // AddDir adds a directory and subdirectories entries to ZipArchive.
  108. func (z *ZipArchive) AddDir(dirPath, absPath string) error {
  109. dir, err := os.Open(absPath)
  110. if err != nil {
  111. return err
  112. }
  113. defer dir.Close()
  114. // Make sure we have all upper level directories.
  115. z.AddEmptyDir(dirPath)
  116. fis, err := dir.Readdir(0)
  117. if err != nil {
  118. return err
  119. }
  120. for _, fi := range fis {
  121. curPath := absPath + "/" + fi.Name()
  122. tmpRecPath := path.Join(dirPath, fi.Name())
  123. if fi.IsDir() {
  124. if err = z.AddDir(tmpRecPath, curPath); err != nil {
  125. return err
  126. }
  127. } else {
  128. if err = z.AddFile(tmpRecPath, curPath); err != nil {
  129. return err
  130. }
  131. }
  132. }
  133. return nil
  134. }
  135. // updateStat should be called after every change for rebuilding statistic.
  136. func (z *ZipArchive) updateStat() {
  137. z.NumFiles = len(z.files)
  138. z.isHasChanged = true
  139. }
  140. // AddFile adds a file entry to ZipArchive.
  141. func (z *ZipArchive) AddFile(fileName, absPath string) error {
  142. fileName = strings.Replace(fileName, "\\", "/", -1)
  143. absPath = strings.Replace(absPath, "\\", "/", -1)
  144. if cae.IsFilter(absPath) {
  145. return nil
  146. }
  147. f, err := os.Open(absPath)
  148. if err != nil {
  149. return err
  150. }
  151. defer f.Close()
  152. fi, err := f.Stat()
  153. if err != nil {
  154. return err
  155. }
  156. file := new(File)
  157. file.FileHeader, err = zip.FileInfoHeader(fi)
  158. if err != nil {
  159. return err
  160. }
  161. file.Name = fileName
  162. file.absPath = absPath
  163. z.AddEmptyDir(path.Dir(fileName))
  164. isExist := false
  165. for _, f := range z.files {
  166. if fileName == f.Name {
  167. f = file
  168. isExist = true
  169. break
  170. }
  171. }
  172. if !isExist {
  173. z.files = append(z.files, file)
  174. }
  175. z.updateStat()
  176. return nil
  177. }
  178. // DeleteIndex deletes an entry in the archive by its index.
  179. func (z *ZipArchive) DeleteIndex(idx int) error {
  180. if idx >= z.NumFiles {
  181. return errors.New("index out of range of number of files")
  182. }
  183. z.files = append(z.files[:idx], z.files[idx+1:]...)
  184. return nil
  185. }
  186. // DeleteName deletes an entry in the archive by its name.
  187. func (z *ZipArchive) DeleteName(name string) error {
  188. for i, f := range z.files {
  189. if f.Name == name {
  190. return z.DeleteIndex(i)
  191. }
  192. }
  193. return errors.New("entry with given name not found")
  194. }