Debian Codegraph @

deploy/deploy.go

raw
1 // Copyright 2019 The Hugo Authors. 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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build withdeploy
15
16 package deploy
17
18 import (
19 "bytes"
20 "compress/gzip"
21 "context"
22 "crypto/md5"
23 "encoding/hex"
24 "errors"
25 "fmt"
26 "io"
27 "mime"
28 "os"
29 "path/filepath"
30 "regexp"
31 "runtime"
32 "sort"
33 "strings"
34 "sync"
35
36 "github.com/dustin/go-humanize"
37 "github.com/gohugoio/hugo/common/hstrings"
38 "github.com/gohugoio/hugo/common/loggers"
39 "github.com/gohugoio/hugo/common/para"
40 "github.com/gohugoio/hugo/config"
41 "github.com/gohugoio/hugo/deploy/deployconfig"
42 "github.com/gohugoio/hugo/media"
43 "github.com/spf13/afero"
44 "golang.org/x/text/unicode/norm"
45
46 "gocloud.dev/blob"
47 _ "gocloud.dev/blob/fileblob" // import
48 _ "gocloud.dev/blob/gcsblob" // import
49 _ "gocloud.dev/blob/s3blob" // import
50 "gocloud.dev/gcerrors"
51 )
52
53 // Deployer supports deploying the site to target cloud providers.
54 type Deployer struct {
55 localFs afero.Fs
56 bucket *blob.Bucket
57
58 mediaTypes media.Types // Hugo's MediaType to guess ContentType
59 quiet bool // true reduces STDOUT // TODO(bep) remove, this is a global feature.
60
61 cfg deployconfig.DeployConfig
62 logger loggers.Logger
63
64 target *deployconfig.Target // the target to deploy to
65
66 // For tests...
67 summary deploySummary // summary of latest Deploy results
68 }
69
70 type deploySummary struct {
71 NumLocal, NumRemote, NumUploads, NumDeletes int
72 }
73
74 const metaMD5Hash = "md5chksum" // the meta key to store md5hash in
75
76 // New constructs a new *Deployer.
77 func New(cfg config.AllProvider, logger loggers.Logger, localFs afero.Fs) (*Deployer, error) {
78 dcfg := cfg.GetConfigSection(deployconfig.DeploymentConfigKey).(deployconfig.DeployConfig)
79 targetName := dcfg.Target
80
81 if len(dcfg.Targets) == 0 {
82 return nil, errors.New("no deployment targets found")
83 }
84 mediaTypes := cfg.GetConfigSection("mediaTypes").(media.Types)
85
86 // Find the target to deploy to.
87 var tgt *deployconfig.Target
88 if targetName == "" {
89 // Default to the first target.
90 tgt = dcfg.Targets[0]
91 } else {
92 for _, t := range dcfg.Targets {
93 if t.Name == targetName {
94 tgt = t
95 }
96 }
97 if tgt == nil {
98 return nil, fmt.Errorf("deployment target %q not found", targetName)
99 }
100 }
101
102 return &Deployer{
103 localFs: localFs,
104 target: tgt,
105 quiet: cfg.BuildExpired(),
106 mediaTypes: mediaTypes,
107 cfg: dcfg,
108 }, nil
109 }
110
111 func (d *Deployer) openBucket(ctx context.Context) (*blob.Bucket, error) {
112 if d.bucket != nil {
113 return d.bucket, nil
114 }
115 d.logger.Printf("Deploying to target %q (%s)\n", d.target.Name, d.target.URL)
116 return blob.OpenBucket(ctx, d.target.URL)
117 }
118
119 // Deploy deploys the site to a target.
120 func (d *Deployer) Deploy(ctx context.Context) error {
121 if d.logger == nil {
122 d.logger = loggers.NewDefault()
123 }
124
125 bucket, err := d.openBucket(ctx)
126 if err != nil {
127 return err
128 }
129
130 if d.cfg.Workers <= 0 {
131 d.cfg.Workers = 10
132 }
133
134 // Load local files from the source directory.
135 var include, exclude hstrings.Matcher
136 var mappath func(string) string
137 if d.target != nil {
138 include, exclude = d.target.IncludeGlob, d.target.ExcludeGlob
139 if d.target.StripIndexHTML {
140 mappath = stripIndexHTML
141 }
142 }
143 local, err := d.walkLocal(d.localFs, d.cfg.Matchers, include, exclude, d.mediaTypes, mappath)
144 if err != nil {
145 return err
146 }
147 d.logger.Infof("Found %d local files.\n", len(local))
148 d.summary.NumLocal = len(local)
149
150 // Load remote files from the target.
151 remote, err := d.walkRemote(ctx, bucket, include, exclude)
152 if err != nil {
153 return err
154 }
155 d.logger.Infof("Found %d remote files.\n", len(remote))
156 d.summary.NumRemote = len(remote)
157
158 // Diff local vs remote to see what changes need to be applied.
159 uploads, deletes := d.findDiffs(local, remote, d.cfg.Force)
160 d.summary.NumUploads = len(uploads)
161 d.summary.NumDeletes = len(deletes)
162 if len(uploads)+len(deletes) == 0 {
163 if !d.quiet {
164 d.logger.Println("No changes required.")
165 }
166 return nil
167 }
168 if !d.quiet {
169 d.logger.Println(summarizeChanges(uploads, deletes))
170 }
171
172 // Ask for confirmation before proceeding.
173 if d.cfg.Confirm && !d.cfg.DryRun {
174 fmt.Printf("Continue? (Y/n) ")
175 var confirm string
176 if _, err := fmt.Scanln(&confirm); err != nil {
177 return err
178 }
179 if confirm != "" && confirm[0] != 'y' && confirm[0] != 'Y' {
180 return errors.New("aborted")
181 }
182 }
183
184 // Order the uploads. They are organized in groups; all uploads in a group
185 // must be complete before moving on to the next group.
186 uploadGroups := applyOrdering(d.cfg.Ordering, uploads)
187
188 nParallel := d.cfg.Workers
189 var errs []error
190 var errMu sync.Mutex // protects errs
191
192 for _, uploads := range uploadGroups {
193 // Short-circuit for an empty group.
194 if len(uploads) == 0 {
195 continue
196 }
197
198 // Within the group, apply uploads in parallel.
199 sem := make(chan struct{}, nParallel)
200 for _, upload := range uploads {
201 if d.cfg.DryRun {
202 if !d.quiet {
203 d.logger.Printf("[DRY RUN] Would upload: %v\n", upload)
204 }
205 continue
206 }
207
208 sem <- struct{}{}
209 go func(upload *fileToUpload) {
210 if err := d.doSingleUpload(ctx, bucket, upload); err != nil {
211 errMu.Lock()
212 defer errMu.Unlock()
213 errs = append(errs, err)
214 }
215 <-sem
216 }(upload)
217 }
218 // Wait for all uploads in the group to finish.
219 for n := nParallel; n > 0; n-- {
220 sem <- struct{}{}
221 }
222 }
223
224 if d.cfg.MaxDeletes != -1 && len(deletes) > d.cfg.MaxDeletes {
225 d.logger.Warnf("Skipping %d deletes because it is more than --maxDeletes (%d). If this is expected, set --maxDeletes to a larger number, or -1 to disable this check.\n", len(deletes), d.cfg.MaxDeletes)
226 d.summary.NumDeletes = 0
227 } else {
228 // Apply deletes in parallel.
229 sort.Slice(deletes, func(i, j int) bool { return deletes[i] < deletes[j] })
230 sem := make(chan struct{}, nParallel)
231 for _, del := range deletes {
232 if d.cfg.DryRun {
233 if !d.quiet {
234 d.logger.Printf("[DRY RUN] Would delete %s\n", del)
235 }
236 continue
237 }
238 sem <- struct{}{}
239 go func(del string) {
240 d.logger.Infof("Deleting %s...\n", del)
241 if err := bucket.Delete(ctx, del); err != nil {
242 if gcerrors.Code(err) == gcerrors.NotFound {
243 d.logger.Warnf("Failed to delete %q because it wasn't found: %v", del, err)
244 } else {
245 errMu.Lock()
246 defer errMu.Unlock()
247 errs = append(errs, err)
248 }
249 }
250 <-sem
251 }(del)
252 }
253 // Wait for all deletes to finish.
254 for n := nParallel; n > 0; n-- {
255 sem <- struct{}{}
256 }
257 }
258
259 if len(errs) > 0 {
260 if !d.quiet {
261 d.logger.Printf("Encountered %d errors.\n", len(errs))
262 }
263 return errs[0]
264 }
265 if !d.quiet {
266 d.logger.Println("Success!")
267 }
268
269 if d.cfg.InvalidateCDN {
270 if d.target.CloudFrontDistributionID != "" {
271 if d.cfg.DryRun {
272 if !d.quiet {
273 d.logger.Printf("[DRY RUN] Would invalidate CloudFront CDN with ID %s\n", d.target.CloudFrontDistributionID)
274 }
275 } else {
276 d.logger.Println("Invalidating CloudFront CDN...")
277 if err := InvalidateCloudFront(ctx, d.target); err != nil {
278 d.logger.Printf("Failed to invalidate CloudFront CDN: %v\n", err)
279 return err
280 }
281 }
282 }
283 if d.target.GoogleCloudCDNOrigin != "" {
284 if d.cfg.DryRun {
285 if !d.quiet {
286 d.logger.Printf("[DRY RUN] Would invalidate Google Cloud CDN with origin %s\n", d.target.GoogleCloudCDNOrigin)
287 }
288 } else {
289 d.logger.Println("Invalidating Google Cloud CDN...")
290 if err := InvalidateGoogleCloudCDN(ctx, d.target.GoogleCloudCDNOrigin); err != nil {
291 d.logger.Printf("Failed to invalidate Google Cloud CDN: %v\n", err)
292 return err
293 }
294 }
295 }
296 d.logger.Println("Success!")
297 }
298 return nil
299 }
300
301 // summarizeChanges creates a text description of the proposed changes.
302 func summarizeChanges(uploads []*fileToUpload, deletes []string) string {
303 uploadSize := int64(0)
304 for _, u := range uploads {
305 uploadSize += u.Local.UploadSize
306 }
307 return fmt.Sprintf("Identified %d file(s) to upload, totaling %s, and %d file(s) to delete.", len(uploads), humanize.Bytes(uint64(uploadSize)), len(deletes))
308 }
309
310 // doSingleUpload executes a single file upload.
311 func (d *Deployer) doSingleUpload(ctx context.Context, bucket *blob.Bucket, upload *fileToUpload) error {
312 d.logger.Infof("Uploading %v...\n", upload)
313 opts := &blob.WriterOptions{
314 CacheControl: upload.Local.CacheControl(),
315 ContentEncoding: upload.Local.ContentEncoding(),
316 ContentType: upload.Local.ContentType(),
317 Metadata: map[string]string{metaMD5Hash: hex.EncodeToString(upload.Local.MD5())},
318 }
319 w, err := bucket.NewWriter(ctx, upload.Local.SlashPath, opts)
320 if err != nil {
321 return err
322 }
323 r, err := upload.Local.Reader()
324 if err != nil {
325 return err
326 }
327 defer r.Close()
328 _, err = io.Copy(w, r)
329 if err != nil {
330 return err
331 }
332 if err := w.Close(); err != nil {
333 return err
334 }
335 return nil
336 }
337
338 // localFile represents a local file from the source. Use newLocalFile to
339 // construct one.
340 type localFile struct {
341 // NativePath is the native path to the file (using file.Separator).
342 NativePath string
343 // SlashPath is NativePath converted to use /.
344 SlashPath string
345 // UploadSize is the size of the content to be uploaded. It may not
346 // be the same as the local file size if the content will be
347 // gzipped before upload.
348 UploadSize int64
349
350 fs afero.Fs
351 matcher *deployconfig.Matcher
352 md5 []byte // cache
353 gzipped bytes.Buffer // cached of gzipped contents if gzipping
354 mediaTypes media.Types
355 }
356
357 // newLocalFile initializes a *localFile.
358 func newLocalFile(fs afero.Fs, nativePath, slashpath string, m *deployconfig.Matcher, mt media.Types) (*localFile, error) {
359 f, err := fs.Open(nativePath)
360 if err != nil {
361 return nil, err
362 }
363 defer f.Close()
364 lf := &localFile{
365 NativePath: nativePath,
366 SlashPath: slashpath,
367 fs: fs,
368 matcher: m,
369 mediaTypes: mt,
370 }
371 if m != nil && m.Gzip {
372 // We're going to gzip the content. Do it once now, and cache the result
373 // in gzipped. The UploadSize is the size of the gzipped content.
374 gz := gzip.NewWriter(&lf.gzipped)
375 if _, err := io.Copy(gz, f); err != nil {
376 return nil, err
377 }
378 if err := gz.Close(); err != nil {
379 return nil, err
380 }
381 lf.UploadSize = int64(lf.gzipped.Len())
382 } else {
383 // Raw content. Just get the UploadSize.
384 info, err := f.Stat()
385 if err != nil {
386 return nil, err
387 }
388 lf.UploadSize = info.Size()
389 }
390 return lf, nil
391 }
392
393 // Reader returns an io.ReadCloser for reading the content to be uploaded.
394 // The caller must call Close on the returned ReaderCloser.
395 // The reader content may not be the same as the local file content due to
396 // gzipping.
397 func (lf *localFile) Reader() (io.ReadCloser, error) {
398 if lf.matcher != nil && lf.matcher.Gzip {
399 // We've got the gzipped contents cached in gzipped.
400 // Note: we can't use lf.gzipped directly as a Reader, since we it discards
401 // data after it is read, and we may read it more than once.
402 return io.NopCloser(bytes.NewReader(lf.gzipped.Bytes())), nil
403 }
404 // Not expected to fail since we did it successfully earlier in newLocalFile,
405 // but could happen due to changes in the underlying filesystem.
406 return lf.fs.Open(lf.NativePath)
407 }
408
409 // CacheControl returns the Cache-Control header to use for lf, based on the
410 // first matching matcher (if any).
411 func (lf *localFile) CacheControl() string {
412 if lf.matcher == nil {
413 return ""
414 }
415 return lf.matcher.CacheControl
416 }
417
418 // ContentEncoding returns the Content-Encoding header to use for lf, based
419 // on the matcher's Content-Encoding and Gzip fields.
420 func (lf *localFile) ContentEncoding() string {
421 if lf.matcher == nil {
422 return ""
423 }
424 if lf.matcher.Gzip {
425 return "gzip"
426 }
427 return lf.matcher.ContentEncoding
428 }
429
430 // ContentType returns the Content-Type header to use for lf.
431 // It first checks if there's a Content-Type header configured via a matching
432 // matcher; if not, it tries to generate one based on the filename extension.
433 // If this fails, the Content-Type will be the empty string. In this case, Go
434 // Cloud will automatically try to infer a Content-Type based on the file
435 // content.
436 func (lf *localFile) ContentType() string {
437 if lf.matcher != nil && lf.matcher.ContentType != "" {
438 return lf.matcher.ContentType
439 }
440
441 ext := filepath.Ext(lf.NativePath)
442 if mimeType, _, found := lf.mediaTypes.GetFirstBySuffix(strings.TrimPrefix(ext, ".")); found {
443 return mimeType.Type
444 }
445
446 return mime.TypeByExtension(ext)
447 }
448
449 // Force returns true if the file should be forced to re-upload based on the
450 // matching matcher.
451 func (lf *localFile) Force() bool {
452 return lf.matcher != nil && lf.matcher.Force
453 }
454
455 // MD5 returns an MD5 hash of the content to be uploaded.
456 func (lf *localFile) MD5() []byte {
457 if len(lf.md5) > 0 {
458 return lf.md5
459 }
460 h := md5.New()
461 r, err := lf.Reader()
462 if err != nil {
463 return nil
464 }
465 defer r.Close()
466 if _, err := io.Copy(h, r); err != nil {
467 return nil
468 }
469 lf.md5 = h.Sum(nil)
470 return lf.md5
471 }
472
473 // knownHiddenDirectory checks if the specified name is a well known
474 // hidden directory.
475 func knownHiddenDirectory(name string) bool {
476 knownDirectories := []string{
477 ".well-known",
478 }
479
480 for _, dir := range knownDirectories {
481 if name == dir {
482 return true
483 }
484 }
485 return false
486 }
487
488 // walkLocal walks the source directory and returns a flat list of files,
489 // using localFile.SlashPath as the map keys.
490 func (d *Deployer) walkLocal(fs afero.Fs, matchers []*deployconfig.Matcher, include, exclude hstrings.Matcher, mediaTypes media.Types, mappath func(string) string) (map[string]*localFile, error) {
491 retval := make(map[string]*localFile)
492 var mu sync.Mutex
493
494 workers := para.New(d.cfg.Workers)
495 g, _ := workers.Start(context.Background())
496
497 err := afero.Walk(fs, "", func(path string, info os.FileInfo, err error) error {
498 if err != nil {
499 return err
500 }
501 if info.IsDir() {
502 // Skip hidden directories.
503 if path != "" && strings.HasPrefix(info.Name(), ".") {
504 // Except for specific hidden directories
505 if !knownHiddenDirectory(info.Name()) {
506 return filepath.SkipDir
507 }
508 }
509 return nil
510 }
511
512 // .DS_Store is an internal MacOS attribute file; skip it.
513 if info.Name() == ".DS_Store" {
514 return nil
515 }
516
517 // Process each file in a worker
518 g.Run(func() error {
519 // When a file system is HFS+, its filepath is in NFD form.
520 if runtime.GOOS == "darwin" {
521 path = norm.NFC.String(path)
522 }
523
524 // Check include/exclude matchers.
525 slashpath := filepath.ToSlash(path)
526 if include != nil && !include.Match(slashpath) {
527 d.logger.Infof(" dropping %q due to include\n", slashpath)
528 return nil
529 }
530 if exclude != nil && exclude.Match(slashpath) {
531 d.logger.Infof(" dropping %q due to exclude\n", slashpath)
532 return nil
533 }
534
535 // Find the first matching matcher (if any).
536 var m *deployconfig.Matcher
537 for _, cur := range matchers {
538 if cur.Matches(slashpath) {
539 m = cur
540 break
541 }
542 }
543 // Apply any additional modifications to the local path, to map it to
544 // the remote path.
545 if mappath != nil {
546 slashpath = mappath(slashpath)
547 }
548 lf, err := newLocalFile(fs, path, slashpath, m, mediaTypes)
549 if err != nil {
550 return err
551 }
552 mu.Lock()
553 retval[lf.SlashPath] = lf
554 mu.Unlock()
555 return nil
556 })
557 return nil
558 })
559 if err != nil {
560 return nil, err
561 }
562 if err := g.Wait(); err != nil {
563 return nil, err
564 }
565 return retval, nil
566 }
567
568 // stripIndexHTML remaps keys matching "<dir>/index.html" to "<dir>/".
569 func stripIndexHTML(slashpath string) string {
570 const suffix = "/index.html"
571 if strings.HasSuffix(slashpath, suffix) {
572 return slashpath[:len(slashpath)-len(suffix)+1]
573 }
574 return slashpath
575 }
576
577 // walkRemote walks the target bucket and returns a flat list.
578 func (d *Deployer) walkRemote(ctx context.Context, bucket *blob.Bucket, include, exclude hstrings.Matcher) (map[string]*blob.ListObject, error) {
579 retval := map[string]*blob.ListObject{}
580 iter := bucket.List(nil)
581 for {
582 obj, err := iter.Next(ctx)
583 if err == io.EOF {
584 break
585 }
586 if err != nil {
587 return nil, err
588 }
589 // Check include/exclude matchers.
590 if include != nil && !include.Match(obj.Key) {
591 d.logger.Infof(" remote dropping %q due to include\n", obj.Key)
592 continue
593 }
594 if exclude != nil && exclude.Match(obj.Key) {
595 d.logger.Infof(" remote dropping %q due to exclude\n", obj.Key)
596 continue
597 }
598 // If the remote didn't give us an MD5, use remote attributes MD5, if that doesn't exist compute one.
599 // This can happen for some providers (e.g., fileblob, which uses the
600 // local filesystem), but not for the most common Cloud providers
601 // (S3, GCS, Azure). Although, it can happen for S3 if the blob was uploaded
602 // via a multi-part upload.
603 // Although it's unfortunate to have to read the file, it's likely better
604 // than assuming a delta and re-uploading it.
605 if len(obj.MD5) == 0 {
606 var attrMD5 []byte
607 attrs, err := bucket.Attributes(ctx, obj.Key)
608 if err == nil {
609 md5String, exists := attrs.Metadata[metaMD5Hash]
610 if exists {
611 attrMD5, _ = hex.DecodeString(md5String)
612 }
613 }
614 if len(attrMD5) == 0 {
615 r, err := bucket.NewReader(ctx, obj.Key, nil)
616 if err == nil {
617 h := md5.New()
618 if _, err := io.Copy(h, r); err == nil {
619 obj.MD5 = h.Sum(nil)
620 }
621 r.Close()
622 }
623 } else {
624 obj.MD5 = attrMD5
625 }
626 }
627 retval[obj.Key] = obj
628 }
629 return retval, nil
630 }
631
632 // uploadReason is an enum of reasons why a file must be uploaded.
633 type uploadReason string
634
635 const (
636 reasonUnknown uploadReason = "unknown"
637 reasonNotFound uploadReason = "not found at target"
638 reasonForce uploadReason = "--force"
639 reasonSize uploadReason = "size differs"
640 reasonMD5Differs uploadReason = "md5 differs"
641 reasonMD5Missing uploadReason = "remote md5 missing"
642 )
643
644 // fileToUpload represents a single local file that should be uploaded to
645 // the target.
646 type fileToUpload struct {
647 Local *localFile
648 Reason uploadReason
649 }
650
651 func (u *fileToUpload) String() string {
652 details := []string{humanize.Bytes(uint64(u.Local.UploadSize))}
653 if s := u.Local.CacheControl(); s != "" {
654 details = append(details, fmt.Sprintf("Cache-Control: %q", s))
655 }
656 if s := u.Local.ContentEncoding(); s != "" {
657 details = append(details, fmt.Sprintf("Content-Encoding: %q", s))
658 }
659 if s := u.Local.ContentType(); s != "" {
660 details = append(details, fmt.Sprintf("Content-Type: %q", s))
661 }
662 return fmt.Sprintf("%s (%s): %v", u.Local.SlashPath, strings.Join(details, ", "), u.Reason)
663 }
664
665 // findDiffs diffs localFiles vs remoteFiles to see what changes should be
666 // applied to the remote target. It returns a slice of *fileToUpload and a
667 // slice of paths for files to delete.
668 func (d *Deployer) findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.ListObject, force bool) ([]*fileToUpload, []string) {
669 var uploads []*fileToUpload
670 var deletes []string
671
672 found := map[string]bool{}
673 for path, lf := range localFiles {
674 upload := false
675 reason := reasonUnknown
676
677 if remoteFile, ok := remoteFiles[path]; ok {
678 // The file exists in remote. Let's see if we need to upload it anyway.
679
680 // TODO: We don't register a diff if the metadata (e.g., Content-Type
681 // header) has changed. This would be difficult/expensive to detect; some
682 // providers return metadata along with their "List" result, but others
683 // (notably AWS S3) do not, so gocloud.dev's blob.Bucket doesn't expose
684 // it in the list result. It would require a separate request per blob
685 // to fetch. At least for now, we work around this by documenting it and
686 // providing a "force" flag (to re-upload everything) and a "force" bool
687 // per matcher (to re-upload all files in a matcher whose headers may have
688 // changed).
689 // Idea: extract a sample set of 1 file per extension + 1 file per matcher
690 // and check those files?
691 if force {
692 upload = true
693 reason = reasonForce
694 } else if lf.Force() {
695 upload = true
696 reason = reasonForce
697 } else if lf.UploadSize != remoteFile.Size {
698 upload = true
699 reason = reasonSize
700 } else if len(remoteFile.MD5) == 0 {
701 // This shouldn't happen unless the remote didn't give us an MD5 hash
702 // from List, AND we failed to compute one by reading the remote file.
703 // Default to considering the files different.
704 upload = true
705 reason = reasonMD5Missing
706 } else if !bytes.Equal(lf.MD5(), remoteFile.MD5) {
707 upload = true
708 reason = reasonMD5Differs
709 }
710 found[path] = true
711 } else {
712 // The file doesn't exist in remote.
713 upload = true
714 reason = reasonNotFound
715 }
716 if upload {
717 d.logger.Debugf("%s needs to be uploaded: %v\n", path, reason)
718 uploads = append(uploads, &fileToUpload{lf, reason})
719 } else {
720 d.logger.Debugf("%s exists at target and does not need to be uploaded", path)
721 }
722 }
723
724 // Remote files that weren't found locally should be deleted.
725 for path := range remoteFiles {
726 if !found[path] {
727 deletes = append(deletes, path)
728 }
729 }
730 return uploads, deletes
731 }
732
733 // applyOrdering returns an ordered slice of slices of uploads.
734 //
735 // The returned slice will have length len(ordering)+1.
736 //
737 // The subslice at index i, for i = 0 ... len(ordering)-1, will have all of the
738 // uploads whose Local.SlashPath matched the regex at ordering[i] (but not any
739 // previous ordering regex).
740 // The subslice at index len(ordering) will have the remaining uploads that
741 // didn't match any ordering regex.
742 //
743 // The subslices are sorted by Local.SlashPath.
744 func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload {
745 // Sort the whole slice by Local.SlashPath first.
746 sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath })
747
748 retval := make([][]*fileToUpload, len(ordering)+1)
749 for _, u := range uploads {
750 matched := false
751 for i, re := range ordering {
752 if re.MatchString(u.Local.SlashPath) {
753 retval[i] = append(retval[i], u)
754 matched = true
755 break
756 }
757 }
758 if !matched {
759 retval[len(ordering)] = append(retval[len(ordering)], u)
760 }
761 }
762 return retval
763 }