Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d3ed12fab | ||
|
|
29809bb8e4 | ||
|
|
35752d0079 | ||
|
|
acda43a74f | ||
|
|
4343b80949 | ||
|
|
c00756810a | ||
|
|
0157a1fb1e | ||
|
|
fc50f3e731 | ||
|
|
869f777594 | ||
|
|
acb6155654 | ||
|
|
f60213545b | ||
|
|
92058f15c4 | ||
|
|
c55634bdf8 | ||
|
|
667903dca0 | ||
|
|
15419f90c2 | ||
|
|
84698c3d28 | ||
|
|
1bbe758bc5 | ||
|
|
4c8bfb7500 | ||
|
|
0c8d098b7f | ||
|
|
895e56e401 | ||
|
|
daacfb6035 | ||
|
|
384e905373 | ||
|
|
de67f29b3f | ||
|
|
40642fee01 | ||
|
|
fdda89ae63 | ||
|
|
d86b72c405 | ||
|
|
03b06ac459 | ||
|
|
38926f43be | ||
|
|
3e78426fc9 | ||
|
|
dac3fa851e | ||
|
|
7b54c7a6e6 | ||
|
|
7200e377dd | ||
|
|
6f1678419f | ||
|
|
6e99f8b301 | ||
|
|
9d4c912e0e | ||
|
|
0737599cd4 | ||
|
|
3b2011c7a0 | ||
|
|
ef26e6d26d | ||
|
|
c0a8b2597d | ||
|
|
74d65bf670 | ||
|
|
a4e6476642 | ||
|
|
6c66b4985d | ||
|
|
b8b3346499 | ||
|
|
9f89102a57 | ||
|
|
075552367e | ||
|
|
ada5559fe1 |
No files matched your search
@@ -37,7 +37,7 @@ jobs:
|
||||
include:
|
||||
- job_name: linux
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
gotags: cmount
|
||||
build_flags: '-include "^linux/"'
|
||||
check: true
|
||||
@@ -48,14 +48,14 @@ jobs:
|
||||
|
||||
- job_name: linux_386
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
goarch: 386
|
||||
gotags: cmount
|
||||
quicktest: true
|
||||
|
||||
- job_name: mac_amd64
|
||||
os: macos-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
gotags: 'cmount'
|
||||
build_flags: '-include "^darwin/amd64" -cgo'
|
||||
quicktest: true
|
||||
@@ -64,14 +64,14 @@ jobs:
|
||||
|
||||
- job_name: mac_arm64
|
||||
os: macos-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
gotags: 'cmount'
|
||||
build_flags: '-include "^darwin/arm64" -cgo -macos-arch arm64 -cgo-cflags=-I/usr/local/include -cgo-ldflags=-L/usr/local/lib'
|
||||
deploy: true
|
||||
|
||||
- job_name: windows
|
||||
os: windows-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
gotags: cmount
|
||||
cgo: '0'
|
||||
build_flags: '-include "^windows/"'
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
|
||||
- job_name: other_os
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.0'
|
||||
go: '~1.26.3'
|
||||
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
|
||||
compile_all: true
|
||||
deploy: true
|
||||
@@ -227,7 +227,7 @@ jobs:
|
||||
id: setup-go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: '~1.26.0'
|
||||
go-version: '~1.26.3'
|
||||
check-latest: true
|
||||
cache: false
|
||||
|
||||
@@ -318,7 +318,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: '~1.26.0'
|
||||
go-version: '~1.26.3'
|
||||
|
||||
- name: Set global environment variables
|
||||
run: |
|
||||
|
||||
@@ -20,3 +20,4 @@ __pycache__
|
||||
.DS_Store
|
||||
resource_windows_*.syso
|
||||
.devcontainer
|
||||
.vscode/launch.json
|
||||
@@ -34,6 +34,13 @@ import (
|
||||
"github.com/zeebo/blake3"
|
||||
)
|
||||
|
||||
// Pacer settings - tuned to match other rclone backends
|
||||
const (
|
||||
minSleep = 10 * time.Millisecond
|
||||
maxSleep = 2 * time.Second
|
||||
decayConstant = 2 // bigger for slower decay, exponential
|
||||
)
|
||||
|
||||
// Cloudinary shouldn't have a trailing dot if there is no path
|
||||
func cldPathDir(somePath string) string {
|
||||
if somePath == "" || somePath == "." {
|
||||
@@ -189,7 +196,7 @@ func NewFs(ctx context.Context, name string, root string, m configmap.Mapper) (f
|
||||
root: root,
|
||||
opt: *opt,
|
||||
cld: cld,
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(1000), pacer.MaxSleep(10000), pacer.DecayConstant(2))),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
srv: rest.NewClient(client),
|
||||
}
|
||||
|
||||
@@ -586,21 +593,18 @@ func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, err
|
||||
if fserrors.ContextError(ctx, &err) {
|
||||
return false, err
|
||||
}
|
||||
// Cloudinary returns rate-limit windows as "Try again on YYYY-MM-DD HH:MM:SS UTC"
|
||||
// embedded in the error message - honour it as a retry-after.
|
||||
if err != nil {
|
||||
tryAgain := "Try again on "
|
||||
if idx := strings.Index(err.Error(), tryAgain); idx != -1 {
|
||||
layout := "2006-01-02 15:04:05 UTC"
|
||||
dateStr := err.Error()[idx+len(tryAgain) : idx+len(tryAgain)+len(layout)]
|
||||
timestamp, err2 := time.Parse(layout, dateStr)
|
||||
if err2 == nil {
|
||||
if timestamp, err2 := time.Parse(layout, dateStr); err2 == nil {
|
||||
return true, fserrors.NewErrorRetryAfter(time.Until(timestamp))
|
||||
}
|
||||
}
|
||||
|
||||
fs.Debugf(nil, "Retrying API error %v", err)
|
||||
return true, err
|
||||
}
|
||||
|
||||
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
|
||||
}
|
||||
|
||||
|
||||
@@ -238,6 +238,14 @@ type MultiPartAbort struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
// FolderPathResponse is returned by GET /folders/{hash}/path
|
||||
//
|
||||
// Path is the breadcrumb from the drive root down to the requested folder.
|
||||
type FolderPathResponse struct {
|
||||
Status string `json:"status"`
|
||||
Path []Item `json:"path"`
|
||||
}
|
||||
|
||||
// SpaceUsageResponse is returned by GET /user/space-usage
|
||||
type SpaceUsageResponse struct {
|
||||
Used int64 `json:"used"`
|
||||
|
||||
+95
-18
@@ -15,6 +15,7 @@ should stay under that.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -54,7 +55,7 @@ const (
|
||||
rootURL = baseURL + "api/v1"
|
||||
maxUploadParts = 10000 // maximum allowed number of parts in a multi-part upload
|
||||
minChunkSize = fs.SizeSuffix(1024 * 1024 * 5)
|
||||
defaultUploadCutoff = fs.SizeSuffix(200 * 1024 * 1024)
|
||||
defaultUploadCutoff = fs.SizeSuffix(5 * 1024 * 1024) // as per https://docs.drime.cloud/uploads-guide
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
@@ -199,13 +200,16 @@ type Options struct {
|
||||
|
||||
// Fs represents a remote drime
|
||||
type Fs struct {
|
||||
name string // name of this remote
|
||||
root string // the path we are working on
|
||||
opt Options // parsed options
|
||||
features *fs.Features // optional features
|
||||
srv *rest.Client // the connection to the server
|
||||
dirCache *dircache.DirCache // Map of directory path to directory id
|
||||
pacer *fs.Pacer // pacer for API calls
|
||||
name string // name of this remote
|
||||
root string // the path we are working on
|
||||
opt Options // parsed options
|
||||
features *fs.Features // optional features
|
||||
srv *rest.Client // the connection to the server
|
||||
dirCache *dircache.DirCache // Map of directory path to directory id
|
||||
pacer *fs.Pacer // pacer for API calls
|
||||
absRootOnce *sync.Once // protects absRoot computation
|
||||
absRoot string // absolute path of f.root from drive root
|
||||
absRootErr error // error from computing absRoot, if any
|
||||
}
|
||||
|
||||
// Object describes a drime object
|
||||
@@ -330,6 +334,62 @@ func (f *Fs) getItem(ctx context.Context, id string, dirID string, leaf string)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// idToAbsolutePath returns the absolute path (from the user's drive root) of
|
||||
// the folder with the given ID.
|
||||
//
|
||||
// Drime exposes GET /folders/{hash}/path which returns the breadcrumb from
|
||||
// drive root down to the folder. The hash format is undocumented but
|
||||
// observed to be base64("<id>|") - every item drime returns has a `hash`
|
||||
// field of that shape (e.g. id 704791396 => "NzA0NzkxMzk2fA"). The docs
|
||||
// example "MTExMzQ0fHBhZA" decodes to "111344|pad", so a non-empty suffix
|
||||
// after the pipe is also accepted; if drime ever starts requiring a
|
||||
// specific suffix this will break.
|
||||
//
|
||||
// Returns "" for an empty/zero ID (drive root).
|
||||
func (f *Fs) idToAbsolutePath(ctx context.Context, id string) (string, error) {
|
||||
if id == "" || id == "0" {
|
||||
return "", nil
|
||||
}
|
||||
hash := base64.StdEncoding.EncodeToString([]byte(id + "|"))
|
||||
opts := rest.Opts{
|
||||
Method: "GET",
|
||||
Path: "/folders/" + hash + "/path",
|
||||
Parameters: url.Values{},
|
||||
}
|
||||
if f.opt.WorkspaceID != "" {
|
||||
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
|
||||
}
|
||||
var result api.FolderPathResponse
|
||||
var resp *http.Response
|
||||
err := f.pacer.Call(func() (bool, error) {
|
||||
var err error
|
||||
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
|
||||
return shouldRetry(ctx, resp, err)
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get folder path for %q: %w", id, err)
|
||||
}
|
||||
parts := make([]string, 0, len(result.Path))
|
||||
for _, item := range result.Path {
|
||||
parts = append(parts, f.opt.Enc.ToStandardName(item.Name))
|
||||
}
|
||||
return path.Join(parts...), nil
|
||||
}
|
||||
|
||||
// absoluteRoot returns the absolute path from the drive root to the Fs root.
|
||||
// Computed once and cached.
|
||||
func (f *Fs) absoluteRoot(ctx context.Context) (string, error) {
|
||||
f.absRootOnce.Do(func() {
|
||||
rootID, err := f.dirCache.RootID(ctx, false)
|
||||
if err != nil {
|
||||
f.absRootErr = err
|
||||
return
|
||||
}
|
||||
f.absRoot, f.absRootErr = f.idToAbsolutePath(ctx, rootID)
|
||||
})
|
||||
return f.absRoot, f.absRootErr
|
||||
}
|
||||
|
||||
// errorHandler parses a non 2xx error response into an error
|
||||
func errorHandler(resp *http.Response) error {
|
||||
body, err := rest.ReadBody(resp)
|
||||
@@ -370,11 +430,12 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
client := fshttp.NewClient(ctx)
|
||||
|
||||
f := &Fs{
|
||||
name: name,
|
||||
root: root,
|
||||
opt: *opt,
|
||||
srv: rest.NewClient(client).SetRoot(rootURL),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
name: name,
|
||||
root: root,
|
||||
opt: *opt,
|
||||
srv: rest.NewClient(client).SetRoot(rootURL),
|
||||
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
|
||||
absRootOnce: new(sync.Once),
|
||||
}
|
||||
f.features = (&fs.Features{
|
||||
CanHaveEmptyDirectories: true,
|
||||
@@ -709,6 +770,11 @@ func (f *Fs) deleteObject(ctx context.Context, id string) error {
|
||||
return shouldRetry(ctx, resp, err)
|
||||
})
|
||||
if err != nil {
|
||||
// If Drime returns 422 with invalid entry ID, the object is already gone.
|
||||
// Map this to a standard not-found error
|
||||
if strings.Contains(err.Error(), "entry ids is invalid") {
|
||||
return fs.ErrorObjectNotFound
|
||||
}
|
||||
return fmt.Errorf("failed to delete item: %w", err)
|
||||
}
|
||||
// Check the individual result codes also
|
||||
@@ -1096,6 +1162,15 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
|
||||
return info, nil, err
|
||||
}
|
||||
|
||||
// The /s3/multipart/create and /s3/entries endpoints interpret
|
||||
// relativePath as an absolute path from the drive root, not relative to
|
||||
// parent_id. Resolve our root's absolute path so we can build it.
|
||||
absRoot, err := f.absoluteRoot(ctx)
|
||||
if err != nil {
|
||||
return info, nil, fmt.Errorf("failed to resolve absolute path of root: %w", err)
|
||||
}
|
||||
relPath := f.opt.Enc.FromStandardPath(path.Join(absRoot, remote))
|
||||
|
||||
// Temporary Object under construction
|
||||
o := &Object{
|
||||
fs: f,
|
||||
@@ -1129,7 +1204,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
|
||||
Size: createSize,
|
||||
Extension: strings.TrimPrefix(path.Ext(leaf), `.`),
|
||||
ParentID: json.Number(directoryID),
|
||||
RelativePath: f.opt.Enc.FromStandardPath(path.Join(f.root, remote)),
|
||||
RelativePath: relPath,
|
||||
WorkspaceID: f.opt.WorkspaceID,
|
||||
}
|
||||
|
||||
@@ -1156,8 +1231,6 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
|
||||
if ext == "" {
|
||||
ext = "bin"
|
||||
}
|
||||
rel := f.opt.Enc.FromStandardPath(path.Join(f.root, remote))
|
||||
|
||||
chunkWriter := &drimeChunkWriter{
|
||||
uploadID: resp.UploadID,
|
||||
key: resp.Key,
|
||||
@@ -1170,7 +1243,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
|
||||
mime: mime,
|
||||
extension: ext,
|
||||
parentID: json.Number(directoryID),
|
||||
relativePath: rel,
|
||||
relativePath: relPath,
|
||||
}
|
||||
info = fs.ChunkWriterInfo{
|
||||
ChunkSize: int64(chunkSize),
|
||||
@@ -1530,7 +1603,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
fs.Debugf(o, "Removing old object on successful upload")
|
||||
deleteErr := o.fs.deleteObject(ctx, id)
|
||||
if deleteErr != nil {
|
||||
err = fmt.Errorf("failed to delete existing object: %w", deleteErr)
|
||||
if errors.Is(deleteErr, fs.ErrorObjectNotFound) {
|
||||
fs.Debugf(o, "Old object already deleted, safely ignoring")
|
||||
} else {
|
||||
err = fmt.Errorf("failed to delete existing object: %w", deleteErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -52,13 +52,21 @@ func (f *Fs) testUploadTimeout(t *testing.T) {
|
||||
ci.Timeout = saveTimeout
|
||||
}()
|
||||
ci.LowLevelRetries = 1
|
||||
ci.Timeout = fs.Duration(idleTimeout)
|
||||
|
||||
upload := func(concurrency int, shutTimeout time.Duration) (obj fs.Object, err error) {
|
||||
// Use the saved (long) timeout while NewFs dials the FTP control
|
||||
// connection and reads the welcome banner. On slow CI servers this
|
||||
// can take longer than idleTimeout, which would cause a spurious
|
||||
// i/o timeout before the test can run. The connection's idle
|
||||
// deadline is captured at dial time, so the data connection
|
||||
// dialled later inside Put will still get idleTimeout - which is
|
||||
// what the test is actually trying to exercise.
|
||||
ci.Timeout = saveTimeout
|
||||
fixFs := deriveFs(ctx, t, f, settings{
|
||||
"concurrency": concurrency,
|
||||
"shut_timeout": shutTimeout,
|
||||
})
|
||||
ci.Timeout = fs.Duration(idleTimeout)
|
||||
|
||||
// Make test object
|
||||
fileTime := fstest.Time("2020-03-08T09:30:00.000000000Z")
|
||||
|
||||
@@ -156,6 +156,7 @@ type Fs struct {
|
||||
endpoint *url.URL
|
||||
endpointURL string // endpoint as a string
|
||||
httpClient *http.Client
|
||||
fileName string // set if we are pointing to a file
|
||||
}
|
||||
|
||||
// Object is a remote object that has been stat'd (so it exists, but is not necessarily open for reading)
|
||||
@@ -297,6 +298,7 @@ func (f *Fs) httpConnection(ctx context.Context, opt *Options) (isFile bool, err
|
||||
|
||||
if isFile {
|
||||
// Correct root if definitely pointing to a file
|
||||
f.fileName = path.Base(f.root)
|
||||
f.root = path.Dir(f.root)
|
||||
if f.root == "." || f.root == "/" {
|
||||
f.root = ""
|
||||
@@ -564,6 +566,17 @@ func (f *Fs) readDir(ctx context.Context, dir string) (names []string, err error
|
||||
// This should return ErrDirNotFound if the directory isn't
|
||||
// found.
|
||||
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
|
||||
// pointed at a single file: only that file is visible
|
||||
if f.fileName != "" {
|
||||
if dir != "" {
|
||||
return nil, fs.ErrorDirNotFound
|
||||
}
|
||||
obj, err := f.NewObject(ctx, f.fileName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fs.DirEntries{obj}, nil
|
||||
}
|
||||
if !strings.HasSuffix(dir, "/") && dir != "" {
|
||||
dir += "/"
|
||||
}
|
||||
|
||||
@@ -331,7 +331,19 @@ func TestIsAFileRoot(t *testing.T) {
|
||||
f, err := NewFs(context.Background(), remoteName, "one%.txt", m)
|
||||
assert.Equal(t, err, fs.ErrorIsFile)
|
||||
|
||||
testListRoot(t, f, false)
|
||||
entries, err := f.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, 1, len(entries))
|
||||
|
||||
e := entries[0]
|
||||
assert.Equal(t, "one%.txt", e.Remote())
|
||||
assert.Equal(t, int64(5+lineEndSize), e.Size())
|
||||
_, ok := e.(*Object)
|
||||
assert.True(t, ok)
|
||||
|
||||
_, err = f.List(context.Background(), "anysub")
|
||||
assert.Equal(t, fs.ErrorDirNotFound, err)
|
||||
}
|
||||
|
||||
func TestIsAFileSubDir(t *testing.T) {
|
||||
|
||||
@@ -280,6 +280,17 @@ enabled, rclone will no longer update the modtime after copying a file.`,
|
||||
Default: false,
|
||||
Advanced: true,
|
||||
},
|
||||
{
|
||||
Name: "fatal_if_no_space",
|
||||
Help: `Make out-of-space errors fatal during transfers.
|
||||
|
||||
When enabled, an ENOSPC error during a write returns a fatal error so
|
||||
that rclone aborts rather than retrying the operation. Useful for
|
||||
backup scripts that should halt loudly on a full disk rather than spin
|
||||
retrying.`,
|
||||
Default: false,
|
||||
Advanced: true,
|
||||
},
|
||||
{
|
||||
Name: "time_type",
|
||||
Help: `Set what kind of time is returned.
|
||||
@@ -349,6 +360,7 @@ type Options struct {
|
||||
NoPreAllocate bool `config:"no_preallocate"`
|
||||
NoSparse bool `config:"no_sparse"`
|
||||
NoSetModTime bool `config:"no_set_modtime"`
|
||||
FatalIfNoSpace bool `config:"fatal_if_no_space"`
|
||||
TimeType timeType `config:"time_type"`
|
||||
Hashes fs.CommaSepList `config:"hashes"`
|
||||
Enc encoder.MultiEncoder `config:"encoding"`
|
||||
@@ -1410,8 +1422,19 @@ func (nwc nopWriterCloser) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// isDiskFullError returns true if err indicates the underlying filesystem
|
||||
// has run out of space.
|
||||
func isDiskFullError(err error) bool {
|
||||
return errors.Is(err, file.ErrDiskFull) || fserrors.IsErrNoSpace(err)
|
||||
}
|
||||
|
||||
// Update the object from in with modTime and size
|
||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
|
||||
defer func() {
|
||||
if err != nil && o.fs.opt.FatalIfNoSpace && isDiskFullError(err) {
|
||||
err = fserrors.FatalError(err)
|
||||
}
|
||||
}()
|
||||
var out io.WriteCloser
|
||||
var hasher *hash.MultiHasher
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//go:build !plan9
|
||||
|
||||
// Tests for the FatalIfNoSpace option and isDiskFullError helper.
|
||||
//
|
||||
// Kept in a separate file with a !plan9 build tag because syscall.ENOSPC
|
||||
// is not portable to plan9, mirroring the split in
|
||||
// fs/fserrors/enospc_error.go vs fs/fserrors/enospc_error_notsupported.go.
|
||||
|
||||
package local
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/lib/file"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// errReader is an io.Reader that always returns the configured error,
|
||||
// used to inject a synthetic disk-full failure into Update's io.Copy.
|
||||
type errReader struct{ err error }
|
||||
|
||||
func (r errReader) Read(p []byte) (int, error) { return 0, r.err }
|
||||
|
||||
// TestIsDiskFullError covers the helper used by the Update defer.
|
||||
func TestIsDiskFullError(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"nil", nil, false},
|
||||
{"unrelated error", errors.New("unrelated error"), false},
|
||||
{"syscall.ENOSPC direct", syscall.ENOSPC, true},
|
||||
{"syscall.ENOSPC wrapped", fmt.Errorf("io.Copy: %w", syscall.ENOSPC), true},
|
||||
{"file.ErrDiskFull direct", file.ErrDiskFull, true},
|
||||
{"file.ErrDiskFull wrapped", fmt.Errorf("preallocate: %w", file.ErrDiskFull), true},
|
||||
{"os.PathError wrapping ENOSPC", &os.PathError{Op: "write", Path: "/foo", Err: syscall.ENOSPC}, true},
|
||||
{"os.SyscallError wrapping ENOSPC", os.NewSyscallError("write", syscall.ENOSPC), true},
|
||||
{"os.PathError wrapping unrelated", &os.PathError{Op: "write", Path: "/foo", Err: syscall.EPERM}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
assert.Equal(t, c.want, isDiskFullError(c.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// updateWithReader runs Update with an injected reader error and the given
|
||||
// FatalIfNoSpace setting, returning the error from Update.
|
||||
func updateWithReader(t *testing.T, fatalIfNoSpace bool, readerErr error) error {
|
||||
t.Helper()
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
f.opt.FatalIfNoSpace = fatalIfNoSpace
|
||||
|
||||
src := object.NewStaticObjectInfo("test.txt", time.Now(), 100, true, nil, f)
|
||||
o := &Object{
|
||||
fs: f,
|
||||
remote: "test.txt",
|
||||
path: filepath.Join(r.LocalName, "test.txt"),
|
||||
}
|
||||
return o.Update(context.Background(), errReader{err: readerErr}, src)
|
||||
}
|
||||
|
||||
// TestUpdateFatalIfNoSpaceOff verifies an ENOSPC during a write is NOT
|
||||
// wrapped as fatal when the option is off.
|
||||
func TestUpdateFatalIfNoSpaceOff(t *testing.T) {
|
||||
err := updateWithReader(t, false, syscall.ENOSPC)
|
||||
require.Error(t, err)
|
||||
assert.False(t, fserrors.IsFatalError(err), "ENOSPC must not be fatal when FatalIfNoSpace=false")
|
||||
}
|
||||
|
||||
// TestUpdateFatalIfNoSpaceOn verifies an ENOSPC during a write IS wrapped as
|
||||
// fatal when the option is on.
|
||||
func TestUpdateFatalIfNoSpaceOn(t *testing.T) {
|
||||
err := updateWithReader(t, true, syscall.ENOSPC)
|
||||
require.Error(t, err)
|
||||
assert.True(t, fserrors.IsFatalError(err), "ENOSPC must be fatal when FatalIfNoSpace=true")
|
||||
}
|
||||
|
||||
// TestUpdateFatalIfNoSpaceOnButNotDiskFull verifies non-disk-full errors are
|
||||
// NOT wrapped as fatal even when the option is on.
|
||||
func TestUpdateFatalIfNoSpaceOnButNotDiskFull(t *testing.T) {
|
||||
err := updateWithReader(t, true, errors.New("unrelated network error"))
|
||||
require.Error(t, err)
|
||||
assert.False(t, fserrors.IsFatalError(err), "non-disk-full errors must not be fatal regardless of option")
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/configstruct"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/rclone/rclone/fs/fshttp"
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
"github.com/rclone/rclone/lib/dircache"
|
||||
"github.com/rclone/rclone/lib/encoder"
|
||||
@@ -420,6 +421,16 @@ func isDecimalString(value string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// protonLogger adapts rclone's fs.Debugf/Logf/Errorf into the
|
||||
// resty.Logger / common.Logger shape expected by Proton-API-Bridge and
|
||||
// go-proton-api so that library output participates in -v / -vv levels
|
||||
// and is captured by --log-file.
|
||||
type protonLogger struct{ f *Fs }
|
||||
|
||||
func (l protonLogger) Errorf(format string, v ...interface{}) { fs.Errorf(l.f, format, v...) }
|
||||
func (l protonLogger) Warnf(format string, v ...interface{}) { fs.Logf(l.f, format, v...) }
|
||||
func (l protonLogger) Debugf(format string, v ...interface{}) { fs.Debugf(l.f, format, v...) }
|
||||
|
||||
func newProtonDrive(ctx context.Context, f *Fs, opt *Options, m configmap.Mapper) (*protonDriveAPI.ProtonDrive, error) {
|
||||
config := protonDriveAPI.NewDefaultConfig()
|
||||
config.AppVersion = opt.AppVersion
|
||||
@@ -428,6 +439,15 @@ func newProtonDrive(ctx context.Context, f *Fs, opt *Options, m configmap.Mapper
|
||||
}
|
||||
config.UserAgent = f.ci.UserAgent // opt.UserAgent
|
||||
|
||||
// Route HTTP through rclone's transport so global flags such as
|
||||
// --dump headers, --no-check-certificate, --user-agent, --bind,
|
||||
// --ca-cert and --header all take effect against Proton Drive.
|
||||
config.Transport = fshttp.NewTransport(ctx)
|
||||
|
||||
// Route bridge and go-proton-api log output through rclone's
|
||||
// logging system so it honours -v / -vv and --log-file.
|
||||
config.Logger = protonLogger{f: f}
|
||||
|
||||
config.ReplaceExistingDraft = opt.ReplaceExistingDraft
|
||||
config.EnableCaching = opt.EnableCaching
|
||||
|
||||
@@ -999,7 +1019,7 @@ func (o *Object) Storable() bool {
|
||||
|
||||
// Open opens the file for read. Call Close() on the returned io.ReadCloser
|
||||
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
|
||||
fs.FixRangeOption(options, *o.originalSize)
|
||||
fs.FixRangeOption(options, o.Size())
|
||||
var offset, limit int64 = 0, -1
|
||||
for _, option := range options { // if the caller passes in nil for options, it will become array of nil
|
||||
switch x := option.(type) {
|
||||
|
||||
@@ -4,20 +4,26 @@ region:
|
||||
au-east-1: AU East 1
|
||||
eu-central: EU Central
|
||||
eu-south-1: EU South 1
|
||||
eu-west-1: EU West 1
|
||||
jp-central-1: JP Central 1
|
||||
uk-east-1: UK East 1
|
||||
us-central-1: US Central 1
|
||||
us-east: US East
|
||||
us-east-1: US East 1
|
||||
us-west: US West
|
||||
us-west-1: US West 1
|
||||
endpoint:
|
||||
au-east-1.object.fastlystorage.app: AU East 1
|
||||
eu-central.object.fastlystorage.app: EU Central
|
||||
eu-south-1.object.fastlystorage.app: EU South 1
|
||||
eu-west-1.object.fastlystorage.app: EU West 1
|
||||
jp-central-1.object.fastlystorage.app: JP Central 1
|
||||
uk-east-1.object.fastlystorage.app: UK East 1
|
||||
us-central-1.object.fastlystorage.app: US Central 1
|
||||
us-east.object.fastlystorage.app: US East
|
||||
us-east-1.object.fastlystorage.app: US East 1
|
||||
us-west.object.fastlystorage.app: US West
|
||||
us-west-1.object.fastlystorage.app: US West 1
|
||||
quirks:
|
||||
force_path_style: true
|
||||
use_already_exists: false
|
||||
|
||||
+4
-2
@@ -1522,8 +1522,10 @@ func s3Connection(ctx context.Context, opt *Options, client *http.Client) (s3Cli
|
||||
}
|
||||
}
|
||||
|
||||
// Create AssumeRole credentials provider
|
||||
awsConfig.Credentials = stscreds.NewAssumeRoleProvider(stsClient, opt.RoleARN, assumeRoleOptions)
|
||||
// Create AssumeRole credentials provider, wrapped in a
|
||||
// CredentialsCache so we don't call AssumeRole on every
|
||||
// request.
|
||||
awsConfig.Credentials = aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(stsClient, opt.RoleARN, assumeRoleOptions))
|
||||
}
|
||||
|
||||
provider = loadProvider(opt.Provider)
|
||||
|
||||
@@ -88,7 +88,7 @@ func init() {
|
||||
if opt.RefreshToken == "" {
|
||||
return fs.ConfigGoto("username")
|
||||
}
|
||||
return fs.ConfigConfirm("refresh", true, "config_refresh", "Already have a token - refresh?")
|
||||
return fs.ConfigConfirm("refresh", true, "config_refresh", "Token already configured - replace it?")
|
||||
case "refresh":
|
||||
if config.Result == "false" {
|
||||
return nil, nil
|
||||
|
||||
@@ -196,7 +196,7 @@ func Bisync(ctx context.Context, fs1, fs2 fs.Fs, optArg *Options) (err error) {
|
||||
}
|
||||
|
||||
if b.critical {
|
||||
if b.retryable && b.opt.Resilient {
|
||||
if b.retryable && b.opt.Resilient && !b.opt.Resync {
|
||||
fs.Errorf(nil, Color(terminal.RedFg, "Bisync critical error: %v"), err)
|
||||
fs.Error(nil, Color(terminal.YellowFg, "Bisync aborted. Error is retryable without --resync due to --resilient mode."))
|
||||
} else {
|
||||
|
||||
@@ -165,6 +165,16 @@ func (b *bisyncRun) resolve(ctxMove context.Context, path1, path2, file, alias s
|
||||
},
|
||||
}
|
||||
|
||||
if b.opt.ConflictLoser == ConflictLoserPathname {
|
||||
switch winningPath {
|
||||
case 1: // keep path1, rename path2
|
||||
r.path1.newName = r.path1.oldName
|
||||
case 2: // keep path2, rename path1
|
||||
r.path2.newName = r.path2.oldName
|
||||
}
|
||||
// case 0 keeps default
|
||||
}
|
||||
|
||||
// handle auto-numbering
|
||||
// note that we still queue copies for both files, whether or not we renamed
|
||||
// we also set these for ConflictLoserDelete in case there is no winner.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
"file2.txt"
|
||||
"file1.txt.path2"
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
@@ -8,3 +8,5 @@
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
|
||||
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt.path2"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
@@ -8,4 +8,4 @@
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
|
||||
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
|
||||
- 33 - - 2005-01-02T00:00:00.000000000+0000 "file2.txt"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
|
||||
+1
-1
@@ -1,5 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
@@ -7,4 +8,3 @@
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
|
||||
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
|
||||
- 0 - - 2000-01-01T00:00:00.000000000+0000 "file2.txt"
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
@@ -8,3 +8,5 @@
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
|
||||
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt.path2"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2005-01-02T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
|
||||
+1
-1
@@ -1,5 +1,6 @@
|
||||
# bisync listing v1 from test
|
||||
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
|
||||
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
|
||||
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
|
||||
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
|
||||
@@ -7,4 +8,3 @@
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
|
||||
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
|
||||
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
|
||||
- 0 - - 2000-01-01T00:00:00.000000000+0000 "file2.txt"
|
||||
@@ -305,3 +305,56 @@ INFO : - [36mPath1[0m [35mDo queued copies to[0m - [36mP
|
||||
INFO : Updating listings
|
||||
INFO : Validating listings for Path1 "{path1/}" vs Path2 "{path2/}"
|
||||
INFO : [32mBisync successful[0m
|
||||
|
||||
[36m(48) :[0m [34mtest --conflict-resolve newer --conflict-loser pathname --conflict-suffix path[0m
|
||||
[36m(49) :[0m [34mtouch-glob 2004-07-23 {datadir/} file1R.txt[0m
|
||||
[36m(50) :[0m [34mcopy-as {datadir/}file1R.txt {path2/} file1.txt[0m
|
||||
[36m(51) :[0m [34mtouch-glob 2004-07-25 {datadir/} file1L.txt[0m
|
||||
[36m(52) :[0m [34mcopy-as {datadir/}file1L.txt {path1/} file1.txt[0m
|
||||
|
||||
[36m(53) :[0m [34mtest bisync run with --conflict-resolve=newer --conflict-loser=pathname --conflict-suffix=path[0m
|
||||
|
||||
[36m(54) :[0m [34mbisync conflict-resolve=newer conflict-loser=pathname conflict-suffix=path[0m
|
||||
INFO : [2mSetting --ignore-listing-checksum as neither --checksum nor --compare checksum are set.[0m
|
||||
INFO : Bisyncing with Comparison Settings:
|
||||
{
|
||||
"Modtime": true,
|
||||
"Size": true,
|
||||
"Checksum": false,
|
||||
"NoSlowHash": false,
|
||||
"SlowHashSyncOnly": false,
|
||||
"DownloadHash": false
|
||||
}
|
||||
INFO : Synching Path1 "{path1/}" with Path2 "{path2/}"
|
||||
INFO : Building Path1 and Path2 listings
|
||||
INFO : Path1 checking for diffs
|
||||
INFO : - [36mPath1[0m [35m[33mFile changed: [35mtime (older)[0m[0m[0m - [36mfile1.txt[0m
|
||||
INFO : - [36mPath1[0m [35m[32mFile is new[0m[0m - [36mfile2.txt[0m
|
||||
INFO : Path1: 2 changes: [32m 1 new[0m, [33m 1 modified[0m, [31m 0 deleted[0m
|
||||
INFO : ([33mModified[0m: [36m 0 newer[0m, [34m 1 older[0m)
|
||||
INFO : Path2 checking for diffs
|
||||
INFO : - [34mPath2[0m [35m[33mFile changed: [35mtime (older)[0m[0m[0m - [36mfile1.txt[0m
|
||||
INFO : - [34mPath2[0m [35m[32mFile is new[0m[0m - [36mfile2.txt[0m
|
||||
INFO : Path2: 2 changes: [32m 1 new[0m, [33m 1 modified[0m, [31m 0 deleted[0m
|
||||
INFO : ([33mModified[0m: [36m 0 newer[0m, [34m 1 older[0m)
|
||||
INFO : Applying changes
|
||||
INFO : Checking potential conflicts...
|
||||
ERROR : file1.txt: {hashtype} differ
|
||||
NOTICE: {path2String}: 1 differences found
|
||||
NOTICE: {path2String}: 1 errors while checking
|
||||
NOTICE: {path2String}: 1 matching files
|
||||
INFO : Finished checking the potential conflicts. 1 differences found
|
||||
NOTICE: - [34mWARNING[0m [35mNew or changed in both paths[0m - [36mfile1.txt[0m
|
||||
INFO : file1.txt: Path1 is newer. Path1: 2004-07-25 00:00:00 +0000 UTC, Path2: 2004-07-23 00:00:00 +0000 UTC, Difference: 48h0m0s
|
||||
INFO : file1.txt: [32mThe winner is: Path1[0m
|
||||
NOTICE: - [36mPath1[0m [35mNot renaming Path1 copy, as it was determined the winner[0m - [36m{path1/}file1.txt[0m
|
||||
NOTICE: - [36mPath1[0m [35m[32mQueue copy to[0m Path2[0m - [36m{path2/}file1.txt[0m
|
||||
NOTICE: - [34mPath2[0m [35mRenaming Path2 copy[0m - [36m{path2/}file1.txt.path2[0m
|
||||
NOTICE: - [34mPath2[0m [35m[32mQueue copy to[0m Path1[0m - [36m{path1/}file1.txt.path2[0m
|
||||
NOTICE: - [34mWARNING[0m [35mNew or changed in both paths[0m - [36mfile2.txt[0m
|
||||
INFO : Files are equal! Skipping: file2.txt
|
||||
INFO : - [34mPath2[0m [35mDo queued copies to[0m - [36mPath1[0m
|
||||
INFO : - [36mPath1[0m [35mDo queued copies to[0m - [36mPath2[0m
|
||||
INFO : Updating listings
|
||||
INFO : Validating listings for Path1 "{path1/}" vs Path2 "{path2/}"
|
||||
INFO : [32mBisync successful[0m
|
||||
+11
-1
@@ -64,4 +64,14 @@ copy-as {datadir/}file1L.txt {path1/} file1.txt
|
||||
copy-as {datadir/}file1L.txt {path2/} file2.txt
|
||||
|
||||
test bisync run with --conflict-resolve=newer --conflict-loser=delete
|
||||
bisync conflict-resolve=newer conflict-loser=delete
|
||||
bisync conflict-resolve=newer conflict-loser=delete
|
||||
|
||||
test --conflict-resolve newer --conflict-loser pathname --conflict-suffix path
|
||||
touch-glob 2004-07-23 {datadir/} file1R.txt
|
||||
copy-as {datadir/}file1R.txt {path2/} file1.txt
|
||||
touch-glob 2004-07-25 {datadir/} file1L.txt
|
||||
copy-as {datadir/}file1L.txt {path1/} file1.txt
|
||||
|
||||
test bisync run with --conflict-resolve=newer --conflict-loser=pathname --conflict-suffix=path
|
||||
# result should be -- "file1.txt", "file1.txt.path2"
|
||||
bisync conflict-resolve=newer conflict-loser=pathname conflict-suffix=path
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/rclone/rclone/fs/cache"
|
||||
"github.com/rclone/rclone/fs/config/configfile"
|
||||
"github.com/rclone/rclone/fs/config/configflags"
|
||||
profiles "github.com/rclone/rclone/fs/config/configprofiles"
|
||||
"github.com/rclone/rclone/fs/config/flags"
|
||||
"github.com/rclone/rclone/fs/filter"
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
@@ -536,6 +537,7 @@ func AddBackendFlags() {
|
||||
func Main() {
|
||||
setupRootCommand(Root)
|
||||
AddBackendFlags()
|
||||
profiles.AddProfiles(context.Background(), Root)
|
||||
if err := Root.Execute(); err != nil {
|
||||
if strings.HasPrefix(err.Error(), "unknown command") && selfupdateEnabled {
|
||||
Root.PrintErrf("You could use '%s selfupdate' to get latest features.\n\n", Root.CommandPath())
|
||||
|
||||
@@ -26,6 +26,7 @@ func init() {
|
||||
configCommand.AddCommand(configTouchCommand)
|
||||
configCommand.AddCommand(configPathsCommand)
|
||||
configCommand.AddCommand(configShowCommand)
|
||||
configCommand.AddCommand(configProfileCommand)
|
||||
configCommand.AddCommand(configRedactedCommand)
|
||||
configCommand.AddCommand(configDumpCommand)
|
||||
configCommand.AddCommand(configProvidersCommand)
|
||||
@@ -123,6 +124,21 @@ var configShowCommand = &cobra.Command{
|
||||
},
|
||||
}
|
||||
|
||||
var configProfileCommand = &cobra.Command{
|
||||
Use: "profile",
|
||||
Short: `Manage saved profiles of flags.`,
|
||||
Long: `Manage saved profiles of flags, stored in the config file under
|
||||
"[profile:NAME]" sections.
|
||||
|
||||
Use the save, list, show and delete subcommands. See ` + "`rclone config profile --help`" + `
|
||||
for the full list, and the [Profiles](/docs/#profiles) section of the
|
||||
docs for an overview of the feature.`,
|
||||
Annotations: map[string]string{
|
||||
"versionIntroduced": "v1.66",
|
||||
},
|
||||
Aliases: []string{"profiles"},
|
||||
}
|
||||
|
||||
var configRedactedCommand = &cobra.Command{
|
||||
Use: "redacted [<remote>]",
|
||||
Short: `Print redacted (decrypted) config file, or the redacted config for a single remote.`,
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// Profile subcommands for `rclone config profile`.
|
||||
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/rclone/rclone/cmd"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
profiles "github.com/rclone/rclone/fs/config/configprofiles"
|
||||
"github.com/rclone/rclone/fs/config/flags"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
configProfileCommand.AddCommand(configProfileListCommand)
|
||||
configProfileCommand.AddCommand(configProfileShowCommand)
|
||||
configProfileCommand.AddCommand(configProfileDeleteCommand)
|
||||
configProfileCommand.AddCommand(configProfileSaveCommand)
|
||||
|
||||
flags.FVarP(configProfileSaveCommand.Flags(), &profileSaveFlagsFrom,
|
||||
"flags-from", "",
|
||||
"Import command-specific flags from these subcommands (comma separated)", "")
|
||||
configProfileSaveCommand.PersistentPreRunE = profileSaveAddFlagsFrom
|
||||
configProfileSaveCommand.FParseErrWhitelist.UnknownFlags = true
|
||||
}
|
||||
|
||||
// profileSaveFlagsFrom backs --flags-from on `rclone config profile save`.
|
||||
var profileSaveFlagsFrom fs.CommaSepList
|
||||
|
||||
var configProfileListCommand = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List the profiles in the config file.",
|
||||
Annotations: map[string]string{
|
||||
"versionIntroduced": "v1.72",
|
||||
},
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
cmd.CheckArgs(0, 0, command, args)
|
||||
profiles.ShowProfiles()
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var configProfileShowCommand = &cobra.Command{
|
||||
Use: "show NAME",
|
||||
Short: "Show the flags saved in a profile.",
|
||||
Annotations: map[string]string{
|
||||
"versionIntroduced": "v1.72",
|
||||
},
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
cmd.CheckArgs(1, 1, command, args)
|
||||
name := args[0]
|
||||
section := config.ProfileSectionPrefix + name
|
||||
if !config.LoadedData().HasSection(section) {
|
||||
return fmt.Errorf("no profile named %q", name)
|
||||
}
|
||||
fmt.Print(profiles.SprintSection(section))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var configProfileDeleteCommand = &cobra.Command{
|
||||
Use: "delete NAME",
|
||||
Short: "Delete a profile.",
|
||||
Annotations: map[string]string{
|
||||
"versionIntroduced": "v1.72",
|
||||
},
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
cmd.CheckArgs(1, 1, command, args)
|
||||
name := args[0]
|
||||
section := config.ProfileSectionPrefix + name
|
||||
if !config.LoadedData().HasSection(section) {
|
||||
return fmt.Errorf("no profile named %q", name)
|
||||
}
|
||||
config.LoadedData().DeleteSection(section)
|
||||
if err := config.LoadedData().Save(); err != nil {
|
||||
return fmt.Errorf("failed to save config: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
var configProfileSaveCommand = &cobra.Command{
|
||||
Use: "save NAME [args...]",
|
||||
Short: "Save the given flags (and optional args) as a reusable profile.",
|
||||
Long: `Save a profile under NAME built from the flags (and, if
|
||||
` + "`--profile-save-args`" + ` is set, the positional arguments) passed
|
||||
on this command line.
|
||||
|
||||
Without ` + "`--flags-from`" + ` only global rclone flags can be saved. To
|
||||
save flags that belong to a specific command (e.g. VFS flags from
|
||||
` + "`rclone mount`" + ` or bisync-specific flags), import that command's
|
||||
flag set with ` + "`--flags-from CMD[,CMD...]`" + `.
|
||||
`,
|
||||
Annotations: map[string]string{
|
||||
"versionIntroduced": "v1.72",
|
||||
},
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
cmd.CheckArgs(1, 100, command, args)
|
||||
name := args[0]
|
||||
ctx := context.Background()
|
||||
opt := profiles.ProfileOptFromCtx(ctx)
|
||||
p := profiles.NewProfile(name)
|
||||
p.NewFromCommand(command, args[1:])
|
||||
return p.Save(ctx, &opt)
|
||||
},
|
||||
}
|
||||
|
||||
// profileSaveAddFlagsFrom is the PersistentPreRunE for
|
||||
// `rclone config profile save`. It interprets --flags-from, merges in
|
||||
// the requested commands' flag sets, then re-parses the command line so
|
||||
// the newly-added flags pick up their values.
|
||||
func profileSaveAddFlagsFrom(saveCmd *cobra.Command, args []string) error {
|
||||
// The first parse was done with UnknownFlags=true so --verbose may
|
||||
// have been counted; preserve its current value across the reparse.
|
||||
var verboseSaved string
|
||||
if vf := saveCmd.Flags().Lookup("verbose"); vf != nil {
|
||||
verboseSaved = vf.Value.String()
|
||||
defer func() {
|
||||
if err := vf.Value.Set(verboseSaved); err != nil {
|
||||
fs.Errorf(nil, "error restoring --verbose: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
for _, sub := range profileSaveFlagsFrom {
|
||||
sc, _, err := cmd.Root.Find([]string{sub})
|
||||
if err != nil {
|
||||
return fmt.Errorf("--flags-from %s: %w", sub, err)
|
||||
}
|
||||
if sc == cmd.Root {
|
||||
return fmt.Errorf("--flags-from %s: not a known subcommand", sub)
|
||||
}
|
||||
saveCmd.Flags().AddFlagSet(sc.Flags())
|
||||
}
|
||||
|
||||
// Re-parse strictly now that the flag set is complete.
|
||||
saveCmd.FParseErrWhitelist.UnknownFlags = false
|
||||
flagArgs, err := argsAfterCommand(saveCmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return saveCmd.ParseFlags(flagArgs)
|
||||
}
|
||||
|
||||
// argsAfterCommand returns the portion of os.Args that came after the
|
||||
// chain of cobra command names leading to cmd.
|
||||
func argsAfterCommand(cmd *cobra.Command) ([]string, error) {
|
||||
depth := 0
|
||||
for c := cmd; c != nil; c = c.Parent() {
|
||||
depth++
|
||||
}
|
||||
if depth > len(os.Args) {
|
||||
return nil, errors.New("internal error: command depth exceeds os.Args length")
|
||||
}
|
||||
return os.Args[depth:], nil
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/rclone/rclone/cmd"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/rc"
|
||||
@@ -191,6 +192,7 @@ For more help see [the GUI docs](/gui/).
|
||||
if err != nil || spaHandler == nil {
|
||||
return fmt.Errorf("failed to start GUI handler: %w", err)
|
||||
}
|
||||
guiServer.Router().Use(middleware.Compress(5))
|
||||
guiServer.Router().Get("/*", spaHandler.ServeHTTP)
|
||||
guiServer.Router().Head("/*", spaHandler.ServeHTTP)
|
||||
guiServer.Serve()
|
||||
|
||||
@@ -2,6 +2,7 @@ package gui
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
iofs "io/fs"
|
||||
"net/http"
|
||||
@@ -11,6 +12,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -302,3 +305,37 @@ func TestHandlerSPAFallbackDeepPath(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Contains(t, string(body), "<div id=\"root\"></div>")
|
||||
}
|
||||
|
||||
func TestHandlerServesGzip(t *testing.T) {
|
||||
dir := writeTestDir(t)
|
||||
srcFS, cleanup, err := guiSourceFS(dir)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = cleanup() })
|
||||
|
||||
h, err := guiHandler(srcFS)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Build a chi router with Compress middleware, mirroring the
|
||||
// production setup in the gui command.
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.Compress(5))
|
||||
r.Get("/*", h.ServeHTTP)
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
resp := w.Result()
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"),
|
||||
"response should be gzip-encoded when client accepts it")
|
||||
|
||||
// Decompress and verify the content is correct.
|
||||
gr, err := gzip.NewReader(resp.Body)
|
||||
require.NoError(t, err)
|
||||
body, err := io.ReadAll(gr)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, gr.Close())
|
||||
assert.Contains(t, string(body), `<div id="root"></div>`)
|
||||
}
|
||||
@@ -13,9 +13,9 @@ func (db *s3Backend) pager(list *gofakes3.ObjectList, page gofakes3.ListBucketPa
|
||||
sort.Slice(list.CommonPrefixes, func(i, j int) bool {
|
||||
return list.CommonPrefixes[i].Prefix < list.CommonPrefixes[j].Prefix
|
||||
})
|
||||
// sort by modtime
|
||||
// sort by key name
|
||||
sort.Slice(list.Contents, func(i, j int) bool {
|
||||
return list.Contents[i].LastModified.Before(list.Contents[j].LastModified.Time)
|
||||
return list.Contents[i].Key < list.Contents[j].Key
|
||||
})
|
||||
tokens := page.MaxKeys
|
||||
if tokens == 0 {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/gofakes3"
|
||||
)
|
||||
|
||||
func TestPagerSortsContentsByKey(t *testing.T) {
|
||||
list := gofakes3.NewObjectList()
|
||||
list.Add(&gofakes3.Content{
|
||||
Key: "b.txt",
|
||||
LastModified: gofakes3.NewContentTime(time.Unix(100, 0)),
|
||||
})
|
||||
list.Add(&gofakes3.Content{
|
||||
Key: "a.txt",
|
||||
LastModified: gofakes3.NewContentTime(time.Unix(200, 0)),
|
||||
})
|
||||
|
||||
got, err := (&s3Backend{}).pager(list, gofakes3.ListBucketPage{MaxKeys: 2})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Contents) != 2 {
|
||||
t.Fatalf("expected 2 contents, got %d", len(got.Contents))
|
||||
}
|
||||
|
||||
if got.Contents[0].Key != "a.txt" || got.Contents[1].Key != "b.txt" {
|
||||
t.Fatalf("expected lexicographic key order [a.txt b.txt], got [%s %s]", got.Contents[0].Key, got.Contents[1].Key)
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,13 @@ supported hash on the backend or you can use a named hash such as
|
||||
"MD5" or "SHA-1". Use the [hashsum](/commands/rclone_hashsum/) command
|
||||
to see the full list.
|
||||
|
||||
### Gzip compression
|
||||
|
||||
The server will compress certain response bodies (text and XML, including
|
||||
WebDAV PROPFIND responses) using gzip when the client advertises gzip
|
||||
support via the ` + "`Accept-Encoding: gzip`" + ` request header. This reduces
|
||||
bandwidth usage.
|
||||
|
||||
### Access WebDAV on Windows
|
||||
|
||||
WebDAV shared folder can be mapped as a drive on Windows, however the default
|
||||
@@ -236,6 +243,20 @@ type WebDAV struct {
|
||||
etagHashType hash.Type
|
||||
}
|
||||
|
||||
func webDAVCompressMiddleware() func(http.Handler) http.Handler {
|
||||
compress := middleware.Compress(5, "text/*", "application/xml")
|
||||
return func(next http.Handler) http.Handler {
|
||||
compressedNext := compress(next)
|
||||
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Range") != "" {
|
||||
next.ServeHTTP(rw, r)
|
||||
return
|
||||
}
|
||||
compressedNext.ServeHTTP(rw, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// check interface
|
||||
var _ webdav.FileSystem = (*WebDAV)(nil)
|
||||
|
||||
@@ -288,6 +309,7 @@ func newWebDAV(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Opt
|
||||
|
||||
router := w.server.Router()
|
||||
router.Use(
|
||||
webDAVCompressMiddleware(),
|
||||
middleware.SetHeader("Accept-Ranges", "bytes"),
|
||||
middleware.SetHeader("Server", "rclone/"+fs.Version),
|
||||
)
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
package webdav
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"flag"
|
||||
"io"
|
||||
@@ -15,7 +16,6 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
"github.com/rclone/rclone/cmd/serve/proxy"
|
||||
@@ -115,22 +115,6 @@ func TestHTTPFunction(t *testing.T) {
|
||||
assert.NoError(t, w.Shutdown())
|
||||
}()
|
||||
testURL := w.server.URLs()[0]
|
||||
pause := time.Millisecond
|
||||
i := 0
|
||||
for ; i < 10; i++ {
|
||||
resp, err := http.Head(testURL)
|
||||
if err == nil {
|
||||
_ = resp.Body.Close()
|
||||
break
|
||||
}
|
||||
// t.Logf("couldn't connect, sleeping for %v: %v", pause, err)
|
||||
time.Sleep(pause)
|
||||
pause *= 2
|
||||
}
|
||||
if i >= 10 {
|
||||
t.Fatal("couldn't connect to server")
|
||||
}
|
||||
|
||||
HelpTestGET(t, testURL)
|
||||
}
|
||||
|
||||
@@ -265,6 +249,103 @@ func HelpTestGET(t *testing.T, testURL string) {
|
||||
}
|
||||
}
|
||||
|
||||
// startAuthenticatedServer creates a webdav server with basic auth against
|
||||
// the test files directory, starts it, waits for it to be ready, and returns
|
||||
// the base URL. It registers cleanup to shut the server down.
|
||||
func startAuthenticatedServer(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
f, err := fs.NewFs(context.Background(), "../http/testdata/files")
|
||||
require.NoError(t, err)
|
||||
|
||||
opt := Opt
|
||||
opt.HTTP.ListenAddr = []string{testBindAddress}
|
||||
opt.Template.Path = testTemplate
|
||||
opt.Auth.BasicUser = testUser
|
||||
opt.Auth.BasicPass = testPass
|
||||
|
||||
w, err := newWebDAV(context.Background(), f, &opt, &vfscommon.Opt, &proxy.Opt)
|
||||
require.NoError(t, err)
|
||||
go func() {
|
||||
require.NoError(t, w.Serve())
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
assert.NoError(t, w.Shutdown())
|
||||
})
|
||||
|
||||
testURL := w.server.URLs()[0]
|
||||
return testURL
|
||||
}
|
||||
|
||||
func TestCompressedTextFile(t *testing.T) {
|
||||
testURL := startAuthenticatedServer(t)
|
||||
|
||||
req, err := http.NewRequest("GET", testURL+"two.txt", nil)
|
||||
require.NoError(t, err)
|
||||
req.SetBasicAuth(testUser, testPass)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
|
||||
|
||||
gr, err := gzip.NewReader(resp.Body)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = gr.Close() }()
|
||||
|
||||
body, err := io.ReadAll(gr)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "0123456789\n", string(body))
|
||||
}
|
||||
|
||||
func TestCompressedPROPFIND(t *testing.T) {
|
||||
testURL := startAuthenticatedServer(t)
|
||||
|
||||
req, err := http.NewRequest("PROPFIND", testURL, nil)
|
||||
require.NoError(t, err)
|
||||
req.SetBasicAuth(testUser, testPass)
|
||||
req.Header.Set("Depth", "1")
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, http.StatusMultiStatus, resp.StatusCode)
|
||||
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
|
||||
|
||||
gr, err := gzip.NewReader(resp.Body)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = gr.Close() }()
|
||||
|
||||
body, err := io.ReadAll(gr)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(body), "multistatus")
|
||||
}
|
||||
|
||||
func TestRangeRequestNotCompressed(t *testing.T) {
|
||||
testURL := startAuthenticatedServer(t)
|
||||
|
||||
req, err := http.NewRequest("GET", testURL+"two.txt", nil)
|
||||
require.NoError(t, err)
|
||||
req.SetBasicAuth(testUser, testPass)
|
||||
req.Header.Set("Accept-Encoding", "gzip")
|
||||
req.Header.Set("Range", "bytes=2-5")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
assert.Equal(t, http.StatusPartialContent, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Content-Encoding"))
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "2345", string(body))
|
||||
}
|
||||
|
||||
func TestRc(t *testing.T) {
|
||||
servetest.TestRc(t, rc.Params{
|
||||
"type": "webdav",
|
||||
|
||||
@@ -1123,3 +1123,11 @@ put them back in again. -->
|
||||
- Yakov Till <37628546+Lyapsus@users.noreply.github.com>
|
||||
- Chris Coughlan <chris@coughlan.io>
|
||||
- John Volk <volkjohn@users.noreply.github.com>
|
||||
- 王一赫 <wyihe5220@gmail.com>
|
||||
- Gustavo V. F. <31892323+Gustavo-V-F@users.noreply.github.com>
|
||||
- Sven Rebhan <36194019+srebhan@users.noreply.github.com>
|
||||
- Copilot <223556219+Copilot@users.noreply.github.com>
|
||||
- KTibow <KTibow@users.noreply.github.com>
|
||||
- kkocdko <31189892+kkocdko@users.noreply.github.com>
|
||||
- Tim Schumacher <tim@tschumacher.net>
|
||||
- ferrumclaudepilgrim <ferrumclaudepilgrim@users.noreply.github.com>
|
||||
@@ -1899,6 +1899,11 @@ about *Unison* and synchronization in general.
|
||||
|
||||
## Changelog
|
||||
|
||||
### `v1.74.2`
|
||||
|
||||
- Fixed an issue causing `--conflict-loser pathname` to produce unexpected
|
||||
behavior if using a non-default `--conflict-resolve` value.
|
||||
|
||||
### `v1.74`
|
||||
|
||||
- Added several missing `rc` parameters.
|
||||
|
||||
+1
-1
@@ -183,7 +183,7 @@ y) Yes
|
||||
n) No
|
||||
y/n> n
|
||||
Remote config
|
||||
Already have a token - refresh?
|
||||
Token already configured - replace it?
|
||||
y) Yes
|
||||
n) No
|
||||
y/n> y
|
||||
|
||||
@@ -6,6 +6,40 @@ description: "Rclone Changelog"
|
||||
|
||||
# Changelog
|
||||
|
||||
## v1.74.1 - 2026-05-08
|
||||
|
||||
[See commits](https://github.com/rclone/rclone/compare/v1.74.0...v1.74.1)
|
||||
|
||||
- Bug Fixes
|
||||
- bisync: Fix retryable without `--resync` error message when `--resync` has a critical failure (Gustavo V. F.)
|
||||
- build
|
||||
- Fix multiple CVEs by upgrading to go1.26.3 (Nick Craig-Wood)
|
||||
- CVE-2026-42501: cmd/go: malicious module proxy can bypass checksum database
|
||||
- CVE-2026-39825: net/http/httputil: ReverseProxy forwards queries with more than urlmaxqueryparams parameters
|
||||
- CVE-2026-39836: net: panic in Dial and LookupPort when handling NUL byte on Windows
|
||||
- CVE-2026-42499: net/mail: quadratic string concatenation in consumePhrase
|
||||
- CVE-2026-39820: net/mail: quadratic string concatentation in consumeComment
|
||||
- CVE-2026-39819: cmd/go: "go bug" follows symlinks in predictable temporary filenames
|
||||
- CVE-2026-39817: cmd/go: "go tool pack" does not sanitize output paths
|
||||
- CVE-2026-33814: net/http: infinite loop in HTTP/2 transport when given bad SETTINGS_MAX_FRAME_SIZE
|
||||
- CVE-2026-39826: html/template: escaper bypass leads to XSS
|
||||
- CVE-2026-33811: net: crash when handling long CNAME response
|
||||
- CVE-2026-39823: html/template: bypass of meta content URL escaping causes XSS
|
||||
- Update golang.org/x/net to v0.53.0 to fix CVE-2026-33814 (Nick Craig-Wood)
|
||||
- cmd/serve/s3: Return object listings in key order (Leon Brocard)
|
||||
- Cloudinary
|
||||
- Fix retrying every error and fix pacer sleep units (Nick Craig-Wood)
|
||||
- Drime
|
||||
- Fix large file uploads landing in drive root instead of configured folder (Nick Craig-Wood)
|
||||
- Fix uploads of 100..200M files (Nick Craig-Wood)
|
||||
- Protondrive
|
||||
- Route HTTP through rclone's transport (Nick Craig-Wood)
|
||||
- Route library logging through rclone's logger (Nick Craig-Wood)
|
||||
- Fix segfault when copying files missing revision metadata (Nick Craig-Wood)
|
||||
- S3
|
||||
- Fix STS call per request by caching AssumeRole credentials (Nick Craig-Wood)
|
||||
- Add new Fastly Object Storage regions (Leon Brocard)
|
||||
|
||||
## v1.74.0 - 2026-05-01
|
||||
|
||||
[See commits](https://github.com/rclone/rclone/compare/v1.73.0...v1.74.0)
|
||||
|
||||
@@ -542,6 +542,212 @@ If two remotes set the same global variable then the first one instantiated will
|
||||
be overridden by the second one. A `global.var` will override all other config
|
||||
methods when the remote is created.
|
||||
|
||||
## Profiles {#profiles}
|
||||
|
||||
Profiles let you save a named set of flags (and optionally arguments)
|
||||
in the config file and reuse them on later command lines, so you
|
||||
don't have to retype long flag combinations every time.
|
||||
|
||||
For example, if you regularly sync a directory to Google Drive with a
|
||||
specific set of flags, you can save that combination once as a
|
||||
profile and from then on use `--profile mybackup` instead.
|
||||
|
||||
### Saving a profile
|
||||
|
||||
Add `--profile-save NAME` to any rclone command. The command will run
|
||||
as normal, and rclone will additionally write all the explicitly-set
|
||||
flags from that command line into the config file under a new section
|
||||
named `[profile:NAME]`. The `profile:` prefix is the namespace
|
||||
profiles live in - because `:` is illegal in remote names, a profile
|
||||
called `backup` and a remote called `backup` can coexist without
|
||||
colliding.
|
||||
|
||||
For example:
|
||||
|
||||
```sh
|
||||
rclone sync src: dst: --checkers 16 --transfers 8 --metadata --profile-save fast-sync
|
||||
```
|
||||
|
||||
writes:
|
||||
|
||||
```ini
|
||||
[profile:fast-sync]
|
||||
checkers = 16
|
||||
transfers = 8
|
||||
metadata = true
|
||||
```
|
||||
|
||||
Only flags whose values you explicitly changed are saved - flags left
|
||||
at their default are not.
|
||||
|
||||
The profile-control flags themselves (`--profile-save`, `--profile`,
|
||||
`--profile-save-args`, `--profile-strict-flags`) are never saved
|
||||
into the profile. `--config` is also excluded - it's
|
||||
environment-specific and would re-point the config storage mid-load
|
||||
when applied from a profile.
|
||||
|
||||
### Using a profile
|
||||
|
||||
Add `--profile NAME` to apply a saved profile:
|
||||
|
||||
```sh
|
||||
rclone sync src: dst: --profile fast-sync
|
||||
```
|
||||
|
||||
This is equivalent to repeating all the flags from the saved profile
|
||||
on the command line.
|
||||
|
||||
You can apply several profiles in one go by passing a comma-separated
|
||||
list. They are applied in lowest-to-highest priority order, so later
|
||||
profiles override earlier ones:
|
||||
|
||||
```sh
|
||||
rclone sync src: dst: --profile common,fast-sync
|
||||
```
|
||||
|
||||
Any flag you pass explicitly on the command line overrides the
|
||||
profile's value for that flag, so you can use a profile as a baseline
|
||||
and tweak individual values for one run.
|
||||
|
||||
For safety, a profile can never turn off `--dry-run` if it was set
|
||||
explicitly on the command line.
|
||||
|
||||
### Including command arguments
|
||||
|
||||
By default `--profile-save` only saves flags. If you also want to
|
||||
save the positional arguments (e.g. the source and destination paths)
|
||||
add `--profile-save-args`:
|
||||
|
||||
```sh
|
||||
rclone sync /local/path remote:backup --profile-save nightly --profile-save-args
|
||||
```
|
||||
|
||||
When the profile is later used, saved arguments are applied
|
||||
automatically - you don't need to pass anything extra at use time.
|
||||
If you pass your own positional arguments on the command line, they
|
||||
take precedence over the profile's saved ones (the profile only
|
||||
fills slots you didn't provide).
|
||||
|
||||
### Strict flag checking
|
||||
|
||||
When you save a profile from one command (say `sync`) and then apply
|
||||
it to another (say `copy`), the profile may contain flags that don't
|
||||
exist on the new command. By default these flags are silently
|
||||
ignored. Pass `--profile-strict-flags` to make rclone error out
|
||||
instead of skipping them.
|
||||
|
||||
### Command-specific flags
|
||||
|
||||
Profiles work with the flag set of the command they're saved from
|
||||
and applied to, so command-specific flags (e.g. the [VFS
|
||||
flags](/commands/rclone_mount/#vfs-options) on `rclone mount`, or
|
||||
bisync's `--resilient`) are saved and loaded just like global flags:
|
||||
|
||||
```sh
|
||||
rclone mount remote: /mnt --vfs-cache-mode full --dir-cache-time 24h \
|
||||
--profile-save media-mount
|
||||
|
||||
rclone mount remote: /mnt --profile media-mount
|
||||
```
|
||||
|
||||
The resulting section looks like any other profile:
|
||||
|
||||
```ini
|
||||
[profile:media-mount]
|
||||
vfs_cache_mode = full
|
||||
dir_cache_time = 24h0m0s
|
||||
```
|
||||
|
||||
If you later apply this profile to a different command that doesn't
|
||||
have those flags (e.g. `rclone copy --profile media-mount`), the
|
||||
VFS flags are silently skipped - or rejected if you also pass
|
||||
`--profile-strict-flags`.
|
||||
|
||||
To build a profile for command-specific flags without actually
|
||||
running the command, use `rclone config profile save NAME --flags-from CMD`:
|
||||
|
||||
```sh
|
||||
rclone config profile save media-mount --flags-from mount \
|
||||
--vfs-cache-mode full --dir-cache-time 24h
|
||||
```
|
||||
|
||||
### Inheriting from parent profiles
|
||||
|
||||
A profile can inherit settings from one or more parent profiles by
|
||||
listing them in `parent_profiles` in the config:
|
||||
|
||||
```ini
|
||||
[profile:shared]
|
||||
checkers = 16
|
||||
metadata = true
|
||||
|
||||
[profile:nightly]
|
||||
parent_profiles = shared
|
||||
transfers = 4
|
||||
```
|
||||
|
||||
Parent names are also given in their user-facing form (without the
|
||||
`profile:` prefix).
|
||||
|
||||
Using `--profile nightly` first applies `shared`, then applies
|
||||
`nightly` on top, so `nightly` overrides any flag the two have in
|
||||
common. Parents themselves can have parents - profiles are resolved
|
||||
recursively.
|
||||
|
||||
### Always applying a profile
|
||||
|
||||
There is no "default profile" mechanism - if you want a profile to
|
||||
apply every time, set it in the environment instead:
|
||||
|
||||
```sh
|
||||
export RCLONE_PROFILE=mybackup
|
||||
```
|
||||
|
||||
`--profile` is exposed as a standard rclone option, so the
|
||||
`RCLONE_PROFILE` environment variable Just Works. Use a shell
|
||||
alias or wrapper script if you want different defaults in different
|
||||
contexts. This keeps "what flags am I actually running with" answerable
|
||||
from the command line and environment alone, with no spooky action
|
||||
from the config file.
|
||||
|
||||
### Managing profiles
|
||||
|
||||
Use the `rclone config profile` subcommands to manage profiles
|
||||
without editing the config file by hand:
|
||||
|
||||
```sh
|
||||
rclone config profile save NAME [args...] [flags...]
|
||||
rclone config profile list
|
||||
rclone config profile show NAME
|
||||
rclone config profile delete NAME
|
||||
```
|
||||
|
||||
- `save` writes a new profile from the flags (and optional positional
|
||||
args, with `--profile-save-args`) given on the command line.
|
||||
Pass `--flags-from CMD[,CMD...]` to make flags from other commands
|
||||
(e.g. `mount`, `bisync`) available for saving without having to
|
||||
actually run those commands.
|
||||
- `list` prints the names of all profiles in the config file.
|
||||
- `show` prints the keys and values stored in one profile.
|
||||
- `delete` removes a profile.
|
||||
|
||||
To edit an existing profile, either re-save it (overwriting the old
|
||||
one) or edit the corresponding `[profile:NAME]` section in the
|
||||
config file by hand.
|
||||
|
||||
### Config file layout
|
||||
|
||||
Profiles live under the `[profile:NAME]` namespace in the config
|
||||
file. The `profile:` prefix is the canonical signal that a section
|
||||
is a profile - `:` is illegal in remote names, so profiles and
|
||||
remotes can share a name without colliding. Profile sections are
|
||||
hidden from `rclone listremotes`, `rclone config show <remote>` and
|
||||
the rc API's `config/dump` (they don't appear as remotes).
|
||||
|
||||
Saved flags are written with their option name in snake_case (e.g.
|
||||
`drive-skip-gdocs` becomes `drive_skip_gdocs = true`). Saved
|
||||
arguments are written as `arg_1 = ...`, `arg_2 = ...` and so on.
|
||||
|
||||
## Quoting and the shell
|
||||
|
||||
When you are typing commands to your computer you are using something
|
||||
@@ -2464,6 +2670,36 @@ See the [Configuration Encryption](#configuration-encryption) for more info.
|
||||
|
||||
See a [Windows PowerShell example on the Wiki](https://github.com/rclone/rclone/wiki/Windows-Powershell-use-rclone-password-command-for-Config-file-password).
|
||||
|
||||
### --profile CommaSepList
|
||||
|
||||
Apply one or more saved profiles to this command, as if their flags
|
||||
had been typed on the command line. Multiple profiles are
|
||||
comma-separated and applied lowest-to-highest priority (later
|
||||
profiles override earlier ones). Explicit command-line flags still
|
||||
take precedence over the profile. See the [Profiles](#profiles)
|
||||
section.
|
||||
|
||||
### --profile-save string
|
||||
|
||||
Save the explicitly-set flags from this command (and optionally its
|
||||
arguments, with `--profile-save-args`) into the config file as a
|
||||
reusable profile under the given name. The command still runs as
|
||||
normal. See the [Profiles](#profiles) section.
|
||||
|
||||
### --profile-save-args
|
||||
|
||||
When used with `--profile-save`, also save the command's positional
|
||||
arguments (e.g. the source and destination paths) into the profile.
|
||||
At use time the saved arguments are applied automatically (the user's
|
||||
own positional arguments, if any, take precedence). See the
|
||||
[Profiles](#profiles) section.
|
||||
|
||||
### --profile-strict-flags
|
||||
|
||||
When used with `--profile`, error out if the profile contains a
|
||||
flag that isn't valid for the current command. The default is to
|
||||
silently skip such flags. See the [Profiles](#profiles) section.
|
||||
|
||||
### -P, --progress
|
||||
|
||||
This flag makes rclone update the stats in a static block in the
|
||||
|
||||
@@ -2009,7 +2009,7 @@ Scroll down and click "+ Add users". Add yourself as a test user and press save.
|
||||
10. Provide the noted client ID and client secret to rclone.
|
||||
|
||||
11. Run the web-based authorization flow from within `rclone config`, by answering
|
||||
"Y" when it asks "Already have a token - refresh?".
|
||||
"Y" when it asks "Token already configured - replace it?".
|
||||
|
||||
Be aware that, due to the "enhanced security" recently introduced by
|
||||
Google, you are theoretically expected to "submit your app for verification"
|
||||
|
||||
@@ -114,6 +114,33 @@ rclone sync --interactive remote:directory /home/local/directory
|
||||
|
||||
This remote is read only - you can't upload files to an HTTP server.
|
||||
|
||||
### Servers without directory listings
|
||||
|
||||
Rclone normally needs the HTTP server to return a parseable directory
|
||||
listing in order to discover files. However if the path points
|
||||
directly at a single file (i.e. it does not end with `/` and the
|
||||
initial HEAD request reports it as a file), rclone will skip the
|
||||
parent directory listing entirely and access the file directly.
|
||||
|
||||
This means rclone can be used to download individual files on HTTP
|
||||
servers that have directory listings disabled, as long as you know the
|
||||
exact URL of each file. For example, given a server that serves
|
||||
`https://example.com/path/file.txt` but returns an error or an
|
||||
unparseable response for `https://example.com/path/`:
|
||||
|
||||
```console
|
||||
rclone copy --http-url https://example.com :http:path/file.txt /tmp/
|
||||
```
|
||||
|
||||
You can use this as a remote in other rclone commands too:
|
||||
|
||||
```console
|
||||
rclone hashsum crc32 --http-url "https://getsamplefiles.com" :archive::http:download/zip/sample-1.zip
|
||||
```
|
||||
|
||||
If you just want to download a file or multiple files by URL then
|
||||
using [copyurl](/commands/rclone_copyurl/) is more efficient.
|
||||
|
||||
### Modification times
|
||||
|
||||
Most HTTP servers store time accurate to 1 second.
|
||||
|
||||
@@ -1243,7 +1243,7 @@ If you see the error above after enabling multi-factor authentication for your
|
||||
account, you can fix it by refreshing your OAuth refresh token. To do that, run
|
||||
`rclone config`, and choose to edit your OneDrive backend. Then, you don't need
|
||||
to actually make any changes until you reach this question:
|
||||
`Already have a token - refresh?`. For this question, answer `y` and go through
|
||||
`Token already configured - replace it?`. For this question, answer `y` and go through
|
||||
the process to refresh your token, just like the first time the backend is
|
||||
configured. After this, rclone should work again for this backend.
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
title: "Sponsor"
|
||||
description: "Sponsor the rclone project."
|
||||
type: page
|
||||
notoc: true
|
||||
aliases:
|
||||
- donate
|
||||
---
|
||||
@@ -21,12 +22,14 @@ Thank you to our sponsors:
|
||||
{{< sponsor src="/img/logos/route4me.svg" width="400" height="200" title="Visit our sponsor Route4Me" link="https://route4me.com/">}}
|
||||
{{< sponsor src="/img/logos/rcloneview.svg" width="300" height="200" title="Visit our sponsor RcloneView" link="https://rcloneview.com/">}}
|
||||
{{< sponsor src="/img/logos/rcloneui.svg" width="300" height="200" title="Visit our sponsor RcloneUI" link="https://github.com/rclone-ui/rclone-ui">}}
|
||||
{{< sponsor src="/img/logos/data-raven.svg" width="300" height="200" title="Data Raven: rclone, managed. Unlimited transfers, no per-GB fees." link="https://dataraven.io/r/rclone">}}
|
||||
{{< sponsor src="/img/logos/shade.svg" width="300" height="200" title="Visit our sponsor Shade" link="https://shade.inc">}}
|
||||
{{< sponsor src="/img/logos/filelu-rclone.svg" width="300" height="200" title="Visit our sponsor FileLu" link="https://filelu.com/">}}
|
||||
{{< sponsor src="/img/logos/torbox.png" width="200" height="200" title="Visit our sponsor TORBOX" link="https://www.torbox.app/">}}
|
||||
{{< sponsor src="/img/logos/spectra-logic.svg" width="300" height="200" title="Visit our sponsor Spectra Logic" link="https://spectralogic.com/">}}
|
||||
{{< sponsor src="/img/logos/servercore.svg" width="300" height="200" title="Visit our sponsor servercore" link="https://servercore.com/services/object-storage/?utm_source=rclone.org&utm_medium=referral&utm_campaign=cloud-s3_rclone_231025_paid">}}
|
||||
{{< sponsor src="/img/logos/exchangerate-api.png" width="300" height="200" title="Visit our sponsor ExchangeRate-API" link="https://www.exchangerate-api.com/">}}
|
||||
{{< sponsor src="/img/logos/impossible-cloud.svg" width="300" height="200" title="Visit our sponsor Impossible Cloud" link="https://www.impossiblecloud.com/">}}
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
backend: protondrive
|
||||
name: Proton Drive
|
||||
tier: Tier 5
|
||||
maintainers: None
|
||||
tier: Tier 4
|
||||
maintainers: Community
|
||||
features_score: 4
|
||||
integration_tests: Failing
|
||||
integration_tests: Passing
|
||||
data_integrity: Hash
|
||||
performance: High
|
||||
adoption: Often used
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
</div>
|
||||
|
||||
{{if .IsHome}}
|
||||
<div id="silver-sponsors">
|
||||
<div class="card">
|
||||
<div class="card-header">Silver Sponsor</div>
|
||||
<div class="card-body">
|
||||
@@ -32,6 +33,25 @@
|
||||
<a href="https://shade.inc/" target="_blank" rel="noopener" title="Visit rclone's sponsor Shade"><img style="max-width: 100%; height: auto;" src="/img/logos/shade.svg"></a><br />
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-header">Silver Sponsor</div>
|
||||
<div class="card-body">
|
||||
<a href="https://dataraven.io/r/rclone" target="_blank" rel="noopener" title="Data Raven: rclone, managed. Unlimited transfers, no per-GB fees."><img style="max-width: 100%; height: auto;" src="/img/logos/data-raven.svg"></a><br />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function() {
|
||||
var container = document.getElementById('silver-sponsors');
|
||||
if (!container) return;
|
||||
var cards = Array.prototype.slice.call(container.children);
|
||||
for (var i = cards.length - 1; i > 0; i--) {
|
||||
var j = Math.floor(Math.random() * (i + 1));
|
||||
var tmp = cards[i]; cards[i] = cards[j]; cards[j] = tmp;
|
||||
}
|
||||
cards.forEach(function(c) { container.appendChild(c); });
|
||||
}());
|
||||
</script>
|
||||
{{end}}
|
||||
|
||||
<div class="card">
|
||||
|
||||
@@ -1 +1 @@
|
||||
v1.74.0
|
||||
v1.75.0
|
||||
@@ -566,6 +566,26 @@ var ConfigOptionsInfo = Options{{
|
||||
Default: "",
|
||||
Help: "HTTP proxy URL.",
|
||||
Groups: "Networking",
|
||||
}, {
|
||||
Name: "profile_save",
|
||||
Default: "",
|
||||
Help: "Save this flag configuration as a reusable preset",
|
||||
Groups: "Config",
|
||||
}, {
|
||||
Name: "profile",
|
||||
Default: []string{},
|
||||
Help: "Apply the flag configuration saved with this name. If more than one is provided, priority will be lowest to highest.",
|
||||
Groups: "Config",
|
||||
}, {
|
||||
Name: "profile_save_args",
|
||||
Default: false,
|
||||
Help: "When used with --profile-save, also save positional args (e.g. the paths being synced) into the profile",
|
||||
Groups: "Config",
|
||||
}, {
|
||||
Name: "profile_strict_flags",
|
||||
Default: false,
|
||||
Help: "If set, --profile will error if any flags are invalid for this command, instead of ignoring.",
|
||||
Groups: "Config",
|
||||
}}
|
||||
|
||||
// ConfigInfo is filesystem config options
|
||||
@@ -680,6 +700,10 @@ type ConfigInfo struct {
|
||||
MaxConnections int `config:"max_connections"`
|
||||
NameTransform []string `config:"name_transform"`
|
||||
HTTPProxy string `config:"http_proxy"`
|
||||
SaveProfile string `config:"profile_save"`
|
||||
UseProfile CommaSepList `config:"profile"`
|
||||
ProfileSaveArgs bool `config:"profile_save_args"`
|
||||
ProfileStrictFlags bool `config:"profile_strict_flags"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -396,6 +396,19 @@ func SaveConfig() {
|
||||
fs.Errorf(nil, "Failed to save config after %d tries: %v", ci.LowLevelRetries, err)
|
||||
}
|
||||
|
||||
// ProfileSectionPrefix is the namespace prefix used for profile
|
||||
// sections in the config file (e.g. [profile:fast-sync]). It lets
|
||||
// profiles and remotes share the config file without colliding on
|
||||
// names: a section called "backup" is a remote, "profile:backup" is
|
||||
// a profile.
|
||||
const ProfileSectionPrefix = "profile:"
|
||||
|
||||
// IsProfileSection reports whether the given section name lives in
|
||||
// the profiles namespace.
|
||||
func IsProfileSection(name string) bool {
|
||||
return strings.HasPrefix(name, ProfileSectionPrefix)
|
||||
}
|
||||
|
||||
// FileSections returns the sections in the config file
|
||||
func FileSections() []string {
|
||||
return LoadedData().GetSectionList()
|
||||
@@ -710,6 +723,9 @@ func DumpRcRemote(name string) (dump rc.Params) {
|
||||
func DumpRcBlob() (dump rc.Params) {
|
||||
dump = rc.Params{}
|
||||
for _, name := range LoadedData().GetSectionList() {
|
||||
if IsProfileSection(name) {
|
||||
continue
|
||||
}
|
||||
dump[name] = DumpRcRemote(name)
|
||||
}
|
||||
return dump
|
||||
|
||||
@@ -61,23 +61,6 @@ func AddFlags(ci *fs.ConfigInfo, flagSet *pflag.FlagSet) {
|
||||
flags.StringVarP(flagSet, &dscp, "dscp", "", "", "Set DSCP value to connections, value or name, e.g. CS1, LE, DF, AF21", "Networking")
|
||||
}
|
||||
|
||||
// ParseHeaders converts the strings passed in via the header flags into HTTPOptions
|
||||
func ParseHeaders(headers []string) []*fs.HTTPOption {
|
||||
opts := []*fs.HTTPOption{}
|
||||
for _, header := range headers {
|
||||
parts := strings.SplitN(header, ":", 2)
|
||||
if len(parts) == 1 {
|
||||
fs.Fatalf(nil, "Failed to parse '%s' as an HTTP header. Expecting a string like: 'Content-Encoding: gzip'", header)
|
||||
}
|
||||
option := &fs.HTTPOption{
|
||||
Key: strings.TrimSpace(parts[0]),
|
||||
Value: strings.TrimSpace(parts[1]),
|
||||
}
|
||||
opts = append(opts, option)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// SetFlags sets flags which aren't part of the config system
|
||||
func SetFlags(ci *fs.ConfigInfo) {
|
||||
// Process obsolete --dump-headers and --dump-bodies flags
|
||||
@@ -153,13 +136,13 @@ func SetFlags(ci *fs.ConfigInfo) {
|
||||
|
||||
// Process --headers-upload, --headers-download, --headers
|
||||
if len(uploadHeaders) != 0 {
|
||||
ci.UploadHeaders = ParseHeaders(uploadHeaders)
|
||||
ci.UploadHeaders = fs.MustParseHeaders(uploadHeaders)
|
||||
}
|
||||
if len(downloadHeaders) != 0 {
|
||||
ci.DownloadHeaders = ParseHeaders(downloadHeaders)
|
||||
ci.DownloadHeaders = fs.MustParseHeaders(downloadHeaders)
|
||||
}
|
||||
if len(headers) != 0 {
|
||||
ci.Headers = ParseHeaders(headers)
|
||||
ci.Headers = fs.MustParseHeaders(headers)
|
||||
}
|
||||
|
||||
// Process --metadata-set
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
// Package profiles handles presets for config
|
||||
package profiles
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
"github.com/rclone/rclone/fs/config/configflags"
|
||||
"github.com/rclone/rclone/fs/operations"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// ignoredFlags are flag names (in profile-key form, i.e. snake_case)
|
||||
// that must never be persisted into a profile or copied out of one.
|
||||
//
|
||||
// "config" is excluded because applying it from a profile would
|
||||
// re-point the config-file storage mid-Use(), while we're reading
|
||||
// the profile out of that very file.
|
||||
var ignoredFlags = []string{"profile", "profile_save", "profile_save_args", "profile_strict_flags", "flags_from", "config"}
|
||||
|
||||
const (
|
||||
argPrefix = "arg_"
|
||||
parentKey = "parent_profiles"
|
||||
)
|
||||
|
||||
// ProfileOpt stores the settings for Profiles
|
||||
type ProfileOpt struct {
|
||||
SaveProfile string // name of profile to save
|
||||
UseProfile fs.CommaSepList // name(s) of profiles to use
|
||||
StrictFlags bool // If set, --profile will error if any flags are invalid for this command, instead of ignoring.
|
||||
SaveArgs bool // When saving, also include positional args (e.g. the paths being synced)
|
||||
}
|
||||
|
||||
// Profile represents a flag/arg configuration to save/use as a reusable preset
|
||||
type Profile struct {
|
||||
Name string // the name of the profile
|
||||
Args []string // command args (ex. the paths being synced)
|
||||
Flags map[string]string // any flags (command, config, backend...)
|
||||
Parents []string // see p.GetParents() to get a slice of *Profiles instead
|
||||
}
|
||||
|
||||
// NewProfile returns a new empty *Profile
|
||||
func NewProfile(name string) *Profile {
|
||||
return &Profile{
|
||||
Name: name,
|
||||
Args: []string{},
|
||||
Flags: map[string]string{},
|
||||
Parents: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
// ProfileOptFromCtx gets a new ProfileOpt from config settings
|
||||
func ProfileOptFromCtx(ctx context.Context) ProfileOpt {
|
||||
ci := fs.GetConfig(ctx)
|
||||
return ProfileOpt{
|
||||
SaveProfile: ci.SaveProfile,
|
||||
UseProfile: ci.UseProfile,
|
||||
StrictFlags: ci.ProfileStrictFlags,
|
||||
SaveArgs: ci.ProfileSaveArgs,
|
||||
}
|
||||
}
|
||||
|
||||
// NewFromCommand sets the profile's Args and Flags from the cmd and args passed in
|
||||
func (p *Profile) NewFromCommand(cmd *cobra.Command, args []string) {
|
||||
p.Args = args
|
||||
|
||||
setProfileVal := func(flag *pflag.Flag) {
|
||||
key := optionToProfileKey(flag.Name)
|
||||
if slices.Contains(ignoredFlags, key) {
|
||||
return
|
||||
}
|
||||
if !flag.Changed {
|
||||
return
|
||||
}
|
||||
p.Flags[key] = flag.Value.String()
|
||||
}
|
||||
|
||||
// .Visit() does not visit the flags we add manually via
|
||||
// --flags-from (in `rclone config profile save`), but .VisitAll()
|
||||
// with a flag.Changed check does, so use that.
|
||||
cmd.Flags().VisitAll(setProfileVal)
|
||||
}
|
||||
|
||||
// sectionName returns the config-file section name for the profile
|
||||
// "name" (e.g. "fast" -> "profile:fast"). Profile.Name itself stays
|
||||
// in its user-facing form.
|
||||
func sectionName(name string) string {
|
||||
return config.ProfileSectionPrefix + name
|
||||
}
|
||||
|
||||
// GetProfile gets a profile from the config
|
||||
func GetProfile(name string) (*Profile, error) {
|
||||
p := NewProfile(name)
|
||||
section := sectionName(p.Name)
|
||||
data := config.LoadedData()
|
||||
if !data.HasSection(section) {
|
||||
return nil, fmt.Errorf("no profile named %q found in config file", p.Name)
|
||||
}
|
||||
|
||||
// Args may appear out of order or be sparse (e.g. arg_3 without
|
||||
// arg_1) so collect them first then size the slice from the max
|
||||
// index.
|
||||
args := map[int]string{}
|
||||
|
||||
keys := data.GetKeyList(section)
|
||||
for _, key := range keys {
|
||||
if slices.Contains(ignoredFlags, key) {
|
||||
continue
|
||||
}
|
||||
|
||||
if key == parentKey {
|
||||
parentList, _ := data.GetValue(section, key)
|
||||
p.Parents = strings.Split(parentList, ",")
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(key, argPrefix) {
|
||||
i, err := argNum(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing arg %s: %v", key, err)
|
||||
}
|
||||
if i < 0 {
|
||||
return nil, fmt.Errorf("arg index out of range: %s", key)
|
||||
}
|
||||
val, _ := data.GetValue(section, key)
|
||||
args[i] = val
|
||||
continue
|
||||
}
|
||||
|
||||
val, _ := data.GetValue(section, key)
|
||||
p.Flags[key] = val
|
||||
}
|
||||
if len(args) > 0 {
|
||||
maxIdx := -1
|
||||
for i := range args {
|
||||
if i > maxIdx {
|
||||
maxIdx = i
|
||||
}
|
||||
}
|
||||
p.Args = make([]string, maxIdx+1)
|
||||
for i, v := range args {
|
||||
p.Args[i] = v
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// GetProfiles gets a slice of profiles
|
||||
func GetProfiles(names []string) ([]*Profile, error) {
|
||||
profiles := []*Profile{}
|
||||
for _, name := range names {
|
||||
p, err := GetProfile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profiles = append(profiles, p)
|
||||
}
|
||||
return profiles, nil
|
||||
}
|
||||
|
||||
// UseProfiles gets one or more Profiles from opt.UseProfile and applies them to context (priority: lowest to highest)
|
||||
func UseProfiles(ctx context.Context, cmd *cobra.Command, args []string, opt *ProfileOpt) error {
|
||||
for _, profileName := range opt.UseProfile {
|
||||
err := GetAndUseProfile(ctx, cmd, args, opt, profileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAndUseProfile gets one Profile and uses it
|
||||
func GetAndUseProfile(ctx context.Context, cmd *cobra.Command, args []string, opt *ProfileOpt, profileName string) error {
|
||||
profile, err := GetProfile(profileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = profile.Use(ctx, cmd, args, opt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save saves a profile to the config file
|
||||
func (p *Profile) Save(ctx context.Context, opt *ProfileOpt) error {
|
||||
var err error
|
||||
p.Name, err = validateProfileName(p.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if operations.SkipDestructive(ctx, p.Name, "save profile") {
|
||||
return nil
|
||||
}
|
||||
|
||||
section := sectionName(p.Name)
|
||||
data := config.LoadedData()
|
||||
data.DeleteSection(section) // clear it if already exists
|
||||
|
||||
for k, v := range p.Flags {
|
||||
// Defensive normalisation: callers building a *Profile
|
||||
// directly may pass keys in either form.
|
||||
data.SetValue(section, optionToProfileKey(k), v)
|
||||
}
|
||||
|
||||
if opt.SaveArgs {
|
||||
p.saveArgs()
|
||||
}
|
||||
|
||||
if len(p.Parents) > 0 {
|
||||
data.SetValue(section, parentKey, strings.Join(p.Parents, ","))
|
||||
}
|
||||
|
||||
if err := data.Save(); err != nil {
|
||||
return fmt.Errorf("error saving config: %v", err)
|
||||
}
|
||||
|
||||
fs.Debugf(p.Name, "saved profile: %v", SprintSection(sectionName(p.Name)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Profile) saveArgs() {
|
||||
section := sectionName(p.Name)
|
||||
for i, arg := range p.Args {
|
||||
config.LoadedData().SetValue(section, argPrefix+fmt.Sprint(i+1), arg)
|
||||
}
|
||||
}
|
||||
|
||||
// Use sets the current command args and flags from the profile struct
|
||||
func (p *Profile) Use(ctx context.Context, cmd *cobra.Command, cobraArgs []string, opt *ProfileOpt) error {
|
||||
// set logging first
|
||||
ci := fs.GetConfig(ctx)
|
||||
section := sectionName(p.Name)
|
||||
if ci.LogLevel == fs.LogLevelNotice {
|
||||
if verbose, ok := config.FileGetValue(section, "verbose"); ok {
|
||||
_ = cmd.Flags().Lookup("verbose").Value.Set(verbose)
|
||||
configflags.SetFlags(ci)
|
||||
}
|
||||
}
|
||||
fs.Debugf(p.Name, "loading profile: %v", SprintSection(section))
|
||||
|
||||
err := p.useParents(ctx, cmd, cobraArgs, opt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = p.useFlags(ctx, cmd, cobraArgs, opt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Apply saved args whenever the profile carries them. Whether or
|
||||
// not args were saved is a per-profile decision made at save time
|
||||
// (--profile-save-args); the user shouldn't have to know or
|
||||
// re-pass that knob at use time.
|
||||
if len(p.Args) > 0 {
|
||||
p.useArgs(ctx, cmd, cobraArgs, opt)
|
||||
}
|
||||
|
||||
// Copy any option-backed flag values we just changed (e.g.
|
||||
// --checkers, --transfers, --metadata, backend flags) out of the
|
||||
// pflag/options registry and into ConfigInfo.
|
||||
if err := fs.GlobalOptionsInit(); err != nil {
|
||||
return fmt.Errorf("failed to reload global options from profile: %w", err)
|
||||
}
|
||||
// Re-run configflags.SetFlags() for the hand-rolled flags it owns
|
||||
// (-v, -q, --bind, --headers, --config, --cache-dir...).
|
||||
configflags.SetFlags(ci)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Profile) useFlags(ctx context.Context, cmd *cobra.Command, cobraArgs []string, opt *ProfileOpt) error {
|
||||
ci := fs.GetConfig(ctx)
|
||||
for rawKey, val := range p.Flags {
|
||||
key := optionToProfileKey(rawKey) // tolerate hyphenated keys from external callers
|
||||
if slices.Contains(ignoredFlags, key) {
|
||||
continue
|
||||
}
|
||||
|
||||
flag := cmd.Flags().Lookup(profileKeyToFlag(key))
|
||||
if flag == nil {
|
||||
if opt.StrictFlags {
|
||||
return fmt.Errorf("invalid flag: %s", profileKeyToFlag(key))
|
||||
}
|
||||
fs.Debugf(p.Name, "ignoring unknown flag %s for this command", profileKeyToFlag(key))
|
||||
continue
|
||||
}
|
||||
|
||||
if ci.DryRun && key == "dry_run" && val == "false" {
|
||||
// disallow overriding --dry-run if it was specifically set
|
||||
fs.Logf(nil, "for safety, profiles cannot change --dry-run from true to false. Ignoring.")
|
||||
continue
|
||||
}
|
||||
logChange(p.Name, key, flag.Value.String(), val)
|
||||
err := flag.Value.Set(val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: error setting val %s from profile: %v", flag.Name, val, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// useArgs fills positional args from the profile's saved Args list,
|
||||
// but only into slots the user did not provide on the command line.
|
||||
// We don't CheckArgs() here as the command will do it later; users
|
||||
// should take care to not exceed MaxArgs.
|
||||
//
|
||||
// Args on parent profiles are generally a bad idea (children would
|
||||
// overwrite parent), but the same precedence rule applies if you
|
||||
// use them.
|
||||
func (p *Profile) useArgs(ctx context.Context, cmd *cobra.Command, cobraArgs []string, opt *ProfileOpt) {
|
||||
userProvided := len(cobraArgs)
|
||||
for i, pArg := range p.Args { // we DO assume that the p.Args are in the right order here.
|
||||
if pArg == "" {
|
||||
continue
|
||||
}
|
||||
if i < userProvided {
|
||||
// User gave an explicit positional arg for this slot - keep it.
|
||||
continue
|
||||
}
|
||||
if i > len(cobraArgs)-1 {
|
||||
cobraArgs = append(cobraArgs, "")
|
||||
}
|
||||
logChange(p.Name, fmt.Sprintf("Arg %d", i+1), cobraArgs[i], pArg)
|
||||
cobraArgs[i] = pArg
|
||||
}
|
||||
|
||||
// rclone command [args...]
|
||||
os.Args = append([]string{os.Args[0], os.Args[1]}, cobraArgs...)
|
||||
os.Args = cleanArgs(os.Args)
|
||||
}
|
||||
|
||||
// allows nested profiles (priority lowest to highest, parents all lower than child)
|
||||
func (p *Profile) useParents(ctx context.Context, cmd *cobra.Command, args []string, opt *ProfileOpt) error {
|
||||
if len(p.Parents) == 0 {
|
||||
return nil
|
||||
}
|
||||
newopt := *opt
|
||||
newopt.UseProfile = p.Parents
|
||||
return UseProfiles(ctx, cmd, args, &newopt)
|
||||
}
|
||||
|
||||
// GetParents returns the parent profiles of this profile
|
||||
func (p *Profile) GetParents() ([]*Profile, error) {
|
||||
return GetProfiles(p.Parents)
|
||||
}
|
||||
|
||||
/*
|
||||
TODO:
|
||||
- should we be storing more in memory to cut down on config.LoadedData() calls?
|
||||
- when profile/key names have illegal characters should we error or auto-convert them? currently we do some of both.
|
||||
- more tests
|
||||
- docs
|
||||
- document handling of blank or default values
|
||||
- UI could use some cleanup (and see the note there about the use of the word "remote")
|
||||
- rc methods
|
||||
- API for other commands (bisync) to save/use profiles
|
||||
- better handle scenario where logging level passed in is higher than that of the profile we're getting/using...
|
||||
...probably needs a defer to make sure debugs are seen (if requested) during profile setting, then set the real level (from profile) after
|
||||
- maybe edit more of the helper functions to use the types and methods instead of modifying config directly
|
||||
- the ProfileOpt logic maybe needs another look -- slightly confusing that we store the profile name both there and in the profile struct.
|
||||
- search other TODOs
|
||||
*/
|
||||
@@ -0,0 +1,47 @@
|
||||
package profiles
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestProfileRequested(t *testing.T) {
|
||||
// Clear any RCLONE_PROFILE* env vars set in the caller's
|
||||
// environment so they don't leak into the test cases. t.Setenv
|
||||
// restores them automatically.
|
||||
t.Setenv("RCLONE_PROFILE", "")
|
||||
t.Setenv("RCLONE_PROFILE_SAVE", "")
|
||||
|
||||
savedArgs := os.Args
|
||||
defer func() { os.Args = savedArgs }()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
env map[string]string
|
||||
expect bool
|
||||
}{
|
||||
{"no flag, no env", []string{"rclone", "ls", "remote:"}, nil, false},
|
||||
{"--profile NAME", []string{"rclone", "ls", "remote:", "--profile", "x"}, nil, true},
|
||||
{"--profile=NAME", []string{"rclone", "ls", "remote:", "--profile=x"}, nil, true},
|
||||
{"--profile-save NAME", []string{"rclone", "ls", "remote:", "--profile-save", "x"}, nil, true},
|
||||
{"--profile-save=NAME", []string{"rclone", "ls", "remote:", "--profile-save=x"}, nil, true},
|
||||
{"--profile-save-args alone does not trigger", []string{"rclone", "ls", "remote:", "--profile-save-args"}, nil, false},
|
||||
{"--profile-strict-flags alone does not trigger", []string{"rclone", "ls", "remote:", "--profile-strict-flags"}, nil, false},
|
||||
{"RCLONE_PROFILE env var", []string{"rclone", "ls", "remote:"}, map[string]string{"RCLONE_PROFILE": "x"}, true},
|
||||
{"RCLONE_PROFILE_SAVE env var", []string{"rclone", "ls", "remote:"}, map[string]string{"RCLONE_PROFILE_SAVE": "x"}, true},
|
||||
{"empty RCLONE_PROFILE does not trigger", []string{"rclone", "ls", "remote:"}, map[string]string{"RCLONE_PROFILE": ""}, false},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
os.Args = c.args
|
||||
for k, v := range c.env {
|
||||
t.Setenv(k, v)
|
||||
}
|
||||
assert.Equal(t, c.expect, profileRequested())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// Package profiles handles presets for config
|
||||
package profiles
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
"github.com/rclone/rclone/fs/config/configfile"
|
||||
"github.com/rclone/rclone/fs/config/configflags"
|
||||
"github.com/rclone/rclone/fs/fspath"
|
||||
fslog "github.com/rclone/rclone/fs/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// AddProfiles handles saving/loading of config profiles
|
||||
// We do this before Root.Execute() because there's otherwise
|
||||
// no good way to add args to an already-executing command
|
||||
func AddProfiles(ctx context.Context, Root *cobra.Command) {
|
||||
if !profileRequested() {
|
||||
return
|
||||
}
|
||||
cmd, remaining, err := Root.Find(os.Args[1:])
|
||||
if err != nil {
|
||||
fs.Fatalf(nil, "Fatal error: %v", err)
|
||||
}
|
||||
// Anything under `rclone config` (notably `config profile save`)
|
||||
// manages profiles directly and must not be intercepted here.
|
||||
for c := cmd; c != nil; c = c.Parent() {
|
||||
if c.Name() == "config" {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Start the logger so debug/info messages from the profile code
|
||||
// reach the user; the normal cobra.OnInitialize path hasn't run
|
||||
// yet because Root.Execute() hasn't been called.
|
||||
fslog.InitLogging()
|
||||
|
||||
if err := cmd.Flags().Parse(remaining); err != nil {
|
||||
fs.Fatalf(nil, "Fatal error: %v", err)
|
||||
}
|
||||
|
||||
ci := fs.GetConfig(ctx)
|
||||
// The hand-rolled flags (--config, --cache-dir, -v, -q, ...) live
|
||||
// on pflag.CommandLine rather than on `cmd`, so parse it as well
|
||||
// to populate the package vars configflags.SetFlags reads from.
|
||||
if err := pflag.CommandLine.Parse(os.Args[1:]); err != nil {
|
||||
fs.Fatalf(nil, "Fatal error: %v", err)
|
||||
}
|
||||
// Populate ConfigInfo from the option-registry values (covers
|
||||
// every option-backed flag including --profile, --profile-save,
|
||||
// and env vars like RCLONE_PROFILE).
|
||||
if err := fs.GlobalOptionsInit(); err != nil {
|
||||
fs.Fatalf(nil, "Failed to initialise global options: %v", err)
|
||||
}
|
||||
// Apply the hand-rolled flags last - SetFlags writes directly to
|
||||
// ConfigInfo (e.g. ci.LogLevel from -vv) and would otherwise be
|
||||
// overwritten by GlobalOptionsInit reloading from the option
|
||||
// defaults.
|
||||
configflags.SetFlags(ci)
|
||||
// Install the config file handler *after* SetFlags has applied
|
||||
// --config (or RCLONE_CONFIG), otherwise the install is a no-op
|
||||
// against an empty path and any save goes to an in-memory
|
||||
// storage that's discarded at exit.
|
||||
configfile.Install()
|
||||
|
||||
if err := HandleProfiles(ctx, cmd, cmd.Flags().Args()); err != nil {
|
||||
fs.Fatalf(nil, "Fatal error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleProfiles handles --profile-save and --profile
|
||||
func HandleProfiles(ctx context.Context, cmd *cobra.Command, args []string) error {
|
||||
opt := ProfileOptFromCtx(ctx)
|
||||
|
||||
if len(opt.UseProfile) > 0 {
|
||||
err := UseProfiles(ctx, cmd, args, &opt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if opt.SaveProfile != "" {
|
||||
saveProfile := NewProfile(opt.SaveProfile)
|
||||
saveProfile.NewFromCommand(cmd, args)
|
||||
return saveProfile.Save(ctx, &opt)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func argNum(key string) (int, error) {
|
||||
s := strings.TrimPrefix(key, argPrefix)
|
||||
i, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return i, err
|
||||
}
|
||||
return i - 1, nil
|
||||
}
|
||||
|
||||
func optionToProfileKey(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
name = strings.ReplaceAll(name, " ", "_")
|
||||
return strings.ToLower(strings.ReplaceAll(name, "-", "_"))
|
||||
}
|
||||
|
||||
// note that this is case-insensitive
|
||||
func profileKeyToFlag(name string) string {
|
||||
return strings.ToLower(strings.ReplaceAll(name, "_", "-"))
|
||||
}
|
||||
|
||||
func validateKeyName(name string) (convertedName string, err error) {
|
||||
convertedName = fspath.MakeConfigName(optionToProfileKey(name))
|
||||
if convertedName != name {
|
||||
return convertedName, errors.New("invalid characters detected")
|
||||
}
|
||||
return convertedName, nil
|
||||
}
|
||||
|
||||
func validateProfileName(name string) (convertedName string, err error) {
|
||||
// Profiles live in the "profile:" namespace so there is no
|
||||
// conflict possible with remote names - we only need to validate
|
||||
// the name's character set.
|
||||
return validateKeyName(name)
|
||||
}
|
||||
|
||||
func logChange(useProfileName, key, oldval, newval string) {
|
||||
if oldval == newval {
|
||||
return
|
||||
}
|
||||
if oldval == "" {
|
||||
oldval = "[blank]"
|
||||
}
|
||||
fs.Infof(useProfileName, "changing %s from %s to %s", key, oldval, newval)
|
||||
}
|
||||
|
||||
// SprintSection returns a string of this section from the config file
|
||||
func SprintSection(name string) string {
|
||||
keys := config.LoadedData().GetKeyList(name)
|
||||
s := fmt.Sprintf("\n[%s]\n", name)
|
||||
for _, key := range keys {
|
||||
if value, ok := config.FileGetValue(name, key); ok {
|
||||
s += fmt.Sprintf("%s%s%s\n", key, " = ", value)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func cleanArgs(s []string) []string {
|
||||
var r []string
|
||||
// s = s[:cap(s)]
|
||||
for _, str := range s {
|
||||
if str != "" {
|
||||
r = append(r, str)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// profileRequested returns true when the user has asked for profile
|
||||
// machinery to fire on this invocation, via either a CLI flag or an
|
||||
// env var.
|
||||
//
|
||||
// We need this *before* cobra/options have done any of their work,
|
||||
// so we look at the raw os.Args / os.Environ directly rather than
|
||||
// reading from ConfigInfo (which is still populated from defaults
|
||||
// at this point).
|
||||
func profileRequested() bool {
|
||||
if os.Getenv("RCLONE_PROFILE") != "" || os.Getenv("RCLONE_PROFILE_SAVE") != "" {
|
||||
return true
|
||||
}
|
||||
return slices.ContainsFunc(os.Args, func(a string) bool {
|
||||
// Exact "--profile" / "--profile-save" and their "=value" forms.
|
||||
// Anything else (e.g. --profile-save-args, --profile-strict-flags)
|
||||
// is a modifier and does not on its own trigger the profile
|
||||
// machinery.
|
||||
return a == "--profile" || strings.HasPrefix(a, "--profile=") ||
|
||||
a == "--profile-save" || strings.HasPrefix(a, "--profile-save=")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package profiles_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
"github.com/rclone/rclone/fs/config/configfile"
|
||||
profiles "github.com/rclone/rclone/fs/config/configprofiles"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newTestCmd returns a cobra.Command with a small synthetic flag set
|
||||
// covering the flag types the profile code actually has to handle.
|
||||
//
|
||||
// It is deliberately decoupled from cmd.Root and the real
|
||||
// configflags/filterflags registrations: tests should exercise the
|
||||
// profile machinery against a known, minimal surface rather than
|
||||
// against the whole of rclone.
|
||||
func newTestCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{Use: "test"}
|
||||
fs := cmd.Flags()
|
||||
fs.Int("checkers", 8, "Number of checkers")
|
||||
fs.Bool("checksum", false, "Use checksum")
|
||||
fs.Bool("metadata", false, "Preserve metadata")
|
||||
fs.Bool("dry-run", false, "Do a trial run")
|
||||
fs.String("backup-dir", "", "Backup directory")
|
||||
fs.String("drive-skip-gdocs", "", "Drive: skip gdocs")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// useTempConfig points the config subsystem at a fresh empty file
|
||||
// inside t.TempDir() and registers cleanup to restore the previous
|
||||
// path.
|
||||
func useTempConfig(t *testing.T) string {
|
||||
t.Helper()
|
||||
configfile.Install()
|
||||
old := config.GetConfigPath()
|
||||
path := filepath.Join(t.TempDir(), "rclone.conf")
|
||||
require.NoError(t, os.WriteFile(path, nil, 0600))
|
||||
require.NoError(t, config.SetConfigPath(path))
|
||||
t.Cleanup(func() {
|
||||
_ = config.SetConfigPath(old)
|
||||
})
|
||||
// Make sure we start from an empty in-memory view too.
|
||||
for _, section := range config.LoadedData().GetSectionList() {
|
||||
config.LoadedData().DeleteSection(section)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// parse parses argv into the given command's flag set and returns the
|
||||
// remaining positional arguments.
|
||||
func parse(t *testing.T, cmd *cobra.Command, argv ...string) []string {
|
||||
t.Helper()
|
||||
require.NoError(t, cmd.Flags().Parse(argv))
|
||||
return cmd.Flags().Args()
|
||||
}
|
||||
|
||||
func TestNewFromCommand_CollectsOnlyChangedFlags(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
cmd := newTestCmd()
|
||||
args := parse(t, cmd,
|
||||
"--checkers", "16",
|
||||
"--checksum",
|
||||
"--drive-skip-gdocs", "true",
|
||||
"src", "dst",
|
||||
)
|
||||
|
||||
p := profiles.NewProfile("name")
|
||||
p.NewFromCommand(cmd, args)
|
||||
|
||||
assert.Equal(t, []string{"src", "dst"}, p.Args)
|
||||
assert.Equal(t, map[string]string{
|
||||
"checkers": "16",
|
||||
"checksum": "true",
|
||||
"drive_skip_gdocs": "true",
|
||||
}, p.Flags)
|
||||
}
|
||||
|
||||
func TestNewFromCommand_SkipsIgnoredFlags(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
cmd := newTestCmd()
|
||||
// Profile-control flags must not be persisted into the profile,
|
||||
// even if the test command happens to define them.
|
||||
cmd.Flags().String("profile-save", "", "")
|
||||
cmd.Flags().String("profile", "", "")
|
||||
cmd.Flags().Bool("profile-save-args", false, "")
|
||||
parse(t, cmd,
|
||||
"--checkers", "4",
|
||||
"--profile-save", "ignored",
|
||||
"--profile", "ignored",
|
||||
"--profile-save-args",
|
||||
)
|
||||
|
||||
p := profiles.NewProfile("name")
|
||||
p.NewFromCommand(cmd, nil)
|
||||
|
||||
assert.Equal(t, map[string]string{"checkers": "4"}, p.Flags)
|
||||
}
|
||||
|
||||
func TestSaveAndGet_RoundTripsFlagsAndArgs(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
p := profiles.NewProfile("preset")
|
||||
p.Flags = map[string]string{
|
||||
"checkers": "16",
|
||||
"metadata": "true",
|
||||
"drive_skip_gdocs": "true",
|
||||
}
|
||||
p.Args = []string{"src", "remote:dst"}
|
||||
p.Parents = []string{"parent_a", "parent_b"}
|
||||
|
||||
opt := &profiles.ProfileOpt{SaveArgs: true}
|
||||
require.NoError(t, p.Save(ctx, opt))
|
||||
|
||||
got, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, p, got)
|
||||
}
|
||||
|
||||
func TestUse_UserPositionalArgsBeatProfileArgs(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Save a profile with positional args.
|
||||
p := profiles.NewProfile("paths")
|
||||
p.Args = []string{"saved-src", "saved-dst"}
|
||||
require.NoError(t, p.Save(ctx, &profiles.ProfileOpt{SaveArgs: true}))
|
||||
|
||||
// useArgs mutates os.Args; save/restore.
|
||||
savedOSArgs := os.Args
|
||||
defer func() { os.Args = savedOSArgs }()
|
||||
os.Args = []string{"rclone", "copy", "user-src", "user-dst", "--profile", "paths"}
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("paths")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, []string{"user-src", "user-dst"}, &profiles.ProfileOpt{}))
|
||||
|
||||
// The user's positional args must win over the profile's.
|
||||
assert.Equal(t, []string{"rclone", "copy", "user-src", "user-dst"}, os.Args)
|
||||
}
|
||||
|
||||
func TestUse_ProfileArgsFillUnprovidedSlots(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
p := profiles.NewProfile("paths")
|
||||
p.Args = []string{"saved-src", "saved-dst"}
|
||||
require.NoError(t, p.Save(ctx, &profiles.ProfileOpt{SaveArgs: true}))
|
||||
|
||||
savedOSArgs := os.Args
|
||||
defer func() { os.Args = savedOSArgs }()
|
||||
// User provided no positional args.
|
||||
os.Args = []string{"rclone", "copy", "--profile", "paths"}
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("paths")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, nil, &profiles.ProfileOpt{}))
|
||||
|
||||
// With no user args, the profile's saved args fill in.
|
||||
assert.Equal(t, []string{"rclone", "copy", "saved-src", "saved-dst"}, os.Args)
|
||||
}
|
||||
|
||||
func TestSave_DefensiveKeyNormalisation(t *testing.T) {
|
||||
// Callers building a *Profile directly may pass keys in either
|
||||
// snake_case or hyphenated form. Both should land in the same
|
||||
// section.
|
||||
useTempConfig(t)
|
||||
p := profiles.NewProfile("preset")
|
||||
p.Flags = map[string]string{"drive-skip-gdocs": "true"}
|
||||
require.NoError(t, p.Save(context.Background(), &profiles.ProfileOpt{}))
|
||||
|
||||
got, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{"drive_skip_gdocs": "true"}, got.Flags)
|
||||
}
|
||||
|
||||
func TestSave_RemoteAndProfileWithSameNameCoexist(t *testing.T) {
|
||||
// Profiles live in the "profile:" namespace so they can share a
|
||||
// name with a remote without colliding.
|
||||
useTempConfig(t)
|
||||
config.LoadedData().SetValue("clash", "type", "drive")
|
||||
require.NoError(t, config.LoadedData().Save())
|
||||
|
||||
p := profiles.NewProfile("clash")
|
||||
p.Flags = map[string]string{"checkers": "4"}
|
||||
require.NoError(t, p.Save(context.Background(), &profiles.ProfileOpt{}))
|
||||
|
||||
// Remote section still intact.
|
||||
rt, ok := config.LoadedData().GetValue("clash", "type")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "drive", rt)
|
||||
// Profile under its namespaced section name.
|
||||
assert.True(t, config.LoadedData().HasSection("profile:clash"))
|
||||
}
|
||||
|
||||
func TestGetProfile_HandlesSparseArgIndices(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
// Write arg_3 with no arg_1 / arg_2 - GetProfile used to crash
|
||||
// here.
|
||||
config.LoadedData().SetValue("profile:preset", "arg_3", "third")
|
||||
require.NoError(t, config.LoadedData().Save())
|
||||
|
||||
got, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"", "", "third"}, got.Args)
|
||||
}
|
||||
|
||||
func TestUse_AppliesFlagValues(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
saved := profiles.NewProfile("preset")
|
||||
saved.Flags = map[string]string{
|
||||
"checkers": "16",
|
||||
"metadata": "true",
|
||||
}
|
||||
require.NoError(t, saved.Save(ctx, &profiles.ProfileOpt{}))
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, nil, &profiles.ProfileOpt{}))
|
||||
|
||||
assert.Equal(t, "16", cmd.Flags().Lookup("checkers").Value.String())
|
||||
assert.Equal(t, "true", cmd.Flags().Lookup("metadata").Value.String())
|
||||
}
|
||||
|
||||
func TestUse_UnknownFlagSkippedByDefault(t *testing.T) {
|
||||
// A profile may carry flags for commands other than the one it
|
||||
// is currently being applied to; non-strict mode should just
|
||||
// ignore them rather than erroring or nil-dereferencing.
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
saved := profiles.NewProfile("preset")
|
||||
saved.Flags = map[string]string{
|
||||
"checkers": "12",
|
||||
"not_a_real_flag": "value",
|
||||
}
|
||||
require.NoError(t, saved.Save(ctx, &profiles.ProfileOpt{}))
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, nil, &profiles.ProfileOpt{}))
|
||||
assert.Equal(t, "12", cmd.Flags().Lookup("checkers").Value.String())
|
||||
}
|
||||
|
||||
func TestUse_UnknownFlagErrorsInStrictMode(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
|
||||
saved := profiles.NewProfile("preset")
|
||||
saved.Flags = map[string]string{"not_a_real_flag": "value"}
|
||||
require.NoError(t, saved.Save(ctx, &profiles.ProfileOpt{}))
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
err = loaded.Use(ctx, cmd, nil, &profiles.ProfileOpt{StrictFlags: true})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not-a-real-flag")
|
||||
}
|
||||
|
||||
func TestUse_Parents_LowestToHighestPriority(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx := context.Background()
|
||||
opt := &profiles.ProfileOpt{}
|
||||
|
||||
parentA := profiles.NewProfile("parent_a")
|
||||
parentA.Flags = map[string]string{
|
||||
"checkers": "4",
|
||||
"metadata": "true",
|
||||
}
|
||||
require.NoError(t, parentA.Save(ctx, opt))
|
||||
|
||||
parentB := profiles.NewProfile("parent_b")
|
||||
parentB.Flags = map[string]string{
|
||||
"checkers": "8",
|
||||
"checksum": "true",
|
||||
}
|
||||
require.NoError(t, parentB.Save(ctx, opt))
|
||||
|
||||
child := profiles.NewProfile("child")
|
||||
child.Flags = map[string]string{"checkers": "16"}
|
||||
child.Parents = []string{"parent_a", "parent_b"}
|
||||
require.NoError(t, child.Save(ctx, opt))
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("child")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, nil, opt))
|
||||
|
||||
// child overrides both parents
|
||||
assert.Equal(t, "16", cmd.Flags().Lookup("checkers").Value.String())
|
||||
// parent_b overrides parent_a where both set the same flag
|
||||
// (n/a here for checkers; for checksum only parent_b sets)
|
||||
assert.Equal(t, "true", cmd.Flags().Lookup("checksum").Value.String())
|
||||
// flag set only by parent_a still applies
|
||||
assert.Equal(t, "true", cmd.Flags().Lookup("metadata").Value.String())
|
||||
}
|
||||
|
||||
func TestUse_DryRunCannotBeTurnedOff(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
|
||||
saved := profiles.NewProfile("preset")
|
||||
saved.Flags = map[string]string{"dry_run": "false"}
|
||||
require.NoError(t, saved.Save(context.Background(), &profiles.ProfileOpt{}))
|
||||
|
||||
// Turn dry-run on *after* saving, otherwise Save itself is
|
||||
// skipped as a destructive op under --dry-run.
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
ci.DryRun = true
|
||||
|
||||
cmd := newTestCmd()
|
||||
loaded, err := profiles.GetProfile("preset")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, loaded.Use(ctx, cmd, nil, &profiles.ProfileOpt{}))
|
||||
// The profile's "dry_run = false" must be ignored.
|
||||
assert.Equal(t, "false", cmd.Flags().Lookup("dry-run").Value.String())
|
||||
// We don't assert on ci.DryRun because Profile.Use re-runs
|
||||
// GlobalOptionsInit, which would copy ci.DryRun back from the
|
||||
// flag default - the relevant guarantee is that the flag was
|
||||
// not overwritten.
|
||||
}
|
||||
|
||||
func TestHandleProfiles_SaveRoundTrip(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
ctx, ci := fs.AddConfig(context.Background())
|
||||
|
||||
cmd := newTestCmd()
|
||||
parse(t, cmd, "--checkers", "32", "--checksum")
|
||||
|
||||
ci.SaveProfile = "fromcmd"
|
||||
require.NoError(t, profiles.HandleProfiles(ctx, cmd, cmd.Flags().Args()))
|
||||
|
||||
loaded, err := profiles.GetProfile("fromcmd")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]string{
|
||||
"checkers": "32",
|
||||
"checksum": "true",
|
||||
}, loaded.Flags)
|
||||
}
|
||||
|
||||
func TestSprintSection_ShowsAllKeys(t *testing.T) {
|
||||
useTempConfig(t)
|
||||
p := profiles.NewProfile("preset")
|
||||
p.Flags = map[string]string{"checkers": "9"}
|
||||
require.NoError(t, p.Save(context.Background(), &profiles.ProfileOpt{}))
|
||||
|
||||
s := profiles.SprintSection("profile:preset")
|
||||
lines := sortedNonBlank(s)
|
||||
want := sortedNonBlank("[profile:preset]\ncheckers = 9\n")
|
||||
assert.Equal(t, want, lines)
|
||||
}
|
||||
|
||||
func sortedNonBlank(s string) []string {
|
||||
out := []string{}
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// TestGlobalOptionsLoadable pins the contract that callers like
|
||||
// HandleProfiles / Profile.Use rely on: fs.GlobalOptionsInit must be
|
||||
// callable on an initialised process without erroring. If the global
|
||||
// options registry ever ends up in a state that can't be loaded the
|
||||
// rest of this suite will start blowing up too, but this gives a
|
||||
// pointed failure.
|
||||
func TestGlobalOptionsLoadable(t *testing.T) {
|
||||
require.NoError(t, fs.GlobalOptionsInit())
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Package profiles handles presets for config
|
||||
package profiles
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
)
|
||||
|
||||
// ShowProfiles prints an overview of every profile in the config file.
|
||||
func ShowProfiles() {
|
||||
profiles := GetProfileList()
|
||||
fmt.Printf("%-20s %s\n", "Name", "Type")
|
||||
fmt.Printf("%-20s %s\n", "====", "====")
|
||||
for _, profile := range profiles {
|
||||
fmt.Printf("%-20s %s\n", profile, "profile")
|
||||
}
|
||||
}
|
||||
|
||||
// GetProfileList returns the user-facing names of all profile
|
||||
// sections (i.e. without the "profile:" prefix), sorted.
|
||||
func GetProfileList() []string {
|
||||
sections := config.LoadedData().GetSectionList()
|
||||
profiles := []string{}
|
||||
for _, s := range sections {
|
||||
if !config.IsProfileSection(s) {
|
||||
continue
|
||||
}
|
||||
profiles = append(profiles, strings.TrimPrefix(s, config.ProfileSectionPrefix))
|
||||
}
|
||||
sort.Strings(profiles)
|
||||
return profiles
|
||||
}
|
||||
+17
-3
@@ -294,7 +294,7 @@ func ChooseNumber(what string, min, max int) int {
|
||||
|
||||
// ShowRemotes shows an overview of the config file
|
||||
func ShowRemotes() {
|
||||
remotes := LoadedData().GetSectionList()
|
||||
remotes := remoteSections()
|
||||
if len(remotes) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -308,12 +308,26 @@ func ShowRemotes() {
|
||||
|
||||
// ChooseRemote chooses a remote name
|
||||
func ChooseRemote() string {
|
||||
remotes := LoadedData().GetSectionList()
|
||||
remotes := remoteSections()
|
||||
sort.Strings(remotes)
|
||||
fmt.Println("Select remote.")
|
||||
return Choose("remote", "value", remotes, nil, "", true, false)
|
||||
}
|
||||
|
||||
// remoteSections returns the section names that are remotes (i.e.
|
||||
// everything except profile sections).
|
||||
func remoteSections() []string {
|
||||
all := LoadedData().GetSectionList()
|
||||
out := make([]string, 0, len(all))
|
||||
for _, s := range all {
|
||||
if IsProfileSection(s) {
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mustFindByName finds the RegInfo for the remote name passed in or
|
||||
// exits with a fatal error.
|
||||
func mustFindByName(name string) *fs.RegInfo {
|
||||
@@ -702,7 +716,7 @@ func ShowRedactedConfig() {
|
||||
// EditConfig edits the config file interactively
|
||||
func EditConfig(ctx context.Context) (err error) {
|
||||
for {
|
||||
haveRemotes := len(LoadedData().GetSectionList()) != 0
|
||||
haveRemotes := len(remoteSections()) != 0
|
||||
what := []string{"eEdit existing remote", "nNew remote", "dDelete remote", "rRename remote", "cCopy remote", "sSet configuration password", "qQuit config"}
|
||||
if haveRemotes {
|
||||
fmt.Printf("Current remotes:\n\n")
|
||||
|
||||
@@ -12,6 +12,10 @@ import (
|
||||
"github.com/rclone/rclone/lib/caller"
|
||||
)
|
||||
|
||||
// logger represents the slog logging facility and should be overridden by
|
||||
// the fs/log handling code.
|
||||
var logger *slog.Logger = slog.Default()
|
||||
|
||||
// LogLevel describes rclone's logs. These are a subset of the syslog log levels.
|
||||
type LogLevel = Enum[logLevelChoices]
|
||||
|
||||
@@ -137,7 +141,7 @@ func LogLevelToSlog(level LogLevel) slog.Level {
|
||||
}
|
||||
|
||||
func logSlog(level LogLevel, text string, attrs []any) {
|
||||
slog.Log(context.Background(), LogLevelToSlog(level), text, attrs...)
|
||||
logger.Log(context.Background(), LogLevelToSlog(level), text, attrs...)
|
||||
}
|
||||
|
||||
func logSlogWithObject(level LogLevel, o any, text string, attrs []any) {
|
||||
@@ -337,3 +341,8 @@ func PrettyPrint(in any, label string, level LogLevel) {
|
||||
}
|
||||
LogPrintf(level, label, "\n%s\n", string(inBytes))
|
||||
}
|
||||
|
||||
// SetLogger overrides the slog logger using the specified handler
|
||||
func SetLogger(h slog.Handler) {
|
||||
logger = slog.New(h)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
@@ -201,7 +202,21 @@ func init() {
|
||||
}
|
||||
|
||||
// InitLogging start the logging as per the command line flags
|
||||
//
|
||||
// This is called explicitly from the CLI, the librclone wrapper and
|
||||
// the test framework, but not from package init, so that importing
|
||||
// rclone as a library has no side effects on the process-wide default
|
||||
// slog logger.
|
||||
func InitLogging() {
|
||||
// Redirect the process-wide default logger through rclone's
|
||||
// handler so that log.Print/log.Fatal and slog.Default() (used by
|
||||
// some standard library and third party code) end up in rclone's
|
||||
// log output.
|
||||
slog.SetDefault(slog.New(Handler))
|
||||
|
||||
// Make log.Printf logs at level Notice
|
||||
slog.SetLogLoggerLevel(fs.SlogLevelNotice)
|
||||
|
||||
// Note that ci only has the defaults in at this point
|
||||
// We set real values in logReload
|
||||
ci := fs.GetConfig(context.Background())
|
||||
|
||||
+8
-5
@@ -27,6 +27,12 @@ var Handler = defaultHandler()
|
||||
// This will be adjusted by InitLogging to be the configured levels
|
||||
// but it is important we have a logger running regardless of whether
|
||||
// InitLogging has been called yet or not.
|
||||
//
|
||||
// Note that this only sets rclone's private logger via fs.SetLogger
|
||||
// so that importing this package has no side effects on the
|
||||
// process-wide default slog logger. The CLI and other rclone-as-a-
|
||||
// program entry points pick up the default logger redirection in
|
||||
// InitLogging instead.
|
||||
func defaultHandler() *OutputHandler {
|
||||
// Default options for default handler
|
||||
opts := &slog.HandlerOptions{
|
||||
@@ -36,11 +42,8 @@ func defaultHandler() *OutputHandler {
|
||||
// Create our handler
|
||||
h := NewOutputHandler(os.Stderr, opts, logFormatDate|logFormatTime)
|
||||
|
||||
// Set the slog default handler
|
||||
slog.SetDefault(slog.New(h))
|
||||
|
||||
// Make log.Printf logs at level Notice
|
||||
slog.SetLogLoggerLevel(fs.SlogLevelNotice)
|
||||
// Set rclone's internal logger so rclone logging works
|
||||
fs.SetLogger(h)
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
@@ -198,6 +198,32 @@ func (o *SeekOption) Mandatory() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// ParseHeaders converts the strings passed in via the header flags into HTTPOptions
|
||||
func ParseHeaders(headers []string) ([]*HTTPOption, error) {
|
||||
opts := []*HTTPOption{}
|
||||
for _, header := range headers {
|
||||
parts := strings.SplitN(header, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("failed to parse %q as an HTTP header. Expecting a string like: 'Cache-Control: no-store'", header)
|
||||
}
|
||||
option := &HTTPOption{
|
||||
Key: strings.TrimSpace(parts[0]),
|
||||
Value: strings.TrimSpace(parts[1]),
|
||||
}
|
||||
opts = append(opts, option)
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
// MustParseHeaders converts the strings passed in via the header flags into HTTPOptions or exits.
|
||||
func MustParseHeaders(headers []string) []*HTTPOption {
|
||||
opts, err := ParseHeaders(headers)
|
||||
if err != nil {
|
||||
Fatalf(nil, "%v", err)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// HTTPOption defines a general purpose HTTP option
|
||||
type HTTPOption struct {
|
||||
Key string
|
||||
|
||||
+2
-6
@@ -83,11 +83,6 @@ var OptionsInfo = fs.Options{{
|
||||
Default: fs.Duration(10 * time.Second),
|
||||
Help: "Interval to check for expired async jobs",
|
||||
Groups: "RC",
|
||||
}, {
|
||||
Name: "metrics_addr",
|
||||
Default: []string{},
|
||||
Help: "IPaddress:Port or :Port to bind metrics server to",
|
||||
Groups: "Metrics",
|
||||
}}.
|
||||
AddPrefix(libhttp.ConfigInfo, "rc", "RC").
|
||||
AddPrefix(libhttp.AuthConfigInfo, "rc", "RC").
|
||||
@@ -95,7 +90,8 @@ var OptionsInfo = fs.Options{{
|
||||
AddPrefix(libhttp.ConfigInfo, "metrics", "Metrics").
|
||||
AddPrefix(libhttp.AuthConfigInfo, "metrics", "Metrics").
|
||||
AddPrefix(libhttp.TemplateConfigInfo, "metrics", "Metrics").
|
||||
SetDefault("rc_addr", []string{"localhost:5572"})
|
||||
SetDefault("rc_addr", []string{"localhost:5572"}).
|
||||
SetDefault("metrics_addr", []string{})
|
||||
|
||||
func init() {
|
||||
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "rc", Opt: &Opt, Options: OptionsInfo})
|
||||
|
||||
+20
-7
@@ -392,13 +392,26 @@ func (s *syncCopyMove) pairChecker(in *pipe, out *pipe, fraction int, wg *sync.W
|
||||
}
|
||||
}
|
||||
// Fix case for case insensitive filesystems
|
||||
if s.ci.FixCase && !s.ci.Immutable && src.Remote() != pair.Dst.Remote() {
|
||||
if newDst, err := operations.Move(s.ctx, s.fdst, nil, src.Remote(), pair.Dst); err != nil {
|
||||
fs.Errorf(pair.Dst, "Error while attempting to rename to %s: %v", src.Remote(), err)
|
||||
s.processError(err)
|
||||
} else {
|
||||
fs.Infof(pair.Dst, "Fixed case by renaming to: %s", src.Remote())
|
||||
pair.Dst = newDst
|
||||
if s.ci.FixCase && !s.ci.Immutable && pair.Dst != nil && src.Remote() != pair.Dst.Remote() {
|
||||
// NeedTransfer's equality check may have deleted pair.Dst as a precursor
|
||||
// to re-uploading it (the way modtime updates are done on backends like
|
||||
// Dropbox that can't set modtime in place). If so, there is nothing to
|
||||
// rename - nil out pair.Dst so the upload below recreates the file at
|
||||
// src.Remote() (the correctly-cased name).
|
||||
if needTransfer {
|
||||
if _, statErr := s.fdst.NewObject(s.ctx, pair.Dst.Remote()); errors.Is(statErr, fs.ErrorObjectNotFound) {
|
||||
fs.Debugf(pair.Dst, "Skipping fix-case rename: destination removed for re-upload, will recreate at %s", src.Remote())
|
||||
pair.Dst = nil
|
||||
}
|
||||
}
|
||||
if pair.Dst != nil {
|
||||
if newDst, err := operations.Move(s.ctx, s.fdst, nil, src.Remote(), pair.Dst); err != nil {
|
||||
fs.Errorf(pair.Dst, "Error while attempting to rename to %s: %v", src.Remote(), err)
|
||||
s.processError(err)
|
||||
} else {
|
||||
fs.Infof(pair.Dst, "Fixed case by renaming to: %s", src.Remote())
|
||||
pair.Dst = newDst
|
||||
}
|
||||
}
|
||||
}
|
||||
if needTransfer {
|
||||
|
||||
@@ -432,7 +432,10 @@ func TestTransformFile(t *testing.T) {
|
||||
|
||||
err = transform.SetOptions(ctx, "all,trimprefix=tic", "all,trimprefix=tac")
|
||||
require.NoError(t, err)
|
||||
err = operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
|
||||
// Retry to wait for eventual consistency.
|
||||
err = fstest.Retry(t, "TransformFile", func() error {
|
||||
return operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
|
||||
})
|
||||
require.NoError(t, err)
|
||||
r.CheckLocalListing(t, []fstest.Item{}, []string{})
|
||||
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe", "toe", "toe/toe"})
|
||||
@@ -462,7 +465,10 @@ func TestManualTransformFile(t *testing.T) {
|
||||
|
||||
err = transform.SetOptions(ctx, "all,trimprefix=tic", "all,trimprefix=tac")
|
||||
require.NoError(t, err)
|
||||
err = operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
|
||||
// Retry to wait for eventual consistency.
|
||||
err = fstest.Retry(t, "TransformFile", func() error {
|
||||
return operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
|
||||
})
|
||||
require.NoError(t, err)
|
||||
r.CheckLocalListing(t, []fstest.Item{}, []string{})
|
||||
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe", "toe", "toe/toe"})
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package fs
|
||||
|
||||
// VersionTag of rclone
|
||||
var VersionTag = "v1.74.0"
|
||||
var VersionTag = "v1.75.0"
|
||||
+22
-9
@@ -118,19 +118,32 @@ func newRun() *Run {
|
||||
return r
|
||||
}
|
||||
|
||||
// run f(), retrying it until it returns with no error or the limit
|
||||
// expires and it calls t.Fatalf
|
||||
func retry(t *testing.T, what string, f func() error) {
|
||||
// Retry calls f and retries with exponential backoff until it returns
|
||||
// nil or *ListRetries attempts have been made. It is intended for tests
|
||||
// that need to ride out eventual consistency in the backend (for example
|
||||
// when an operation has just modified an asset and a subsequent lookup
|
||||
// in another API has not caught up yet).
|
||||
//
|
||||
// The final error is returned so the caller can decide how to react.
|
||||
func Retry(t *testing.T, what string, f func() error) error {
|
||||
t.Helper()
|
||||
var err error
|
||||
for try := 1; try <= *ListRetries; try++ {
|
||||
sleep := time.Second
|
||||
retries := *ListRetries
|
||||
for try := 1; try <= retries; try++ {
|
||||
err = f()
|
||||
if err == nil {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
t.Logf("%s failed - try %d/%d: %v", what, try, *ListRetries, err)
|
||||
time.Sleep(time.Second)
|
||||
if try == retries {
|
||||
break
|
||||
}
|
||||
t.Logf("%s failed - try %d/%d: sleeping %v: %v", what, try, retries, sleep, err)
|
||||
time.Sleep(sleep)
|
||||
sleep = (sleep * 3) / 2
|
||||
}
|
||||
t.Logf("%s failed: %v", what, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// newRunIndividual initialise the remote and local for testing and
|
||||
@@ -156,7 +169,7 @@ func newRunIndividual(t *testing.T, individual bool) *Run {
|
||||
for _, entry := range entries {
|
||||
switch x := entry.(type) {
|
||||
case fs.Object:
|
||||
retry(t, fmt.Sprintf("removing file %q", x.Remote()), func() error { return x.Remove(ctx) })
|
||||
_ = Retry(t, fmt.Sprintf("removing file %q", x.Remote()), func() error { return x.Remove(ctx) })
|
||||
case fs.Directory:
|
||||
toDelete = append(toDelete, x.Remote())
|
||||
}
|
||||
@@ -170,7 +183,7 @@ func newRunIndividual(t *testing.T, individual bool) *Run {
|
||||
sort.Strings(toDelete)
|
||||
for i := len(toDelete) - 1; i >= 0; i-- {
|
||||
dir := toDelete[i]
|
||||
retry(t, fmt.Sprintf("removing dir %q", dir), func() error {
|
||||
_ = Retry(t, fmt.Sprintf("removing dir %q", dir), func() error {
|
||||
return r.Fremote.Rmdir(ctx, dir)
|
||||
})
|
||||
}
|
||||
|
||||
+23
-18
@@ -111,6 +111,7 @@ backends:
|
||||
- backend: "cloudinary"
|
||||
remote: "TestCloudinary:"
|
||||
fastlist: false
|
||||
listretries: 5
|
||||
ignore:
|
||||
# fs/operations
|
||||
- TestCheckSum
|
||||
@@ -157,6 +158,16 @@ backends:
|
||||
- backend: "dropbox"
|
||||
remote: "TestDropbox:"
|
||||
fastlist: false
|
||||
ignore:
|
||||
# The bisync normalization test relies on uploading distinct NFC and NFD
|
||||
# versions of the same filename and on having modtime updates that don't
|
||||
# require a delete+re-upload. Dropbox normalizes unicode server-side
|
||||
# (NFD -> NFC) and can't set modtime in place, so the test takes a
|
||||
# different code path that produces a different log without functional
|
||||
# difference - the file state ends up correct either way.
|
||||
- TestBisyncRemoteLocal/normalization
|
||||
- TestBisyncLocalRemote/normalization
|
||||
- TestBisyncRemoteRemote/normalization
|
||||
# - backend: "filefabric"
|
||||
# remote: "TestFileFabric:"
|
||||
# fastlist: false
|
||||
@@ -479,17 +490,17 @@ backends:
|
||||
ignoretests:
|
||||
- cmd/bisync
|
||||
- cmd/gitannex
|
||||
- backend: "webdav"
|
||||
remote: "TestWebdavInfiniteScale:"
|
||||
ignore:
|
||||
- TestIntegration/FsMkdir/FsEncoding/punctuation
|
||||
- TestIntegration/FsMkdir/FsEncoding/invalid_UTF-8
|
||||
env:
|
||||
- RCLONE_NO_CHECK_CERTIFICATE=true
|
||||
fastlist: false
|
||||
ignoretests:
|
||||
- cmd/bisync
|
||||
- cmd/gitannex
|
||||
# - backend: "webdav"
|
||||
# remote: "TestWebdavInfiniteScale:"
|
||||
# ignore:
|
||||
# - TestIntegration/FsMkdir/FsEncoding/punctuation
|
||||
# - TestIntegration/FsMkdir/FsEncoding/invalid_UTF-8
|
||||
# env:
|
||||
# - RCLONE_NO_CHECK_CERTIFICATE=true
|
||||
# fastlist: false
|
||||
# ignoretests:
|
||||
# - cmd/bisync
|
||||
# - cmd/gitannex
|
||||
- backend: "webdav"
|
||||
remote: "TestWebdavRclone:"
|
||||
ignore:
|
||||
@@ -572,13 +583,6 @@ backends:
|
||||
- TestApplyTransforms
|
||||
ignoretests:
|
||||
- cmd/bisync
|
||||
- backend: "seafile"
|
||||
remote: "TestSeafileV6:"
|
||||
fastlist: false
|
||||
ignore:
|
||||
- TestIntegration/FsMkdir/FsPutFiles/FsDirMove
|
||||
ignoretests:
|
||||
- cmd/gitannex
|
||||
- backend: "seafile"
|
||||
remote: "TestSeafile:"
|
||||
fastlist: true
|
||||
@@ -692,3 +696,4 @@ backends:
|
||||
- cmd/bisync
|
||||
fastlist: false
|
||||
extratime: 2.0
|
||||
listretries: 5
|
||||
@@ -71,8 +71,8 @@ require (
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8
|
||||
github.com/quasilyte/go-ruleguard/dsl v0.3.23
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1
|
||||
github.com/rclone/go-proton-api v1.0.1
|
||||
github.com/rclone/Proton-API-Bridge v1.0.3
|
||||
github.com/rclone/go-proton-api v1.0.2
|
||||
github.com/rclone/gofakes3 v0.0.4
|
||||
github.com/rfjakob/eme v1.2.0
|
||||
github.com/rivo/uniseg v0.4.7
|
||||
@@ -94,11 +94,11 @@ require (
|
||||
github.com/zeebo/xxh3 v1.1.0
|
||||
go.etcd.io/bbolt v1.4.3
|
||||
goftp.io/server/v2 v2.0.2
|
||||
golang.org/x/crypto v0.49.0
|
||||
golang.org/x/net v0.52.0
|
||||
golang.org/x/crypto v0.50.0
|
||||
golang.org/x/net v0.53.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sync v0.20.0
|
||||
golang.org/x/sys v0.42.0
|
||||
golang.org/x/sys v0.43.0
|
||||
golang.org/x/text v0.36.0
|
||||
golang.org/x/time v0.15.0
|
||||
google.golang.org/api v0.275.0
|
||||
@@ -284,5 +284,5 @@ require (
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/pquerna/otp v1.5.0
|
||||
golang.org/x/mobile v0.0.0-20260312152759-81488f6aeb60
|
||||
golang.org/x/term v0.41.0
|
||||
golang.org/x/term v0.42.0
|
||||
)
|
||||
@@ -594,10 +594,10 @@ github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SA
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/rasky/go-xdr v0.0.0-20170124162913-1a41d1a06c93 h1:UVArwN/wkKjMVhh2EQGC0tEc1+FqiLlvYXY5mQ2f8Wg=
|
||||
github.com/rasky/go-xdr v0.0.0-20170124162913-1a41d1a06c93/go.mod h1:Nfe4efndBz4TibWycNE+lqyJZiMX4ycx+QKV8Ta0f/o=
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1 h1:iLSWfK4SSKRrM1t8DtvMSTUrVOAnkfJ+zdU9hIwgu4s=
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1/go.mod h1:26RAest751Ofk+F/d8xtl4UyWXrZvMQwn39U8rm/WKM=
|
||||
github.com/rclone/go-proton-api v1.0.1 h1:Nb7E1d0kPpniupBTqvf0JCmAfRdmuQx0IVjfo5T1/jg=
|
||||
github.com/rclone/go-proton-api v1.0.1/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/Proton-API-Bridge v1.0.3 h1:Bs7RC4xCFSN0BPIYVda/BNxp0qo3NV0gB2VZqx2KIew=
|
||||
github.com/rclone/Proton-API-Bridge v1.0.3/go.mod h1:26RAest751Ofk+F/d8xtl4UyWXrZvMQwn39U8rm/WKM=
|
||||
github.com/rclone/go-proton-api v1.0.2 h1:cJtJUab0MGJ3C6q5kiEJs3pbyhSLnOKMyYOQehA0PBc=
|
||||
github.com/rclone/go-proton-api v1.0.2/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/gofakes3 v0.0.4 h1:LswpC49VY/UJ1zucoL5ktnOEX6lq3qK7e1aFIAfqCbk=
|
||||
github.com/rclone/gofakes3 v0.0.4/go.mod h1:j/UoS+2/Mr7xAlfKhyVC58YyFQmh9uoQA5YZQXQUqmg=
|
||||
github.com/relvacode/iso8601 v1.7.0 h1:BXy+V60stMP6cpswc+a93Mq3e65PfXCgDFfhvNNGrdo=
|
||||
@@ -773,8 +773,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -856,8 +856,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -932,8 +932,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -945,8 +945,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
||||
@@ -199,6 +199,18 @@ func MiddlewareCORS(allowOrigin string) Middleware {
|
||||
}
|
||||
}
|
||||
|
||||
// MiddlewareResponseHeaders instantiates middleware that apply custom headers to every response
|
||||
func MiddlewareResponseHeaders(headers []*fs.HTTPOption) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for _, header := range headers {
|
||||
w.Header().Set(header.Key, header.Value)
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// MiddlewareStripPrefix instantiates middleware that removes the BaseURL from the path
|
||||
func MiddlewareStripPrefix(prefix string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
|
||||
@@ -583,3 +583,66 @@ func TestMiddlewareCORSWithAuth(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareResponseHeaders(t *testing.T) {
|
||||
servers := []struct {
|
||||
name string
|
||||
http Config
|
||||
header http.Header
|
||||
}{
|
||||
{
|
||||
name: "SingleHeader",
|
||||
http: Config{
|
||||
ListenAddr: []string{"127.0.0.1:0"},
|
||||
ResponseHeaders: []string{"X-Test-Header: test-value"},
|
||||
},
|
||||
header: http.Header{
|
||||
"X-Test-Header": []string{"test-value"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "MultipleHeaders",
|
||||
http: Config{
|
||||
ListenAddr: []string{"127.0.0.1:0"},
|
||||
ResponseHeaders: []string{"X-Header-One: one", "X-Header-Two: two"},
|
||||
},
|
||||
header: http.Header{
|
||||
"X-Header-One": []string{"one"},
|
||||
"X-Header-Two": []string{"two"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, ss := range servers {
|
||||
t.Run(ss.name, func(t *testing.T) {
|
||||
s, err := NewServer(context.Background(), WithConfig(ss.http))
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, s.Shutdown())
|
||||
}()
|
||||
|
||||
expected := []byte("header-test")
|
||||
s.Router().Mount("/", testEchoHandler(expected))
|
||||
s.Serve()
|
||||
|
||||
url := testGetServerURL(t, s)
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "should return ok")
|
||||
testExpectRespBody(t, resp, expected)
|
||||
|
||||
for key, vals := range ss.header {
|
||||
require.Contains(t, resp.Header, key, "response should contain custom header")
|
||||
require.Equal(t, vals, resp.Header.Values(key), "header value should match")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+17
-1
@@ -53,6 +53,10 @@ for a transfer.
|
||||
` + "`--{{ .Prefix }}max-header-bytes`" + ` controls the maximum number of bytes the server will
|
||||
accept in the HTTP header.
|
||||
|
||||
` + "`--{{ .Prefix }}response-header`" + ` can be used to set an HTTP header for all responses,
|
||||
will overriding existing values. The flag may be repeated to add multiple
|
||||
headers. Use the format ` + "`Header-Name: value`" + `.
|
||||
|
||||
` + "`--{{ .Prefix }}baseurl`" + ` controls the URL prefix that rclone serves from. By default
|
||||
rclone will serve from the root. If you used ` + "`--{{ .Prefix }}baseurl \"/rclone\"`" + ` then
|
||||
rclone would serve from a URL starting with "/rclone/". This is
|
||||
@@ -167,6 +171,10 @@ var ConfigInfo = fs.Options{{
|
||||
Name: "allow_origin",
|
||||
Default: "",
|
||||
Help: "Origin which cross-domain request (CORS) can be executed from",
|
||||
}, {
|
||||
Name: "response_header",
|
||||
Default: []string{},
|
||||
Help: "Set HTTP header for all responses, overriding existing values",
|
||||
}}
|
||||
|
||||
// Config contains options for the http Server
|
||||
@@ -181,8 +189,9 @@ type Config struct {
|
||||
TLSCertBody []byte `config:"-"` // TLS PEM public key certificate body (can also include intermediate/CA certificates), ignores TLSCert
|
||||
TLSKeyBody []byte `config:"-"` // TLS PEM private key body, ignores TLSKey
|
||||
ClientCA string `config:"client_ca"` // Path to TLS PEM CA file with certificate authorities to verify clients with
|
||||
MinTLSVersion string `config:"min_tls_version"` // MinTLSVersion contains the minimum TLS version that is acceptable.
|
||||
MinTLSVersion string `config:"min_tls_version"` // MinTLSVersion contains the minimum TLS version that is acceptable
|
||||
AllowOrigin string `config:"allow_origin"` // AllowOrigin sets the Access-Control-Allow-Origin header
|
||||
ResponseHeaders []string `config:"response_header"` // Set HTTP header for all responses, overriding existing values
|
||||
}
|
||||
|
||||
// AddFlagsPrefix adds flags for the httplib
|
||||
@@ -197,6 +206,7 @@ func (cfg *Config) AddFlagsPrefix(flagSet *pflag.FlagSet, prefix string) {
|
||||
flags.StringVarP(flagSet, &cfg.BaseURL, prefix+"baseurl", "", cfg.BaseURL, "Prefix for URLs - leave blank for root", prefix)
|
||||
flags.StringVarP(flagSet, &cfg.MinTLSVersion, prefix+"min-tls-version", "", cfg.MinTLSVersion, "Minimum TLS version that is acceptable", prefix)
|
||||
flags.StringVarP(flagSet, &cfg.AllowOrigin, prefix+"allow-origin", "", cfg.AllowOrigin, "Origin which cross-domain request (CORS) can be executed from", prefix)
|
||||
flags.StringArrayVarP(flagSet, &cfg.ResponseHeaders, prefix+"response-header", "", cfg.ResponseHeaders, "Set HTTP header for all responses, overriding existing values", prefix)
|
||||
}
|
||||
|
||||
// AddHTTPFlagsPrefix adds flags for the httplib
|
||||
@@ -348,7 +358,13 @@ func NewServer(ctx context.Context, options ...Option) (*Server, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
responseHeaders, err := fs.ParseHeaders(s.cfg.ResponseHeaders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.mux.Use(MiddlewareCORS(s.cfg.AllowOrigin))
|
||||
s.mux.Use(MiddlewareResponseHeaders(responseHeaders))
|
||||
|
||||
s.initAuth()
|
||||
|
||||
|
||||
@@ -624,7 +624,7 @@ func ConfigOAuth(ctx context.Context, name string, m configmap.Mapper, ri *fs.Re
|
||||
// See if already have a token
|
||||
tokenString, ok := m.Get("token")
|
||||
if ok && tokenString != "" {
|
||||
return fs.ConfigConfirm(newState("*oauth-confirm"), true, "config_refresh_token", "Already have a token - refresh?")
|
||||
return fs.ConfigConfirm(newState("*oauth-confirm"), true, "config_refresh_token", "Token already configured - replace it?")
|
||||
}
|
||||
return fs.ConfigGoto(newState("*oauth-confirm"))
|
||||
case "*oauth-confirm":
|
||||
|
||||
Reference in new issue
Block a user