blob: 740572895f6e0509f97d16c558f6c91a5bd5a001 [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
Colin Cross2fe66872015-03-30 17:20:39 -070060type fileArg struct {
Nan Zhangf281bd82017-04-25 16:47:45 -070061 pathPrefixInZip, sourcePrefixToStrip string
62 sourceFiles []string
Nan Zhang9067b042017-03-17 14:04:43 -070063}
64
65type pathMapping struct {
66 dest, src string
Nan Zhangf281bd82017-04-25 16:47:45 -070067 zipMethod uint16
68}
69
70type uniqueSet map[string]bool
71
72func (u *uniqueSet) String() string {
73 return `""`
74}
75
76func (u *uniqueSet) Set(s string) error {
77 if _, found := (*u)[s]; found {
78 return fmt.Errorf("File %q was specified twice as a file to not deflate", s)
79 } else {
80 (*u)[s] = true
81 }
82
83 return nil
Colin Cross2fe66872015-03-30 17:20:39 -070084}
85
86type fileArgs []fileArg
87
Nan Zhangf281bd82017-04-25 16:47:45 -070088type file struct{}
89
90type listFiles struct{}
91
92func (f *file) String() string {
Colin Cross2fe66872015-03-30 17:20:39 -070093 return `""`
94}
95
Nan Zhangf281bd82017-04-25 16:47:45 -070096func (f *file) Set(s string) error {
Colin Cross2fe66872015-03-30 17:20:39 -070097 if *relativeRoot == "" {
Nan Zhang9067b042017-03-17 14:04:43 -070098 return fmt.Errorf("must pass -C before -f or -l")
Colin Cross2fe66872015-03-30 17:20:39 -070099 }
100
Nan Zhangf281bd82017-04-25 16:47:45 -0700101 fArgs = append(fArgs, fileArg{
102 pathPrefixInZip: filepath.Clean(*rootPrefix),
103 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
104 sourceFiles: []string{s},
105 })
106
Colin Cross2fe66872015-03-30 17:20:39 -0700107 return nil
108}
109
Nan Zhangf281bd82017-04-25 16:47:45 -0700110func (l *listFiles) String() string {
111 return `""`
112}
113
114func (l *listFiles) Set(s string) error {
115 if *relativeRoot == "" {
116 return fmt.Errorf("must pass -C before -f or -l")
117 }
118
119 list, err := ioutil.ReadFile(s)
120 if err != nil {
121 return err
122 }
123
124 fArgs = append(fArgs, fileArg{
125 pathPrefixInZip: filepath.Clean(*rootPrefix),
126 sourcePrefixToStrip: filepath.Clean(*relativeRoot),
127 sourceFiles: strings.Split(string(list), "\n"),
128 })
129
130 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700131}
132
133var (
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700134 out = flag.String("o", "", "file to write zip file to")
135 manifest = flag.String("m", "", "input jar manifest file name")
136 directories = flag.Bool("d", false, "include directories in zip")
Nan Zhang9067b042017-03-17 14:04:43 -0700137 rootPrefix = flag.String("P", "", "path prefix within the zip at which to place files")
Colin Cross2fe66872015-03-30 17:20:39 -0700138 relativeRoot = flag.String("C", "", "path to use as relative root of files in next -f or -l argument")
Dan Willemsen017d8932016-08-04 15:43:03 -0700139 parallelJobs = flag.Int("j", runtime.NumCPU(), "number of parallel threads to use")
140 compLevel = flag.Int("L", 5, "deflate compression level (0-9)")
Jeff Gastona2976952017-08-22 17:51:25 -0700141 emulateJar = flag.Bool("jar", false, "modify the resultant .zip to emulate the output of 'jar'")
Nan Zhang9067b042017-03-17 14:04:43 -0700142
Nan Zhangf281bd82017-04-25 16:47:45 -0700143 fArgs fileArgs
144 nonDeflatedFiles = make(uniqueSet)
Dan Willemsen017d8932016-08-04 15:43:03 -0700145
146 cpuProfile = flag.String("cpuprofile", "", "write cpu profile to file")
147 traceFile = flag.String("trace", "", "write trace to file")
Colin Cross2fe66872015-03-30 17:20:39 -0700148)
149
150func init() {
Nan Zhangf281bd82017-04-25 16:47:45 -0700151 flag.Var(&listFiles{}, "l", "file containing list of .class files")
152 flag.Var(&file{}, "f", "file to include in zip")
153 flag.Var(&nonDeflatedFiles, "s", "file path to be stored within the zip without compression")
Colin Cross2fe66872015-03-30 17:20:39 -0700154}
155
156func usage() {
Dan Willemsen47ec28f2016-08-10 16:12:30 -0700157 fmt.Fprintf(os.Stderr, "usage: soong_zip -o zipfile [-m manifest] -C dir [-f|-l file]...\n")
Colin Cross2fe66872015-03-30 17:20:39 -0700158 flag.PrintDefaults()
159 os.Exit(2)
160}
161
Colin Crosse19c7932015-04-24 15:08:38 -0700162type zipWriter struct {
Colin Cross2fe66872015-03-30 17:20:39 -0700163 time time.Time
164 createdDirs map[string]bool
165 directories bool
Colin Crosse19c7932015-04-24 15:08:38 -0700166
Dan Willemsen017d8932016-08-04 15:43:03 -0700167 errors chan error
168 writeOps chan chan *zipEntry
169
Jeff Gaston175f34c2017-08-17 21:43:21 -0700170 cpuRateLimiter *CPURateLimiter
171 memoryRateLimiter *MemoryRateLimiter
Dan Willemsen017d8932016-08-04 15:43:03 -0700172
173 compressorPool sync.Pool
174 compLevel int
175}
176
177type zipEntry struct {
178 fh *zip.FileHeader
179
180 // List of delayed io.Reader
181 futureReaders chan chan io.Reader
Jeff Gaston175f34c2017-08-17 21:43:21 -0700182
183 // Only used for passing into the MemoryRateLimiter to ensure we
184 // release as much memory as much as we request
185 allocatedSize int64
Colin Cross2fe66872015-03-30 17:20:39 -0700186}
187
188func main() {
189 flag.Parse()
190
Dan Willemsen017d8932016-08-04 15:43:03 -0700191 if *cpuProfile != "" {
192 f, err := os.Create(*cpuProfile)
193 if err != nil {
194 fmt.Fprintln(os.Stderr, err.Error())
195 os.Exit(1)
196 }
197 defer f.Close()
198 pprof.StartCPUProfile(f)
199 defer pprof.StopCPUProfile()
200 }
201
202 if *traceFile != "" {
203 f, err := os.Create(*traceFile)
204 if err != nil {
205 fmt.Fprintln(os.Stderr, err.Error())
206 os.Exit(1)
207 }
208 defer f.Close()
209 err = trace.Start(f)
210 if err != nil {
211 fmt.Fprintln(os.Stderr, err.Error())
212 os.Exit(1)
213 }
214 defer trace.Stop()
215 }
216
Colin Cross2fe66872015-03-30 17:20:39 -0700217 if *out == "" {
218 fmt.Fprintf(os.Stderr, "error: -o is required\n")
219 usage()
220 }
221
Colin Crosse19c7932015-04-24 15:08:38 -0700222 w := &zipWriter{
Dan Willemsen77a6b862016-08-04 20:38:47 -0700223 time: time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC),
Colin Cross2fe66872015-03-30 17:20:39 -0700224 createdDirs: make(map[string]bool),
225 directories: *directories,
Dan Willemsen017d8932016-08-04 15:43:03 -0700226 compLevel: *compLevel,
Colin Cross2fe66872015-03-30 17:20:39 -0700227 }
228
Nan Zhang9067b042017-03-17 14:04:43 -0700229 pathMappings := []pathMapping{}
230 set := make(map[string]string)
231
Nan Zhangf281bd82017-04-25 16:47:45 -0700232 for _, fa := range fArgs {
233 for _, src := range fa.sourceFiles {
234 if err := fillPathPairs(fa.pathPrefixInZip,
235 fa.sourcePrefixToStrip, src, set, &pathMappings); err != nil {
Nan Zhang9067b042017-03-17 14:04:43 -0700236 log.Fatal(err)
237 }
238 }
239 }
240
Nan Zhang9067b042017-03-17 14:04:43 -0700241 err := w.write(*out, pathMappings, *manifest)
Colin Cross2fe66872015-03-30 17:20:39 -0700242 if err != nil {
243 fmt.Fprintln(os.Stderr, err.Error())
244 os.Exit(1)
245 }
246}
247
Nan Zhang9067b042017-03-17 14:04:43 -0700248func fillPathPairs(prefix, rel, src string, set map[string]string, pathMappings *[]pathMapping) error {
249 src = strings.TrimSpace(src)
250 if src == "" {
251 return nil
252 }
253 src = filepath.Clean(src)
254 dest, err := filepath.Rel(rel, src)
255 if err != nil {
256 return err
257 }
258 dest = filepath.Join(prefix, dest)
259
260 if _, found := set[dest]; found {
261 return fmt.Errorf("found two file paths to be copied into dest path: %q,"+
262 " both [%q]%q and [%q]%q!",
263 dest, dest, src, dest, set[dest])
264 } else {
265 set[dest] = src
266 }
267
Nan Zhangf281bd82017-04-25 16:47:45 -0700268 zipMethod := zip.Deflate
269 if _, found := nonDeflatedFiles[dest]; found {
270 zipMethod = zip.Store
271 }
272 *pathMappings = append(*pathMappings,
273 pathMapping{dest: dest, src: src, zipMethod: zipMethod})
Nan Zhang9067b042017-03-17 14:04:43 -0700274
275 return nil
276}
277
Jeff Gastona2976952017-08-22 17:51:25 -0700278func jarSort(mappings []pathMapping) {
279 less := func(i int, j int) (smaller bool) {
280 return jar.EntryNamesLess(mappings[i].dest, mappings[j].dest)
281 }
282 sort.SliceStable(mappings, less)
283}
284
Nan Zhang9067b042017-03-17 14:04:43 -0700285func (z *zipWriter) write(out string, pathMappings []pathMapping, manifest string) error {
Colin Cross2fe66872015-03-30 17:20:39 -0700286 f, err := os.Create(out)
287 if err != nil {
288 return err
289 }
290
291 defer f.Close()
292 defer func() {
293 if err != nil {
294 os.Remove(out)
295 }
296 }()
297
Dan Willemsen017d8932016-08-04 15:43:03 -0700298 z.errors = make(chan error)
299 defer close(z.errors)
Colin Cross2fe66872015-03-30 17:20:39 -0700300
Dan Willemsen017d8932016-08-04 15:43:03 -0700301 // This channel size can be essentially unlimited -- it's used as a fifo
302 // queue decouple the CPU and IO loads. Directories don't require any
303 // compression time, but still cost some IO. Similar with small files that
304 // can be very fast to compress. Some files that are more difficult to
305 // compress won't take a corresponding longer time writing out.
306 //
307 // The optimum size here depends on your CPU and IO characteristics, and
308 // the the layout of your zip file. 1000 was chosen mostly at random as
309 // something that worked reasonably well for a test file.
310 //
311 // The RateLimit object will put the upper bounds on the number of
312 // parallel compressions and outstanding buffers.
313 z.writeOps = make(chan chan *zipEntry, 1000)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700314 z.cpuRateLimiter = NewCPURateLimiter(int64(*parallelJobs))
315 z.memoryRateLimiter = NewMemoryRateLimiter(0)
316 defer func() {
317 z.cpuRateLimiter.Stop()
318 z.memoryRateLimiter.Stop()
319 }()
Jeff Gastona2976952017-08-22 17:51:25 -0700320
321 if manifest != "" {
322 if !*emulateJar {
323 return errors.New("must specify --jar when specifying a manifest via -m")
324 }
325 pathMappings = append(pathMappings, pathMapping{"META-INF/MANIFEST.MF", manifest, zip.Deflate})
326 }
327
328 if *emulateJar {
329 jarSort(pathMappings)
330 }
331
Dan Willemsen017d8932016-08-04 15:43:03 -0700332 go func() {
333 var err error
334 defer close(z.writeOps)
335
Nan Zhang9067b042017-03-17 14:04:43 -0700336 for _, ele := range pathMappings {
Nan Zhangf281bd82017-04-25 16:47:45 -0700337 err = z.writeFile(ele.dest, ele.src, ele.zipMethod)
Dan Willemsen017d8932016-08-04 15:43:03 -0700338 if err != nil {
339 z.errors <- err
340 return
341 }
342 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700343 }()
344
345 zipw := zip.NewWriter(f)
346
347 var currentWriteOpChan chan *zipEntry
348 var currentWriter io.WriteCloser
349 var currentReaders chan chan io.Reader
350 var currentReader chan io.Reader
351 var done bool
352
353 for !done {
354 var writeOpsChan chan chan *zipEntry
355 var writeOpChan chan *zipEntry
356 var readersChan chan chan io.Reader
357
358 if currentReader != nil {
359 // Only read and process errors
360 } else if currentReaders != nil {
361 readersChan = currentReaders
362 } else if currentWriteOpChan != nil {
363 writeOpChan = currentWriteOpChan
364 } else {
365 writeOpsChan = z.writeOps
366 }
367
368 select {
369 case writeOp, ok := <-writeOpsChan:
370 if !ok {
371 done = true
372 }
373
374 currentWriteOpChan = writeOp
375
376 case op := <-writeOpChan:
377 currentWriteOpChan = nil
378
379 if op.fh.Method == zip.Deflate {
380 currentWriter, err = zipw.CreateCompressedHeader(op.fh)
381 } else {
382 var zw io.Writer
Jeff Gastonc5eb66d2017-08-24 14:11:27 -0700383
384 op.fh.CompressedSize64 = op.fh.UncompressedSize64
385
386 zw, err = zipw.CreateHeaderAndroid(op.fh)
Dan Willemsen017d8932016-08-04 15:43:03 -0700387 currentWriter = nopCloser{zw}
388 }
389 if err != nil {
390 return err
391 }
392
393 currentReaders = op.futureReaders
394 if op.futureReaders == nil {
395 currentWriter.Close()
396 currentWriter = nil
397 }
Jeff Gaston175f34c2017-08-17 21:43:21 -0700398 z.memoryRateLimiter.Finish(op.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700399
400 case futureReader, ok := <-readersChan:
401 if !ok {
402 // Done with reading
403 currentWriter.Close()
404 currentWriter = nil
405 currentReaders = nil
406 }
407
408 currentReader = futureReader
409
410 case reader := <-currentReader:
Jeff Gaston175f34c2017-08-17 21:43:21 -0700411 _, err = io.Copy(currentWriter, reader)
Dan Willemsen017d8932016-08-04 15:43:03 -0700412 if err != nil {
413 return err
414 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700415
416 currentReader = nil
417
418 case err = <-z.errors:
Colin Cross2fe66872015-03-30 17:20:39 -0700419 return err
420 }
421 }
422
Dan Willemsen017d8932016-08-04 15:43:03 -0700423 // One last chance to catch an error
424 select {
425 case err = <-z.errors:
426 return err
427 default:
428 zipw.Close()
429 return nil
Colin Cross2fe66872015-03-30 17:20:39 -0700430 }
Colin Cross2fe66872015-03-30 17:20:39 -0700431}
432
Nan Zhangf281bd82017-04-25 16:47:45 -0700433func (z *zipWriter) writeFile(dest, src string, method uint16) error {
Dan Willemsen017d8932016-08-04 15:43:03 -0700434 var fileSize int64
Dan Willemsen10462b32017-03-15 19:02:51 -0700435 var executable bool
Dan Willemsen017d8932016-08-04 15:43:03 -0700436
Nan Zhang9067b042017-03-17 14:04:43 -0700437 if s, err := os.Lstat(src); err != nil {
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700438 return err
439 } else if s.IsDir() {
Colin Cross957cc4e2015-04-24 15:10:32 -0700440 if z.directories {
Nan Zhang9067b042017-03-17 14:04:43 -0700441 return z.writeDirectory(dest)
Colin Cross957cc4e2015-04-24 15:10:32 -0700442 }
443 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700444 } else if s.Mode()&os.ModeSymlink != 0 {
Nan Zhang9067b042017-03-17 14:04:43 -0700445 return z.writeSymlink(dest, src)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700446 } else if !s.Mode().IsRegular() {
Nan Zhang9067b042017-03-17 14:04:43 -0700447 return fmt.Errorf("%s is not a file, directory, or symlink", src)
Dan Willemsen017d8932016-08-04 15:43:03 -0700448 } else {
449 fileSize = s.Size()
Dan Willemsen10462b32017-03-15 19:02:51 -0700450 executable = s.Mode()&0100 != 0
Colin Cross957cc4e2015-04-24 15:10:32 -0700451 }
452
Colin Crosse19c7932015-04-24 15:08:38 -0700453 if z.directories {
Nan Zhang9067b042017-03-17 14:04:43 -0700454 dir, _ := filepath.Split(dest)
Colin Crosse19c7932015-04-24 15:08:38 -0700455 err := z.writeDirectory(dir)
456 if err != nil {
457 return err
Colin Cross2fe66872015-03-30 17:20:39 -0700458 }
459 }
460
Dan Willemsen017d8932016-08-04 15:43:03 -0700461 compressChan := make(chan *zipEntry, 1)
462 z.writeOps <- compressChan
463
464 // Pre-fill a zipEntry, it will be sent in the compressChan once
465 // we're sure about the Method and CRC.
466 ze := &zipEntry{
467 fh: &zip.FileHeader{
Nan Zhang9067b042017-03-17 14:04:43 -0700468 Name: dest,
Nan Zhangf281bd82017-04-25 16:47:45 -0700469 Method: method,
Dan Willemsen017d8932016-08-04 15:43:03 -0700470
471 UncompressedSize64: uint64(fileSize),
472 },
473 }
474 ze.fh.SetModTime(z.time)
Dan Willemsen10462b32017-03-15 19:02:51 -0700475 if executable {
476 ze.fh.SetMode(0700)
477 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700478
Nan Zhang9067b042017-03-17 14:04:43 -0700479 r, err := os.Open(src)
Dan Willemsen017d8932016-08-04 15:43:03 -0700480 if err != nil {
481 return err
482 }
483
Jeff Gaston175f34c2017-08-17 21:43:21 -0700484 ze.allocatedSize = fileSize
485 z.cpuRateLimiter.Request()
486 z.memoryRateLimiter.Request(ze.allocatedSize)
Dan Willemsen017d8932016-08-04 15:43:03 -0700487
Nan Zhangf281bd82017-04-25 16:47:45 -0700488 if method == zip.Deflate && fileSize >= minParallelFileSize {
Dan Willemsen017d8932016-08-04 15:43:03 -0700489 wg := new(sync.WaitGroup)
490
491 // Allocate enough buffer to hold all readers. We'll limit
492 // this based on actual buffer sizes in RateLimit.
493 ze.futureReaders = make(chan chan io.Reader, (fileSize/parallelBlockSize)+1)
494
495 // Calculate the CRC in the background, since reading the entire
496 // file could take a while.
497 //
498 // We could split this up into chuncks as well, but it's faster
499 // than the compression. Due to the Go Zip API, we also need to
500 // know the result before we can begin writing the compressed
501 // data out to the zipfile.
502 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700503 go z.crcFile(r, ze, compressChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700504
505 for start := int64(0); start < fileSize; start += parallelBlockSize {
506 sr := io.NewSectionReader(r, start, parallelBlockSize)
507 resultChan := make(chan io.Reader, 1)
508 ze.futureReaders <- resultChan
509
Jeff Gaston175f34c2017-08-17 21:43:21 -0700510 z.cpuRateLimiter.Request()
Dan Willemsen017d8932016-08-04 15:43:03 -0700511
512 last := !(start+parallelBlockSize < fileSize)
513 var dict []byte
514 if start >= windowSize {
515 dict, err = ioutil.ReadAll(io.NewSectionReader(r, start-windowSize, windowSize))
516 }
517
518 wg.Add(1)
Jeff Gaston175f34c2017-08-17 21:43:21 -0700519 go z.compressPartialFile(sr, dict, last, resultChan, wg)
Dan Willemsen017d8932016-08-04 15:43:03 -0700520 }
521
522 close(ze.futureReaders)
523
524 // Close the file handle after all readers are done
525 go func(wg *sync.WaitGroup, f *os.File) {
526 wg.Wait()
527 f.Close()
528 }(wg, r)
529 } else {
Jeff Gaston175f34c2017-08-17 21:43:21 -0700530 go z.compressWholeFile(ze, r, compressChan)
Dan Willemsen017d8932016-08-04 15:43:03 -0700531 }
532
533 return nil
534}
535
Jeff Gaston175f34c2017-08-17 21:43:21 -0700536func (z *zipWriter) crcFile(r io.Reader, ze *zipEntry, resultChan chan *zipEntry, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700537 defer wg.Done()
Jeff Gaston175f34c2017-08-17 21:43:21 -0700538 defer z.cpuRateLimiter.Finish()
Dan Willemsen017d8932016-08-04 15:43:03 -0700539
540 crc := crc32.NewIEEE()
541 _, err := io.Copy(crc, r)
542 if err != nil {
543 z.errors <- err
544 return
545 }
546
547 ze.fh.CRC32 = crc.Sum32()
548 resultChan <- ze
549 close(resultChan)
550}
551
Jeff Gaston175f34c2017-08-17 21:43:21 -0700552func (z *zipWriter) compressPartialFile(r io.Reader, dict []byte, last bool, resultChan chan io.Reader, wg *sync.WaitGroup) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700553 defer wg.Done()
554
555 result, err := z.compressBlock(r, dict, last)
556 if err != nil {
557 z.errors <- err
558 return
559 }
560
Jeff Gaston175f34c2017-08-17 21:43:21 -0700561 z.cpuRateLimiter.Finish()
562
Dan Willemsen017d8932016-08-04 15:43:03 -0700563 resultChan <- result
564}
565
566func (z *zipWriter) compressBlock(r io.Reader, dict []byte, last bool) (*bytes.Buffer, error) {
567 buf := new(bytes.Buffer)
568 var fw *flate.Writer
569 var err error
570 if len(dict) > 0 {
571 // There's no way to Reset a Writer with a new dictionary, so
572 // don't use the Pool
573 fw, err = flate.NewWriterDict(buf, z.compLevel, dict)
574 } else {
575 var ok bool
576 if fw, ok = z.compressorPool.Get().(*flate.Writer); ok {
577 fw.Reset(buf)
578 } else {
579 fw, err = flate.NewWriter(buf, z.compLevel)
580 }
581 defer z.compressorPool.Put(fw)
582 }
583 if err != nil {
584 return nil, err
585 }
586
587 _, err = io.Copy(fw, r)
588 if err != nil {
589 return nil, err
590 }
591 if last {
592 fw.Close()
593 } else {
594 fw.Flush()
595 }
596
597 return buf, nil
598}
599
Jeff Gaston175f34c2017-08-17 21:43:21 -0700600func (z *zipWriter) compressWholeFile(ze *zipEntry, r *os.File, compressChan chan *zipEntry) {
Dan Willemsen017d8932016-08-04 15:43:03 -0700601 defer r.Close()
602
Dan Willemsen017d8932016-08-04 15:43:03 -0700603 crc := crc32.NewIEEE()
Dan Willemsena8b55022017-03-15 21:49:26 -0700604 _, err := io.Copy(crc, r)
Colin Cross2fe66872015-03-30 17:20:39 -0700605 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700606 z.errors <- err
607 return
Colin Cross2fe66872015-03-30 17:20:39 -0700608 }
609
Dan Willemsena8b55022017-03-15 21:49:26 -0700610 ze.fh.CRC32 = crc.Sum32()
Colin Cross2fe66872015-03-30 17:20:39 -0700611
Dan Willemsen017d8932016-08-04 15:43:03 -0700612 _, err = r.Seek(0, 0)
Colin Cross2fe66872015-03-30 17:20:39 -0700613 if err != nil {
Dan Willemsen017d8932016-08-04 15:43:03 -0700614 z.errors <- err
615 return
Colin Cross2fe66872015-03-30 17:20:39 -0700616 }
617
Nan Zhangf281bd82017-04-25 16:47:45 -0700618 readFile := func(r *os.File) ([]byte, error) {
619 _, err = r.Seek(0, 0)
620 if err != nil {
621 return nil, err
622 }
623
624 buf, err := ioutil.ReadAll(r)
625 if err != nil {
626 return nil, err
627 }
628
629 return buf, nil
630 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700631
Dan Willemsena8b55022017-03-15 21:49:26 -0700632 ze.futureReaders = make(chan chan io.Reader, 1)
Dan Willemsen017d8932016-08-04 15:43:03 -0700633 futureReader := make(chan io.Reader, 1)
634 ze.futureReaders <- futureReader
635 close(ze.futureReaders)
636
Nan Zhangf281bd82017-04-25 16:47:45 -0700637 if ze.fh.Method == zip.Deflate {
638 compressed, err := z.compressBlock(r, nil, true)
639 if err != nil {
640 z.errors <- err
641 return
642 }
643 if uint64(compressed.Len()) < ze.fh.UncompressedSize64 {
644 futureReader <- compressed
Nan Zhangf281bd82017-04-25 16:47:45 -0700645 } else {
646 buf, err := readFile(r)
647 if err != nil {
648 z.errors <- err
649 return
650 }
651 ze.fh.Method = zip.Store
652 futureReader <- bytes.NewReader(buf)
Nan Zhangf281bd82017-04-25 16:47:45 -0700653 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700654 } else {
Nan Zhangf281bd82017-04-25 16:47:45 -0700655 buf, err := readFile(r)
Dan Willemsen017d8932016-08-04 15:43:03 -0700656 if err != nil {
657 z.errors <- err
658 return
659 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700660 ze.fh.Method = zip.Store
661 futureReader <- bytes.NewReader(buf)
Dan Willemsen017d8932016-08-04 15:43:03 -0700662 }
Nan Zhangf281bd82017-04-25 16:47:45 -0700663
Jeff Gaston175f34c2017-08-17 21:43:21 -0700664 z.cpuRateLimiter.Finish()
665
Dan Willemsen017d8932016-08-04 15:43:03 -0700666 close(futureReader)
667
668 compressChan <- ze
669 close(compressChan)
Colin Cross2fe66872015-03-30 17:20:39 -0700670}
Colin Crosse19c7932015-04-24 15:08:38 -0700671
672func (z *zipWriter) writeDirectory(dir string) error {
Jeff Gaston2d174132017-08-15 18:05:56 -0700673 // clean the input
674 cleanDir := filepath.Clean(dir)
675
676 // discover any uncreated directories in the path
677 zipDirs := []string{}
678 for cleanDir != "" && cleanDir != "." && !z.createdDirs[cleanDir] {
679
680 z.createdDirs[cleanDir] = true
681 // parent directories precede their children
682 zipDirs = append([]string{cleanDir}, zipDirs...)
683
684 cleanDir = filepath.Dir(cleanDir)
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700685 }
686
Jeff Gaston2d174132017-08-15 18:05:56 -0700687 // make a directory entry for each uncreated directory
688 for _, cleanDir := range zipDirs {
Colin Crosse19c7932015-04-24 15:08:38 -0700689 dirHeader := &zip.FileHeader{
Jeff Gaston2d174132017-08-15 18:05:56 -0700690 Name: cleanDir + "/",
Colin Crosse19c7932015-04-24 15:08:38 -0700691 }
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700692 dirHeader.SetMode(0700 | os.ModeDir)
Colin Crosse19c7932015-04-24 15:08:38 -0700693 dirHeader.SetModTime(z.time)
694
Dan Willemsen017d8932016-08-04 15:43:03 -0700695 ze := make(chan *zipEntry, 1)
696 ze <- &zipEntry{
697 fh: dirHeader,
Colin Crosse19c7932015-04-24 15:08:38 -0700698 }
Dan Willemsen017d8932016-08-04 15:43:03 -0700699 close(ze)
700 z.writeOps <- ze
Colin Crosse19c7932015-04-24 15:08:38 -0700701 }
702
703 return nil
704}
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700705
706func (z *zipWriter) writeSymlink(rel, file string) error {
707 if z.directories {
708 dir, _ := filepath.Split(rel)
709 if err := z.writeDirectory(dir); err != nil {
710 return err
711 }
712 }
713
714 fileHeader := &zip.FileHeader{
715 Name: rel,
716 }
717 fileHeader.SetModTime(z.time)
718 fileHeader.SetMode(0700 | os.ModeSymlink)
719
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700720 dest, err := os.Readlink(file)
721 if err != nil {
722 return err
723 }
724
Dan Willemsen017d8932016-08-04 15:43:03 -0700725 ze := make(chan *zipEntry, 1)
726 futureReaders := make(chan chan io.Reader, 1)
727 futureReader := make(chan io.Reader, 1)
728 futureReaders <- futureReader
729 close(futureReaders)
730 futureReader <- bytes.NewBufferString(dest)
731 close(futureReader)
732
Dan Willemsen017d8932016-08-04 15:43:03 -0700733 ze <- &zipEntry{
734 fh: fileHeader,
735 futureReaders: futureReaders,
736 }
737 close(ze)
738 z.writeOps <- ze
739
740 return nil
Dan Willemsena59a3bc2016-08-03 17:47:23 -0700741}