blob: 955fe68d0c08453f1f3ecd8ae2637537573b2e51 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Jeff Gaston11b5c512017-10-12 12:19:14 -070015package zip
Colin Cross2fe66872015-03-30 17:20:39 -070016
17import (
Dan Willemsen017d8932016-08-04 15:43:03 -070018 "bytes"
19 "compress/flate"
Jeff Gastona2976952017-08-22 17:51:25 -070020 "errors"
Colin Cross2fe66872015-03-30 17:20:39 -070021 "fmt"
Dan Willemsen017d8932016-08-04 15:43:03 -070022 "hash/crc32"
Colin Cross2fe66872015-03-30 17:20:39 -070023 "io"
24 "io/ioutil"
25 "os"
26 "path/filepath"
Jeff Gastona2976952017-08-22 17:51:25 -070027 "sort"
Colin Cross2fe66872015-03-30 17:20:39 -070028 "strings"
Dan Willemsen017d8932016-08-04 15:43:03 -070029 "sync"
Colin Cross1d98ee22018-09-18 17:05:15 -070030 "syscall"
Colin Cross2fe66872015-03-30 17:20:39 -070031 "time"
Colin Crossfd708b52021-03-23 14:16:05 -070032
33 "android/soong/response"
Dan Willemsen017d8932016-08-04 15:43:03 -070034
Colin Crossf83c1502017-11-10 13:11:02 -080035 "github.com/google/blueprint/pathtools"
36
Jeff Gastona2976952017-08-22 17:51:25 -070037 "android/soong/jar"
Dan Willemsen017d8932016-08-04 15:43:03 -070038 "android/soong/third_party/zip"
Colin Cross2fe66872015-03-30 17:20:39 -070039)
40
Dan Willemsen017d8932016-08-04 15:43:03 -070041// Block size used during parallel compression of a single file.
42const parallelBlockSize = 1 * 1024 * 1024 // 1MB
43
44// Minimum file size to use parallel compression. It requires more
45// flate.Writer allocations, since we can't change the dictionary
46// during Reset
47const minParallelFileSize = parallelBlockSize * 6
48
49// Size of the ZIP compression window (32KB)
50const windowSize = 32 * 1024
51
52type nopCloser struct {
53 io.Writer
54}
55
56func (nopCloser) Close() error {
57 return nil
58}
59
Jeff Gastoncef50b92017-08-23 15:41:35 -070060type byteReaderCloser struct {
Colin Cross635acc92017-09-12 22:50:46 -070061 *bytes.Reader
Jeff Gastoncef50b92017-08-23 15:41:35 -070062 io.Closer
63}
64
Nan Zhang9067b042017-03-17 14:04:43 -070065type pathMapping struct {
66 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070067 zipMethod uint16
68}
69
Jeff Gastonc3bdc972017-10-12 12:18:19 -070070type FileArg struct {
71 PathPrefixInZip, SourcePrefixToStrip string
72 SourceFiles []string
Colin Crossb7c69112018-09-18 16:51:43 -070073 JunkPaths bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -070074 GlobDir string
75}
76
Colin Crossfe945b42018-09-27 15:00:07 -070077type FileArgsBuilder struct {
78 state FileArg
79 err error
80 fs pathtools.FileSystem
81
82 fileArgs []FileArg
83}
84
85func NewFileArgsBuilder() *FileArgsBuilder {
86 return &FileArgsBuilder{
87 fs: pathtools.OsFs,
88 }
89}
90
91func (b *FileArgsBuilder) JunkPaths(v bool) *FileArgsBuilder {
92 b.state.JunkPaths = v
93 b.state.SourcePrefixToStrip = ""
94 return b
95}
96
97func (b *FileArgsBuilder) SourcePrefixToStrip(prefixToStrip string) *FileArgsBuilder {
98 b.state.JunkPaths = false
99 b.state.SourcePrefixToStrip = prefixToStrip
100 return b
101}
102
103func (b *FileArgsBuilder) PathPrefixInZip(rootPrefix string) *FileArgsBuilder {
104 b.state.PathPrefixInZip = rootPrefix
105 return b
106}
107
108func (b *FileArgsBuilder) File(name string) *FileArgsBuilder {
109 if b.err != nil {
110 return b
111 }
112
113 arg := b.state
114 arg.SourceFiles = []string{name}
115 b.fileArgs = append(b.fileArgs, arg)
116 return b
117}
118
119func (b *FileArgsBuilder) Dir(name string) *FileArgsBuilder {
120 if b.err != nil {
121 return b
122 }
123
124 arg := b.state
125 arg.GlobDir = name
126 b.fileArgs = append(b.fileArgs, arg)
127 return b
128}
129
Sasha Smundak8eedba62020-11-16 19:00:27 -0800130// List reads the file names from the given file and adds them to the source files list.
Colin Crossfe945b42018-09-27 15:00:07 -0700131func (b *FileArgsBuilder) List(name string) *FileArgsBuilder {
132 if b.err != nil {
133 return b
134 }
135
136 f, err := b.fs.Open(name)
137 if err != nil {
138 b.err = err
139 return b
140 }
141 defer f.Close()
142
143 list, err := ioutil.ReadAll(f)
144 if err != nil {
145 b.err = err
146 return b
147 }
148
149 arg := b.state
Jiyong Park04bbf982019-11-04 13:18:41 +0900150 arg.SourceFiles = strings.Fields(string(list))
Colin Crossfe945b42018-09-27 15:00:07 -0700151 b.fileArgs = append(b.fileArgs, arg)
152 return b
153}
154
Sasha Smundak8eedba62020-11-16 19:00:27 -0800155// RspFile reads the file names from given .rsp file and adds them to the source files list.
Colin Cross053fca12020-08-19 13:51:47 -0700156func (b *FileArgsBuilder) RspFile(name string) *FileArgsBuilder {
157 if b.err != nil {
158 return b
159 }
160
161 f, err := b.fs.Open(name)
162 if err != nil {
163 b.err = err
164 return b
165 }
166 defer f.Close()
167
Colin Crossfd708b52021-03-23 14:16:05 -0700168 arg := b.state
169 arg.SourceFiles, err = response.ReadRspFile(f)
Colin Cross053fca12020-08-19 13:51:47 -0700170 if err != nil {
171 b.err = err
172 return b
173 }
Colin Crosscaf4d4c2021-02-03 15:15:14 -0800174 for i := range arg.SourceFiles {
175 arg.SourceFiles[i] = pathtools.MatchEscape(arg.SourceFiles[i])
176 }
Colin Cross053fca12020-08-19 13:51:47 -0700177 b.fileArgs = append(b.fileArgs, arg)
178 return b
179}
180
Colin Crossfe945b42018-09-27 15:00:07 -0700181func (b *FileArgsBuilder) Error() error {
182 if b == nil {
183 return nil
184 }
185 return b.err
186}
187
188func (b *FileArgsBuilder) FileArgs() []FileArg {
189 if b == nil {
190 return nil
191 }
192 return b.fileArgs
193}
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700194
Colin Cross1d98ee22018-09-18 17:05:15 -0700195type IncorrectRelativeRootError struct {
196 RelativeRoot string
197 Path string
198}
199
200func (x IncorrectRelativeRootError) Error() string {
201 return fmt.Sprintf("path %q is outside relative root %q", x.Path, x.RelativeRoot)
202}
203
Colin Cross7ddd08a2022-08-15 15:47:41 -0700204type ConflictingFileError struct {
205 Dest string
206 Prev string
207 Src string
208}
209
210func (x ConflictingFileError) Error() string {
211 return fmt.Sprintf("destination %q has two files %q and %q", x.Dest, x.Prev, x.Src)
212}
213
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700214type ZipWriter struct {
Colin Crosse5580972017-08-30 17:40:21 -0700215 time time.Time
216 createdFiles map[string]string
217 createdDirs map[string]string
218 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700219
Dan Willemsen017d8932016-08-04 15:43:03 -0700220 errors chan error
221 writeOps chan chan *zipEntry
222
Jeff Gaston175f34c2017-08-17 21:43:21 -0700223 cpuRateLimiter *CPURateLimiter
224 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700225
226 compressorPool sync.Pool
227 compLevel int
Colin Cross05518bc2018-09-27 15:06:19 -0700228
Colin Cross4be8f9e2018-09-28 15:16:48 -0700229 followSymlinks pathtools.ShouldFollowSymlinks
230 ignoreMissingFiles bool
Colin Cross09f11052018-09-21 15:12:39 -0700231
Colin Cross4be8f9e2018-09-28 15:16:48 -0700232 stderr io.Writer
233 fs pathtools.FileSystem
Dan Willemsen017d8932016-08-04 15:43:03 -0700234}
235
236type zipEntry struct {
237 fh *zip.FileHeader
238
239 // List of delayed io.Reader
240 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700241
242 // Only used for passing into the MemoryRateLimiter to ensure we
243 // release as much memory as much as we request
244 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700245}
246
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700247type ZipArgs struct {
Colin Crossfe945b42018-09-27 15:00:07 -0700248 FileArgs []FileArg
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700249 OutputFilePath string
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700250 EmulateJar bool
Colin Cross9cb51db2019-06-17 14:12:41 -0700251 SrcJar bool
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700252 AddDirectoryEntriesToZip bool
253 CompressionLevel int
254 ManifestSourcePath string
255 NumParallelJobs int
256 NonDeflatedFiles map[string]bool
Colin Crossf83c1502017-11-10 13:11:02 -0800257 WriteIfChanged bool
Colin Cross09f11052018-09-21 15:12:39 -0700258 StoreSymlinks bool
Colin Cross4be8f9e2018-09-28 15:16:48 -0700259 IgnoreMissingFiles bool
Colin Cross09f11052018-09-21 15:12:39 -0700260
Colin Cross4be8f9e2018-09-28 15:16:48 -0700261 Stderr io.Writer
Colin Cross09f11052018-09-21 15:12:39 -0700262 Filesystem pathtools.FileSystem
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700263}
Colin Cross2fe66872015-03-30 17:20:39 -0700264
Sasha Smundak8eedba62020-11-16 19:00:27 -0800265func zipTo(args ZipArgs, w io.Writer) error {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700266 if args.EmulateJar {
267 args.AddDirectoryEntriesToZip = true
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700268 }
269
Colin Cross09f11052018-09-21 15:12:39 -0700270 // Have Glob follow symlinks if they are not being stored as symlinks in the zip file.
271 followSymlinks := pathtools.ShouldFollowSymlinks(!args.StoreSymlinks)
272
Colin Cross05518bc2018-09-27 15:06:19 -0700273 z := &ZipWriter{
Colin Cross4be8f9e2018-09-28 15:16:48 -0700274 time: jar.DefaultTime,
275 createdDirs: make(map[string]string),
276 createdFiles: make(map[string]string),
277 directories: args.AddDirectoryEntriesToZip,
278 compLevel: args.CompressionLevel,
279 followSymlinks: followSymlinks,
280 ignoreMissingFiles: args.IgnoreMissingFiles,
281 stderr: args.Stderr,
282 fs: args.Filesystem,
Colin Cross2fe66872015-03-30 17:20:39 -0700283 }
Colin Cross05518bc2018-09-27 15:06:19 -0700284
285 if z.fs == nil {
286 z.fs = pathtools.OsFs
287 }
288
Colin Cross4be8f9e2018-09-28 15:16:48 -0700289 if z.stderr == nil {
290 z.stderr = os.Stderr
291 }
292
Nan Zhang9067b042017-03-17 14:04:43 -0700293 pathMappings := []pathMapping{}
Nan Zhang9067b042017-03-17 14:04:43 -0700294
Colin Crossd3216292018-09-14 15:06:31 -0700295 noCompression := args.CompressionLevel == 0
296
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700297 for _, fa := range args.FileArgs {
Colin Cross1d98ee22018-09-18 17:05:15 -0700298 var srcs []string
299 for _, s := range fa.SourceFiles {
300 s = strings.TrimSpace(s)
301 if s == "" {
302 continue
303 }
304
Colin Cross82ea3fb2021-04-05 17:48:26 -0700305 result, err := z.fs.Glob(s, nil, followSymlinks)
Colin Cross1d98ee22018-09-18 17:05:15 -0700306 if err != nil {
307 return err
308 }
Colin Cross82ea3fb2021-04-05 17:48:26 -0700309 if len(result.Matches) == 0 {
Colin Cross4be8f9e2018-09-28 15:16:48 -0700310 err := &os.PathError{
311 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700312 Path: s,
313 Err: os.ErrNotExist,
314 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700315 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800316 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700317 } else {
318 return err
319 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700320 }
Colin Cross82ea3fb2021-04-05 17:48:26 -0700321 srcs = append(srcs, result.Matches...)
Colin Cross1d98ee22018-09-18 17:05:15 -0700322 }
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700323 if fa.GlobDir != "" {
Colin Cross1d98ee22018-09-18 17:05:15 -0700324 if exists, isDir, err := z.fs.Exists(fa.GlobDir); err != nil {
325 return err
Colin Cross4be8f9e2018-09-28 15:16:48 -0700326 } else if !exists && !args.IgnoreMissingFiles {
327 err := &os.PathError{
328 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700329 Path: fa.GlobDir,
330 Err: os.ErrNotExist,
331 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700332 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800333 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700334 } else {
335 return err
336 }
337 } else if !isDir && !args.IgnoreMissingFiles {
338 err := &os.PathError{
339 Op: "lstat",
Colin Cross1d98ee22018-09-18 17:05:15 -0700340 Path: fa.GlobDir,
341 Err: syscall.ENOTDIR,
342 }
Colin Cross4be8f9e2018-09-28 15:16:48 -0700343 if args.IgnoreMissingFiles {
Dan Willemsenedc934c2018-12-27 12:41:25 -0800344 fmt.Fprintln(z.stderr, "warning:", err)
Colin Cross4be8f9e2018-09-28 15:16:48 -0700345 } else {
346 return err
347 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700348 }
Colin Cross82ea3fb2021-04-05 17:48:26 -0700349 result, err := z.fs.Glob(filepath.Join(fa.GlobDir, "**/*"), nil, followSymlinks)
Colin Cross1d98ee22018-09-18 17:05:15 -0700350 if err != nil {
351 return err
352 }
Colin Cross82ea3fb2021-04-05 17:48:26 -0700353 srcs = append(srcs, result.Matches...)
Colin Cross7b10cf12017-08-30 14:12:21 -0700354 }
355 for _, src := range srcs {
Colin Crossb7c69112018-09-18 16:51:43 -0700356 err := fillPathPairs(fa, src, &pathMappings, args.NonDeflatedFiles, noCompression)
Colin Crossd3216292018-09-14 15:06:31 -0700357 if err != nil {
Colin Cross05518bc2018-09-27 15:06:19 -0700358 return err
Nan Zhang9067b042017-03-17 14:04:43 -0700359 }
360 }
361 }
362
Colin Cross9cb51db2019-06-17 14:12:41 -0700363 return z.write(w, pathMappings, args.ManifestSourcePath, args.EmulateJar, args.SrcJar, args.NumParallelJobs)
Colin Cross05518bc2018-09-27 15:06:19 -0700364}
365
Sasha Smundak8eedba62020-11-16 19:00:27 -0800366// Zip creates an output zip archive from given sources.
Colin Cross05518bc2018-09-27 15:06:19 -0700367func Zip(args ZipArgs) error {
368 if args.OutputFilePath == "" {
369 return fmt.Errorf("output file path must be nonempty")
370 }
371
Colin Crossf83c1502017-11-10 13:11:02 -0800372 buf := &bytes.Buffer{}
373 var out io.Writer = buf
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700374
Colin Cross665b6782021-03-15 15:28:40 -0700375 var zipErr error
376
Colin Crossf83c1502017-11-10 13:11:02 -0800377 if !args.WriteIfChanged {
378 f, err := os.Create(args.OutputFilePath)
379 if err != nil {
380 return err
381 }
382
383 defer f.Close()
384 defer func() {
Colin Cross665b6782021-03-15 15:28:40 -0700385 if zipErr != nil {
Colin Crossf83c1502017-11-10 13:11:02 -0800386 os.Remove(args.OutputFilePath)
387 }
388 }()
389
390 out = f
391 }
392
Colin Cross665b6782021-03-15 15:28:40 -0700393 zipErr = zipTo(args, out)
394 if zipErr != nil {
395 return zipErr
Colin Crossf83c1502017-11-10 13:11:02 -0800396 }
397
398 if args.WriteIfChanged {
399 err := pathtools.WriteFileIfChanged(args.OutputFilePath, buf.Bytes(), 0666)
400 if err != nil {
401 return err
402 }
403 }
404
405 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700406}
407
Colin Crossb7c69112018-09-18 16:51:43 -0700408func fillPathPairs(fa FileArg, src string, pathMappings *[]pathMapping,
Colin Crossd3216292018-09-14 15:06:31 -0700409 nonDeflatedFiles map[string]bool, noCompression bool) error {
410
Colin Crossb7c69112018-09-18 16:51:43 -0700411 var dest string
412
413 if fa.JunkPaths {
414 dest = filepath.Base(src)
415 } else {
416 var err error
417 dest, err = filepath.Rel(fa.SourcePrefixToStrip, src)
418 if err != nil {
419 return err
420 }
Colin Cross1d98ee22018-09-18 17:05:15 -0700421 if strings.HasPrefix(dest, "../") {
422 return IncorrectRelativeRootError{
423 Path: src,
424 RelativeRoot: fa.SourcePrefixToStrip,
425 }
426 }
Nan Zhang9067b042017-03-17 14:04:43 -0700427 }
Colin Crossb7c69112018-09-18 16:51:43 -0700428 dest = filepath.Join(fa.PathPrefixInZip, dest)
Nan Zhang9067b042017-03-17 14:04:43 -0700429
Nan Zhangf281bd82017-04-25 16:47:45 -0700430 zipMethod := zip.Deflate
Colin Crossd3216292018-09-14 15:06:31 -0700431 if _, found := nonDeflatedFiles[dest]; found || noCompression {
Nan Zhangf281bd82017-04-25 16:47:45 -0700432 zipMethod = zip.Store
433 }
434 *pathMappings = append(*pathMappings,
435 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700436
437 return nil
438}
439
Jeff Gastona2976952017-08-22 17:51:25 -0700440func jarSort(mappings []pathMapping) {
Sasha Smundak8eedba62020-11-16 19:00:27 -0800441 sort.SliceStable(mappings, func(i int, j int) bool {
Jeff Gastona2976952017-08-22 17:51:25 -0700442 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
Sasha Smundak8eedba62020-11-16 19:00:27 -0800443 })
Jeff Gastona2976952017-08-22 17:51:25 -0700444}
445
Colin Cross9cb51db2019-06-17 14:12:41 -0700446func (z *ZipWriter) write(f io.Writer, pathMappings []pathMapping, manifest string, emulateJar, srcJar bool,
447 parallelJobs int) error {
448
Dan Willemsen017d8932016-08-04 15:43:03 -0700449 z.errors = make(chan error)
450 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700451
Dan Willemsen017d8932016-08-04 15:43:03 -0700452 // This channel size can be essentially unlimited -- it's used as a fifo
453 // queue decouple the CPU and IO loads. Directories don't require any
454 // compression time, but still cost some IO. Similar with small files that
455 // can be very fast to compress. Some files that are more difficult to
456 // compress won't take a corresponding longer time writing out.
457 //
458 // The optimum size here depends on your CPU and IO characteristics, and
459 // the the layout of your zip file. 1000 was chosen mostly at random as
460 // something that worked reasonably well for a test file.
461 //
462 // The RateLimit object will put the upper bounds on the number of
463 // parallel compressions and outstanding buffers.
464 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700465 z.cpuRateLimiter = NewCPURateLimiter(int64(parallelJobs))
Jeff Gaston175f34c2017-08-17 21:43:21 -0700466 z.memoryRateLimiter = NewMemoryRateLimiter(0)
467 defer func() {
468 z.cpuRateLimiter.Stop()
469 z.memoryRateLimiter.Stop()
470 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700471
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700472 if manifest != "" && !emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700473 return errors.New("must specify --jar when specifying a manifest via -m")
Jeff Gastona2976952017-08-22 17:51:25 -0700474 }
475
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700476 if emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700477 // manifest may be empty, in which case addManifest will fill in a default
478 pathMappings = append(pathMappings, pathMapping{jar.ManifestFile, manifest, zip.Deflate})
479
Jeff Gastona2976952017-08-22 17:51:25 -0700480 jarSort(pathMappings)
481 }
482
Dan Willemsen017d8932016-08-04 15:43:03 -0700483 go func() {
484 var err error
485 defer close(z.writeOps)
486
Nan Zhang9067b042017-03-17 14:04:43 -0700487 for _, ele := range pathMappings {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700488 if emulateJar && ele.dest == jar.ManifestFile {
Jeff Gastoncef50b92017-08-23 15:41:35 -0700489 err = z.addManifest(ele.dest, ele.src, ele.zipMethod)
490 } else {
Colin Cross9cb51db2019-06-17 14:12:41 -0700491 err = z.addFile(ele.dest, ele.src, ele.zipMethod, emulateJar, srcJar)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700492 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700493 if err != nil {
494 z.errors <- err
495 return
496 }
497 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700498 }()
499
500 zipw := zip.NewWriter(f)
501
502 var currentWriteOpChan chan *zipEntry
503 var currentWriter io.WriteCloser
504 var currentReaders chan chan io.Reader
505 var currentReader chan io.Reader
506 var done bool
507
508 for !done {
509 var writeOpsChan chan chan *zipEntry
510 var writeOpChan chan *zipEntry
511 var readersChan chan chan io.Reader
512
513 if currentReader != nil {
514 // Only read and process errors
515 } else if currentReaders != nil {
516 readersChan = currentReaders
517 } else if currentWriteOpChan != nil {
518 writeOpChan = currentWriteOpChan
519 } else {
520 writeOpsChan = z.writeOps
521 }
522
523 select {
524 case writeOp, ok := <-writeOpsChan:
525 if !ok {
526 done = true
527 }
528
529 currentWriteOpChan = writeOp
530
531 case op := <-writeOpChan:
532 currentWriteOpChan = nil
533
Colin Crossf83c1502017-11-10 13:11:02 -0800534 var err error
Dan Willemsen017d8932016-08-04 15:43:03 -0700535 if op.fh.Method == zip.Deflate {
536 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
537 } else {
538 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700539
540 op.fh.CompressedSize64 = op.fh.UncompressedSize64
541
542 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700543 currentWriter = nopCloser{zw}
544 }
545 if err != nil {
546 return err
547 }
548
549 currentReaders = op.futureReaders
550 if op.futureReaders == nil {
551 currentWriter.Close()
552 currentWriter = nil
553 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700554 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700555
556 case futureReader, ok := <-readersChan:
557 if !ok {
558 // Done with reading
559 currentWriter.Close()
560 currentWriter = nil
561 currentReaders = nil
562 }
563
564 currentReader = futureReader
565
566 case reader := <-currentReader:
Colin Crossf83c1502017-11-10 13:11:02 -0800567 _, err := io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700568 if err != nil {
569 return err
570 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700571
572 currentReader = nil
573
Colin Crossf83c1502017-11-10 13:11:02 -0800574 case err := <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700575 return err
576 }
577 }
578
Dan Willemsen017d8932016-08-04 15:43:03 -0700579 // One last chance to catch an error
580 select {
Colin Crossf83c1502017-11-10 13:11:02 -0800581 case err := <-z.errors:
Dan Willemsen017d8932016-08-04 15:43:03 -0700582 return err
583 default:
584 zipw.Close()
585 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700586 }
Colin Cross2fe66872015-03-30 17:20:39 -0700587}
588
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700589// imports (possibly with compression) <src> into the zip at sub-path <dest>
Colin Cross9cb51db2019-06-17 14:12:41 -0700590func (z *ZipWriter) addFile(dest, src string, method uint16, emulateJar, srcJar bool) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700591 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700592 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700593
Colin Cross09f11052018-09-21 15:12:39 -0700594 var s os.FileInfo
595 var err error
596 if z.followSymlinks {
597 s, err = z.fs.Stat(src)
598 } else {
599 s, err = z.fs.Lstat(src)
600 }
601
602 if err != nil {
Colin Cross4be8f9e2018-09-28 15:16:48 -0700603 if os.IsNotExist(err) && z.ignoreMissingFiles {
604 fmt.Fprintln(z.stderr, "warning:", err)
605 return nil
606 }
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700607 return err
Colin Cross9cb51db2019-06-17 14:12:41 -0700608 }
609
610 createParentDirs := func(dest, src string) error {
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700611 if err := z.writeDirectory(filepath.Dir(dest), src, emulateJar); err != nil {
Colin Crosse5580972017-08-30 17:40:21 -0700612 return err
613 }
614
615 if prev, exists := z.createdDirs[dest]; exists {
616 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
617 }
Colin Cross7ddd08a2022-08-15 15:47:41 -0700618
619 return nil
620 }
621
622 checkDuplicateFiles := func(dest, src string) (bool, error) {
Colin Crosse5580972017-08-30 17:40:21 -0700623 if prev, exists := z.createdFiles[dest]; exists {
Colin Cross7ddd08a2022-08-15 15:47:41 -0700624 if prev != src {
625 return true, ConflictingFileError{
626 Dest: dest,
627 Prev: prev,
628 Src: src,
629 }
630 }
631 return true, nil
Colin Crosse5580972017-08-30 17:40:21 -0700632 }
633
634 z.createdFiles[dest] = src
Colin Cross7ddd08a2022-08-15 15:47:41 -0700635 return false, nil
Colin Cross9cb51db2019-06-17 14:12:41 -0700636 }
637
638 if s.IsDir() {
639 if z.directories {
640 return z.writeDirectory(dest, src, emulateJar)
641 }
642 return nil
643 } else if s.Mode()&os.ModeSymlink != 0 {
644 err = createParentDirs(dest, src)
645 if err != nil {
646 return err
647 }
648
Colin Cross7ddd08a2022-08-15 15:47:41 -0700649 duplicate, err := checkDuplicateFiles(dest, src)
650 if err != nil {
651 return err
652 }
653 if duplicate {
654 return nil
655 }
656
Colin Cross9cb51db2019-06-17 14:12:41 -0700657 return z.writeSymlink(dest, src)
658 } else if s.Mode().IsRegular() {
659 r, err := z.fs.Open(src)
660 if err != nil {
661 return err
662 }
663
664 if srcJar && filepath.Ext(src) == ".java" {
665 // rewrite the destination using the package path if it can be determined
666 pkg, err := jar.JavaPackage(r, src)
667 if err != nil {
668 // ignore errors for now, leaving the file at in its original location in the zip
669 } else {
670 dest = filepath.Join(filepath.Join(strings.Split(pkg, ".")...), filepath.Base(src))
671 }
672
673 _, err = r.Seek(0, io.SeekStart)
674 if err != nil {
675 return err
676 }
Colin Crosse5580972017-08-30 17:40:21 -0700677 }
678
Dan Willemsen017d8932016-08-04 15:43:03 -0700679 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700680 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700681
Colin Cross9cb51db2019-06-17 14:12:41 -0700682 header := &zip.FileHeader{
683 Name: dest,
684 Method: method,
685 UncompressedSize64: uint64(fileSize),
686 }
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700687
Chris Grossfa5b4e92021-06-02 12:56:08 -0700688 mode := os.FileMode(0644)
Colin Cross9cb51db2019-06-17 14:12:41 -0700689 if executable {
Chris Grossfa5b4e92021-06-02 12:56:08 -0700690 mode = 0755
Colin Cross9cb51db2019-06-17 14:12:41 -0700691 }
Colin Crosse070c3a2021-05-11 16:03:57 -0700692 header.SetMode(mode)
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700693
Colin Cross9cb51db2019-06-17 14:12:41 -0700694 err = createParentDirs(dest, src)
695 if err != nil {
696 return err
697 }
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700698
Colin Cross7ddd08a2022-08-15 15:47:41 -0700699 duplicate, err := checkDuplicateFiles(dest, src)
700 if err != nil {
701 return err
702 }
703 if duplicate {
704 return nil
705 }
706
Colin Cross9cb51db2019-06-17 14:12:41 -0700707 return z.writeFileContents(header, r)
708 } else {
709 return fmt.Errorf("%s is not a file, directory, or symlink", src)
710 }
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700711}
712
Sasha Smundak8eedba62020-11-16 19:00:27 -0800713func (z *ZipWriter) addManifest(dest string, src string, _ uint16) error {
Colin Crosse5580972017-08-30 17:40:21 -0700714 if prev, exists := z.createdDirs[dest]; exists {
715 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
716 }
717 if prev, exists := z.createdFiles[dest]; exists {
Colin Cross7ddd08a2022-08-15 15:47:41 -0700718 if prev != src {
719 return ConflictingFileError{
720 Dest: dest,
721 Prev: prev,
722 Src: src,
723 }
724 }
725 return nil
Colin Crosse5580972017-08-30 17:40:21 -0700726 }
727
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700728 if err := z.writeDirectory(filepath.Dir(dest), src, true); err != nil {
Colin Cross635acc92017-09-12 22:50:46 -0700729 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700730 }
731
Colin Cross05518bc2018-09-27 15:06:19 -0700732 var contents []byte
733 if src != "" {
734 f, err := z.fs.Open(src)
735 if err != nil {
736 return err
737 }
738
739 contents, err = ioutil.ReadAll(f)
740 f.Close()
741 if err != nil {
742 return err
743 }
744 }
745
746 fh, buf, err := jar.ManifestFileContents(contents)
Colin Cross635acc92017-09-12 22:50:46 -0700747 if err != nil {
748 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700749 }
750
Colin Cross635acc92017-09-12 22:50:46 -0700751 reader := &byteReaderCloser{bytes.NewReader(buf), ioutil.NopCloser(nil)}
752
753 return z.writeFileContents(fh, reader)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700754}
755
Colin Cross05518bc2018-09-27 15:06:19 -0700756func (z *ZipWriter) writeFileContents(header *zip.FileHeader, r pathtools.ReaderAtSeekerCloser) (err error) {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700757
758 header.SetModTime(z.time)
759
Dan Willemsen017d8932016-08-04 15:43:03 -0700760 compressChan := make(chan *zipEntry, 1)
761 z.writeOps <- compressChan
762
763 // Pre-fill a zipEntry, it will be sent in the compressChan once
764 // we're sure about the Method and CRC.
765 ze := &zipEntry{
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700766 fh: header,
Dan Willemsen10462b32017-03-15 19:02:51 -0700767 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700768
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700769 ze.allocatedSize = int64(header.UncompressedSize64)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700770 z.cpuRateLimiter.Request()
771 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700772
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700773 fileSize := int64(header.UncompressedSize64)
774 if fileSize == 0 {
775 fileSize = int64(header.UncompressedSize)
776 }
777
778 if header.Method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700779 wg := new(sync.WaitGroup)
780
781 // Allocate enough buffer to hold all readers. We'll limit
782 // this based on actual buffer sizes in RateLimit.
783 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
784
785 // Calculate the CRC in the background, since reading the entire
786 // file could take a while.
787 //
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700788 // We could split this up into chunks as well, but it's faster
Dan Willemsen017d8932016-08-04 15:43:03 -0700789 // than the compression. Due to the Go Zip API, we also need to
790 // know the result before we can begin writing the compressed
791 // data out to the zipfile.
792 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700793 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700794
795 for start := int64(0); start < fileSize; start += parallelBlockSize {
796 sr := io.NewSectionReader(r, start, parallelBlockSize)
797 resultChan := make(chan io.Reader, 1)
798 ze.futureReaders <- resultChan
799
Jeff Gaston175f34c2017-08-17 21:43:21 -0700800 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700801
802 last := !(start+parallelBlockSize < fileSize)
803 var dict []byte
804 if start >= windowSize {
805 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700806 if err != nil {
807 return err
808 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700809 }
810
811 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700812 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700813 }
814
815 close(ze.futureReaders)
816
817 // Close the file handle after all readers are done
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700818 go func(wg *sync.WaitGroup, closer io.Closer) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700819 wg.Wait()
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700820 closer.Close()
Dan Willemsen017d8932016-08-04 15:43:03 -0700821 }(wg, r)
822 } else {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700823 go func() {
824 z.compressWholeFile(ze, r, compressChan)
825 r.Close()
826 }()
Dan Willemsen017d8932016-08-04 15:43:03 -0700827 }
828
829 return nil
830}
831
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700832func (z *ZipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700833 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700834 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700835
836 crc := crc32.NewIEEE()
837 _, err := io.Copy(crc, r)
838 if err != nil {
839 z.errors <- err
840 return
841 }
842
843 ze.fh.CRC32 = crc.Sum32()
844 resultChan <- ze
845 close(resultChan)
846}
847
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700848func (z *ZipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700849 defer wg.Done()
850
851 result, err := z.compressBlock(r, dict, last)
852 if err != nil {
853 z.errors <- err
854 return
855 }
856
Jeff Gaston175f34c2017-08-17 21:43:21 -0700857 z.cpuRateLimiter.Finish()
858
Dan Willemsen017d8932016-08-04 15:43:03 -0700859 resultChan <- result
860}
861
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700862func (z *ZipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700863 buf := new(bytes.Buffer)
864 var fw *flate.Writer
865 var err error
866 if len(dict) > 0 {
867 // There's no way to Reset a Writer with a new dictionary, so
868 // don't use the Pool
869 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
870 } else {
871 var ok bool
872 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
873 fw.Reset(buf)
874 } else {
875 fw, err = flate.NewWriter(buf, z.compLevel)
876 }
877 defer z.compressorPool.Put(fw)
878 }
879 if err != nil {
880 return nil, err
881 }
882
883 _, err = io.Copy(fw, r)
884 if err != nil {
885 return nil, err
886 }
887 if last {
888 fw.Close()
889 } else {
890 fw.Flush()
891 }
892
893 return buf, nil
894}
895
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700896func (z *ZipWriter) compressWholeFile(ze *zipEntry, r io.ReadSeeker, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700897
Dan Willemsen017d8932016-08-04 15:43:03 -0700898 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700899 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700900 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700901 z.errors <- err
902 return
Colin Cross2fe66872015-03-30 17:20:39 -0700903 }
904
Dan Willemsena8b55022017-03-15 21:49:26 -0700905 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700906
Dan Willemsen017d8932016-08-04 15:43:03 -0700907 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700908 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700909 z.errors <- err
910 return
Colin Cross2fe66872015-03-30 17:20:39 -0700911 }
912
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700913 readFile := func(reader io.ReadSeeker) ([]byte, error) {
914 _, err := reader.Seek(0, 0)
Nan Zhangf281bd82017-04-25 16:47:45 -0700915 if err != nil {
916 return nil, err
917 }
918
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700919 buf, err := ioutil.ReadAll(reader)
Nan Zhangf281bd82017-04-25 16:47:45 -0700920 if err != nil {
921 return nil, err
922 }
923
924 return buf, nil
925 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700926
Dan Willemsena8b55022017-03-15 21:49:26 -0700927 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700928 futureReader := make(chan io.Reader, 1)
929 ze.futureReaders <- futureReader
930 close(ze.futureReaders)
931
Nan Zhangf281bd82017-04-25 16:47:45 -0700932 if ze.fh.Method == zip.Deflate {
933 compressed, err := z.compressBlock(r, nil, true)
934 if err != nil {
935 z.errors <- err
936 return
937 }
938 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
939 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700940 } else {
941 buf, err := readFile(r)
942 if err != nil {
943 z.errors <- err
944 return
945 }
946 ze.fh.Method = zip.Store
947 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700948 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700949 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700950 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700951 if err != nil {
952 z.errors <- err
953 return
954 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700955 ze.fh.Method = zip.Store
956 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700957 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700958
Jeff Gaston175f34c2017-08-17 21:43:21 -0700959 z.cpuRateLimiter.Finish()
960
Dan Willemsen017d8932016-08-04 15:43:03 -0700961 close(futureReader)
962
963 compressChan <- ze
964 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700965}
Colin Crosse19c7932015-04-24 15:08:38 -0700966
Colin Crosse5580972017-08-30 17:40:21 -0700967// writeDirectory annotates that dir is a directory created for the src file or directory, and adds
968// the directory entry to the zip file if directories are enabled.
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700969func (z *ZipWriter) writeDirectory(dir string, src string, emulateJar bool) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700970 // clean the input
Colin Crosse5580972017-08-30 17:40:21 -0700971 dir = filepath.Clean(dir)
Jeff Gaston2d174132017-08-15 18:05:56 -0700972
973 // discover any uncreated directories in the path
Sasha Smundak8eedba62020-11-16 19:00:27 -0800974 var zipDirs []string
Colin Crosse5580972017-08-30 17:40:21 -0700975 for dir != "" && dir != "." {
976 if _, exists := z.createdDirs[dir]; exists {
977 break
978 }
Jeff Gaston2d174132017-08-15 18:05:56 -0700979
Colin Crosse5580972017-08-30 17:40:21 -0700980 if prev, exists := z.createdFiles[dir]; exists {
981 return fmt.Errorf("destination %q is both a directory %q and a file %q", dir, src, prev)
982 }
983
984 z.createdDirs[dir] = src
Jeff Gaston2d174132017-08-15 18:05:56 -0700985 // parent directories precede their children
Colin Crosse5580972017-08-30 17:40:21 -0700986 zipDirs = append([]string{dir}, zipDirs...)
Jeff Gaston2d174132017-08-15 18:05:56 -0700987
Colin Crosse5580972017-08-30 17:40:21 -0700988 dir = filepath.Dir(dir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700989 }
990
Colin Crosse5580972017-08-30 17:40:21 -0700991 if z.directories {
992 // make a directory entry for each uncreated directory
993 for _, cleanDir := range zipDirs {
Colin Cross635acc92017-09-12 22:50:46 -0700994 var dirHeader *zip.FileHeader
Colin Crosse19c7932015-04-24 15:08:38 -0700995
Jeff Gastonc3bdc972017-10-12 12:18:19 -0700996 if emulateJar && cleanDir+"/" == jar.MetaDir {
Colin Cross635acc92017-09-12 22:50:46 -0700997 dirHeader = jar.MetaDirFileHeader()
998 } else {
999 dirHeader = &zip.FileHeader{
1000 Name: cleanDir + "/",
1001 }
Chris Grossfa5b4e92021-06-02 12:56:08 -07001002 dirHeader.SetMode(0755 | os.ModeDir)
Colin Crosse5580972017-08-30 17:40:21 -07001003 }
Jeff Gaston8edbb3a2017-08-22 20:05:28 -07001004
Colin Cross635acc92017-09-12 22:50:46 -07001005 dirHeader.SetModTime(z.time)
1006
Colin Crosse5580972017-08-30 17:40:21 -07001007 ze := make(chan *zipEntry, 1)
1008 ze <- &zipEntry{
1009 fh: dirHeader,
1010 }
1011 close(ze)
1012 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -07001013 }
Colin Crosse19c7932015-04-24 15:08:38 -07001014 }
1015
1016 return nil
1017}
Dan Willemsena59a3bc2016-08-03 17:47:23 -07001018
Jeff Gastonc3bdc972017-10-12 12:18:19 -07001019func (z *ZipWriter) writeSymlink(rel, file string) error {
Dan Willemsena59a3bc2016-08-03 17:47:23 -07001020 fileHeader := &zip.FileHeader{
1021 Name: rel,
1022 }
1023 fileHeader.SetModTime(z.time)
Colin Cross297d9bc2018-06-22 16:37:47 -07001024 fileHeader.SetMode(0777 | os.ModeSymlink)
Dan Willemsena59a3bc2016-08-03 17:47:23 -07001025
Colin Cross05518bc2018-09-27 15:06:19 -07001026 dest, err := z.fs.Readlink(file)
Dan Willemsena59a3bc2016-08-03 17:47:23 -07001027 if err != nil {
1028 return err
1029 }
1030
Colin Cross297d9bc2018-06-22 16:37:47 -07001031 fileHeader.UncompressedSize64 = uint64(len(dest))
1032 fileHeader.CRC32 = crc32.ChecksumIEEE([]byte(dest))
1033
Dan Willemsen017d8932016-08-04 15:43:03 -07001034 ze := make(chan *zipEntry, 1)
1035 futureReaders := make(chan chan io.Reader, 1)
1036 futureReader := make(chan io.Reader, 1)
1037 futureReaders <- futureReader
1038 close(futureReaders)
1039 futureReader <- bytes.NewBufferString(dest)
1040 close(futureReader)
1041
Dan Willemsen017d8932016-08-04 15:43:03 -07001042 ze <- &zipEntry{
1043 fh: fileHeader,
1044 futureReaders: futureReaders,
1045 }
1046 close(ze)
1047 z.writeOps <- ze
1048
1049 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -07001050}