github.com/xhghs/rclone@v1.51.1-0.20200430155106-e186a28cced8/fstest/test_all/clean.go (about)

     1  // Clean the left over test files
     2  
     3  // +build go1.11
     4  
     5  package main
     6  
     7  import (
     8  	"context"
     9  	"log"
    10  	"regexp"
    11  
    12  	"github.com/pkg/errors"
    13  	"github.com/rclone/rclone/fs"
    14  	"github.com/rclone/rclone/fs/list"
    15  	"github.com/rclone/rclone/fs/operations"
    16  )
    17  
    18  // MatchTestRemote matches the remote names used for testing (copied
    19  // from fstest/fstest.go so we don't have to import that and get all
    20  // its flags)
    21  var MatchTestRemote = regexp.MustCompile(`^rclone-test-[abcdefghijklmnopqrstuvwxyz0123456789]{24}(_segments)?$`)
    22  
    23  // cleanFs runs a single clean fs for left over directories
    24  func cleanFs(remote string) error {
    25  	f, err := fs.NewFs(remote)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	entries, err := list.DirSorted(context.Background(), f, true, "")
    30  	if err != nil {
    31  		return err
    32  	}
    33  	var lastErr error
    34  	err = entries.ForDirError(func(dir fs.Directory) error {
    35  		dirPath := dir.Remote()
    36  		fullPath := remote + dirPath
    37  		if MatchTestRemote.MatchString(dirPath) {
    38  			if *dryRun {
    39  				log.Printf("Not Purging %s - -dry-run", fullPath)
    40  				return nil
    41  			}
    42  			log.Printf("Purging %s", fullPath)
    43  			dir, err := fs.NewFs(fullPath)
    44  			if err != nil {
    45  				err = errors.Wrap(err, "NewFs failed")
    46  				lastErr = err
    47  				fs.Errorf(fullPath, "%v", err)
    48  				return nil
    49  			}
    50  			err = operations.Purge(context.Background(), dir, "")
    51  			if err != nil {
    52  				err = errors.Wrap(err, "Purge failed")
    53  				lastErr = err
    54  				fs.Errorf(dir, "%v", err)
    55  				return nil
    56  			}
    57  		}
    58  		return nil
    59  	})
    60  	if err != nil {
    61  		return err
    62  	}
    63  	return lastErr
    64  }
    65  
    66  // cleanRemotes cleans the list of remotes passed in
    67  func cleanRemotes(remotes []string) error {
    68  	var lastError error
    69  	for _, remote := range remotes {
    70  		log.Printf("%q - Cleaning", remote)
    71  		err := cleanFs(remote)
    72  		if err != nil {
    73  			lastError = err
    74  			log.Printf("Failed to purge %q: %v", remote, err)
    75  		}
    76  	}
    77  	return lastError
    78  }