blob: cb9df9af507b41645dabc96fe56f9e08a0c145b3 [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
15package main
16
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 "flag"
22 "fmt"
Dan Willemsen017d8932016-08-04 15:43:03 -070023 "hash/crc32"
Colin Cross2fe66872015-03-30 17:20:39 -070024 "io"
25 "io/ioutil"
Nan Zhang9067b042017-03-17 14:04:43 -070026 "log"
Colin Cross2fe66872015-03-30 17:20:39 -070027 "os"
28 "path/filepath"
Dan Willemsen017d8932016-08-04 15:43:03 -070029 "runtime"
30 "runtime/pprof"
31 "runtime/trace"
Jeff Gastona2976952017-08-22 17:51:25 -070032 "sort"
Colin Cross2fe66872015-03-30 17:20:39 -070033 "strings"
Dan Willemsen017d8932016-08-04 15:43:03 -070034 "sync"
Colin Cross2fe66872015-03-30 17:20:39 -070035 "time"
Dan Willemsen017d8932016-08-04 15:43:03 -070036
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
Colin Cross2fe66872015-03-30 17:20:39 -070065type fileArg struct {
Nan Zhangf281bd82017-04-25 16:47:45 -070066 pathPrefixInZip, sourcePrefixToStrip string
67 sourceFiles []string
Colin Cross7b10cf12017-08-30 14:12:21 -070068 globDir string
Nan Zhang9067b042017-03-17 14:04:43 -070069}
70
71type pathMapping struct {
72 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070073 zipMethod uint16
74}
75
76type uniqueSet map[string]bool
77
78func (u *uniqueSet) String() string {
79 return `""`
80}
81
82func (u *uniqueSet) Set(s string) error {
83 if _, found := (*u)[s]; found {
84 return fmt.Errorf("File %q was specified twice as a file to not deflate", s)
85 } else {
86 (*u)[s] = true
87 }
88
89 return nil
Colin Cross2fe66872015-03-30 17:20:39 -070090}
91
92type fileArgs []fileArg
93
Nan Zhangf281bd82017-04-25 16:47:45 -070094type file struct{}
95
96type listFiles struct{}
97
Colin Cross7b10cf12017-08-30 14:12:21 -070098type dir struct{}
99
Nan Zhangf281bd82017-04-25 16:47:45 -0700100func (f *file) String() string {
Colin Cross2fe66872015-03-30 17:20:39 -0700101 return `""`
102}
103
Nan Zhangf281bd82017-04-25 16:47:45 -0700104func (f *file) Set(s string) error {
Colin Cross2fe66872015-03-30 17:20:39 -0700105 if *relativeRoot == "" {
Colin Cross7b10cf12017-08-30 14:12:21 -0700106 return fmt.Errorf("must pass -C before -f")
Colin Cross2fe66872015-03-30 17:20:39 -0700107 }
108
Nan Zhangf281bd82017-04-25 16:47:45 -0700109 fArgs = append(fArgs, fileArg{
110 pathPrefixInZip: filepath.Clean(*rootPrefix),
111 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
112 sourceFiles: []string{s},
113 })
114
Colin Cross2fe66872015-03-30 17:20:39 -0700115 return nil
116}
117
Nan Zhangf281bd82017-04-25 16:47:45 -0700118func (l *listFiles) String() string {
119 return `""`
120}
121
122func (l *listFiles) Set(s string) error {
123 if *relativeRoot == "" {
Colin Cross7b10cf12017-08-30 14:12:21 -0700124 return fmt.Errorf("must pass -C before -l")
Nan Zhangf281bd82017-04-25 16:47:45 -0700125 }
126
127 list, err := ioutil.ReadFile(s)
128 if err != nil {
129 return err
130 }
131
132 fArgs = append(fArgs, fileArg{
133 pathPrefixInZip: filepath.Clean(*rootPrefix),
134 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
135 sourceFiles: strings.Split(string(list), "\n"),
136 })
137
138 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700139}
140
Colin Cross7b10cf12017-08-30 14:12:21 -0700141func (d *dir) String() string {
142 return `""`
143}
144
145func (d *dir) Set(s string) error {
146 if *relativeRoot == "" {
147 return fmt.Errorf("must pass -C before -D")
148 }
149
150 fArgs = append(fArgs, fileArg{
151 pathPrefixInZip: filepath.Clean(*rootPrefix),
152 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
153 globDir: filepath.Clean(s),
154 })
155
156 return nil
157}
158
Colin Cross2fe66872015-03-30 17:20:39 -0700159var (
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700160 out = flag.String("o", "", "file to write zip file to")
161 manifest = flag.String("m", "", "input jar manifest file name")
162 directories = flag.Bool("d", false, "include directories in zip")
Nan Zhang9067b042017-03-17 14:04:43 -0700163 rootPrefix = flag.String("P", "", "path prefix within the zip at which to place files")
Colin Cross7b10cf12017-08-30 14:12:21 -0700164 relativeRoot = flag.String("C", "", "path to use as relative root of files in following -f, -l, or -D arguments")
Dan Willemsen017d8932016-08-04 15:43:03 -0700165 parallelJobs = flag.Int("j", runtime.NumCPU(), "number of parallel threads to use")
166 compLevel = flag.Int("L", 5, "deflate compression level (0-9)")
Jeff Gastona2976952017-08-22 17:51:25 -0700167 emulateJar = flag.Bool("jar", false, "modify the resultant .zip to emulate the output of 'jar'")
Nan Zhang9067b042017-03-17 14:04:43 -0700168
Nan Zhangf281bd82017-04-25 16:47:45 -0700169 fArgs fileArgs
170 nonDeflatedFiles = make(uniqueSet)
Dan Willemsen017d8932016-08-04 15:43:03 -0700171
172 cpuProfile = flag.String("cpuprofile", "", "write cpu profile to file")
173 traceFile = flag.String("trace", "", "write trace to file")
Colin Cross2fe66872015-03-30 17:20:39 -0700174)
175
176func init() {
Nan Zhangf281bd82017-04-25 16:47:45 -0700177 flag.Var(&listFiles{}, "l", "file containing list of .class files")
Colin Cross7b10cf12017-08-30 14:12:21 -0700178 flag.Var(&dir{}, "D", "directory to include in zip")
Nan Zhangf281bd82017-04-25 16:47:45 -0700179 flag.Var(&file{}, "f", "file to include in zip")
180 flag.Var(&nonDeflatedFiles, "s", "file path to be stored within the zip without compression")
Colin Cross2fe66872015-03-30 17:20:39 -0700181}
182
183func usage() {
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700184 fmt.Fprintf(os.Stderr, "usage: soong_zip -o zipfile [-m manifest] -C dir [-f|-l file]...\n")
Colin Cross2fe66872015-03-30 17:20:39 -0700185 flag.PrintDefaults()
186 os.Exit(2)
187}
188
Colin Crosse19c7932015-04-24 15:08:38 -0700189type zipWriter struct {
Colin Crosse5580972017-08-30 17:40:21 -0700190 time time.Time
191 createdFiles map[string]string
192 createdDirs map[string]string
193 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700194
Dan Willemsen017d8932016-08-04 15:43:03 -0700195 errors chan error
196 writeOps chan chan *zipEntry
197
Jeff Gaston175f34c2017-08-17 21:43:21 -0700198 cpuRateLimiter *CPURateLimiter
199 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700200
201 compressorPool sync.Pool
202 compLevel int
203}
204
205type zipEntry struct {
206 fh *zip.FileHeader
207
208 // List of delayed io.Reader
209 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700210
211 // Only used for passing into the MemoryRateLimiter to ensure we
212 // release as much memory as much as we request
213 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700214}
215
216func main() {
217 flag.Parse()
218
Dan Willemsen017d8932016-08-04 15:43:03 -0700219 if *cpuProfile != "" {
220 f, err := os.Create(*cpuProfile)
221 if err != nil {
222 fmt.Fprintln(os.Stderr, err.Error())
223 os.Exit(1)
224 }
225 defer f.Close()
226 pprof.StartCPUProfile(f)
227 defer pprof.StopCPUProfile()
228 }
229
230 if *traceFile != "" {
231 f, err := os.Create(*traceFile)
232 if err != nil {
233 fmt.Fprintln(os.Stderr, err.Error())
234 os.Exit(1)
235 }
236 defer f.Close()
237 err = trace.Start(f)
238 if err != nil {
239 fmt.Fprintln(os.Stderr, err.Error())
240 os.Exit(1)
241 }
242 defer trace.Stop()
243 }
244
Colin Cross2fe66872015-03-30 17:20:39 -0700245 if *out == "" {
246 fmt.Fprintf(os.Stderr, "error: -o is required\n")
247 usage()
248 }
249
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700250 if *emulateJar {
251 *directories = true
252 }
253
Colin Crosse19c7932015-04-24 15:08:38 -0700254 w := &zipWriter{
Colin Cross635acc92017-09-12 22:50:46 -0700255 time: jar.DefaultTime,
Colin Crosse5580972017-08-30 17:40:21 -0700256 createdDirs: make(map[string]string),
257 createdFiles: make(map[string]string),
258 directories: *directories,
259 compLevel: *compLevel,
Colin Cross2fe66872015-03-30 17:20:39 -0700260 }
261
Nan Zhang9067b042017-03-17 14:04:43 -0700262 pathMappings := []pathMapping{}
Nan Zhang9067b042017-03-17 14:04:43 -0700263
Nan Zhangf281bd82017-04-25 16:47:45 -0700264 for _, fa := range fArgs {
Colin Cross7b10cf12017-08-30 14:12:21 -0700265 srcs := fa.sourceFiles
266 if fa.globDir != "" {
267 srcs = append(srcs, recursiveGlobFiles(fa.globDir)...)
268 }
269 for _, src := range srcs {
Nan Zhangf281bd82017-04-25 16:47:45 -0700270 if err := fillPathPairs(fa.pathPrefixInZip,
Colin Crosse5580972017-08-30 17:40:21 -0700271 fa.sourcePrefixToStrip, src, &pathMappings); err != nil {
Nan Zhang9067b042017-03-17 14:04:43 -0700272 log.Fatal(err)
273 }
274 }
275 }
276
Nan Zhang9067b042017-03-17 14:04:43 -0700277 err := w.write(*out, pathMappings, *manifest)
Colin Cross2fe66872015-03-30 17:20:39 -0700278 if err != nil {
279 fmt.Fprintln(os.Stderr, err.Error())
280 os.Exit(1)
281 }
282}
283
Colin Crosse5580972017-08-30 17:40:21 -0700284func fillPathPairs(prefix, rel, src string, pathMappings *[]pathMapping) error {
Nan Zhang9067b042017-03-17 14:04:43 -0700285 src = strings.TrimSpace(src)
286 if src == "" {
287 return nil
288 }
289 src = filepath.Clean(src)
290 dest, err := filepath.Rel(rel, src)
291 if err != nil {
292 return err
293 }
294 dest = filepath.Join(prefix, dest)
295
Nan Zhangf281bd82017-04-25 16:47:45 -0700296 zipMethod := zip.Deflate
297 if _, found := nonDeflatedFiles[dest]; found {
298 zipMethod = zip.Store
299 }
300 *pathMappings = append(*pathMappings,
301 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700302
303 return nil
304}
305
Jeff Gastona2976952017-08-22 17:51:25 -0700306func jarSort(mappings []pathMapping) {
307 less := func(i int, j int) (smaller bool) {
308 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
309 }
310 sort.SliceStable(mappings, less)
311}
312
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700313type readerSeekerCloser interface {
314 io.Reader
315 io.ReaderAt
316 io.Closer
317 io.Seeker
318}
319
Nan Zhang9067b042017-03-17 14:04:43 -0700320func (z *zipWriter) write(out string, pathMappings []pathMapping, manifest string) error {
Colin Cross2fe66872015-03-30 17:20:39 -0700321 f, err := os.Create(out)
322 if err != nil {
323 return err
324 }
325
326 defer f.Close()
327 defer func() {
328 if err != nil {
329 os.Remove(out)
330 }
331 }()
332
Dan Willemsen017d8932016-08-04 15:43:03 -0700333 z.errors = make(chan error)
334 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700335
Dan Willemsen017d8932016-08-04 15:43:03 -0700336 // This channel size can be essentially unlimited -- it's used as a fifo
337 // queue decouple the CPU and IO loads. Directories don't require any
338 // compression time, but still cost some IO. Similar with small files that
339 // can be very fast to compress. Some files that are more difficult to
340 // compress won't take a corresponding longer time writing out.
341 //
342 // The optimum size here depends on your CPU and IO characteristics, and
343 // the the layout of your zip file. 1000 was chosen mostly at random as
344 // something that worked reasonably well for a test file.
345 //
346 // The RateLimit object will put the upper bounds on the number of
347 // parallel compressions and outstanding buffers.
348 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700349 z.cpuRateLimiter = NewCPURateLimiter(int64(*parallelJobs))
350 z.memoryRateLimiter = NewMemoryRateLimiter(0)
351 defer func() {
352 z.cpuRateLimiter.Stop()
353 z.memoryRateLimiter.Stop()
354 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700355
Colin Cross635acc92017-09-12 22:50:46 -0700356 if manifest != "" && !*emulateJar {
357 return errors.New("must specify --jar when specifying a manifest via -m")
Jeff Gastona2976952017-08-22 17:51:25 -0700358 }
359
360 if *emulateJar {
Colin Cross635acc92017-09-12 22:50:46 -0700361 // manifest may be empty, in which case addManifest will fill in a default
362 pathMappings = append(pathMappings, pathMapping{jar.ManifestFile, manifest, zip.Deflate})
363
Jeff Gastona2976952017-08-22 17:51:25 -0700364 jarSort(pathMappings)
365 }
366
Dan Willemsen017d8932016-08-04 15:43:03 -0700367 go func() {
368 var err error
369 defer close(z.writeOps)
370
Nan Zhang9067b042017-03-17 14:04:43 -0700371 for _, ele := range pathMappings {
Colin Cross34540312017-09-06 12:52:37 -0700372 if *emulateJar && ele.dest == jar.ManifestFile {
Jeff Gastoncef50b92017-08-23 15:41:35 -0700373 err = z.addManifest(ele.dest, ele.src, ele.zipMethod)
374 } else {
375 err = z.addFile(ele.dest, ele.src, ele.zipMethod)
376 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700377 if err != nil {
378 z.errors <- err
379 return
380 }
381 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700382 }()
383
384 zipw := zip.NewWriter(f)
385
386 var currentWriteOpChan chan *zipEntry
387 var currentWriter io.WriteCloser
388 var currentReaders chan chan io.Reader
389 var currentReader chan io.Reader
390 var done bool
391
392 for !done {
393 var writeOpsChan chan chan *zipEntry
394 var writeOpChan chan *zipEntry
395 var readersChan chan chan io.Reader
396
397 if currentReader != nil {
398 // Only read and process errors
399 } else if currentReaders != nil {
400 readersChan = currentReaders
401 } else if currentWriteOpChan != nil {
402 writeOpChan = currentWriteOpChan
403 } else {
404 writeOpsChan = z.writeOps
405 }
406
407 select {
408 case writeOp, ok := <-writeOpsChan:
409 if !ok {
410 done = true
411 }
412
413 currentWriteOpChan = writeOp
414
415 case op := <-writeOpChan:
416 currentWriteOpChan = nil
417
418 if op.fh.Method == zip.Deflate {
419 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
420 } else {
421 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700422
423 op.fh.CompressedSize64 = op.fh.UncompressedSize64
424
425 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700426 currentWriter = nopCloser{zw}
427 }
428 if err != nil {
429 return err
430 }
431
432 currentReaders = op.futureReaders
433 if op.futureReaders == nil {
434 currentWriter.Close()
435 currentWriter = nil
436 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700437 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700438
439 case futureReader, ok := <-readersChan:
440 if !ok {
441 // Done with reading
442 currentWriter.Close()
443 currentWriter = nil
444 currentReaders = nil
445 }
446
447 currentReader = futureReader
448
449 case reader := <-currentReader:
Jeff Gaston175f34c2017-08-17 21:43:21 -0700450 _, err = io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700451 if err != nil {
452 return err
453 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700454
455 currentReader = nil
456
457 case err = <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700458 return err
459 }
460 }
461
Dan Willemsen017d8932016-08-04 15:43:03 -0700462 // One last chance to catch an error
463 select {
464 case err = <-z.errors:
465 return err
466 default:
467 zipw.Close()
468 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700469 }
Colin Cross2fe66872015-03-30 17:20:39 -0700470}
471
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700472// imports (possibly with compression) <src> into the zip at sub-path <dest>
Jeff Gastoncef50b92017-08-23 15:41:35 -0700473func (z *zipWriter) addFile(dest, src string, method uint16) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700474 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700475 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700476
Nan Zhang9067b042017-03-17 14:04:43 -0700477 if s, err := os.Lstat(src); err != nil {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700478 return err
479 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700480 if z.directories {
Colin Crosse5580972017-08-30 17:40:21 -0700481 return z.writeDirectory(dest, src)
Colin Cross957cc4e2015-04-24 15:10:32 -0700482 }
483 return nil
Dan Willemsen017d8932016-08-04 15:43:03 -0700484 } else {
Colin Crosse5580972017-08-30 17:40:21 -0700485 if err := z.writeDirectory(filepath.Dir(dest), src); err != nil {
486 return err
487 }
488
489 if prev, exists := z.createdDirs[dest]; exists {
490 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
491 }
492 if prev, exists := z.createdFiles[dest]; exists {
493 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
494 }
495
496 z.createdFiles[dest] = src
497
498 if s.Mode()&os.ModeSymlink != 0 {
499 return z.writeSymlink(dest, src)
500 } else if !s.Mode().IsRegular() {
501 return fmt.Errorf("%s is not a file, directory, or symlink", src)
502 }
503
Dan Willemsen017d8932016-08-04 15:43:03 -0700504 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700505 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700506 }
507
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700508 r, err := os.Open(src)
509 if err != nil {
510 return err
511 }
512
513 header := &zip.FileHeader{
514 Name: dest,
515 Method: method,
516 UncompressedSize64: uint64(fileSize),
517 }
518
519 if executable {
520 header.SetMode(0700)
521 }
522
523 return z.writeFileContents(header, r)
524}
525
Jeff Gastoncef50b92017-08-23 15:41:35 -0700526func (z *zipWriter) addManifest(dest string, src string, method uint16) error {
Colin Crosse5580972017-08-30 17:40:21 -0700527 if prev, exists := z.createdDirs[dest]; exists {
528 return fmt.Errorf("destination %q is both a directory %q and a file %q", dest, prev, src)
529 }
530 if prev, exists := z.createdFiles[dest]; exists {
531 return fmt.Errorf("destination %q has two files %q and %q", dest, prev, src)
532 }
533
Colin Cross635acc92017-09-12 22:50:46 -0700534 if err := z.writeDirectory(filepath.Dir(dest), src); err != nil {
535 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700536 }
537
Colin Cross635acc92017-09-12 22:50:46 -0700538 fh, buf, err := jar.ManifestFileContents(src)
539 if err != nil {
540 return err
Jeff Gastoncef50b92017-08-23 15:41:35 -0700541 }
542
Colin Cross635acc92017-09-12 22:50:46 -0700543 reader := &byteReaderCloser{bytes.NewReader(buf), ioutil.NopCloser(nil)}
544
545 return z.writeFileContents(fh, reader)
Jeff Gastoncef50b92017-08-23 15:41:35 -0700546}
547
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700548func (z *zipWriter) writeFileContents(header *zip.FileHeader, r readerSeekerCloser) (err error) {
549
550 header.SetModTime(z.time)
551
Dan Willemsen017d8932016-08-04 15:43:03 -0700552 compressChan := make(chan *zipEntry, 1)
553 z.writeOps <- compressChan
554
555 // Pre-fill a zipEntry, it will be sent in the compressChan once
556 // we're sure about the Method and CRC.
557 ze := &zipEntry{
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700558 fh: header,
Dan Willemsen10462b32017-03-15 19:02:51 -0700559 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700560
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700561 ze.allocatedSize = int64(header.UncompressedSize64)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700562 z.cpuRateLimiter.Request()
563 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700564
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700565 fileSize := int64(header.UncompressedSize64)
566 if fileSize == 0 {
567 fileSize = int64(header.UncompressedSize)
568 }
569
570 if header.Method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700571 wg := new(sync.WaitGroup)
572
573 // Allocate enough buffer to hold all readers. We'll limit
574 // this based on actual buffer sizes in RateLimit.
575 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
576
577 // Calculate the CRC in the background, since reading the entire
578 // file could take a while.
579 //
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700580 // We could split this up into chunks as well, but it's faster
Dan Willemsen017d8932016-08-04 15:43:03 -0700581 // than the compression. Due to the Go Zip API, we also need to
582 // know the result before we can begin writing the compressed
583 // data out to the zipfile.
584 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700585 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700586
587 for start := int64(0); start < fileSize; start += parallelBlockSize {
588 sr := io.NewSectionReader(r, start, parallelBlockSize)
589 resultChan := make(chan io.Reader, 1)
590 ze.futureReaders <- resultChan
591
Jeff Gaston175f34c2017-08-17 21:43:21 -0700592 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700593
594 last := !(start+parallelBlockSize < fileSize)
595 var dict []byte
596 if start >= windowSize {
597 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700598 if err != nil {
599 return err
600 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700601 }
602
603 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700604 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700605 }
606
607 close(ze.futureReaders)
608
609 // Close the file handle after all readers are done
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700610 go func(wg *sync.WaitGroup, closer io.Closer) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700611 wg.Wait()
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700612 closer.Close()
Dan Willemsen017d8932016-08-04 15:43:03 -0700613 }(wg, r)
614 } else {
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700615 go func() {
616 z.compressWholeFile(ze, r, compressChan)
617 r.Close()
618 }()
Dan Willemsen017d8932016-08-04 15:43:03 -0700619 }
620
621 return nil
622}
623
Jeff Gaston175f34c2017-08-17 21:43:21 -0700624func (z *zipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700625 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700626 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700627
628 crc := crc32.NewIEEE()
629 _, err := io.Copy(crc, r)
630 if err != nil {
631 z.errors <- err
632 return
633 }
634
635 ze.fh.CRC32 = crc.Sum32()
636 resultChan <- ze
637 close(resultChan)
638}
639
Jeff Gaston175f34c2017-08-17 21:43:21 -0700640func (z *zipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700641 defer wg.Done()
642
643 result, err := z.compressBlock(r, dict, last)
644 if err != nil {
645 z.errors <- err
646 return
647 }
648
Jeff Gaston175f34c2017-08-17 21:43:21 -0700649 z.cpuRateLimiter.Finish()
650
Dan Willemsen017d8932016-08-04 15:43:03 -0700651 resultChan <- result
652}
653
654func (z *zipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
655 buf := new(bytes.Buffer)
656 var fw *flate.Writer
657 var err error
658 if len(dict) > 0 {
659 // There's no way to Reset a Writer with a new dictionary, so
660 // don't use the Pool
661 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
662 } else {
663 var ok bool
664 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
665 fw.Reset(buf)
666 } else {
667 fw, err = flate.NewWriter(buf, z.compLevel)
668 }
669 defer z.compressorPool.Put(fw)
670 }
671 if err != nil {
672 return nil, err
673 }
674
675 _, err = io.Copy(fw, r)
676 if err != nil {
677 return nil, err
678 }
679 if last {
680 fw.Close()
681 } else {
682 fw.Flush()
683 }
684
685 return buf, nil
686}
687
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700688func (z *zipWriter) compressWholeFile(ze *zipEntry, r io.ReadSeeker, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700689
Dan Willemsen017d8932016-08-04 15:43:03 -0700690 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700691 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700692 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700693 z.errors <- err
694 return
Colin Cross2fe66872015-03-30 17:20:39 -0700695 }
696
Dan Willemsena8b55022017-03-15 21:49:26 -0700697 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700698
Dan Willemsen017d8932016-08-04 15:43:03 -0700699 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700700 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700701 z.errors <- err
702 return
Colin Cross2fe66872015-03-30 17:20:39 -0700703 }
704
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700705 readFile := func(reader io.ReadSeeker) ([]byte, error) {
706 _, err := reader.Seek(0, 0)
Nan Zhangf281bd82017-04-25 16:47:45 -0700707 if err != nil {
708 return nil, err
709 }
710
Jeff Gaston66dd6e52017-08-23 15:12:48 -0700711 buf, err := ioutil.ReadAll(reader)
Nan Zhangf281bd82017-04-25 16:47:45 -0700712 if err != nil {
713 return nil, err
714 }
715
716 return buf, nil
717 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700718
Dan Willemsena8b55022017-03-15 21:49:26 -0700719 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700720 futureReader := make(chan io.Reader, 1)
721 ze.futureReaders <- futureReader
722 close(ze.futureReaders)
723
Nan Zhangf281bd82017-04-25 16:47:45 -0700724 if ze.fh.Method == zip.Deflate {
725 compressed, err := z.compressBlock(r, nil, true)
726 if err != nil {
727 z.errors <- err
728 return
729 }
730 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
731 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700732 } else {
733 buf, err := readFile(r)
734 if err != nil {
735 z.errors <- err
736 return
737 }
738 ze.fh.Method = zip.Store
739 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700740 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700741 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700742 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700743 if err != nil {
744 z.errors <- err
745 return
746 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700747 ze.fh.Method = zip.Store
748 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700749 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700750
Jeff Gaston175f34c2017-08-17 21:43:21 -0700751 z.cpuRateLimiter.Finish()
752
Dan Willemsen017d8932016-08-04 15:43:03 -0700753 close(futureReader)
754
755 compressChan <- ze
756 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700757}
Colin Crosse19c7932015-04-24 15:08:38 -0700758
Colin Crosse5580972017-08-30 17:40:21 -0700759// writeDirectory annotates that dir is a directory created for the src file or directory, and adds
760// the directory entry to the zip file if directories are enabled.
761func (z *zipWriter) writeDirectory(dir, src string) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700762 // clean the input
Colin Crosse5580972017-08-30 17:40:21 -0700763 dir = filepath.Clean(dir)
Jeff Gaston2d174132017-08-15 18:05:56 -0700764
765 // discover any uncreated directories in the path
766 zipDirs := []string{}
Colin Crosse5580972017-08-30 17:40:21 -0700767 for dir != "" && dir != "." {
768 if _, exists := z.createdDirs[dir]; exists {
769 break
770 }
Jeff Gaston2d174132017-08-15 18:05:56 -0700771
Colin Crosse5580972017-08-30 17:40:21 -0700772 if prev, exists := z.createdFiles[dir]; exists {
773 return fmt.Errorf("destination %q is both a directory %q and a file %q", dir, src, prev)
774 }
775
776 z.createdDirs[dir] = src
Jeff Gaston2d174132017-08-15 18:05:56 -0700777 // parent directories precede their children
Colin Crosse5580972017-08-30 17:40:21 -0700778 zipDirs = append([]string{dir}, zipDirs...)
Jeff Gaston2d174132017-08-15 18:05:56 -0700779
Colin Crosse5580972017-08-30 17:40:21 -0700780 dir = filepath.Dir(dir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700781 }
782
Colin Crosse5580972017-08-30 17:40:21 -0700783 if z.directories {
784 // make a directory entry for each uncreated directory
785 for _, cleanDir := range zipDirs {
Colin Cross635acc92017-09-12 22:50:46 -0700786 var dirHeader *zip.FileHeader
Colin Crosse19c7932015-04-24 15:08:38 -0700787
Colin Cross635acc92017-09-12 22:50:46 -0700788 if *emulateJar && cleanDir+"/" == jar.MetaDir {
789 dirHeader = jar.MetaDirFileHeader()
790 } else {
791 dirHeader = &zip.FileHeader{
792 Name: cleanDir + "/",
793 }
794 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse5580972017-08-30 17:40:21 -0700795 }
Jeff Gaston8edbb3a2017-08-22 20:05:28 -0700796
Colin Cross635acc92017-09-12 22:50:46 -0700797 dirHeader.SetModTime(z.time)
798
Colin Crosse5580972017-08-30 17:40:21 -0700799 ze := make(chan *zipEntry, 1)
800 ze <- &zipEntry{
801 fh: dirHeader,
802 }
803 close(ze)
804 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700805 }
Colin Crosse19c7932015-04-24 15:08:38 -0700806 }
807
808 return nil
809}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700810
811func (z *zipWriter) writeSymlink(rel, file string) error {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700812 fileHeader := &zip.FileHeader{
813 Name: rel,
814 }
815 fileHeader.SetModTime(z.time)
816 fileHeader.SetMode(0700 | os.ModeSymlink)
817
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700818 dest, err := os.Readlink(file)
819 if err != nil {
820 return err
821 }
822
Dan Willemsen017d8932016-08-04 15:43:03 -0700823 ze := make(chan *zipEntry, 1)
824 futureReaders := make(chan chan io.Reader, 1)
825 futureReader := make(chan io.Reader, 1)
826 futureReaders <- futureReader
827 close(futureReaders)
828 futureReader <- bytes.NewBufferString(dest)
829 close(futureReader)
830
Dan Willemsen017d8932016-08-04 15:43:03 -0700831 ze <- &zipEntry{
832 fh: fileHeader,
833 futureReaders: futureReaders,
834 }
835 close(ze)
836 z.writeOps <- ze
837
838 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700839}
Colin Cross7b10cf12017-08-30 14:12:21 -0700840
841func recursiveGlobFiles(path string) []string {
842 var files []string
843 filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
844 if !info.IsDir() {
845 files = append(files, path)
846 }
847 return nil
848 })
849
850 return files
851}