Compare commits

..
Author SHA1 Message Date
Nick Craig-Wood 13a1d23bb8 mega: fix nil pointer panic when login with session keys fails - fixes #9232
When LoginWithKeys failed (e.g. after clearing Mega trash or with a
stale session), the error was silently ignored and only logged at debug
level. This left the filesystem uninitialized so GetRoot() returned
nil, causing a nil pointer dereference panic in findDir.

This returns the login error instead of swallowing it, and adds a nil
check for GetRoot() in findRoot, and adds defensive nil node checks in
findDir and findObject.
2026-03-05 12:30:43 +00:00
28 changed files with 223 additions and 1289 deletions

No files matched your search

@@ -100,7 +100,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: manifest,manifest-descriptor # Important for digest annotation (used by Github packages)
with:
@@ -122,10 +122,10 @@ jobs:
type=raw,value=beta,enable={{is_default_branch}}
- name: Setup QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Load Go Build Cache for Docker
id: go-cache
@@ -148,7 +148,7 @@ jobs:
skip-extraction: ${{ steps.go-cache.outputs.cache-hit }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
@@ -159,7 +159,7 @@ jobs:
- name: Build and Publish Image Digest
id: build
uses: docker/build-push-action@v7
uses: docker/build-push-action@v6
with:
file: Dockerfile
context: .
@@ -210,7 +210,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
with:
@@ -261,16 +261,16 @@ jobs:
env.write(f"ANNOTATIONS={annotations_string}\n")
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
-1
View File
@@ -146,7 +146,6 @@ MANUAL.txt: MANUAL.md
commanddocs: rclone
go generate ./lib/transform
go generate ./cmd/bisync
-@rmdir -p '$$HOME/.config/rclone'
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs --config=/notfound docs/content/
@[ ! -e '$$HOME' ] || (echo 'Error: created unwanted directory named $$HOME' && exit 1)
+1 -2
View File
@@ -32,11 +32,10 @@ This file describes how to make the various kinds of releases
- make sign_upload
- make check_sign
- make upload
- make upload_test_website # check sponsors are correct/unchanged
- make upload_website
- make upload_github
- make startdev # make startstable for stable branch
- \# announce with forum post, twitter post, and post to annoucements list
- \# announce with forum post, twitter post, patreon post
## Update dependencies
+32 -38
View File
@@ -41,7 +41,6 @@ import (
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/rest"
"github.com/rclone/rclone/lib/resume"
)
const (
@@ -597,7 +596,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
BucketBased: true,
BucketBasedRootOK: true,
ChunkWriterDoesntSeek: true,
CanResumeListing: true,
}).Fill(ctx, f)
// Set the test flag if required
if opt.TestMode != "" {
@@ -806,7 +804,7 @@ var errEndList = errors.New("end list")
// If hidden is set then it will list the hidden (deleted) files too.
//
// if findFile is set it will look for files called (bucket, directory)
func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBucket bool, recurse bool, limit int, hidden bool, findFile bool, startAfter string, fn listFn) error {
func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBucket bool, recurse bool, limit int, hidden bool, findFile bool, fn listFn) error {
if !findFile {
if prefix != "" {
prefix += "/"
@@ -833,9 +831,7 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
Prefix: f.opt.Enc.FromStandardPath(directory),
Delimiter: delimiter,
}
if startAfter != "" {
request.StartFileName = f.opt.Enc.FromStandardPath(startAfter)
} else if directory != "" {
if directory != "" {
request.StartFileName = f.opt.Enc.FromStandardPath(directory)
}
opts := rest.Opts{
@@ -934,6 +930,27 @@ func (f *Fs) itemToDirEntry(ctx context.Context, remote string, object *api.File
return o, nil
}
// listDir lists a single directory
func (f *Fs) listDir(ctx context.Context, bucket, directory, prefix string, addBucket bool, callback func(fs.DirEntry) error) (err error) {
last := ""
err = f.list(ctx, bucket, directory, prefix, f.rootBucket == "", false, 0, f.opt.Versions, false, func(remote string, object *api.File, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory, &last)
if err != nil {
return err
}
if entry != nil {
return callback(entry)
}
return nil
})
if err != nil {
return err
}
// bucket must be present if listing succeeded
f.cache.MarkOK(bucket)
return nil
}
// listBuckets returns all the buckets to out
func (f *Fs) listBuckets(ctx context.Context) (entries fs.DirEntries, err error) {
err = f.listBucketsToFn(ctx, "", func(bucket *api.Bucket) error {
@@ -973,15 +990,9 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// These need not be returned in any particular order. If
// callback returns an error then the listing will stop
// immediately.
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
bucket, directory := f.split(dir)
startAfter, callback, done, err := resume.Setup(ctx, bucket != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error {
list := list.NewHelper(callback)
bucket, directory := f.split(dir)
if bucket == "" {
if directory != "" {
return fs.ErrorListBucketRequired
@@ -997,21 +1008,10 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
}
}
} else {
last := ""
err := f.list(ctx, bucket, directory, f.rootDirectory, f.rootBucket == "", false, 0, f.opt.Versions, false, startAfter, func(remote string, object *api.File, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory, &last)
if err != nil {
return err
}
if entry != nil {
return list.Add(entry)
}
return nil
})
err := f.listDir(ctx, bucket, directory, f.rootDirectory, f.rootBucket == "", list.Add)
if err != nil {
return err
}
f.cache.MarkOK(bucket)
}
return list.Flush()
}
@@ -1032,18 +1032,12 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
//
// Don't implement this unless you have a more efficient way
// of listing recursively that doing a directory traversal.
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) {
bucket, directory := f.split(dir)
startAfter, callback, done, err := resume.Setup(ctx, bucket != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
list := list.NewHelper(callback)
listR := func(bucket, directory, prefix string, addBucket bool) error {
last := ""
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, f.opt.Versions, false, startAfter, func(remote string, object *api.File, isDirectory bool) error {
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, f.opt.Versions, false, func(remote string, object *api.File, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory, &last)
if err != nil {
return err
@@ -1070,7 +1064,7 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
f.cache.MarkOK(bucket)
}
} else {
err := listR(bucket, directory, f.rootDirectory, f.rootBucket == "")
err = listR(bucket, directory, f.rootDirectory, f.rootBucket == "")
if err != nil {
return err
}
@@ -1464,7 +1458,7 @@ func (f *Fs) purge(ctx context.Context, dir string, oldOnly bool, deleteHidden b
}
last := ""
checkErr(f.list(ctx, bucket, directory, f.rootDirectory, f.rootBucket == "", true, 0, true, false, "", func(remote string, object *api.File, isDirectory bool) error {
checkErr(f.list(ctx, bucket, directory, f.rootDirectory, f.rootBucket == "", true, 0, true, false, func(remote string, object *api.File, isDirectory bool) error {
if !isDirectory {
oi, err := f.newObjectWithInfo(ctx, object.Name, object)
if err != nil {
@@ -1669,7 +1663,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
}
_, err = f.NewObject(ctx, remote)
if err == fs.ErrorObjectNotFound || err == fs.ErrorNotAFile {
err2 := f.list(ctx, bucket, bucketPath, f.rootDirectory, f.rootBucket == "", false, 1, f.opt.Versions, false, "", func(remote string, object *api.File, isDirectory bool) error {
err2 := f.list(ctx, bucket, bucketPath, f.rootDirectory, f.rootBucket == "", false, 1, f.opt.Versions, false, func(remote string, object *api.File, isDirectory bool) error {
err = nil
return nil
})
@@ -1811,7 +1805,7 @@ func (o *Object) getMetaDataListing(ctx context.Context) (info *api.File, err er
maxSearched = maxVersions
}
err = o.fs.list(ctx, bucket, bucketPath, "", false, true, maxSearched, o.fs.opt.Versions, true, "", func(remote string, object *api.File, isDirectory bool) error {
err = o.fs.list(ctx, bucket, bucketPath, "", false, true, maxSearched, o.fs.opt.Versions, true, func(remote string, object *api.File, isDirectory bool) error {
if isDirectory {
return nil
}
+1 -1
View File
@@ -528,7 +528,7 @@ func (f *Fs) InternalTestCleanupUnfinished(t *testing.T) {
func listAllFiles(ctx context.Context, t *testing.T, f *Fs, dirName string) []string {
bucket, directory := f.split(dirName)
foundFiles := []string{}
require.NoError(t, f.list(ctx, bucket, directory, "", false, true, 0, true, false, "", func(remote string, object *api.File, isDirectory bool) error {
require.NoError(t, f.list(ctx, bucket, directory, "", false, true, 0, true, false, func(remote string, object *api.File, isDirectory bool) error {
if !isDirectory {
foundFiles = append(foundFiles, object.Name)
}
+8 -1
View File
@@ -284,7 +284,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
}
err = srv.LoginWithKeys(opt.SessionID, decodedMasterKey)
if err != nil {
fs.Debugf(f, "login with previous auth keys failed: %v", err)
return nil, fmt.Errorf("couldn't login with session ID and master key: %w", err)
}
}
}
@@ -341,6 +341,8 @@ func (f *Fs) findDir(rootNode *mega.Node, dir string) (node *mega.Node, err erro
node, err = f.findNode(rootNode, dir)
if err == mega.ENOENT {
return nil, fs.ErrorDirNotFound
} else if err == nil && node == nil {
return nil, fs.ErrorDirNotFound
} else if err == nil && node.GetType() == mega.FILE {
return nil, fs.ErrorIsFile
}
@@ -352,6 +354,8 @@ func (f *Fs) findObject(rootNode *mega.Node, file string) (node *mega.Node, err
node, err = f.findNode(rootNode, file)
if err == mega.ENOENT {
return nil, fs.ErrorObjectNotFound
} else if err == nil && node == nil {
return nil, fs.ErrorObjectNotFound
} else if err == nil && node.GetType() != mega.FILE {
return nil, fs.ErrorIsDir // all other node types are directories
}
@@ -446,6 +450,9 @@ func (f *Fs) findRoot(ctx context.Context, create bool) (*mega.Node, error) {
// Check for preexisting root
absRoot := f.srv.FS.GetRoot()
if absRoot == nil {
return nil, errors.New("couldn't find root directory: filesystem not initialized (is the account authenticated?)")
}
node, err := f.findDir(absRoot, f.root)
//log.Printf("findRoot findDir %p %v", node, err)
if err == nil {
@@ -23,7 +23,6 @@ import (
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/resume"
)
// Register with Fs
@@ -129,7 +128,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
SetTier: true,
GetTier: true,
SlowModTime: true,
CanResumeListing: true,
}).Fill(ctx, f)
if f.rootBucket != "" && f.rootDirectory != "" && !strings.HasSuffix(root, "/") {
// Check to see if the (bucket,directory) is actually an existing file
@@ -272,16 +270,10 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// These need not be returned in any particular order. If
// callback returns an error then the listing will stop
// immediately.
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error {
list := list.NewHelper(callback)
bucketName, directory := f.split(dir)
fs.Debugf(f, "listing: bucket : %v, directory: %v", bucketName, dir)
startAfter, callback, done, err := resume.Setup(ctx, bucketName != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
list := list.NewHelper(callback)
if bucketName == "" {
if directory != "" {
return fs.ErrorListBucketRequired
@@ -297,21 +289,10 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
}
}
} else {
fn := func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory)
if err != nil {
return err
}
if entry != nil {
return list.Add(entry)
}
return nil
}
err := f.list(ctx, bucketName, directory, f.rootDirectory, f.rootBucket == "", false, 0, startAfter, fn)
err := f.listDir(ctx, bucketName, directory, f.rootDirectory, f.rootBucket == "", list.Add)
if err != nil {
return err
}
f.cache.MarkOK(bucketName)
}
return list.Flush()
}
@@ -329,7 +310,7 @@ type listFn func(remote string, object *objectstorage.ObjectSummary, isDirectory
// If hidden is set then it will list the hidden (deleted) files too.
// if findFile is set it will look for files called (bucket, directory)
func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBucket bool, recurse bool, limit int,
startAfter string, fn listFn) (err error) {
fn listFn) (err error) {
if prefix != "" {
prefix += "/"
}
@@ -355,9 +336,6 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
if delimiter != "" {
request.Delimiter = common.String(delimiter)
}
if startAfter != "" {
request.Start = common.String(startAfter)
}
for {
var resp objectstorage.ListObjectsResponse
@@ -464,6 +442,27 @@ func (f *Fs) itemToDirEntry(ctx context.Context, remote string, object *objectst
return o, nil
}
// listDir lists a single directory
func (f *Fs) listDir(ctx context.Context, bucket, directory, prefix string, addBucket bool, callback func(fs.DirEntry) error) (err error) {
fn := func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory)
if err != nil {
return err
}
if entry != nil {
return callback(entry)
}
return nil
}
err = f.list(ctx, bucket, directory, prefix, addBucket, false, 0, fn)
if err != nil {
return err
}
// bucket must be present if listing succeeded
f.cache.MarkOK(bucket)
return nil
}
// listBuckets returns all the buckets to out
func (f *Fs) listBuckets(ctx context.Context) (entries fs.DirEntries, err error) {
if f.opt.Provider == noAuth {
@@ -719,17 +718,11 @@ immediately.
Don't implement this unless you have a more efficient way
of listing recursively that doing a directory traversal.
*/
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) {
bucketName, directory := f.split(dir)
startAfter, callback, done, err := resume.Setup(ctx, bucketName != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
list := list.NewHelper(callback)
listR := func(bucket, directory, prefix string, addBucket bool) error {
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, startAfter, func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory)
if err != nil {
return err
@@ -756,7 +749,7 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
f.cache.MarkOK(bucketName)
}
} else {
err := listR(bucketName, directory, f.rootDirectory, f.rootBucket == "")
err = listR(bucketName, directory, f.rootDirectory, f.rootBucket == "")
if err != nil {
return err
}
+34 -47
View File
@@ -63,7 +63,6 @@ import (
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
"github.com/rclone/rclone/lib/resume"
"github.com/rclone/rclone/lib/transferaccounter"
"github.com/rclone/rclone/lib/version"
)
@@ -1832,7 +1831,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
SetTier: provider.StorageClass.Len() > 0,
GetTier: provider.StorageClass.Len() > 0,
SlowModTime: true,
CanResumeListing: true,
}).Fill(ctx, f)
if opt.Provider == "AWS" {
f.features.DoubleSlash = true
@@ -2043,10 +2041,6 @@ func (f *Fs) newV1List(req *s3.ListObjectsV2Input) bucketLister {
// Convert v2 req into v1 req
//structs.SetFrom(&l.req, req)
setFrom_s3ListObjectsInput_s3ListObjectsV2Input(&l.req, req)
// Map v2 StartAfter to v1 Marker (same semantics: list after this key)
if req.StartAfter != nil {
l.req.Marker = req.StartAfter
}
return l
}
@@ -2312,7 +2306,6 @@ type listOpt struct {
versionAt fs.Time // if set only show versions <= this time
noSkipMarkers bool // if set return dir marker objects
restoreStatus bool // if set return restore status in listing too
startAfter string // if set, start listing strictly after this key
}
// list lists the objects into the function supplied with the opt
@@ -2358,9 +2351,6 @@ func (f *Fs) list(ctx context.Context, opt listOpt, fn listFn) error {
if f.opt.RequesterPays {
req.RequestPayer = types.RequestPayerRequester
}
if opt.startAfter != "" {
req.StartAfter = &opt.startAfter
}
var listBucket bucketLister
switch {
case opt.withVersions || opt.versionAt.IsSet():
@@ -2527,6 +2517,35 @@ func (f *Fs) itemToDirEntry(ctx context.Context, remote string, object *types.Ob
return o, nil
}
// listDir lists files and directories to out
func (f *Fs) listDir(ctx context.Context, bucket, directory, prefix string, addBucket bool, callback func(fs.DirEntry) error) (err error) {
// List the objects and directories
err = f.list(ctx, listOpt{
bucket: bucket,
directory: directory,
prefix: prefix,
addBucket: addBucket,
withVersions: f.opt.Versions,
versionAt: f.opt.VersionAt,
hidden: f.opt.VersionDeleted,
}, func(remote string, object *types.Object, versionID *string, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, versionID, isDirectory)
if err != nil {
return err
}
if entry != nil {
return callback(entry)
}
return nil
})
if err != nil {
return err
}
// bucket must be present if listing succeeded
f.cache.MarkOK(bucket)
return nil
}
// listBuckets lists the buckets to out
func (f *Fs) listBuckets(ctx context.Context) (entries fs.DirEntries, err error) {
req := s3.ListBucketsInput{}
@@ -2573,15 +2592,9 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// These need not be returned in any particular order. If
// callback returns an error then the listing will stop
// immediately.
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
bucket, directory := f.split(dir)
startAfter, callback, done, err := resume.Setup(ctx, bucket != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) error {
list := list.NewHelper(callback)
bucket, directory := f.split(dir)
if bucket == "" {
if directory != "" {
return fs.ErrorListBucketRequired
@@ -2597,29 +2610,10 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
}
}
} else {
err := f.list(ctx, listOpt{
bucket: bucket,
directory: directory,
prefix: f.rootDirectory,
addBucket: f.rootBucket == "",
withVersions: f.opt.Versions,
versionAt: f.opt.VersionAt,
hidden: f.opt.VersionDeleted,
startAfter: startAfter,
}, func(remote string, object *types.Object, versionID *string, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, versionID, isDirectory)
if err != nil {
return err
}
if entry != nil {
return list.Add(entry)
}
return nil
})
err := f.listDir(ctx, bucket, directory, f.rootDirectory, f.rootBucket == "", list.Add)
if err != nil {
return err
}
f.cache.MarkOK(bucket)
}
return list.Flush()
}
@@ -2640,14 +2634,8 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
//
// Don't implement this unless you have a more efficient way
// of listing recursively than doing a directory traversal.
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (err error) {
bucket, directory := f.split(dir)
startAfter, callback, done, err := resume.Setup(ctx, bucket != "", f, dir, callback)
if err != nil {
return err
}
defer done(&returnErr)
list := list.NewHelper(callback)
listR := func(bucket, directory, prefix string, addBucket bool) error {
return f.list(ctx, listOpt{
@@ -2659,7 +2647,6 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
withVersions: f.opt.Versions,
versionAt: f.opt.VersionAt,
hidden: f.opt.VersionDeleted,
startAfter: startAfter,
}, func(remote string, object *types.Object, versionID *string, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, versionID, isDirectory)
if err != nil {
@@ -2687,7 +2674,7 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
f.cache.MarkOK(bucket)
}
} else {
err := listR(bucket, directory, f.rootDirectory, f.rootBucket == "")
err = listR(bucket, directory, f.rootDirectory, f.rootBucket == "")
if err != nil {
return err
}
+3 -4
View File
@@ -127,14 +127,14 @@ func init() {
// and the Command line syntax section of docs/content/bisync.md (it doesn't update automatically)
flags.BoolVarP(cmdFlags, &Opt.Resync, "resync", "1", Opt.Resync, "Performs the resync run. Equivalent to --resync-mode path1. Consider using --verbose or --dry-run first.", "")
flags.FVarP(cmdFlags, &Opt.ResyncMode, "resync-mode", "", "During resync, prefer the version that is: path1, path2, newer, older, larger, smaller (default: path1 if --resync, otherwise none for no resync.)", "")
flags.BoolVarP(cmdFlags, &Opt.CheckAccess, "check-access", "", Opt.CheckAccess, MakeHelp("Ensure expected {CHECKFILE} files are found on both Path1 and Path2 filesystems, else abort."), "")
flags.StringVarP(cmdFlags, &Opt.CheckFilename, "check-filename", "", Opt.CheckFilename, MakeHelp("Filename for --check-access (default: {CHECKFILE})"), "")
flags.BoolVarP(cmdFlags, &Opt.CheckAccess, "check-access", "", Opt.CheckAccess, makeHelp("Ensure expected {CHECKFILE} files are found on both Path1 and Path2 filesystems, else abort."), "")
flags.StringVarP(cmdFlags, &Opt.CheckFilename, "check-filename", "", Opt.CheckFilename, makeHelp("Filename for --check-access (default: {CHECKFILE})"), "")
flags.BoolVarP(cmdFlags, &Opt.Force, "force", "", Opt.Force, "Bypass --max-delete safety check and run the sync. Consider using with --verbose", "")
flags.FVarP(cmdFlags, &Opt.CheckSync, "check-sync", "", "Controls comparison of final listings: true|false|only (default: true)", "")
flags.BoolVarP(cmdFlags, &Opt.CreateEmptySrcDirs, "create-empty-src-dirs", "", Opt.CreateEmptySrcDirs, "Sync creation and deletion of empty directories. (Not compatible with --remove-empty-dirs)", "")
flags.BoolVarP(cmdFlags, &Opt.RemoveEmptyDirs, "remove-empty-dirs", "", Opt.RemoveEmptyDirs, "Remove ALL empty directories at the final cleanup step.", "")
flags.StringVarP(cmdFlags, &Opt.FiltersFile, "filters-file", "", Opt.FiltersFile, "Read filtering patterns from a file", "")
flags.StringVarP(cmdFlags, &Opt.Workdir, "workdir", "", Opt.Workdir, MakeHelp("Use custom working dir - useful for testing. (default: {WORKDIR})"), "")
flags.StringVarP(cmdFlags, &Opt.Workdir, "workdir", "", Opt.Workdir, makeHelp("Use custom working dir - useful for testing. (default: {WORKDIR})"), "")
flags.StringVarP(cmdFlags, &Opt.BackupDir1, "backup-dir1", "", Opt.BackupDir1, "--backup-dir for Path1. Must be a non-overlapping path on the same remote.", "")
flags.StringVarP(cmdFlags, &Opt.BackupDir2, "backup-dir2", "", Opt.BackupDir2, "--backup-dir for Path2. Must be a non-overlapping path on the same remote.", "")
flags.StringVarP(cmdFlags, &Opt.DebugName, "debugname", "", Opt.DebugName, "Debug by tracking one file at various points throughout a bisync run (when -v or -vv)", "")
@@ -153,7 +153,6 @@ func init() {
flags.StringVarP(cmdFlags, &Opt.ConflictSuffixFlag, "conflict-suffix", "", Opt.ConflictSuffixFlag, "Suffix to use when renaming a --conflict-loser. Can be either one string or two comma-separated strings to assign different suffixes to Path1/Path2. (default: 'conflict')", "")
_ = cmdFlags.MarkHidden("debugname")
_ = cmdFlags.MarkHidden("localtime")
addRC()
}
// bisync command definition
+53 -65
View File
@@ -1,77 +1,65 @@
//go:build none
// Create the help text for the rc
//
// Run with go generate ./cmd/bisync (defined in rc.go)
package main
package bisync
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/muesli/reflow/wordwrap"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/cmd/bisync"
"github.com/rclone/rclone/fs"
"github.com/spf13/pflag"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// Output the help to stdout
func main() {
out := os.Stdout
if len(os.Args) > 1 {
var err error
out, err = os.Create(os.Args[1])
if err != nil {
fs.Fatalf(nil, "Open output failed: %v", err)
}
defer out.Close()
}
fmt.Fprintf(out, "<!--- Docs generated by help.go - use go generate to rebuild - DO NOT EDIT --->\n\n")
fmt.Fprint(out, RcHelp())
func makeHelp(help string) string {
replacer := strings.NewReplacer(
"|", "`",
"{MAXDELETE}", strconv.Itoa(DefaultMaxDelete),
"{CHECKFILE}", DefaultCheckFilename,
// "{WORKDIR}", DefaultWorkdir,
)
return replacer.Replace(help)
}
// RcHelp returns the rc help
func RcHelp() string {
return wordwrap.String(bisync.MakeHelp(`This takes the following parameters:
var shortHelp = `Perform bidirectional synchronization between two paths.`
var rcHelp = makeHelp(`This takes the following parameters
- path1 - a remote directory string e.g. |drive:path1|
- path2 - a remote directory string e.g. |drive:path2|
- dryRun - dry-run mode
- resync - performs the resync run
- checkAccess - abort if {CHECKFILE} files are not found on both filesystems
- checkFilename - file name for checkAccess (default: {CHECKFILE})
- maxDelete - abort sync if percentage of deleted files is above
this threshold (default: {MAXDELETE})
- force - Bypass maxDelete safety check and run the sync
- checkSync - |true| by default, |false| disables comparison of final listings,
|only| will skip sync, only compare listings from the last run
- createEmptySrcDirs - Sync creation and deletion of empty directories.
(Not compatible with --remove-empty-dirs)
- removeEmptyDirs - remove empty directories at the final cleanup step
- filtersFile - read filtering patterns from a file
- ignoreListingChecksum - Do not use checksums for listings
- resilient - Allow future runs to retry after certain less-serious errors, instead of requiring resync.
- workdir - server directory for history files (default: |~/.cache/rclone/bisync|)
- backupdir1 - --backup-dir for Path1. Must be a non-overlapping path on the same remote.
- backupdir2 - --backup-dir for Path2. Must be a non-overlapping path on the same remote.
- noCleanup - retain working files
- path1 (required) - (string) a remote directory string e.g. ||drive:path1||
- path2 (required) - (string) a remote directory string e.g. ||drive:path2||
- dryRun - (bool) dry-run mode
`+GenerateParams()+`
See [bisync command help](https://rclone.org/commands/rclone_bisync/)
and [full bisync description](https://rclone.org/bisync/)
for more information.
`), 76)
}
for more information.`)
// example: "create-empty-src-dirs" -> "createEmptySrcDirs"
func toCamel(s string) string {
split := strings.Split(s, "-")
builder := strings.Builder{}
for i, word := range split {
if i == 0 { // first word always all lowercase
builder.WriteString(strings.ToLower(word))
continue
}
builder.WriteString(cases.Title(language.AmericanEnglish).String(word))
}
return builder.String()
}
var longHelp = shortHelp + makeHelp(`
// GenerateParams automatically generates the param list from commandDefinition.Flags
func GenerateParams() string {
builder := strings.Builder{}
fn := func(flag *pflag.Flag) {
if flag.Hidden {
return
}
builder.WriteString(fmt.Sprintf("- %s - (%s) %s \n", toCamel(flag.Name), flag.Value.Type(), flag.Usage))
}
commandDefinition, _, _ := cmd.Root.Find([]string{"bisync"})
commandDefinition.Flags().VisitAll(fn)
return builder.String()
}
[Bisync](https://rclone.org/bisync/) provides a
bidirectional cloud sync solution in rclone.
It retains the Path1 and Path2 filesystem listings from the prior run.
On each successive run it will:
- list files on Path1 and Path2, and check for changes on each side.
Changes include |New|, |Newer|, |Older|, and |Deleted| files.
- Propagate changes on Path1 to Path2, and vice-versa.
Bisync is considered an **advanced command**, so use with care.
Make sure you have read and understood the entire [manual](https://rclone.org/bisync)
(especially the [Limitations](https://rclone.org/bisync/#limitations) section)
before using, or data loss can result. Questions can be asked in the
[Rclone Forum](https://forum.rclone.org/).
See [full bisync description](https://rclone.org/bisync/) for details.`)
+25 -124
View File
@@ -1,22 +1,16 @@
//go:generate go run help.go rc.md
package bisync
import (
"context"
_ "embed"
"errors"
"log"
"path/filepath"
"strconv"
"strings"
"github.com/rclone/rclone/cmd/bisync/bilib"
"github.com/rclone/rclone/fs"
fslog "github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/rc"
)
func addRC() {
func init() {
rc.Add(rc.Call{
Path: "sync/bisync",
AuthRequired: true,
@@ -26,42 +20,6 @@ func addRC() {
})
}
//go:embed rc.md
var rcHelp string
var shortHelp = `Perform bidirectional synchronization between two paths.`
var longHelp = shortHelp + MakeHelp(`
[Bisync](https://rclone.org/bisync/) provides a
bidirectional cloud sync solution in rclone.
It retains the Path1 and Path2 filesystem listings from the prior run.
On each successive run it will:
- list files on Path1 and Path2, and check for changes on each side.
Changes include ||New||, ||Newer||, ||Older||, and ||Deleted|| files.
- Propagate changes on Path1 to Path2, and vice-versa.
Bisync is considered an **advanced command**, so use with care.
Make sure you have read and understood the entire [manual](https://rclone.org/bisync)
(especially the [Limitations](https://rclone.org/bisync/#limitations) section)
before using, or data loss can result. Questions can be asked in the
[Rclone Forum](https://forum.rclone.org/).
See [full bisync description](https://rclone.org/bisync/) for details.
`)
// MakeHelp replaces some dynamic variables for the help docs
func MakeHelp(help string) string {
replacer := strings.NewReplacer(
"||", "`",
"{MAXDELETE}", strconv.Itoa(DefaultMaxDelete),
"{CHECKFILE}", DefaultCheckFilename,
"{WORKDIR}", DefaultWorkdir,
)
return replacer.Replace(help)
}
func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
opt := &Options{}
octx, ci := fs.AddConfig(ctx)
@@ -83,86 +41,56 @@ func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
}
if opt.Resync, err = in.GetBool("resync"); rc.NotErrParamNotFound(err) {
fs.Debugf("resync", "optional parameter is missing. using default value: %v", opt.Resync)
return
}
if opt.CheckAccess, err = in.GetBool("checkAccess"); rc.NotErrParamNotFound(err) {
fs.Debugf("checkAccess", "optional parameter is missing. using default value: %v", opt.CheckAccess)
return
}
if opt.Force, err = in.GetBool("force"); rc.NotErrParamNotFound(err) {
fs.Debugf("force", "optional parameter is missing. using default value: %v", opt.Force)
return
}
if opt.CreateEmptySrcDirs, err = in.GetBool("createEmptySrcDirs"); rc.NotErrParamNotFound(err) {
fs.Debugf("createEmptySrcDirs", "optional parameter is missing. using default value: %v", opt.CreateEmptySrcDirs)
return
}
if opt.RemoveEmptyDirs, err = in.GetBool("removeEmptyDirs"); rc.NotErrParamNotFound(err) {
fs.Debugf("removeEmptyDirs", "optional parameter is missing. using default value: %v", opt.RemoveEmptyDirs)
return
}
if opt.NoCleanup, err = in.GetBool("noCleanup"); rc.NotErrParamNotFound(err) {
fs.Debugf("noCleanup", "optional parameter is missing. using default value: %v", opt.NoCleanup)
return
}
if opt.IgnoreListingChecksum, err = in.GetBool("ignoreListingChecksum"); rc.NotErrParamNotFound(err) {
fs.Debugf("ignoreListingChecksum", "optional parameter is missing. using default value: %v", opt.IgnoreListingChecksum)
return
}
if opt.Resilient, err = in.GetBool("resilient"); rc.NotErrParamNotFound(err) {
fs.Debugf("resilient", "optional parameter is missing. using default value: %v", opt.Resilient)
return
}
if opt.CheckFilename, err = in.GetString("checkFilename"); rc.NotErrParamNotFound(err) {
opt.CheckFilename = DefaultCheckFilename
fs.Debugf("checkFilename", "optional parameter is missing. using default value: %v", opt.CheckFilename)
return
}
if opt.FiltersFile, err = in.GetString("filtersFile"); rc.NotErrParamNotFound(err) {
fs.Debugf("filtersFile", "optional parameter is missing. using default value: %v", opt.FiltersFile)
return
}
if opt.Workdir, err = in.GetString("workdir"); rc.NotErrParamNotFound(err) {
// "" sets correct default later
fs.Debugf("workdir", "optional parameter is missing. using default value: %v", opt.Workdir)
return
}
if opt.BackupDir1, err = in.GetString("backupDir1"); rc.NotErrParamNotFound(err) {
// we accept an alternate capitalization here for backward compatibility.
if opt.BackupDir1, err = in.GetString("backupdir1"); rc.NotErrParamNotFound(err) {
fs.Debugf("backupDir1", "optional parameter is missing. using default value: %v", opt.BackupDir1)
}
if opt.BackupDir1, err = in.GetString("backupdir1"); rc.NotErrParamNotFound(err) {
return
}
if opt.BackupDir2, err = in.GetString("backupDir2"); rc.NotErrParamNotFound(err) {
// we accept an alternate capitalization here for backward compatibility.
if opt.BackupDir2, err = in.GetString("backupdir2"); rc.NotErrParamNotFound(err) {
fs.Debugf("backupDir2", "optional parameter is missing. using default value: %v", opt.BackupDir2)
}
if opt.BackupDir2, err = in.GetString("backupdir2"); rc.NotErrParamNotFound(err) {
return
}
if err = setEnum(in, "checkSync", "true", opt.CheckSync.Set); err != nil {
checkSync, err := in.GetString("checkSync")
if rc.NotErrParamNotFound(err) {
return nil, err
}
if err = setEnum(in, "resyncMode", opt.ResyncMode.String(), opt.ResyncMode.Set); err != nil {
if checkSync == "" {
checkSync = "true"
}
if err := opt.CheckSync.Set(checkSync); err != nil {
return nil, err
}
if err = setEnum(in, "conflictResolve", opt.ConflictResolve.String(), opt.ConflictResolve.Set); err != nil {
return nil, err
}
if err = setEnum(in, "conflictLoser", opt.ConflictLoser.String(), opt.ConflictLoser.Set); err != nil {
return nil, err
}
if opt.ConflictSuffixFlag, err = in.GetString("conflictSuffix"); rc.NotErrParamNotFound(err) {
fs.Debugf("conflictSuffix", "optional parameter is missing. using default value: %v", opt.ConflictSuffixFlag)
}
if opt.Recover, err = in.GetBool("recover"); rc.NotErrParamNotFound(err) {
fs.Debugf("recover", "optional parameter is missing. using default value: %v", opt.Recover)
}
if opt.CompareFlag, err = in.GetString("compare"); rc.NotErrParamNotFound(err) {
fs.Debugf("compare", "optional parameter is missing. using default value: %v", opt.CompareFlag)
}
if opt.Compare.NoSlowHash, err = in.GetBool("noSlowHash"); rc.NotErrParamNotFound(err) {
fs.Debugf("noSlowHash", "optional parameter is missing. using default value: %v", opt.Compare.NoSlowHash)
}
if opt.Compare.SlowHashSyncOnly, err = in.GetBool("slowHashSyncOnly"); rc.NotErrParamNotFound(err) {
fs.Debugf("slowHashSyncOnly", "optional parameter is missing. using default value: %v", opt.Compare.SlowHashSyncOnly)
}
if opt.Compare.DownloadHash, err = in.GetBool("downloadHash"); rc.NotErrParamNotFound(err) {
fs.Debugf("downloadHash", "optional parameter is missing. using default value: %v", opt.Compare.DownloadHash)
}
if opt.MaxLock, err = in.GetFsDuration("maxLock"); rc.NotErrParamNotFound(err) {
opt.MaxLock = 0
fs.Debugf("maxLock", "optional parameter is missing. using default value: %v", opt.MaxLock)
}
fs1, err := rc.GetFsNamed(octx, in, "path1")
if err != nil {
@@ -177,33 +105,6 @@ func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
output := bilib.CaptureOutput(func() {
err = Bisync(octx, fs1, fs2, opt)
})
workDir, _ := filepath.Abs(DefaultWorkdir)
if opt.Workdir != "" {
workDir, _ = filepath.Abs(opt.Workdir)
}
basePath := bilib.BasePath(ctx, workDir, fs1, fs2)
_, _ = log.Writer().Write(output)
return rc.Params{
"output": string(output),
"session": bilib.SessionName(fs1, fs2),
"workDir": workDir,
"basePath": basePath,
"listing1": basePath + ".path1.lst",
"listing2": basePath + ".path2.lst",
"logFile": fslog.Opt.File,
}, err
}
func setEnum(in rc.Params, name string, defaultVal string, set func(s string) error) error {
v, err := in.GetString(name)
if rc.NotErrParamNotFound(err) || v == "" {
v = defaultVal
fs.Debugf(name, "optional parameter is missing. using default value: %v", v)
}
if err := set(v); err != nil {
return err
}
return nil
return rc.Params{"output": string(output)}, err
}
-61
View File
@@ -1,61 +0,0 @@
<!--- Docs generated by help.go - use go generate to rebuild - DO NOT EDIT --->
This takes the following parameters:
- path1 (required) - (string) a remote directory string e.g. `drive:path1`
- path2 (required) - (string) a remote directory string e.g. `drive:path2`
- dryRun - (bool) dry-run mode
- backupDir1 - (string) --backup-dir for Path1. Must be a non-overlapping path on
the same remote.
- backupDir2 - (string) --backup-dir for Path2. Must be a non-overlapping path on
the same remote.
- checkAccess - (bool) Ensure expected RCLONE_TEST files are found on both
Path1 and Path2 filesystems, else abort.
- checkFilename - (string) Filename for --check-access (default: RCLONE_TEST)
- checkSync - (string) Controls comparison of final listings: true|false|only
(default: true)
- compare - (string) Comma-separated list of bisync-specific compare options ex.
'size,modtime,checksum' (default: 'size,modtime')
- conflictLoser - (ConflictLoserAction) Action to take on the loser of a sync
conflict (when there is a winner) or on both files (when there is no
winner): , num, pathname, delete (default: num)
- conflictResolve - (string) Automatically resolve conflicts by preferring the
version that is: none, path1, path2, newer, older, larger, smaller (default:
none)
- conflictSuffix - (string) Suffix to use when renaming a --conflict-loser. Can
be either one string or two comma-separated strings to assign different
suffixes to Path1/Path2. (default: 'conflict')
- createEmptySrcDirs - (bool) Sync creation and deletion of empty directories.
(Not compatible with --remove-empty-dirs)
- downloadHash - (bool) Compute hash by downloading when otherwise
unavailable. (warning: may be slow and use lots of data!)
- filtersFile - (string) Read filtering patterns from a file
- force - (bool) Bypass --max-delete safety check and run the sync. Consider
using with --verbose
- ignoreListingChecksum - (bool) Do not use checksums for listings (add --ignore-
checksum to additionally skip post-copy checksum checks)
- maxLock - (Duration) Consider lock files older than this to be expired
(default: 0 (never expire)) (minimum: 2m)
- noCleanup - (bool) Retain working files (useful for troubleshooting and
testing).
- noSlowHash - (bool) Ignore listing checksums only on backends where they are
slow
- recover - (bool) Automatically recover from interruptions without requiring --
resync.
- removeEmptyDirs - (bool) Remove ALL empty directories at the final cleanup
step.
- resilient - (bool) Allow future runs to retry after certain less-serious
errors, instead of requiring --resync.
- resync - (bool) Performs the resync run. Equivalent to --resync-mode path1.
Consider using --verbose or --dry-run first.
- resyncMode - (string) During resync, prefer the version that is: path1,
path2, newer, older, larger, smaller (default: path1 if --resync, otherwise
none for no resync.)
- slowHashSyncOnly - (bool) Ignore slow checksums for listings and deltas, but
still consider them during sync calls.
- workdir - (string) Use custom working dir - useful for testing. (default:
~/.cache/rclone/bisync)
See [bisync command help](https://rclone.org/commands/rclone_bisync/)
and [full bisync description](https://rclone.org/bisync/)
for more information.
-1
View File
@@ -1094,4 +1094,3 @@ put them back in again. -->
- Bjoern Franke <bjo@schafweide.org>
- razorloves <razorloves@gmail.com>
- Duncan F <131309315+duncanaf@users.noreply.github.com>
- Billy Hughes <w.g.h.hughes@gmail.com>
-6
View File
@@ -1897,12 +1897,6 @@ about *Unison* and synchronization in general.
## Changelog
### `v1.74`
- Added several missing `rc` parameters.
- Optional `rc` parameters are now truly optional.
- `rc` output now provides more structured information.
### `v1.71`
- `bisync` is now officially released from beta.
-25
View File
@@ -6,31 +6,6 @@ description: "Rclone Changelog"
# Changelog
## v1.73.2 - 2026-03-06
[See commits](https://github.com/rclone/rclone/compare/v1.73.1...v1.73.2)
- Bug Fixes
- build
- Update to go 1.25.8 to fix CVE-2026-27137 CVE-2026-27138 CVE-2026-25679 CVE-2026-27142 (Nick Craig-Wood)
- Update github.com/cloudflare/circl to v1.6.3 to fix CVE-2026-1229 (Nick Craig-Wood)
- Update to golang.org/x/net v0.51.0 to fix CVE-2026-27141 (Nick Craig-Wood)
- docs fixes:
- bisync: Add group Sync to the bisync command (Jan-Philipp Reßler)
- Note that --use-server-modtime only works on some backends (Nick Craig-Wood)
- Document unsupported S3 object keys with double slashes (Adam Kasztenny)
- Fix headers hierarchy for mount.md (Dark Dragon)
- Fix new drive flag typo in changelog (razorloves)
- Archive
- Extract: fix extraction with "./" prefix from tar entry paths (Varun Chawla)
- Drime
- Fix chunk-uploaded files ignoring workspace ID (a1pcm)
- Internxt
- Fix Entry doesn't belong in directory errors on windows (jzunigax2)
- WebDAV
- Escape reserved characters in URL path segments (Varun Chawla)
- Add missing headers for CORS (Romāns Potašovs)
## v1.73.1 - 2026-02-17
[See commits](https://github.com/rclone/rclone/compare/v1.73.0...v1.73.1)
-44
View File
@@ -2546,50 +2546,6 @@ This sets the interval between each retry specified by `--retries`
The default is `0`. Use `0` to disable.
### --resume-listings string
Set this to a local directory path to enable resumable listings.
When a long-running listing operation (e.g. `ls`, `sync`, `copy`) is
interrupted, rclone saves checkpoint files in this directory so that
the next run can resume from where it left off rather than starting
from scratch.
This is useful when working with very large buckets containing
millions or billions of files, where listing alone can take hours or
days.
How it works:
- During listing, rclone saves a checkpoint after each page of results
from the backend.
- If the operation is interrupted (e.g. Ctrl-C, crash, reboot), the
checkpoint records how far the listing got.
- On the next run with the same `--resume-listings` directory, rclone
detects the checkpoint and resumes listing from that point.
- When a listing completes successfully, its checkpoint is
automatically deleted.
Only backends that support key-name-based pagination can resume
listings. Currently supported backends include S3, B2, and Oracle
Object Storage. Other backends will work normally but won't benefit
from resume checkpoints.
Resume works with both normal listings and `--fast-list` (ListR).
`--resume-listings` cannot be used with `sync` or other commands that
delete files from the destination. A resumed listing skips
already-listed source files, which would cause them to appear missing
and be deleted from the destination. Use `--resume-listings` with
`copy` or `ls` instead.
After a resumed run completes, it is recommended to do one full run
without `--resume-listings` to catch any files that were added in the
already-processed key range between runs.
```console
rclone copy --resume-listings /tmp/rclone-resume s3:big-bucket /local/dest
```
### --server-side-across-configs
Allow server-side operations (e.g. copy or move) to work across
+1 -1
View File
@@ -36,7 +36,7 @@
"beta" "This feature is currently in beta must be used with care."
}}
{{ if .Params.versionIntroduced }}<span class="badge badge-pill badge-secondary float-right" style="margin-top: 30px; font-size: 100%" title="This feature needs Rclone {{ .Params.versionIntroduced }} or later.">added in {{ .Params.versionIntroduced }}</span>{{ end }}
{{ if .Params.versionIntroduced }}<span class="badge badge-pill badge-secondary float-right" style="margin-top: 30px; font-size: 100%" title="This feature needs Rclone {{ .Params.versionIntroduced }} or later.">{{ .Params.versionIntroduced }}</span>{{ end }}
{{ with .Params.status | lower }}
{{ $statusCode := . }}
-1
View File
@@ -89,7 +89,6 @@ Returns the following values:
{
"bytes": total transferred bytes since the start of the group,
"checks": number of files checked,
"deletedDirs": number of directories deleted,
"deletes" : number of files deleted,
"elapsedTime": time in floating point seconds since rclone was started,
"errors": number of errors,
-6
View File
@@ -277,11 +277,6 @@ var ConfigOptionsInfo = Options{{
Default: false,
Help: "Use recursive list if available; uses more memory but fewer transactions",
Groups: "Listing",
}, {
Name: "resume_listings",
Default: "",
Help: "Local directory path for saving listing checkpoints so interrupted listings can be resumed",
Groups: "Listing",
}, {
Name: "list_cutoff",
Default: 1_000_000,
@@ -622,7 +617,6 @@ type ConfigInfo struct {
Suffix string `config:"suffix"`
SuffixKeepExtension bool `config:"suffix_keep_extension"`
UseListR bool `config:"fast_list"`
ResumeListings string `config:"resume_listings"`
ListCutoff int `config:"list_cutoff"`
BufferSize SizeSuffix `config:"buffer_size"`
BwLimit BwTimetable `config:"bwlimit"`
-5
View File
@@ -174,10 +174,6 @@ type Features struct {
// immediately.
ListP func(ctx context.Context, dir string, callback ListRCallback) error
// CanResumeListing indicates the backend handles --resume-listings
// internally in its ListP/ListR implementations.
CanResumeListing bool
// About gets quota information from the Fs
About func(ctx context.Context) (*Usage, error)
@@ -460,7 +456,6 @@ func (ft *Features) Mask(ctx context.Context, f Fs) *Features {
if mask.ListP == nil {
ft.ListP = nil
}
ft.CanResumeListing = ft.CanResumeListing && mask.CanResumeListing
if mask.About == nil {
ft.About = nil
}
+21 -41
View File
@@ -125,7 +125,7 @@ type OutputHandler struct {
mu sync.Mutex
output []outputFn // log to writer if empty or the last item
outputExtra []outputExtra // log to all these additional places
format logFormat // protected by mu
format logFormat
jsonBuf bytes.Buffer
jsonHandler *slog.JSONHandler
}
@@ -139,13 +139,6 @@ type outputExtra struct {
// Define the type of the override logger
type outputFn func(level slog.Level, text string)
// getFormat returns the current log format flags under the mutex.
func (h *OutputHandler) getFormat() logFormat {
h.mu.Lock()
defer h.mu.Unlock()
return h.format
}
// NewOutputHandler creates a new OutputHandler with the specified flags.
//
// This is designed to use log/slog but produce output which is
@@ -222,22 +215,16 @@ func (h *OutputHandler) setWriter(writer io.Writer) {
// Set the format flags to that passed in.
func (h *OutputHandler) setFormat(format logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format = format
}
// clear format flags that this output type doesn't want
func (h *OutputHandler) clearFormatFlags(bitMask logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format &^= bitMask
}
// set format flags that this output type requires
func (h *OutputHandler) setFormatFlags(bitMask logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format |= bitMask
}
@@ -251,37 +238,37 @@ func (h *OutputHandler) Enabled(_ context.Context, level slog.Level) bool {
}
// Create a log header in Go standard log format.
func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, format logFormat, level slog.Level, t time.Time, object string, lineInfo string) {
func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, level slog.Level, t time.Time, object string, lineInfo string) {
// Add time in Go standard format if requested
if format&(logFormatDate|logFormatTime|logFormatMicroseconds) != 0 {
if format&logFormatUTC != 0 {
if h.format&(logFormatDate|logFormatTime|logFormatMicroseconds) != 0 {
if h.format&logFormatUTC != 0 {
t = t.UTC()
}
if format&logFormatDate != 0 {
if h.format&logFormatDate != 0 {
year, month, day := t.Date()
fmt.Fprintf(buf, "%04d/%02d/%02d ", year, month, day)
}
if format&(logFormatTime|logFormatMicroseconds) != 0 {
if h.format&(logFormatTime|logFormatMicroseconds) != 0 {
hour, min, sec := t.Clock()
fmt.Fprintf(buf, "%02d:%02d:%02d", hour, min, sec)
if format&logFormatMicroseconds != 0 {
if h.format&logFormatMicroseconds != 0 {
fmt.Fprintf(buf, ".%06d", t.Nanosecond()/1e3)
}
buf.WriteByte(' ')
}
}
// Add source code filename:line if requested
if format&(logFormatShortFile|logFormatLongFile) != 0 && lineInfo != "" {
if h.format&(logFormatShortFile|logFormatLongFile) != 0 && lineInfo != "" {
buf.WriteString(lineInfo)
buf.WriteByte(':')
buf.WriteByte(' ')
}
// Add PID if requested
if format&logFormatPid != 0 {
if h.format&logFormatPid != 0 {
fmt.Fprintf(buf, "[%d] ", os.Getpid())
}
// Add log level if required
if format&logFormatNoLevel == 0 {
if h.format&logFormatNoLevel == 0 {
levelStr := slogLevelToString(level)
fmt.Fprintf(buf, "%-6s: ", levelStr)
}
@@ -294,9 +281,9 @@ func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, format logFormat,
}
// Create a log in standard Go log format into buf.
func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, format logFormat, r slog.Record) error {
func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) error {
var lineInfo string
if format&(logFormatShortFile|logFormatLongFile) != 0 {
if h.format&(logFormatShortFile|logFormatLongFile) != 0 {
lineInfo = getCaller(2)
}
@@ -309,7 +296,7 @@ func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, format l
return true
})
h.formatStdLogHeader(buf, format, r.Level, r.Time, object, lineInfo)
h.formatStdLogHeader(buf, r.Level, r.Time, object, lineInfo)
buf.WriteString(r.Message)
if buf.Len() == 0 || buf.Bytes()[buf.Len()-1] != '\n' { // Ensure newline
buf.WriteByte('\n')
@@ -318,13 +305,13 @@ func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, format l
}
// Create a log in JSON format into buf.
func (h *OutputHandler) jsonLog(ctx context.Context, buf *bytes.Buffer, format logFormat, r slog.Record) (err error) {
func (h *OutputHandler) jsonLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) (err error) {
// Call the JSON handler to create the JSON in buf
r.AddAttrs(
slog.String("source", getCaller(2)),
)
// Add PID if requested
if format&logFormatPid != 0 {
if h.format&logFormatPid != 0 {
r.AddAttrs(slog.Int("pid", os.Getpid()))
}
h.mu.Lock()
@@ -344,15 +331,8 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
buf *bytes.Buffer
)
// Read the format under the mutex once so it is consistent
// throughout this call. The mutex is released before calling
// jsonLog/textLog (which may re-acquire it) to avoid deadlock.
h.mu.Lock()
format := h.format
h.mu.Unlock()
// Check whether we need to build Text or JSON logs or both
needJSON := format&logFormatJSON != 0
needJSON := h.format&logFormatJSON != 0
needText := !needJSON
for _, out := range h.outputExtra {
if out.json {
@@ -365,7 +345,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
if needJSON {
var bufJSONBack [256]byte
bufJSON = bytes.NewBuffer(bufJSONBack[:0])
err = h.jsonLog(ctx, bufJSON, format, r)
err = h.jsonLog(ctx, bufJSON, r)
if err != nil {
return err
}
@@ -374,7 +354,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
if needText {
var bufTextBack [256]byte
bufText = bytes.NewBuffer(bufTextBack[:0])
err = h.textLog(ctx, bufText, format, r)
err = h.textLog(ctx, bufText, r)
if err != nil {
return err
}
@@ -384,7 +364,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
defer h.mu.Unlock()
// Do the log, either to the default destination or to the alternate logging system
if format&logFormatJSON != 0 {
if h.format&logFormatJSON != 0 {
buf = bufJSON
} else {
buf = bufText
@@ -410,13 +390,13 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
// WithAttrs creates a new handler with the same writer, options, and flags.
// Attributes are ignored for the output format of this specific handler.
func (h *OutputHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.getFormat())
return NewOutputHandler(h.writer, &h.opts, h.format)
}
// WithGroup creates a new handler with the same writer, options, and flags.
// Groups are ignored for the output format of this specific handler.
func (h *OutputHandler) WithGroup(name string) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.getFormat())
return NewOutputHandler(h.writer, &h.opts, h.format)
}
// Check interface
+7 -106
View File
@@ -4,11 +4,9 @@ import (
"bytes"
"context"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
"testing"
"time"
@@ -93,9 +91,9 @@ func TestFormatStdLogHeader(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
h := NewOutputHandler(&bytes.Buffer{}, nil, tc.format)
h := &OutputHandler{format: tc.format}
buf := &bytes.Buffer{}
h.formatStdLogHeader(buf, tc.format, slog.LevelInfo, t0, tc.object, tc.lineInfo)
h.formatStdLogHeader(buf, slog.LevelInfo, t0, tc.object, tc.lineInfo)
if !strings.HasPrefix(buf.String(), tc.wantPrefix) {
t.Errorf("%s: got %q; want prefix %q", tc.name, buf.String(), tc.wantPrefix)
}
@@ -116,13 +114,13 @@ func TestEnabled(t *testing.T) {
// Test clearFormatFlags and setFormatFlags bitwise ops.
func TestClearSetFormatFlags(t *testing.T) {
h := NewOutputHandler(&bytes.Buffer{}, nil, logFormatDate|logFormatTime)
h := &OutputHandler{format: logFormatDate | logFormatTime}
h.clearFormatFlags(logFormatTime)
assert.True(t, h.getFormat()&logFormatTime == 0)
assert.True(t, h.format&logFormatTime == 0)
h.setFormatFlags(logFormatMicroseconds)
assert.True(t, h.getFormat()&logFormatMicroseconds != 0)
assert.True(t, h.format&logFormatMicroseconds != 0)
}
// Test SetOutput and ResetOutput override the default writer.
@@ -233,7 +231,7 @@ func TestTextLogAndJsonLog(t *testing.T) {
// textLog
bufText := &bytes.Buffer{}
require.NoError(t, h.textLog(context.Background(), bufText, h.getFormat(), r))
require.NoError(t, h.textLog(context.Background(), bufText, r))
out := bufText.String()
if !strings.Contains(out, "WARNING") || !strings.Contains(out, "obj:") || !strings.HasSuffix(out, "\n") {
t.Errorf("textLog output = %q", out)
@@ -241,110 +239,13 @@ func TestTextLogAndJsonLog(t *testing.T) {
// jsonLog
bufJSON := &bytes.Buffer{}
require.NoError(t, h.jsonLog(context.Background(), bufJSON, h.getFormat(), r))
require.NoError(t, h.jsonLog(context.Background(), bufJSON, r))
j := bufJSON.String()
if !strings.Contains(j, `"level":"warning"`) || !strings.Contains(j, `"msg":"msg!"`) {
t.Errorf("jsonLog output = %q", j)
}
}
// Test concurrent access to the handler does not race or deadlock.
func TestOutputHandlerConcurrency(t *testing.T) {
h := NewOutputHandler(io.Discard, nil, logFormatDate|logFormatTime)
ctx := context.Background()
const goroutines = 10
const iterations = 500
var wg sync.WaitGroup
// Goroutines calling Handle (text format)
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
r := slog.NewRecord(t0, slog.LevelInfo, "concurrent text", 0)
r.AddAttrs(slog.String("object", "obj"))
_ = h.Handle(ctx, r)
}
}()
}
// Goroutines calling setFormat (switching between text and JSON)
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
if j%2 == 0 {
h.setFormat(logFormatDate | logFormatTime)
} else {
h.setFormat(logFormatJSON)
}
}
}()
}
// Goroutines calling setFormatFlags / clearFormatFlags
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
h.setFormatFlags(logFormatPid | logFormatMicroseconds)
h.clearFormatFlags(logFormatPid | logFormatMicroseconds)
}
}()
// Goroutines calling SetLevel
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
if j%2 == 0 {
h.SetLevel(slog.LevelDebug)
} else {
h.SetLevel(slog.LevelInfo)
}
}
}()
// Goroutines calling SetOutput / ResetOutput
wg.Add(1)
go func() {
defer wg.Done()
noop := func(_ slog.Level, _ string) {}
for j := 0; j < iterations; j++ {
h.SetOutput(noop)
h.ResetOutput()
}
}()
// Goroutines calling WithAttrs / WithGroup (reads format)
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
_ = h.WithAttrs(nil)
_ = h.WithGroup("g")
}
}()
// Use a channel with a timeout to detect deadlocks
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// success
case <-time.After(30 * time.Second):
t.Fatal("timed out waiting for concurrent goroutines — probable deadlock")
}
}
// Table-driven test for JSON vs text Handle behavior.
func TestHandleFormatFlags(t *testing.T) {
r := slog.NewRecord(t0, slog.LevelInfo, "hi", 0)
-3
View File
@@ -1341,9 +1341,6 @@ func runSyncCopyMove(ctx context.Context, fdst, fsrc fs.Fs, deleteMode fs.Delete
if deleteMode != fs.DeleteModeOff && DoMove {
return fserrors.FatalError(errors.New("can't delete and move at the same time"))
}
if ci.ResumeListings != "" && deleteMode != fs.DeleteModeOff {
return fserrors.FatalError(errors.New("can't use --resume-listings with sync or other delete modes - a resumed listing skips already-listed files which would cause them to be deleted from the destination"))
}
// Run an extra pass to delete only
if deleteMode == fs.DeleteModeBefore {
if ci.TrackRenames {
-149
View File
@@ -38,7 +38,6 @@ import (
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/resume"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -1136,154 +1135,6 @@ func Run(t *testing.T, opt *Opt) {
fstest.CheckListing(t, f, []fstest.Item{file1, file2})
})
// TestFsCanResumeListing tests the resumable listing feature
t.Run("FsCanResumeListing", func(t *testing.T) {
skipIfNotOk(t)
if !f.Features().CanResumeListing {
t.Skip("FS does not support resumable listings")
}
require.NotNil(t, f.Features().ListP, "CanResumeListing backends must have ListP")
// Helper to collect all entries from ListP
listAll := func(ctx context.Context, dir string) fs.DirEntries {
t.Helper()
var entries fs.DirEntries
err := f.Features().ListP(ctx, dir, func(e fs.DirEntries) error {
entries = append(entries, e...)
return nil
})
require.NoError(t, err)
return entries
}
// List without resume - get baseline
baseEntries := listAll(ctx, "")
require.NotEmpty(t, baseEntries, "test requires existing files")
t.Run("CheckpointSavedAndCleaned", func(t *testing.T) {
// List with --resume-listings enabled
resumeDir := t.TempDir()
resumeCtx, resumeCi := fs.AddConfig(ctx)
resumeCi.ResumeListings = resumeDir
entries := listAll(resumeCtx, "")
assert.Equal(t, len(baseEntries), len(entries), "resumed listing should return same entries when no checkpoint exists")
// After successful completion, checkpoint should be cleaned up
dirEntries, err := os.ReadDir(resumeDir)
require.NoError(t, err)
// Filter out any non-json files
var jsonFiles []os.DirEntry
for _, e := range dirEntries {
if strings.HasSuffix(e.Name(), ".json") {
jsonFiles = append(jsonFiles, e)
}
}
assert.Empty(t, jsonFiles, "checkpoint should be deleted after successful listing")
})
t.Run("ResumeFromCheckpoint", func(t *testing.T) {
// Sort baseline entries to find a good startAfter key
var names []string
for _, e := range baseEntries {
names = append(names, e.Remote())
}
sort.Strings(names)
if len(names) < 2 {
t.Skip("need at least 2 entries to test resume")
}
// Pick the first name as startAfter - resumed listing should skip it
startAfter := names[0]
// Create a checkpoint that resumes after the first entry
resumeDir := t.TempDir()
store, err := resume.NewStore(resumeDir)
require.NoError(t, err)
remoteName := fs.ConfigString(f)
require.NoError(t, store.Save(&resume.Checkpoint{
RemoteName: remoteName,
Dir: "",
LastKey: startAfter,
}))
// List with resume - should skip entries <= startAfter
resumeCtx, resumeCi := fs.AddConfig(ctx)
resumeCi.ResumeListings = resumeDir
resumedEntries := listAll(resumeCtx, "")
var resumedNames []string
for _, e := range resumedEntries {
resumedNames = append(resumedNames, e.Remote())
}
// The resumed listing should have fewer entries
assert.Less(t, len(resumedEntries), len(baseEntries),
"resumed listing should have fewer entries than full listing")
// The startAfter entry should not appear in the resumed listing
assert.NotContains(t, resumedNames, startAfter,
"entry at checkpoint should not appear in resumed listing")
// All resumed entries should exist in the full listing
for _, name := range resumedNames {
assert.Contains(t, names, name,
"resumed entry %q should exist in full listing", name)
}
})
// Test ListR resume if available
if f.Features().ListR != nil {
t.Run("ListRResumeFromCheckpoint", func(t *testing.T) {
// Get baseline from ListR
var baseNames []string
err := f.Features().ListR(ctx, "", func(entries fs.DirEntries) error {
for _, e := range entries {
baseNames = append(baseNames, e.Remote())
}
return nil
})
require.NoError(t, err)
sort.Strings(baseNames)
if len(baseNames) < 2 {
t.Skip("need at least 2 entries to test ListR resume")
}
startAfter := baseNames[0]
// Create checkpoint
resumeDir := t.TempDir()
store, err := resume.NewStore(resumeDir)
require.NoError(t, err)
remoteName := fs.ConfigString(f)
require.NoError(t, store.Save(&resume.Checkpoint{
RemoteName: remoteName,
Dir: "",
LastKey: startAfter,
}))
// List with resume
resumeCtx, resumeCi := fs.AddConfig(ctx)
resumeCi.ResumeListings = resumeDir
var resumedNames []string
err = f.Features().ListR(resumeCtx, "", func(entries fs.DirEntries) error {
for _, e := range entries {
resumedNames = append(resumedNames, e.Remote())
}
return nil
})
require.NoError(t, err)
assert.Less(t, len(resumedNames), len(baseNames),
"resumed ListR should have fewer entries than full listing")
assert.NotContains(t, resumedNames, startAfter,
"entry at checkpoint should not appear in resumed ListR")
})
}
})
// TestFsNewObjectDir tests NewObject on a directory which should produce fs.ErrorIsDir if possible or fs.ErrorObjectNotFound if not
t.Run("FsNewObjectDir", func(t *testing.T) {
skipIfNotOk(t)
-1
View File
@@ -60,7 +60,6 @@ require (
github.com/minio/minio-go/v7 v7.0.98
github.com/mitchellh/go-homedir v1.1.0
github.com/moby/sys/mountinfo v0.7.2
github.com/muesli/reflow v0.3.0
github.com/ncw/swift/v2 v2.0.5
github.com/oracle/oci-go-sdk/v65 v65.108.2
github.com/patrickmn/go-cache v2.1.0+incompatible
-5
View File
@@ -499,7 +499,6 @@ github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stg
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ=
github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mholt/archives v0.1.5 h1:Fh2hl1j7VEhc6DZs2DLMgiBNChUux154a1G+2esNvzQ=
@@ -524,8 +523,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncw/swift/v2 v2.0.5 h1:9o5Gsd7bInAFEqsGPcaUdsboMbqf8lnNtxqWKFT9iz8=
@@ -601,8 +598,6 @@ github.com/relvacode/iso8601 v1.7.0 h1:BXy+V60stMP6cpswc+a93Mq3e65PfXCgDFfhvNNGr
github.com/relvacode/iso8601 v1.7.0/go.mod h1:FlNp+jz+TXpyRqgmM7tnzHHzBnz776kmAH2h3sZCn0I=
github.com/rfjakob/eme v1.2.0 h1:8dAHL+WVAw06+7DkRKnRiFp1JL3QjcJEZFqDnndUaSI=
github.com/rfjakob/eme v1.2.0/go.mod h1:cVvpasglm/G3ngEfcfT/Wt0GwhkuO32pf/poW6Nyk1k=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
-214
View File
@@ -1,214 +0,0 @@
// Package resume manages checkpoint state files for resumable listings.
//
// When --resume-listings is set to a local directory path, rclone
// saves listing progress so that interrupted listings can be resumed
// from where they left off rather than starting from scratch.
package resume
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/rclone/rclone/fs"
)
const checkpointVersion = 1
// Checkpoint represents the saved state of a listing in progress.
type Checkpoint struct {
Version int `json:"version"`
RemoteName string `json:"remoteName"` // e.g. "s3:mybucket/path"
Dir string `json:"dir"` // directory being listed
LastKey string `json:"lastKey"` // last key delivered to callback
UpdatedAt time.Time `json:"updatedAt"`
}
// Store manages checkpoint files in a local directory.
type Store struct {
dir string
}
// NewStore creates a Store that persists checkpoints in dir.
// The directory is created if it does not exist.
func NewStore(dir string) (*Store, error) {
if err := os.MkdirAll(dir, 0o777); err != nil {
return nil, fmt.Errorf("resume: create store directory: %w", err)
}
return &Store{dir: dir}, nil
}
// stateKey returns a deterministic file path for the given remote+dir.
func (s *Store) stateKey(remoteName, dir string) string {
h := sha256.Sum256([]byte(remoteName + ":" + dir))
return filepath.Join(s.dir, fmt.Sprintf("%x.json", h))
}
// Load reads a checkpoint for the given remote and directory.
// Returns nil, nil if no checkpoint exists or the checkpoint doesn't
// match (wrong version, different remote/dir).
func (s *Store) Load(remoteName, dir string) (*Checkpoint, error) {
path := s.stateKey(remoteName, dir)
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, fmt.Errorf("resume: read checkpoint: %w", err)
}
var cp Checkpoint
if err := json.Unmarshal(data, &cp); err != nil {
return nil, fmt.Errorf("resume: unmarshal checkpoint: %w", err)
}
if cp.Version != checkpointVersion {
return nil, nil
}
if cp.RemoteName != remoteName || cp.Dir != dir {
return nil, nil
}
return &cp, nil
}
// Save atomically writes a checkpoint to disk.
func (s *Store) Save(cp *Checkpoint) error {
cp.Version = checkpointVersion
cp.UpdatedAt = time.Now().UTC()
payload, err := json.MarshalIndent(cp, "", " ")
if err != nil {
return fmt.Errorf("resume: marshal checkpoint: %w", err)
}
path := s.stateKey(cp.RemoteName, cp.Dir)
// Atomic write: temp file + rename
tmpFile, err := os.CreateTemp(s.dir, ".rclone-resume-*.tmp")
if err != nil {
return fmt.Errorf("resume: create temp file: %w", err)
}
tmpPath := tmpFile.Name()
_, writeErr := tmpFile.Write(payload)
closeErr := tmpFile.Close()
if writeErr != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("resume: write temp file: %w", writeErr)
}
if closeErr != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("resume: close temp file: %w", closeErr)
}
if err := os.Rename(tmpPath, path); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("resume: rename temp file: %w", err)
}
return nil
}
// WrapCallback loads any existing checkpoint for this remote+dir and returns:
// - startAfter: last key from a previous interrupted listing ("" if none)
// - wrappedCallback: tracks lastKey per page, saves checkpoint after each page
// - done: defer this — it deletes the checkpoint only if *errp == nil
func (s *Store) WrapCallback(remoteName, dir string, callback fs.ListRCallback) (
startAfter string, wrappedCallback fs.ListRCallback, done func(errp *error), err error) {
cp, err := s.Load(remoteName, dir)
if err != nil {
return "", nil, nil, fmt.Errorf("resume: load checkpoint: %w", err)
}
if cp != nil {
startAfter = cp.LastKey
fs.Infof(nil, "Resuming listing of %q from checkpoint %q", dir, startAfter)
}
var lastKey string
wrappedCallback = func(entries fs.DirEntries) error {
// Track the max key in this page for checkpointing
for _, entry := range entries {
key := entry.Remote()
if key > lastKey {
lastKey = key
}
}
// Pass entries through to the original callback
if err := callback(entries); err != nil {
return err
}
// Save checkpoint after each page
if lastKey != "" {
saveCP := &Checkpoint{
RemoteName: remoteName,
Dir: dir,
LastKey: lastKey,
}
if err := s.Save(saveCP); err != nil {
fs.Errorf(nil, "Failed to save listing checkpoint: %v", err)
}
}
return nil
}
done = func(errp *error) {
if *errp != nil {
return
}
if err := s.Delete(remoteName, dir); err != nil {
fs.Errorf(nil, "Failed to delete listing checkpoint: %v", err)
}
}
return startAfter, wrappedCallback, done, nil
}
// Setup is the top-level entry point for backends to add resume support.
//
// If --resume-listings is not configured or enabled is false, it returns
// passthrough values: startAfter="", the original callback, and a no-op done.
//
// Otherwise it creates a Store, loads any existing checkpoint, and wraps the
// callback to save progress after each page. done should be deferred — it
// deletes the checkpoint only when *errp == nil.
//
// Typical usage in a backend ListP/ListR:
//
// func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (returnErr error) {
// bucket, directory := f.split(dir)
// startAfter, callback, done, err := resume.Setup(ctx, bucket != "", f, dir, callback)
// if err != nil { return err }
// defer done(&returnErr)
// ...
// }
func Setup(ctx context.Context, enabled bool, f fs.Fs, dir string, callback fs.ListRCallback) (
startAfter string, wrappedCallback fs.ListRCallback, done func(errp *error), err error) {
ci := fs.GetConfig(ctx)
if !enabled || ci.ResumeListings == "" {
return "", callback, func(*error) {}, nil
}
store, err := NewStore(ci.ResumeListings)
if err != nil {
return "", nil, nil, err
}
return store.WrapCallback(fs.ConfigString(f), dir, callback)
}
// Delete removes the checkpoint for the given remote and directory.
// It is not an error if the checkpoint does not exist.
func (s *Store) Delete(remoteName, dir string) error {
path := s.stateKey(remoteName, dir)
err := os.Remove(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("resume: delete checkpoint: %w", err)
}
return nil
}
-293
View File
@@ -1,293 +0,0 @@
package resume
import (
"context"
"testing"
"time"
_ "github.com/rclone/rclone/backend/memory"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSaveLoadRoundTrip(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp := &Checkpoint{
RemoteName: "s3:mybucket/path",
Dir: "subdir/",
LastKey: "subdir/file-1000",
}
require.NoError(t, store.Save(cp))
loaded, err := store.Load("s3:mybucket/path", "subdir/")
require.NoError(t, err)
require.NotNil(t, loaded)
assert.Equal(t, checkpointVersion, loaded.Version)
assert.Equal(t, "s3:mybucket/path", loaded.RemoteName)
assert.Equal(t, "subdir/", loaded.Dir)
assert.Equal(t, "subdir/file-1000", loaded.LastKey)
assert.False(t, loaded.UpdatedAt.IsZero())
}
func TestLoadNotFound(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp, err := store.Load("s3:mybucket", "")
require.NoError(t, err)
assert.Nil(t, cp)
}
func TestLoadRemoteMismatch(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp := &Checkpoint{
RemoteName: "s3:bucket-a",
Dir: "dir/",
LastKey: "dir/obj-500",
}
require.NoError(t, store.Save(cp))
// Different remote name - hash differs, so file not found
loaded, err := store.Load("s3:bucket-b", "dir/")
require.NoError(t, err)
assert.Nil(t, loaded)
}
func TestLoadDirMismatch(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp := &Checkpoint{
RemoteName: "s3:bucket",
Dir: "dir-a/",
LastKey: "dir-a/obj-500",
}
require.NoError(t, store.Save(cp))
// Different dir - hash differs, so file not found
loaded, err := store.Load("s3:bucket", "dir-b/")
require.NoError(t, err)
assert.Nil(t, loaded)
}
func TestDelete(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp := &Checkpoint{
RemoteName: "s3:bucket",
Dir: "",
LastKey: "obj-100",
}
require.NoError(t, store.Save(cp))
// Verify it exists
loaded, err := store.Load("s3:bucket", "")
require.NoError(t, err)
require.NotNil(t, loaded)
// Delete
require.NoError(t, store.Delete("s3:bucket", ""))
// Verify it's gone
loaded, err = store.Load("s3:bucket", "")
require.NoError(t, err)
assert.Nil(t, loaded)
}
func TestDeleteNonExistent(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
// Should not error
require.NoError(t, store.Delete("s3:bucket", "missing/"))
}
func TestWrapCallbackNoCheckpoint(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
var received fs.DirEntries
callback := func(entries fs.DirEntries) error {
received = append(received, entries...)
return nil
}
startAfter, wrapped, done, err := store.WrapCallback("s3:bucket", "dir", callback)
require.NoError(t, err)
assert.Equal(t, "", startAfter, "no checkpoint should give empty startAfter")
// Send a page of entries
entries := fs.DirEntries{
fs.NewDir("dir/aaa", time.Time{}),
fs.NewDir("dir/zzz", time.Time{}),
}
require.NoError(t, wrapped(entries))
assert.Len(t, received, 2, "entries should pass through")
// Checkpoint should exist now
cp, err := store.Load("s3:bucket", "dir")
require.NoError(t, err)
require.NotNil(t, cp)
assert.Equal(t, "dir/zzz", cp.LastKey)
// Call done with nil error - checkpoint should be deleted
var noErr error
done(&noErr)
cp, err = store.Load("s3:bucket", "dir")
require.NoError(t, err)
assert.Nil(t, cp)
}
func TestWrapCallbackWithCheckpoint(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
// Save an existing checkpoint
require.NoError(t, store.Save(&Checkpoint{
RemoteName: "s3:bucket",
Dir: "",
LastKey: "file-500",
}))
callback := func(entries fs.DirEntries) error { return nil }
startAfter, _, _, err := store.WrapCallback("s3:bucket", "", callback)
require.NoError(t, err)
assert.Equal(t, "file-500", startAfter, "should resume from checkpoint")
}
func TestWrapCallbackTracksMaxKey(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
callback := func(entries fs.DirEntries) error { return nil }
_, wrapped, _, err := store.WrapCallback("s3:bucket", "", callback)
require.NoError(t, err)
// First page
require.NoError(t, wrapped(fs.DirEntries{
fs.NewDir("bbb", time.Time{}),
fs.NewDir("aaa", time.Time{}),
}))
cp, err := store.Load("s3:bucket", "")
require.NoError(t, err)
require.NotNil(t, cp)
assert.Equal(t, "bbb", cp.LastKey, "should track max key across entries")
// Second page with higher keys
require.NoError(t, wrapped(fs.DirEntries{
fs.NewDir("ddd", time.Time{}),
fs.NewDir("ccc", time.Time{}),
}))
cp, err = store.Load("s3:bucket", "")
require.NoError(t, err)
require.NotNil(t, cp)
assert.Equal(t, "ddd", cp.LastKey, "should track max key across pages")
}
func TestSetupDisabled(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.ResumeListings = "" // not configured
called := false
callback := func(entries fs.DirEntries) error {
called = true
return nil
}
startAfter, wrapped, done, err := Setup(ctx, true, nil, "", callback)
require.NoError(t, err)
assert.Equal(t, "", startAfter)
// Should be the original callback (passthrough)
require.NoError(t, wrapped(nil))
assert.True(t, called)
// done should be safe to call
var noErr error
done(&noErr)
}
func TestSetupEnabledFalse(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.ResumeListings = t.TempDir()
callback := func(entries fs.DirEntries) error { return nil }
// enabled=false should return passthrough even with ResumeListings set
startAfter, _, done, err := Setup(ctx, false, nil, "", callback)
require.NoError(t, err)
assert.Equal(t, "", startAfter)
var noErr error
done(&noErr)
}
func TestSetupEnabled(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.ResumeListings = t.TempDir()
memFs, err := fs.NewFs(ctx, ":memory:")
require.NoError(t, err)
remoteName := fs.ConfigString(memFs)
var received fs.DirEntries
callback := func(entries fs.DirEntries) error {
received = append(received, entries...)
return nil
}
startAfter, wrapped, done, err := Setup(ctx, true, memFs, "dir", callback)
require.NoError(t, err)
assert.Equal(t, "", startAfter, "no prior checkpoint")
// Send entries through wrapped callback
require.NoError(t, wrapped(fs.DirEntries{
fs.NewDir("dir/file1", time.Time{}),
}))
assert.Len(t, received, 1)
// Checkpoint should exist
store, err := NewStore(ci.ResumeListings)
require.NoError(t, err)
cp, err := store.Load(remoteName, "dir")
require.NoError(t, err)
require.NotNil(t, cp)
assert.Equal(t, "dir/file1", cp.LastKey)
// done() cleans up on success
var noErr error
done(&noErr)
cp, err = store.Load(remoteName, "dir")
require.NoError(t, err)
assert.Nil(t, cp)
}
func TestSaveOverwrites(t *testing.T) {
store, err := NewStore(t.TempDir())
require.NoError(t, err)
cp := &Checkpoint{
RemoteName: "s3:bucket",
Dir: "",
LastKey: "obj-100",
}
require.NoError(t, store.Save(cp))
cp.LastKey = "obj-200"
require.NoError(t, store.Save(cp))
loaded, err := store.Load("s3:bucket", "")
require.NoError(t, err)
require.NotNil(t, loaded)
assert.Equal(t, "obj-200", loaded.LastKey)
}