Compare commits

...
117 Commits
Author SHA1 Message Date
Nick Craig-Wood 93e8a976ef Version v1.67.0 2024-06-14 16:04:51 +01:00
nielash 8470bdf810 s3: fix 405 error on HEAD for delete marker with versionId
When getting an object by specifying a versionId in the request, if the
specified version is a delete marker, it returns 405 (Method Not Allowed),
instead of 404 (Not Found) which would be returned without a versionId. See
https://docs.aws.amazon.com/AmazonS3/latest/userguide/DeleteMarker.html

Before this change, we were only looking for 404 (and not 405) to determine
whether the object exists. This meant that in some circumstances (ex. when
Versioning is enabled for the bucket and we have a non-null X-Amz-Version-Id), we
deemed the object to exist when we should not have.

After this change, 405 (Method Not Allowed) is treated the same as 404 (Not
Found) for the purposes of headObject.

See https://forum.rclone.org/t/bisync-rename-failed-method-not-allowed/45723/13
2024-06-13 18:09:29 +01:00
Nick Craig-Wood 1aa3a37a28 gitannex: make tests run more quietly - use go test -v for more info
These tests were generating 1000s of lines of logs and making it
difficult to figure out what was failing in other tests.
2024-06-13 17:33:56 +01:00
albertony ae887ad042 jottacloud: set metadata on server side copy and move - fixes #7900 2024-06-13 16:19:36 +01:00
Nick Craig-Wood d279fea44a qingstor: disable integration tests as test account suspended
QingStor support have disabled the integration test account with this message

尊敬的用户您好:依据监管部门相关内容安全合规要求,QingStor即日起限制对
个人客户提供对象存储服务,您的对象存储服务将被系统置于禁用状态,如需继
续使用QingsStor对象存储服务,您可以通过工单或者拨打400热线申请开通,未
解封期间您的数据将不受影响,感谢您的谅解和支持。

Which google translate renders as

> Dear user: In accordance with the relevant content security
> compliance requirements of the regulatory authorities, QingStor will
> limit the provision of object storage services to individual
> customers from now on. Your object storage service will be disabled
> by the system. If you need to continue to use the QingsStor object
> storage service, you can apply for activation through a work order
> or by calling the 400 hotline. Your data will not be affected during
> the period of unblocking. Thank you for your understanding and
> support.
2024-06-13 12:50:35 +01:00
Nick Craig-Wood 282e34f2d5 operations: add operations.ReadFile to read the contents of a file into memory 2024-06-13 12:48:46 +01:00
Nick Craig-Wood 021f25a748 fs: make ConfigFs take an fs.Info which makes it more useful 2024-06-13 12:48:46 +01:00
Nick Craig-Wood 18e9d039ad touch: fix using -R on certain backends
On backends which return a valid object for "" with NewObject then
touch was going wrong as it thought it was passed an object.

This should not happen normally but s3 can be configured with
--s3-no-head where it is happy to believe that all objects exist.
2024-06-12 17:57:28 +01:00
Nick Craig-Wood cbcfb90d9a serve s3: fix XML of error message
This updates the s3 libary to fix the XML of the error response

Fixes #7749
2024-06-12 17:53:57 +01:00
Nick Craig-Wood caba22a585 fs/logger: make the tests deterministic
Previously this used `rclone test makefiles --seed 0` which sets a
random seed and every now and again we get this error

    Failed to open file "$WORK\\src\\moru": open $WORK\src\moru: is a directory

Because a file with the same name was created as a file in the src and
a dir in the dst.

This fixes it by using determinstic seeds each time.
2024-06-12 16:39:30 +01:00
Nick Craig-Wood 3fef8016b5 zoho: sleep for 60 seconds if rate limit error received 2024-06-12 16:34:30 +01:00
Nick Craig-Wood edf6537c61 zoho: remove simple file names complication which is no longer needed 2024-06-12 16:34:27 +01:00
Nick Craig-Wood 00f0e9df9d zoho: retry reading info if size wasn't returned 2024-06-12 16:34:24 +01:00
Nick Craig-Wood e6ab644350 zoho: fix throttling problem when uploading files
Before this change rclone checked to see if a file existed before
uploading it. It did this to avoid making duplicate files. This
involved listing the destination directory to see if the file existed
which was rate limited by Zoho.

However Zoho can't have duplicate files anyway so this fix just
removes that check and the PutUnchecked method which isn't needed.

See: https://forum.rclone.org/t/second-followup-on-the-older-topic-rclone-invokes-more-number-of-workdrive-s-files-listing-api-calls-which-exceeds-the-throttling-limit/45697
See: https://forum.rclone.org/t/followup-on-the-older-topic-rclone-invokes-more-number-of-workdrive-s-files-listing-api-calls-which-exceeds-the-throttling-limit/44794
2024-06-12 16:34:18 +01:00
Nick Craig-Wood 61c18e3b60 zoho: use cursor listing for improved performance
Cursor listing enables us to list up to 1,000 items per call
(previously it was 10) and uses one less transaction per call.

See: https://forum.rclone.org/t/second-followup-on-the-older-topic-rclone-invokes-more-number-of-workdrive-s-files-listing-api-calls-which-exceeds-the-throttling-limit/45697/4
2024-06-12 16:34:11 +01:00
Nick Craig-Wood d068e0b1a9 operations: fix hashing problem in integration tests
Before this change backends which supported more than one hash (eg
pcloud) or backends which wrapped backends supporting more than one
hash (combine) would fail the TestMultithreadCopy and
TestMultithreadCopyAbort with an error like

    Failed to make new multi hasher: requested set 000001ff contains unknown hash types

This was caused by the tests limiting the globally available hashes to
the first hash supplied by the backend.

This was added in this commit

d5d28a7513 operations: fix overwrite of destination when multi-thread transfer fails

to overcome the tests taking >100s on the local backend because they
made every single hash that the local backend. It brought this time
down to 20s.

This commit fixes the problem and retains the CPU speedup by only
applying the fix from the original commit if the destination backend
is the local backend. This fixes the common case (testing on the local
backend). This does not fix the problem for a backend which wraps the
local backend (eg combine) but this is run only on the integration
test machine and not on all the CI.
2024-06-12 11:11:54 +01:00
Nick Craig-Wood a341065b8d Add Bill Fraser to contributors 2024-06-12 11:11:54 +01:00
Nick Craig-Wood 0c29a1fe31 Add Florian Klink to contributors 2024-06-12 11:11:54 +01:00
Nick Craig-Wood 1a40300b5f Add Michał Dzienisiewicz to contributors 2024-06-12 11:11:54 +01:00
dependabot[bot] 44be27729a build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azidentity
Bumps [github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://github.com/Azure/azure-sdk-for-go) from 1.5.2 to 1.6.0.
- [Release notes](https://github.com/Azure/azure-sdk-for-go/releases)
- [Changelog](https://github.com/Azure/azure-sdk-for-go/blob/main/documentation/release.md)
- [Commits](https://github.com/Azure/azure-sdk-for-go/compare/sdk/internal/v1.5.2...sdk/azcore/v1.6.0)

---
updated-dependencies:
- dependency-name: github.com/Azure/azure-sdk-for-go/sdk/azidentity
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-12 09:33:04 +01:00
wiserain b7624287ac pikpak: implement configurable chunk size for multipart upload
Previously, the fixed 10MB chunk size could lead to exceeding the maximum 
allowed number of parts for very large files. Similar to other backends, options for 
chunk size and upload concurrency are now user-configurable. Additionally, 
the internal library is used to automatically adjust chunk size to prevent exceeding 
upload part limitations.

Fixes #7850
2024-06-12 13:19:25 +09:00
Evan Harris 6db9f7180f docs: added info about --progress terminal width 2024-06-11 21:37:40 +01:00
wiserain b601961e54 pikpak: remove PublicLink from integration tests
This commit removes the test for PublicLink as it is not currently supported in the test environment.

This removes it from the integration tests to avoid meaningless retries.
2024-06-12 04:43:49 +09:00
Nick Craig-Wood 51aca9cf9d onedrive: add --onedrive-hard-delete to permanently delete files
Fixes #7812
2024-06-11 17:48:15 +01:00
Bill Fraser 7c0645dda9 dropbox: add option to override root namespace
This lets you, for example, use shared folders without mounting them
into your home namespace first, as long as you know their namespace ID.

(The --dropbox-shared-folders flag could thus be changed to not need to
mount the shared folder first, but I'm not doing that here as it's a
behavior change, who knows, maybe somebody relies on it.)
2024-06-11 12:49:01 +01:00
Florian Klink aed77a8fb2 tree-wide: replace /bin/bash with /usr/bin/env bash
The latter is more portable, while the former only works on systems
where /bin/bash exists (or is symlinked appropriately).
2024-06-11 12:47:47 +01:00
Michał Dzienisiewicz 4250dd98f3 protondrive: don't auth with an empty access token 2024-06-11 12:46:00 +01:00
nielash c13118246c serve s3: fix in-memory metadata storing wrong modtime
Before this change, serve s3 did not consistently save the correct modtime value
in memory after putting or copying an object, which could sometimes cause an
incorrect modtime to be returned. This change fixes the issue by ensuring that
both "mtime" and "X-Amz-Meta-Mtime" are updated in b.meta when we have fresh data.

The issue was discovered on the TestBisyncRemoteRemote/ext_paths test.
2024-06-11 12:10:43 +01:00
nielash a56cd52025 vfs: fix renaming a directory
Before this change, renaming a directory d failed to rename its key in
d.parent.items, which caused trouble later when doing Dir.Stat on a
subdirectory. This change fixes the issue.
2024-06-11 12:09:19 +01:00
nielash 3ae4534ce6 fstest: make RandomRemoteName shorter
Use 12 random characters instead of 24, to avoid trouble on the bisync tests
2024-06-11 12:02:48 +01:00
nielash 9c287c72d6 googlephotos: remove unnecessary nil check
golangci-lint was complaining about this. `entry` can never be nil because
itemToDirEntry never returns a nil interface value
2024-06-11 11:55:42 +01:00
nielash 862d5d6086 s3, googlecloudstorage, azureblob: fix encoding issue with dir path comparison
`remote` has been converted ToStandardPath a few lines above, so `directory`
needs to be converted the same way in order to be compared properly. This was
spotted on `TestBisyncRemoteRemote/extended_filenames` for
`TestS3,directory_markers:` and `TestGoogleCloudStorage,directory_markers:`
which tripped over a directory name containing a Line Feed symbol.
2024-06-11 11:54:54 +01:00
Nick Craig-Wood 003f4531fe sync: don't test reading metadata if we can't write it 2024-06-11 11:31:35 +01:00
Nick Craig-Wood a52e887ddd linkbox: ignore TestListDirSorted test until encoding is implemented 2024-06-11 11:31:35 +01:00
Nick Craig-Wood b7681e72bf Add Tomasz Melcer to contributors 2024-06-11 11:31:35 +01:00
wiserain ce5024bf33 pikpak: improve upload reliability and resolve potential file conflicts
This attempts to resolve upload conflicts by implementing cancel/cleanup on failed
uploads

* fix panic error on defer cancel upload
* increase pacer min sleep from 10 to 100 ms
* stop using uploadByForm()
* introduce force sleep before and after async tasks
* use pacer's retry scheme instead of manual implementation

Fixes #7787
2024-06-10 18:08:07 +01:00
Tomasz Melcer d2af114139 sftp: --sftp-connections to limit maximum number of connections
Done based on a similar feature in the ftp remote. However, the switch
name is different, as `concurrency` is already taken by a different
feature.
2024-06-09 18:36:30 +01:00
Nick Craig-Wood c8d6b02dd6 ulozto: fix panic in various integration tests
Before this change some of the integration tests were producing this error

    panic: runtime error: invalid memory address or nil pointer dereference

This was caused by an `fs.Object` of which the type (`*Object`) was
not `nil`, but the value within was `nil`. These do not compare as
`nil` leading to the panic.

This is a classic Go gotcha: https://go.dev/doc/faq#nil_error

This was easily fixed by changing the type of one function to return
fs.Object instead of *Object.
2024-06-08 17:44:11 +01:00
Nick Craig-Wood 55cac4c34d swift: fix integration tester with use_segments_container=false 2024-06-08 17:44:11 +01:00
Nick Craig-Wood 7ce60a47e8 drive: fix tests for backend query command
The tests assumed that there would be only one match, but on the
integration test server there are multiple matches due to failed test
runs.
2024-06-08 17:44:11 +01:00
Nick Craig-Wood 27496fb26d mailru: attempt to fix throttling by decreasing min sleep to 100ms
Before this change we waited a minimum of 10ms between API calls for
mailru.

The tests no longer pass at this rate, so this increases the time to
100ms.

See #7768
2024-06-08 17:44:11 +01:00
Nick Craig-Wood 39f8d039fe sync: fix expecting SFTP to have MkdirMetadata method: optional feature not implemented
Before this fix we attempted to copy metadata to SFTP backends despite
them not being capable of it.

This fixes the problem by making the need to copy metadata explicit
rather than implicit in a value being present or not.
2024-06-08 17:44:11 +01:00
Nick Craig-Wood 57f5ad188b operations: fix incorrect modtime on some multipart transfers
In this commit

6a0a54ab97 operations: fix missing metadata for multipart transfers to local disk

We broke the setting of modification times when doing multipart
transfers from a backend which didn't support metadata to a backend
which did support metadata.

This was fixed by setting the "mtime" in the metadata if it was
missing.
2024-06-08 17:44:11 +01:00
Nick Craig-Wood 76798d5bb1 sync: fix tests on backends which can't have empty directories 2024-06-08 17:44:11 +01:00
Nick Craig-Wood 5921bb0efd cache: fix tests when testing for Object.SetMetadata 2024-06-08 17:44:11 +01:00
Nick Craig-Wood ce0d8a70a3 Add Charles Hamilton to contributors 2024-06-08 17:44:11 +01:00
Nick Craig-Wood c23a40cb2a Add Thomas Schneider to contributors 2024-06-08 17:44:11 +01:00
Nick Craig-Wood 86a1951a56 Add Bruno Fernandes to contributors 2024-06-08 17:44:11 +01:00
Charles Hamilton b778ec0142 windows: make rclone work with SeBackupPrivilege and/or SeRestorePrivilege
On Windows, this change includes the `FILE_FLAG_BACKUP_SEMANTICS` in
all calls to `CreateFile`.

Adding this flag allows is useful when rclone is running within a
security context that has `SeBackupPrivilege` and/or `SeRestorePrivilege`
token privileges enabled.

Without this flag, rclone cannot properly leverage special security
groups such as Backup Operators who possess the these privileges.

See: https://forum.rclone.org/t/rclone-sebackupprivilege-file-flag-backup-semantics/45339
See: https://github.com/rclone/rclone/pull/7877.
2024-06-07 13:26:30 +01:00
Dan McArdle dac7f76b14 cmd/gitannex: Update command docs
Mentioned the possibility of skipping the symlink for new versions of
git-annex. (Probably deserves a test once the new git-annex trickles
down to CI platforms.)

I stopped trying to explain each config parameter here. Rather, the doc
now shows the user how to ask git-annex to describe config parameters
with `--whatelse`.
2024-06-06 17:42:27 +01:00
Dan McArdle 446d6b28b8 cmd/gitannex: Support synonyms of config values 2024-06-06 17:42:27 +01:00
Thomas Schneider 7e04ff9528 S3: Ceph Backend use already exist changed to true (now tested) - fixes #7871 2024-06-06 11:27:07 +01:00
Bruno Fernandes 4568feb5f9 s3: Add Magalu S3 Object Storage as provider 2024-06-06 11:25:45 +01:00
Nick Craig-Wood b9a2d3b6b9 config: fix default value for description 2024-06-06 09:25:17 +01:00
Nick Craig-Wood 775e567a7b b2: update URLs to new home 2024-06-06 09:25:17 +01:00
Nick Craig-Wood 59fc7ac193 Add yumeiyin to contributors 2024-06-06 09:25:17 +01:00
albertony fea61cac9e serve dlna: make BrowseMetadata more compliant - fixes #7883 2024-06-02 14:07:45 +02:00
albertony 3f3e4b055e Fix new lint issues reported by golangci-lint v1.59.0
Error return value of `fmt.Fprintf` is not checked (errcheck)
2024-05-31 09:48:32 +02:00
yumeiyin 2257c03391 docs: fix some comments 2024-05-24 21:39:40 +02:00
Nick Craig-Wood 8f1c309c81 build: update all dependencies 2024-05-22 15:50:31 +01:00
Nick Craig-Wood 8e2f596fd0 drive: debug when we are ignoring permissions #7853 2024-05-21 15:32:26 +01:00
Nick Craig-Wood de742ffc67 Add Dominik Joe Pantůček to contributors 2024-05-21 15:32:26 +01:00
Dominik Joe Pantůček 181ed55662 docs: crypt: fix incorrect terminology
This fixes the misuse of the key-derivation term (salt) used in place
of symmetric cipher nonce (IV) in the crypt remote documentation.
2024-05-20 23:21:21 +01:00
Nick Craig-Wood a5700a4a53 operations: rework rcat so that it doesn't call the --metadata-mapper twice
The --metadata-mapper was being called twice for files that rclone
needed to stream to disk,

This happened only for:
- files bigger than --upload-streaming-cutoff
- on backends which didn't support PutStream

This also meant that these were being logged as two transfers which
was a little strange.

This fixes the problem by not using operations.Copy to upload the file
once it has been streamed to disk, instead using the Put method on the
backend.

This should have no effect on reliability of the transfers as we retry
Put if possible.

This also tidies up the Rcat function to make the different ways of
uploading the data clearer and make it easy to see that it gets
verified on all those paths.

See #7848
2024-05-20 18:16:54 +01:00
Nick Craig-Wood faa58315c5 operations: ensure SrcFsType is set correctly when using --metadata-mapper
Before this change on files which have unknown length (like Google
Documents) the SrcFsType would be set to "memoryFs".

This change fixes the problem by getting the Copy function to pass the
src Fs into a variant of Rcat.

Fixes #7848
2024-05-20 18:16:54 +01:00
Nick Craig-Wood 7b89735ae7 onedrive: allow setting permissions to fail if failok flag is set
For example using

    --onedrive-metadata-permissions read,write,failok

Will allow permissions to be read and written but if the writing
fails, then only an ERROR will be written in the log and the transfer
won't fail.
2024-05-17 11:03:46 +01:00
Nick Craig-Wood 91192c2c5e Add Evan McBeth to contributors 2024-05-17 11:03:46 +01:00
Evan McBeth 96e39ea486 docs: improve readability in faq 2024-05-16 15:35:42 +02:00
Nick Craig-Wood 488ed28635 fs: fix panic when using --metadata-mapper on large google doc files
Before this change, attempting to copy a large google doc while using
the metadata mapper caused a panic. Google doc files use Rcat to
download as they have an unknown size, and when the size of the doc
file got above --streaming-upload-cutoff it used a
object.NewStaticObjectInfo with a `nil` Fs to upload the file which
caused the crash in the metadata mapper code.

This change makes sure that the Fs in object.NewStaticObjectInfo is
never nil, and it returns MemoryFs which is consistent with the Rcat
code when the source is sized below the --streaming-upload-cutoff
threshold.

Fixes #7845
2024-05-16 10:05:08 +01:00
Nick Craig-Wood b059c96322 Add JT Olio to contributors 2024-05-16 10:05:08 +01:00
Nick Craig-Wood 6d22168a8c Add overallteach to contributors 2024-05-16 10:05:08 +01:00
JT Olio e34e2df600 go.mod: update storj.io/uplink to latest release
significant performance and stability improvements
2024-05-16 08:43:57 +01:00
overallteach 6607102034 chore: fix function name in comment
Signed-off-by: overallteach <cricis@foxmail.com>
2024-05-15 19:30:17 +01:00
Nick Craig-Wood c6c327e4e7 build: update issue label notification machinery 2024-05-15 15:07:45 +01:00
Nick Craig-Wood 6a0a54ab97 operations: fix missing metadata for multipart transfers to local disk
Before this change multipart downloads to the local disk with
--metadata failed to have their metadata set properly.

This was because the OpenWriterAt interface doesn't receive metadata
when creating the object.

This patch fixes the problem by using the recently introduced
Object.SetMetadata method to set the metadata on the object after the
download has completed (when using --metadata). If the backend we are
copying to is using OpenWriterAt but the Object doesn't support
SetMetadata then it will write an ERROR level log but complete
successfully. This should not happen at the moment as only the local
backend supports metadata and OpenWriterAt but it may in the future.

It also adds a test to check metadata is preserved when doing
multipart transfers.

Fixes #7424
2024-05-14 12:51:03 +01:00
Nick Craig-Wood 629e895da8 local: implement Object.SetMetadata 2024-05-14 12:51:03 +01:00
Nick Craig-Wood cc634213a5 fs: define the optional interface SetMetadata and implement it in wrapping backends
This also implements backend integration tests for the feature
2024-05-14 12:51:03 +01:00
Nick Craig-Wood e9e9feb21e drive: allow setting metadata to fail if failok flag is set
For example using

    --drive-metadata-permissions read,write,failok

Will allow metadata to be read and written but if the writing fails,
then only an ERROR will be written in the log and the transfer won't
fail.
2024-05-13 19:44:03 +01:00
Dan McArdle f26fc8f07c cmd/gitannex: When tags do not match, run e2e tests anyway
Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 96703bb31e build: Inject rclone version tag when testing
This enables gitannex end-to-end tests to run on CI. Otherwise, the
version would not match and tests that check the rclone version would
fail like so:

```
=== RUN   TestEndToEnd
    e2e_test.go:199: Skipping due to rclone version: expected version "v1.67.0-DEV", but got "v1.67.0-beta.7905.220bbe24d.merge"
--- SKIP: TestEndToEnd (0.07s)
```

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 96d3adc771 cmd/gitannex: Remove assumption in e2e test version check 2024-05-13 18:44:31 +01:00
Dan McArdle f82822baca .github/workflows: Install git-annex-remote-rclone on Linux and macOS
Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle af33a4f822 cmd/gitannex: Add TestEndToEndMigration tests
For each layout mode, these tests start with a git-annex-remote-rclone
remote, migrate it to a git-annex-remote-rclone-builtin remote. They
verify that a file copied pre-migration is still present and that `git
annex testremote` passes.

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle a675cc6677 cmd/gitannex: Describe new rclonelayout config in help
Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle ad605ee356 cmd/gitannex: Drop chdir from e2e tests
Now that e2e tests are running in parallel, undoing the chdir to the
temp dir was causing flaky failures on cleanup. We don't need it anyway
because the worrisome subcommands have their working directory
controlled by `runInRepo()`.

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 4ab235c06c cmd/gitannex: Repeat TestEndToEnd for all layout modes
I'm hopeful that running these in parallel will not impact CI runtime
very much, but that likely depends on the number of CPU cores and
whether the tmp filesystem is backed by memory vs a physical disk.

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 9a2b85d71c cmd/gitannex: Refactor e2e tests, add layout compat tests
TestEndToEndRepoLayoutCompat exercises git-annex-remote-rclone-builtin
and git-annex-remote-rclone on the same rclone remote to ensure they are
compatible. It repeats the same test for all known layout modes.

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 29b58dd4c5 cmd/gitannex: Add support for different layouts
This commit adds support for the same repo layouts supported by
git-annex-remote-rclone. This should enable git-annex users with remotes
of type "rclone" to switch to a "rclone-builtin" without needing to
retransfer content.

Issue #7625
2024-05-13 18:44:31 +01:00
Dan McArdle 36ad4eb145 cmd/gitannex: Simplify messageParser's finalParameter() func
Issue #7625
2024-05-13 18:44:31 +01:00
nielash 61ab519791 chunker: fix finalizer already set error
Before this change, cache.PinUntilFinalized was called twice if the root pointed
to a composite multi-chunk file without metadata, resulting in a fatal "finalizer
already set" error. This change fixes the issue.
2024-05-13 18:33:54 +01:00
nielash 678941afc1 mailru: use --tpslimit 10 on bisync tests
see https://github.com/rclone/rclone/issues/7768#issuecomment-2060888980
2024-05-13 18:33:11 +01:00
nielash b153254b3a bisync: ignore "Implicitly create directory" messages on tests 2024-05-13 18:32:55 +01:00
nielash 17cd7a9496 quatrix: fix f.String() not including subpath 2024-05-13 18:32:41 +01:00
Nick Craig-Wood 0735f44f91 operations: fix lsjson --encrypted when using --crypt-XXX parameters
Before this change an `rclone lsjson --encrypted` command where
additional `--crypt-` parameters were supplied on the command line:

    rclone lsjson --crypt-description XXX --encrypted secret:

Produced an error like this:

    Failed to lsjson: ListJSON failed to load config for crypt remote: config name contains invalid characters...

This was due to an incorrect lookup of the crypt config to create the
encrypted mapping.

Fixes #7833
2024-05-13 17:59:58 +01:00
Nick Craig-Wood 04c69959b8 Add Sunny to contributors 2024-05-13 17:59:58 +01:00
Nick Craig-Wood 25cc8c927a Add Michael Terry to contributors 2024-05-13 17:59:58 +01:00
Sunny 6356b51b33 serve http: added content-length header when html directory is served 2024-05-13 17:24:54 +01:00
albertony 1890608f55 docs: minor formatting improvement 2024-05-13 12:50:22 +02:00
Michael Terry cd76fd9219 oauthutil: clear client secret if client ID is set
When an external OAuth flow is being used (i.e. a client ID and an
OAuth token are set in the config), a client secret should not be set.
If one is, the server may reject a token refresh attempt.

But there's no way to clear out a backend's default client secret via
configuration, since empty-string config values are ignored.

So instead, when a client ID is set, we should clear out any default
client secret, since it wouldn't apply anyway.
2024-05-11 16:03:32 +01:00
Nick Craig-Wood 5b8cdaff39 drive: fix description being overwritten on server side moves
Before this the description for files got overwritten on server side
moves.

This change stops rclone setting the description to the leaf name
completely.

See: https://forum.rclone.org/t/file-descriptions-in-google-drive-not-shown-after-dedupe/45510
Fixes: #7770
2024-05-11 15:59:40 +01:00
albertony f2f559230c bump golangci/golangci-lint-action from 4 to 6
Version 5 removed go cache management, and therefore also options skip-pkg-cache and
skip-build-cache, because the cache related to go itself is already handled by
actions/setup-go, and now it only caches golangci-lint analysis. Since we run multiple
golangci-lint-action steps for different goos, we want to cache package and build cache
and golangci-lint results from all of them, and therefore this commit now changes the
approach by disabling all built-in caching and introducing a separate cache step to
handle it properly.
2024-05-11 14:43:29 +02:00
nielash e0b38cc9ac onedrive: add support for group permissions
This change adds support for "group" identities, and SharePoint variants
"siteUser" and "siteGroup". It also adds support for using any identity type
(including "application" and "device") as a recipient source when adding
permissions.
2024-05-10 16:25:08 +01:00
nielash 68dc79eddd onedrive: fix references to deprecated permissions properties
Before this change, metadata permissions used the `grantedTo` and
`grantedToIdentities` properties, which are deprecated on OneDrive Business in
favor of `grantedToV2` and `grantedToIdentitiesV2`. After this change, OneDrive
Business uses the new V2 versions, while OneDrive Personal still uses the
originals, as the V2 versions are not available for OneDrive Personal. (see
https://learn.microsoft.com/en-us/answers/questions/1079737/inconsistency-between-grantedtov2-and-grantedto-re)
2024-05-10 16:25:08 +01:00
nielash 76cea0c704 onedrive: skip writing permissions with 'owner' role
The 'owner' role is an implicit role that can't be removed, so don't try to.
2024-05-10 16:25:08 +01:00
Nick Craig-Wood 41d5d8b88a build: add issue label notification machinery 2024-05-10 16:15:28 +01:00
Nick Craig-Wood aa2746d0de union: fix deleting dirs when all remotes can't have empty dirs 2024-05-10 11:15:12 +01:00
wiserain b2f6aac754 pikpak: improve getFile() usage
Previously, `getFile()` was called indiscriminately during uploads, moves, 
and download link generation. This could lead to users with download limit 
causing subsequent operations like uploads and moves to fail. 
This PR optimizes the use of getFile(), by only calling it 
when it's strictly necessary.
2024-05-08 09:09:56 +09:00
Eric Wolf a0dacf4930 docs: exit code 9 requires --error-on-no-transfer
Updated exit code 9 definition to include that it requires the use of the "--error-on-no-transfer" flag with a link to that section.
2024-05-07 09:18:05 +02:00
IoT Maestro c5ff5afc21 ulozto: Fix handling of root paths with leading / trailing slashes.
This fixes #7796
2024-05-04 20:04:30 +01:00
Nick Craig-Wood bd8523f208 fstest: reduce precision of directory time checks on CI
For unknown reasons the precision of modification times of directories
on the CI is > 15mS compared to files which are 100nS. The tests
work fine when run in Virtualbox though so I conjecture this is
something to do with the file system used there.
2024-05-03 12:29:18 +01:00
nielash 0bfd70c405 sync: remove now superfluous copyEmptyDirectories function 2024-05-03 12:29:18 +01:00
Nick Craig-Woodandnielash 47735d8fe1 sync: fix failed to update directory timestamp or metadata: directory not found
See: https://forum.rclone.org/t/empty-dirs-not-wanted/45059/14
Co-authored-by: nielash <nielronash@gmail.com>
2024-05-03 12:29:18 +01:00
Nick Craig-Woodandnielash 617534112b sync: fix directory modification times not being set
Co-authored-by: nielash <nielronash@gmail.com>
2024-05-03 12:29:18 +01:00
Nick Craig-Woodandnielash 271ec43189 sync: don't need to sync directories if they haven't been modified
Before this change we synced directories regardless if the source
directory existed. It is irrelevant whether the source directory
exists or not, what we need to know is has the directory been
modified.

Co-authored-by: nielash <nielronash@gmail.com>
2024-05-03 12:29:18 +01:00
Nick Craig-Wood 10eb4742dd sync: fix creation of empty directories when --create-empty-src-dirs=false
In v1.66.0 the changes to enable metadata preservation on directories
introduced a regression, namely that empty directories were created
despite the state of the --create-empty-src-dirs flag.

This patch fixes the problem by letting the normal rclone directory
creation create the directories and fixing up their timestamps and
metadata afterwards if --create-empty-src-dirs=false.

Fixes #7689
See: https://forum.rclone.org/t/empty-dirs-not-wanted/45059/
See: https://forum.rclone.org/t/how-to-ignore-empty-directories-when-uploading-from-windows/45057/
2024-05-03 12:29:18 +01:00
Nick Craig-Wood 2a2ec06ec1 sync: fix management of empty directories to make it more accurate
Before this change we used the same datastructure for managing empty
directories for both --create-empty-src-dirs in sync/copy/move and for
the --delete-empty-src-dirs flag in move.

These two uses are subtly incompatible and this change uses a separate
datastructure for both uses. This makes it more accurate and easier to
understand.
2024-05-03 12:29:18 +01:00
Nick Craig-Wood 7237b142fa drive: be more explicit in debug when setting permissions fail 2024-05-02 18:10:16 +01:00
208 changed files with 48953 additions and 37401 deletions

No files matched your search

+26 -8
View File
@@ -124,7 +124,7 @@ jobs:
sudo modprobe fuse
sudo chmod 666 /dev/fuse
sudo chown root:$USER /etc/fuse.conf
sudo apt-get install fuse3 libfuse-dev rpm pkg-config git-annex
sudo apt-get install fuse3 libfuse-dev rpm pkg-config git-annex git-annex-remote-rclone
if: matrix.os == 'ubuntu-latest'
- name: Install Libraries on macOS
@@ -137,7 +137,7 @@ jobs:
brew untap --force homebrew/cask
brew update
brew install --cask macfuse
brew install git-annex
brew install git-annex git-annex-remote-rclone
if: matrix.os == 'macos-latest'
- name: Install Libraries on Windows
@@ -223,24 +223,42 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Get runner parameters
id: get-runner-parameters
shell: bash
run: |
echo "year-week=$(/bin/date -u "+%Y%V")" >> $GITHUB_OUTPUT
echo "runner-os-version=$ImageOS" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@v4
- name: Install Go
id: setup-go
uses: actions/setup-go@v5
with:
go-version: '>=1.22.0-rc.1'
check-latest: true
cache: false
- name: Cache
uses: actions/cache@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.cache/golangci-lint
key: golangci-lint-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: golangci-lint-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-
- name: Code quality test (Linux)
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
with:
version: latest
skip-cache: false # Caching enabled (which is default) on this first lint step only, it handles complete cache of build, go modules and golangci-lint analysis which was necessary to get all lint steps to properly take advantage of it
skip-cache: true
- name: Code quality test (Windows)
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
env:
GOOS: "windows"
with:
@@ -248,7 +266,7 @@ jobs:
skip-cache: true
- name: Code quality test (macOS)
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
env:
GOOS: "darwin"
with:
@@ -256,7 +274,7 @@ jobs:
skip-cache: true
- name: Code quality test (FreeBSD)
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
env:
GOOS: "freebsd"
with:
@@ -264,7 +282,7 @@ jobs:
skip-cache: true
- name: Code quality test (OpenBSD)
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
env:
GOOS: "openbsd"
with:
+15
View File
@@ -0,0 +1,15 @@
name: Notify users based on issue labels
on:
issues:
types: [labeled]
jobs:
notify:
runs-on: ubuntu-latest
steps:
- uses: jenschelkopf/issue-label-notification-action@1.3
with:
token: ${{ secrets.NOTIFY_ACTION_TOKEN }}
recipients: |
Support Contract=@rclone/support
Generated
+11749 -12929
View File
File diff suppressed because it is too large. Load diff
Generated
+1282 -176
View File
File diff suppressed because it is too large. Load diff
Generated
+13207 -10610
View File
File diff suppressed because it is too large. Load diff
+7 -6
View File
@@ -43,6 +43,7 @@ ifdef GOTAGS
BUILDTAGS=-tags "$(GOTAGS)"
LINTTAGS=--build-tags "$(GOTAGS)"
endif
LDFLAGS=--ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)"
.PHONY: rclone test_all vars version
@@ -50,7 +51,7 @@ rclone:
ifeq ($(GO_OS),windows)
go run bin/resource_windows.go -version $(TAG) -syso resource_windows_`go env GOARCH`.syso
endif
go build -v --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS) $(BUILD_ARGS)
go build -v $(LDFLAGS) $(BUILDTAGS) $(BUILD_ARGS)
ifeq ($(GO_OS),windows)
rm resource_windows_`go env GOARCH`.syso
endif
@@ -59,7 +60,7 @@ endif
mv -v `go env GOPATH`/bin/rclone`go env GOEXE`.new `go env GOPATH`/bin/rclone`go env GOEXE`
test_all:
go install --ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)" $(BUILDTAGS) $(BUILD_ARGS) github.com/rclone/rclone/fstest/test_all
go install $(LDFLAGS) $(BUILDTAGS) $(BUILD_ARGS) github.com/rclone/rclone/fstest/test_all
vars:
@echo SHELL="'$(SHELL)'"
@@ -87,13 +88,13 @@ test: rclone test_all
# Quick test
quicktest:
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) ./...
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) ./...
racequicktest:
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) -cpu=2 -race ./...
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -cpu=2 -race ./...
compiletest:
RCLONE_CONFIG="/notfound" go test $(BUILDTAGS) -run XXX ./...
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -run XXX ./...
# Do source code quality checks
check: rclone
@@ -238,7 +239,7 @@ fetch_binaries:
rclone -P sync --exclude "/testbuilds/**" --delete-excluded $(BETA_UPLOAD) build/
serve: website
cd docs && hugo server -v -w --disableFastRender
cd docs && hugo server --logLevel info -w --disableFastRender
tag: retag doc
bin/make_changelog.py $(LAST_TAG) $(VERSION) > docs/content/changelog.md.new
+1
View File
@@ -73,6 +73,7 @@ Rclone *("rsync for cloud storage")* is a command-line program to sync files and
* Liara Object Storage [:page_facing_up:](https://rclone.org/s3/#liara-object-storage)
* Linkbox [:page_facing_up:](https://rclone.org/linkbox)
* Linode Object Storage [:page_facing_up:](https://rclone.org/s3/#linode)
* Magalu Object Storage [:page_facing_up:](https://rclone.org/s3/#magalu)
* Mail.ru Cloud [:page_facing_up:](https://rclone.org/mailru/)
* Memset Memstore [:page_facing_up:](https://rclone.org/swift/)
* Mega [:page_facing_up:](https://rclone.org/mega/)
+38 -9
View File
@@ -37,18 +37,44 @@ This file describes how to make the various kinds of releases
## Update dependencies
Early in the next release cycle update the dependencies
Early in the next release cycle update the dependencies.
* Review any pinned packages in go.mod and remove if possible
* make updatedirect
* make GOTAGS=cmount
* make compiletest
* git commit -a -v
* make update
* make GOTAGS=cmount
* make compiletest
* `make updatedirect`
* `make GOTAGS=cmount`
* `make compiletest`
* Fix anything which doesn't compile at this point and commit changes here
* `git commit -a -v -m "build: update all dependencies"`
If the `make updatedirect` upgrades the version of go in the `go.mod`
then go to manual mode. `go1.20` here is the lowest supported version
in the `go.mod`.
```
go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all > /tmp/potential-upgrades
go get -d $(cat /tmp/potential-upgrades)
go mod tidy -go=1.20 -compat=1.20
```
If the `go mod tidy` fails use the output from it to remove the
package which can't be upgraded from `/tmp/potential-upgrades` when
done
```
git co go.mod go.sum
```
And try again.
Optionally upgrade the direct and indirect dependencies. This is very
likely to fail if the manual method was used abve - in that case
ignore it as it is too time consuming to fix.
* `make update`
* `make GOTAGS=cmount`
* `make compiletest`
* roll back any updates which didn't compile
* git commit -a -v --amend
* `git commit -a -v --amend`
* **NB** watch out for this changing the default go version in `go.mod`
Note that `make update` updates all direct and indirect dependencies
@@ -57,6 +83,9 @@ doing that so it may be necessary to roll back dependencies to the
version specified by `make updatedirect` in order to get rclone to
build.
Once it compiles locally, push it on a test branch and commit fixes
until the tests pass.
## Tidy beta
At some point after the release run
+1 -1
View File
@@ -1088,7 +1088,7 @@ func (f *Fs) list(ctx context.Context, containerName, directory, prefix string,
isDirectory := isDirectoryMarker(*file.Properties.ContentLength, file.Metadata, remote)
if isDirectory {
// Don't insert the root directory
if remote == directory {
if remote == f.opt.Enc.ToStandardPath(directory) {
continue
}
// process directory markers as directories
+3 -3
View File
@@ -102,7 +102,7 @@ below will cause b2 to return specific errors:
* "force_cap_exceeded"
These will be set in the "X-Bz-Test-Mode" header which is documented
in the [b2 integrations checklist](https://www.backblaze.com/b2/docs/integration_checklist.html).`,
in the [b2 integrations checklist](https://www.backblaze.com/docs/cloud-storage-integration-checklist).`,
Default: "",
Hide: fs.OptionHideConfigurator,
Advanced: true,
@@ -244,7 +244,7 @@ See: [rclone backend lifecycle](#lifecycle) for setting lifecycles after bucket
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
Advanced: true,
// See: https://www.backblaze.com/b2/docs/files.html
// See: https://www.backblaze.com/docs/cloud-storage-files
// Encode invalid UTF-8 bytes as json doesn't handle them properly.
// FIXME: allow /, but not leading, trailing or double
Default: (encoder.Display |
@@ -1566,7 +1566,7 @@ func (o *Object) Size() int64 {
//
// Make sure it is lower case.
//
// Remove unverified prefix - see https://www.backblaze.com/b2/docs/uploading.html
// Remove unverified prefix - see https://www.backblaze.com/docs/cloud-storage-upload-files-with-the-native-api
// Some tools (e.g. Cyberduck) use this
func cleanSHA1(sha1 string) string {
const unverified = "unverified:"
+1 -1
View File
@@ -23,7 +23,7 @@ import (
)
// Test b2 string encoding
// https://www.backblaze.com/b2/docs/string_encoding.html
// https://www.backblaze.com/docs/cloud-storage-native-api-string-encoding
var encodeTest = []struct {
fullyEncoded string
+1 -1
View File
@@ -1,6 +1,6 @@
// Upload large files for b2
//
// Docs - https://www.backblaze.com/b2/docs/large_files.html
// Docs - https://www.backblaze.com/docs/cloud-storage-large-files
package b2
+1 -1
View File
@@ -18,7 +18,7 @@ func TestIntegration(t *testing.T) {
RemoteName: "TestCache:",
NilObject: (*cache.Object)(nil),
UnimplementableFsMethods: []string{"PublicLink", "OpenWriterAt", "OpenChunkWriter", "DirSetModTime", "MkdirMetadata"},
UnimplementableObjectMethods: []string{"MimeType", "ID", "GetTier", "SetTier", "Metadata"},
UnimplementableObjectMethods: []string{"MimeType", "ID", "GetTier", "SetTier", "Metadata", "SetMetadata"},
UnimplementableDirectoryMethods: []string{"Metadata", "SetMetadata", "SetModTime"},
SkipInvalidUTF8: true, // invalid UTF-8 confuses the cache
})
+1 -2
View File
@@ -308,7 +308,6 @@ func NewFs(ctx context.Context, name, rpath string, m configmap.Mapper) (fs.Fs,
root: rpath,
opt: *opt,
}
cache.PinUntilFinalized(f.base, f)
f.dirSort = true // processEntries requires that meta Objects prerun data chunks atm.
if err := f.configure(opt.NameFormat, opt.MetaFormat, opt.HashType, opt.Transactions); err != nil {
@@ -326,9 +325,9 @@ func NewFs(ctx context.Context, name, rpath string, m configmap.Mapper) (fs.Fs,
if testErr == fs.ErrorIsFile {
f.base = newBase
err = testErr
cache.PinUntilFinalized(f.base, f)
}
}
cache.PinUntilFinalized(f.base, f)
// Correct root if definitely pointing to a file
if err == fs.ErrorIsFile {
+1
View File
@@ -36,6 +36,7 @@ func TestIntegration(t *testing.T) {
"GetTier",
"SetTier",
"Metadata",
"SetMetadata",
},
UnimplementableFsMethods: []string{
"PublicLink",
+11
View File
@@ -1119,6 +1119,17 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
return do.Metadata(ctx)
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
do, ok := o.Object.(fs.SetMetadataer)
if !ok {
return fs.ErrorNotImplemented
}
return do.SetMetadata(ctx, metadata)
}
// SetTier performs changing storage tier of the Object if
// multiple storage classes supported
func (o *Object) SetTier(tier string) error {
+11
View File
@@ -1286,6 +1286,17 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
return do.Metadata(ctx)
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
do, ok := o.Object.(fs.SetMetadataer)
if !ok {
return fs.ErrorNotImplemented
}
return do.SetMetadata(ctx, metadata)
}
// Hash returns the selected checksum of the file
// If no checksum is available it returns ""
func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) {
+11
View File
@@ -1248,6 +1248,17 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
return do.Metadata(ctx)
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
do, ok := o.Object.(fs.SetMetadataer)
if !ok {
return fs.ErrorNotImplemented
}
return do.SetMetadata(ctx, metadata)
}
// MimeType returns the content type of the Object if
// known, or "" if not
//
+11 -8
View File
@@ -151,6 +151,7 @@ func (rwChoices) Choices() []fs.BitsChoicesInfo {
{Bit: uint64(rwOff), Name: "off"},
{Bit: uint64(rwRead), Name: "read"},
{Bit: uint64(rwWrite), Name: "write"},
{Bit: uint64(rwFailOK), Name: "failok"},
}
}
@@ -160,6 +161,7 @@ type rwChoice = fs.Bits[rwChoices]
const (
rwRead rwChoice = 1 << iota
rwWrite
rwFailOK
rwOff rwChoice = 0
)
@@ -173,6 +175,9 @@ var rwExamples = fs.OptionExamples{{
}, {
Value: rwWrite.String(),
Help: "Write the value only",
}, {
Value: rwFailOK.String(),
Help: "If writing fails log errors only, don't fail the transfer",
}, {
Value: (rwRead | rwWrite).String(),
Help: "Read and Write the value.",
@@ -1747,10 +1752,9 @@ func (f *Fs) createDir(ctx context.Context, pathID, leaf string, metadata fs.Met
leaf = f.opt.Enc.FromStandardName(leaf)
pathID = actualID(pathID)
createInfo := &drive.File{
Name: leaf,
Description: leaf,
MimeType: driveFolderType,
Parents: []string{pathID},
Name: leaf,
MimeType: driveFolderType,
Parents: []string{pathID},
}
var updateMetadata updateMetadataFn
if len(metadata) > 0 {
@@ -2430,7 +2434,6 @@ func (f *Fs) createFileInfo(ctx context.Context, remote string, modTime time.Tim
// Define the metadata for the file we are going to create.
createInfo := &drive.File{
Name: leaf,
Description: leaf,
Parents: []string{directoryID},
ModifiedTime: modTime.Format(timeFormatOut),
}
@@ -2830,7 +2833,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
// FIXME remove this when google fixes the problem!
if isDoc {
// A short sleep is needed here in order to make the
// change effective, without it is is ignored. This is
// change effective, without it is ignored. This is
// probably some eventual consistency nastiness.
sleepTime := 2 * time.Second
fs.Debugf(f, "Sleeping for %v before setting the modtime to work around drive bug - see #4517", sleepTime)
@@ -3773,7 +3776,7 @@ file named "foo ' \.txt":
The result is a JSON array of matches, for example:
[
[
{
"createdTime": "2017-06-29T19:58:28.537Z",
"id": "0AxBe_CDEF4zkGHI4d0FjYko2QkD",
@@ -3789,7 +3792,7 @@ The result is a JSON array of matches, for example:
"size": "311",
"webViewLink": "https://drive.google.com/file/d/0AxBe_CDEF4zkGHI4d0FjYko2QkD/view?usp=drivesdk\u0026resourcekey=0-ABCDEFGHIXJQpIGqBJq3MC"
}
]`,
]`,
}}
// Command the backend to run a named command
+5 -3
View File
@@ -551,9 +551,11 @@ func (f *Fs) InternalTestQuery(t *testing.T) {
results, err := f.query(ctx, fmt.Sprintf("%strashed=false and name='%s'", parent, escapedItem))
require.NoError(t, err)
require.Len(t, results, 1)
assert.Len(t, results[0].Id, 33)
assert.Equal(t, results[0].Name, item)
require.True(t, len(results) > 0)
for _, result := range results {
assert.True(t, len(result.Id) > 0)
assert.Equal(t, result.Name, item)
}
parent = fmt.Sprintf("'%s' in parents and ", results[0].Id)
}
})
+22 -5
View File
@@ -152,7 +152,7 @@ func (f *Fs) setPermissions(ctx context.Context, info *drive.File, permissions [
return f.shouldRetry(ctx, err)
})
if err != nil {
fs.Errorf(f, "Failed to set permission: %v", err)
fs.Errorf(f, "Failed to set permission %s for %q: %v", perm.Role, perm.EmailAddress, err)
errs.Add(err)
}
}
@@ -262,7 +262,7 @@ func (f *Fs) setLabels(ctx context.Context, info *drive.File, labels []*drive.La
return f.shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("failed to set owner: %w", err)
return fmt.Errorf("failed to set labels: %w", err)
}
return nil
}
@@ -372,6 +372,7 @@ func (o *baseObject) parseMetadata(ctx context.Context, info *drive.File) (err e
// shared drives.
if o.fs.isTeamDrive && !info.HasAugmentedPermissions {
// Don't process permissions if there aren't any specifically set
fs.Debugf(o, "Ignoring %d permissions and %d permissionIds as is shared drive with hasAugmentedPermissions false", len(info.Permissions), len(info.PermissionIds))
info.Permissions = nil
info.PermissionIds = nil
}
@@ -553,7 +554,12 @@ func (f *Fs) updateMetadata(ctx context.Context, updateInfo *drive.File, meta fs
}
// Can't set Owner on upload so need to set afterwards
callbackFns = append(callbackFns, func(ctx context.Context, info *drive.File) error {
return f.setOwner(ctx, info, v)
err := f.setOwner(ctx, info, v)
if err != nil && f.opt.MetadataOwner.IsSet(rwFailOK) {
fs.Errorf(f, "Ignoring error as failok is set: %v", err)
return nil
}
return err
})
case "permissions":
if !f.opt.MetadataPermissions.IsSet(rwWrite) {
@@ -566,7 +572,13 @@ func (f *Fs) updateMetadata(ctx context.Context, updateInfo *drive.File, meta fs
}
// Can't set Permissions on upload so need to set afterwards
callbackFns = append(callbackFns, func(ctx context.Context, info *drive.File) error {
return f.setPermissions(ctx, info, perms)
err := f.setPermissions(ctx, info, perms)
if err != nil && f.opt.MetadataPermissions.IsSet(rwFailOK) {
// We've already logged the permissions errors individually here
fs.Debugf(f, "Ignoring error as failok is set: %v", err)
return nil
}
return err
})
case "labels":
if !f.opt.MetadataLabels.IsSet(rwWrite) {
@@ -579,7 +591,12 @@ func (f *Fs) updateMetadata(ctx context.Context, updateInfo *drive.File, meta fs
}
// Can't set Labels on upload so need to set afterwards
callbackFns = append(callbackFns, func(ctx context.Context, info *drive.File) error {
return f.setLabels(ctx, info, labels)
err := f.setLabels(ctx, info, labels)
if err != nil && f.opt.MetadataLabels.IsSet(rwFailOK) {
fs.Errorf(f, "Ignoring error as failok is set: %v", err)
return nil
}
return err
})
case "folder-color-rgb":
updateInfo.FolderColorRgb = v
+15 -3
View File
@@ -216,7 +216,10 @@ are supported.
Note that we don't unmount the shared folder afterwards so the
--dropbox-shared-folders can be omitted after the first use of a particular
shared folder.`,
shared folder.
See also --dropbox-root-namespace for an alternative way to work with shared
folders.`,
Default: false,
Advanced: true,
}, {
@@ -237,6 +240,11 @@ shared folder.`,
encoder.EncodeDel |
encoder.EncodeRightSpace |
encoder.EncodeInvalidUtf8,
}, {
Name: "root_namespace",
Help: "Specify a different Dropbox namespace ID to use as the root for all paths.",
Default: "",
Advanced: true,
}}...), defaultBatcherOptions.FsOptions("For full info see [the main docs](https://rclone.org/dropbox/#batch-mode)\n\n")...),
})
}
@@ -253,6 +261,7 @@ type Options struct {
AsyncBatch bool `config:"async_batch"`
PacerMinSleep fs.Duration `config:"pacer_min_sleep"`
Enc encoder.MultiEncoder `config:"encoding"`
RootNsid string `config:"root_namespace"`
}
// Fs represents a remote dropbox server
@@ -502,8 +511,11 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
f.features.Fill(ctx, f)
// If root starts with / then use the actual root
if strings.HasPrefix(root, "/") {
if f.opt.RootNsid != "" {
f.ns = f.opt.RootNsid
fs.Debugf(f, "Overriding root namespace to %q", f.ns)
} else if strings.HasPrefix(root, "/") {
// If root starts with / then use the actual root
var acc *users.FullAccount
err = f.pacer.Call(func() (bool, error) {
acc, err = f.users.GetCurrentAccount()
@@ -697,7 +697,7 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
// is this a directory marker?
if isDirectory {
// Don't insert the root directory
if remote == directory {
if remote == f.opt.Enc.ToStandardPath(directory) {
continue
}
// process directory markers as directories
+1 -3
View File
@@ -620,9 +620,7 @@ func (f *Fs) listDir(ctx context.Context, prefix string, filter api.SearchFilter
if err != nil {
return err
}
if entry != nil {
entries = append(entries, entry)
}
entries = append(entries, entry)
return nil
})
if err != nil {
+11
View File
@@ -535,6 +535,17 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
return do.Metadata(ctx)
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
do, ok := o.Object.(fs.SetMetadataer)
if !ok {
return fs.ErrorNotImplemented
}
return do.SetMetadata(ctx, metadata)
}
// Check the interfaces are satisfied
var (
_ fs.Fs = (*Fs)(nil)
+64 -20
View File
@@ -1487,16 +1487,38 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, fs.ErrorCantMove
}
err := f.mkParentDir(ctx, remote)
meta, err := fs.GetMetadataOptions(ctx, f, src, fs.MetadataAsOpenOptions(ctx))
if err != nil {
return nil, err
}
if err := f.mkParentDir(ctx, remote); err != nil {
return nil, err
}
info, err := f.copyOrMove(ctx, "cp", srcObj.filePath(), remote)
// if destination was a trashed file then after a successful copy the copied file is still in trash (bug in api?)
if err == nil && bool(info.Deleted) && !f.opt.TrashedOnly && info.State == "COMPLETED" {
fs.Debugf(src, "Server-side copied to trashed destination, restoring")
info, err = f.createOrUpdate(ctx, remote, srcObj.createTime, srcObj.modTime, srcObj.size, srcObj.md5)
if err == nil {
var createTime time.Time
var createTimeMeta bool
var modTime time.Time
var modTimeMeta bool
if meta != nil {
createTime, createTimeMeta = srcObj.parseFsMetadataTime(meta, "btime")
if !createTimeMeta {
createTime = srcObj.createTime
}
modTime, modTimeMeta = srcObj.parseFsMetadataTime(meta, "mtime")
if !modTimeMeta {
modTime = srcObj.modTime
}
}
if bool(info.Deleted) && !f.opt.TrashedOnly && info.State == "COMPLETED" {
// Workaround necessary when destination was a trashed file, to avoid the copied file also being in trash (bug in api?)
fs.Debugf(src, "Server-side copied to trashed destination, restoring")
info, err = f.createOrUpdate(ctx, remote, createTime, modTime, info.Size, info.MD5)
} else if createTimeMeta || modTimeMeta {
info, err = f.createOrUpdate(ctx, remote, createTime, modTime, info.Size, info.MD5)
}
}
if err != nil {
@@ -1523,12 +1545,30 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, fs.ErrorCantMove
}
err := f.mkParentDir(ctx, remote)
meta, err := fs.GetMetadataOptions(ctx, f, src, fs.MetadataAsOpenOptions(ctx))
if err != nil {
return nil, err
}
if err := f.mkParentDir(ctx, remote); err != nil {
return nil, err
}
info, err := f.copyOrMove(ctx, "mv", srcObj.filePath(), remote)
if err != nil && meta != nil {
createTime, createTimeMeta := srcObj.parseFsMetadataTime(meta, "btime")
if !createTimeMeta {
createTime = srcObj.createTime
}
modTime, modTimeMeta := srcObj.parseFsMetadataTime(meta, "mtime")
if !modTimeMeta {
modTime = srcObj.modTime
}
if createTimeMeta || modTimeMeta {
info, err = f.createOrUpdate(ctx, remote, createTime, modTime, info.Size, info.MD5)
}
}
if err != nil {
return nil, fmt.Errorf("couldn't move file: %w", err)
}
@@ -1786,6 +1826,20 @@ func (o *Object) readMetaData(ctx context.Context, force bool) (err error) {
return o.setMetaData(info)
}
// parseFsMetadataTime parses a time string from fs.Metadata with key
func (o *Object) parseFsMetadataTime(m fs.Metadata, key string) (t time.Time, ok bool) {
value, ok := m[key]
if ok {
var err error
t, err = time.Parse(time.RFC3339Nano, value) // metadata stores RFC3339Nano timestamps
if err != nil {
fs.Debugf(o, "failed to parse metadata %s: %q: %v", key, value, err)
ok = false
}
}
return t, ok
}
// ModTime returns the modification time of the object
//
// It attempts to read the objects mtime and if that isn't present the
@@ -1957,21 +2011,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
var createdTime string
var modTime string
if meta != nil {
if v, ok := meta["btime"]; ok {
t, err := time.Parse(time.RFC3339Nano, v) // metadata stores RFC3339Nano timestamps
if err != nil {
fs.Debugf(o, "failed to parse metadata btime: %q: %v", v, err)
} else {
createdTime = api.Rfc3339Time(t).String() // jottacloud api wants RFC3339 timestamps
}
if t, ok := o.parseFsMetadataTime(meta, "btime"); ok {
createdTime = api.Rfc3339Time(t).String() // jottacloud api wants RFC3339 timestamps
}
if v, ok := meta["mtime"]; ok {
t, err := time.Parse(time.RFC3339Nano, v)
if err != nil {
fs.Debugf(o, "failed to parse metadata mtime: %q: %v", v, err)
} else {
modTime = api.Rfc3339Time(t).String()
}
if t, ok := o.parseFsMetadataTime(meta, "mtime"); ok {
modTime = api.Rfc3339Time(t).String()
}
}
if modTime == "" { // prefer mtime in meta as Modified time, fallback to source ModTime
+13
View File
@@ -1555,6 +1555,18 @@ func (o *Object) writeMetadata(metadata fs.Metadata) (err error) {
return err
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
err := o.writeMetadata(metadata)
if err != nil {
return fmt.Errorf("SetMetadata failed on Object: %w", err)
}
// Re-read info now we have finished setting stuff
return o.lstat()
}
func cleanRootPath(s string, noUNC bool, enc encoder.MultiEncoder) string {
if runtime.GOOS != "windows" || !strings.HasPrefix(s, "\\") {
if !filepath.IsAbs(s) {
@@ -1629,6 +1641,7 @@ var (
_ fs.MkdirMetadataer = &Fs{}
_ fs.Object = &Object{}
_ fs.Metadataer = &Object{}
_ fs.SetMetadataer = &Object{}
_ fs.Directory = &Directory{}
_ fs.SetModTimer = &Directory{}
_ fs.SetMetadataer = &Directory{}
+2 -2
View File
@@ -46,8 +46,8 @@ import (
// Global constants
const (
minSleepPacer = 10 * time.Millisecond
maxSleepPacer = 2 * time.Second
minSleepPacer = 100 * time.Millisecond
maxSleepPacer = 5 * time.Second
decayConstPacer = 2 // bigger for slower decay, exponential
metaExpirySec = 20 * 60 // meta server expiration time
serverExpirySec = 3 * 60 // download server expiration time
+37 -8
View File
@@ -42,6 +42,8 @@ var _ error = (*Error)(nil)
type Identity struct {
DisplayName string `json:"displayName,omitempty"`
ID string `json:"id,omitempty"`
Email string `json:"email,omitempty"` // not officially documented, but seems to sometimes exist
LoginName string `json:"loginName,omitempty"` // SharePoint only
}
// IdentitySet is a keyed collection of Identity objects. It is used
@@ -51,6 +53,9 @@ type IdentitySet struct {
User Identity `json:"user,omitempty"`
Application Identity `json:"application,omitempty"`
Device Identity `json:"device,omitempty"`
Group Identity `json:"group,omitempty"`
SiteGroup Identity `json:"siteGroup,omitempty"` // The SharePoint group associated with this action. Optional.
SiteUser Identity `json:"siteUser,omitempty"` // The SharePoint user associated with this action. Optional.
}
// Quota groups storage space quota-related information on OneDrive into a single structure.
@@ -215,14 +220,16 @@ const (
// PermissionsType provides information about a sharing permission granted for a DriveItem resource.
// Sharing permissions have a number of different forms. The Permission resource represents these different forms through facets on the resource.
type PermissionsType struct {
ID string `json:"id"` // The unique identifier of the permission among all permissions on the item. Read-only.
GrantedTo *IdentitySet `json:"grantedTo,omitempty"` // For user type permissions, the details of the users & applications for this permission. Read-only.
GrantedToIdentities []*IdentitySet `json:"grantedToIdentities,omitempty"` // For link type permissions, the details of the users to whom permission was granted. Read-only.
Invitation *SharingInvitationType `json:"invitation,omitempty"` // Details of any associated sharing invitation for this permission. Read-only.
InheritedFrom *ItemReference `json:"inheritedFrom,omitempty"` // Provides a reference to the ancestor of the current permission, if it is inherited from an ancestor. Read-only.
Link *SharingLinkType `json:"link,omitempty"` // Provides the link details of the current permission, if it is a link type permissions. Read-only.
Roles []Role `json:"roles,omitempty"` // The type of permission (read, write, owner, member). Read-only.
ShareID string `json:"shareId,omitempty"` // A unique token that can be used to access this shared item via the shares API. Read-only.
ID string `json:"id"` // The unique identifier of the permission among all permissions on the item. Read-only.
GrantedTo *IdentitySet `json:"grantedTo,omitempty"` // For user type permissions, the details of the users & applications for this permission. Read-only. Deprecated on OneDrive Business only.
GrantedToIdentities []*IdentitySet `json:"grantedToIdentities,omitempty"` // For link type permissions, the details of the users to whom permission was granted. Read-only. Deprecated on OneDrive Business only.
GrantedToV2 *IdentitySet `json:"grantedToV2,omitempty"` // For user type permissions, the details of the users & applications for this permission. Read-only. Not available for OneDrive Personal.
GrantedToIdentitiesV2 []*IdentitySet `json:"grantedToIdentitiesV2,omitempty"` // For link type permissions, the details of the users to whom permission was granted. Read-only. Not available for OneDrive Personal.
Invitation *SharingInvitationType `json:"invitation,omitempty"` // Details of any associated sharing invitation for this permission. Read-only.
InheritedFrom *ItemReference `json:"inheritedFrom,omitempty"` // Provides a reference to the ancestor of the current permission, if it is inherited from an ancestor. Read-only.
Link *SharingLinkType `json:"link,omitempty"` // Provides the link details of the current permission, if it is a link type permissions. Read-only.
Roles []Role `json:"roles,omitempty"` // The type of permission (read, write, owner, member). Read-only.
ShareID string `json:"shareId,omitempty"` // A unique token that can be used to access this shared item via the shares API. Read-only.
}
// Role represents the type of permission (read, write, owner, member)
@@ -592,3 +599,25 @@ type SiteResource struct {
type SiteResponse struct {
Sites []SiteResource `json:"value"`
}
// GetGrantedTo returns the GrantedTo property.
// This is to get around the odd problem of
// GrantedTo being deprecated on OneDrive Business, while
// GrantedToV2 is unavailable on OneDrive Personal.
func (p *PermissionsType) GetGrantedTo(driveType string) *IdentitySet {
if driveType == "personal" {
return p.GrantedTo
}
return p.GrantedToV2
}
// GetGrantedToIdentities returns the GrantedToIdentities property.
// This is to get around the odd problem of
// GrantedToIdentities being deprecated on OneDrive Business, while
// GrantedToIdentitiesV2 is unavailable on OneDrive Personal.
func (p *PermissionsType) GetGrantedToIdentities(driveType string) []*IdentitySet {
if driveType == "personal" {
return p.GrantedToIdentities
}
return p.GrantedToIdentitiesV2
}
+50 -10
View File
@@ -133,6 +133,7 @@ func (rwChoices) Choices() []fs.BitsChoicesInfo {
{Bit: uint64(rwOff), Name: "off"},
{Bit: uint64(rwRead), Name: "read"},
{Bit: uint64(rwWrite), Name: "write"},
{Bit: uint64(rwFailOK), Name: "failok"},
}
}
@@ -142,6 +143,7 @@ type rwChoice = fs.Bits[rwChoices]
const (
rwRead rwChoice = 1 << iota
rwWrite
rwFailOK
rwOff rwChoice = 0
)
@@ -158,6 +160,9 @@ var rwExamples = fs.OptionExamples{{
}, {
Value: (rwRead | rwWrite).String(),
Help: "Read and Write the value.",
}, {
Value: rwFailOK.String(),
Help: "If writing fails log errors only, don't fail the transfer",
}}
// Metadata describes metadata properties shared by both Objects and Directories
@@ -363,6 +368,15 @@ func (m *Metadata) WritePermissions(ctx context.Context) (err error) {
if m.normalizedID == "" {
return errors.New("internal error: normalizedID is missing")
}
if m.fs.opt.MetadataPermissions.IsSet(rwFailOK) {
// If failok is set, allow the permissions setting to fail and only log an ERROR
defer func() {
if err != nil {
fs.Errorf(m.fs, "Ignoring error as failok is set: %v", err)
err = nil
}
}()
}
// compare current to queued and sort into add/update/remove queues
add, update, remove := m.sortPermissions()
@@ -396,7 +410,7 @@ func (m *Metadata) sortPermissions() (add, update, remove []*api.PermissionsType
if n.ID != "" {
// sanity check: ensure there's a matching "old" id with a non-matching role
if !slices.ContainsFunc(old, func(o *api.PermissionsType) bool {
return o.ID == n.ID && slices.Compare(o.Roles, n.Roles) != 0 && len(o.Roles) > 0 && len(n.Roles) > 0
return o.ID == n.ID && slices.Compare(o.Roles, n.Roles) != 0 && len(o.Roles) > 0 && len(n.Roles) > 0 && !slices.Contains(o.Roles, api.OwnerRole)
}) {
fs.Debugf(m.remote, "skipping update for invalid roles: %v (perm ID: %v)", n.Roles, n.ID)
continue
@@ -418,6 +432,10 @@ func (m *Metadata) sortPermissions() (add, update, remove []*api.PermissionsType
}
}
for _, o := range old {
if slices.Contains(o.Roles, api.OwnerRole) {
fs.Debugf(m.remote, "skipping remove permission -- can't remove 'owner' role")
continue
}
newHasOld := slices.ContainsFunc(new, func(n *api.PermissionsType) bool {
if n == nil || n.ID == "" {
return false // can't remove perms without an ID
@@ -471,13 +489,13 @@ func (m *Metadata) processPermissions(ctx context.Context, add, update, remove [
}
// fillRecipients looks for recipients to add from the permission passed in.
// It looks for an email address in identity.User.ID and DisplayName, otherwise it uses the identity.User.ID as r.ObjectID.
// It looks for an email address in identity.User.Email, ID, and DisplayName, otherwise it uses the identity.User.ID as r.ObjectID.
// It considers both "GrantedTo" and "GrantedToIdentities".
func fillRecipients(p *api.PermissionsType) (recipients []api.DriveRecipient) {
func fillRecipients(p *api.PermissionsType, driveType string) (recipients []api.DriveRecipient) {
if p == nil {
return recipients
}
ids := make(map[string]struct{}, len(p.GrantedToIdentities)+1)
ids := make(map[string]struct{}, len(p.GetGrantedToIdentities(driveType))+1)
isUnique := func(s string) bool {
_, ok := ids[s]
return !ok && s != ""
@@ -487,7 +505,10 @@ func fillRecipients(p *api.PermissionsType) (recipients []api.DriveRecipient) {
r := api.DriveRecipient{}
id := ""
if strings.ContainsRune(identity.User.ID, '@') {
if strings.ContainsRune(identity.User.Email, '@') {
id = identity.User.Email
r.Email = id
} else if strings.ContainsRune(identity.User.ID, '@') {
id = identity.User.ID
r.Email = id
} else if strings.ContainsRune(identity.User.DisplayName, '@') {
@@ -503,12 +524,31 @@ func fillRecipients(p *api.PermissionsType) (recipients []api.DriveRecipient) {
ids[id] = struct{}{}
recipients = append(recipients, r)
}
for _, identity := range p.GrantedToIdentities {
addRecipient(identity)
forIdentitySet := func(iSet *api.IdentitySet) {
if iSet == nil {
return
}
iS := *iSet
forIdentity := func(i api.Identity) {
if i != (api.Identity{}) {
iS.User = i
addRecipient(&iS)
}
}
forIdentity(iS.User)
forIdentity(iS.SiteUser)
forIdentity(iS.Group)
forIdentity(iS.SiteGroup)
forIdentity(iS.Application)
forIdentity(iS.Device)
}
if p.GrantedTo != nil && p.GrantedTo.User != (api.Identity{}) {
addRecipient(p.GrantedTo)
for _, identitySet := range p.GetGrantedToIdentities(driveType) {
forIdentitySet(identitySet)
}
forIdentitySet(p.GetGrantedTo(driveType))
return recipients
}
@@ -518,7 +558,7 @@ func (m *Metadata) addPermission(ctx context.Context, p *api.PermissionsType) (n
opts := m.fs.newOptsCall(m.normalizedID, "POST", "/invite")
req := &api.AddPermissionsRequest{
Recipients: fillRecipients(p),
Recipients: fillRecipients(p, m.fs.driveType),
RequireSignIn: m.fs.driveType != driveTypePersonal, // personal and business have conflicting requirements
Roles: p.Roles,
}
+2 -1
View File
@@ -109,7 +109,8 @@ To update an existing permission, include both the Permission ID and the new
`roles` to be assigned. `roles` is the only property that can be changed.
To remove permissions, pass in a blob containing only the permissions you wish
to keep (which can be empty, to remove all.)
to keep (which can be empty, to remove all.) Note that the `owner` role will be
ignored, as it cannot be removed.
Note that both reading and writing permissions requires extra API calls, so if
you don't need to read or write permissions it is recommended to omit
+19 -1
View File
@@ -241,6 +241,18 @@ modification time and removes all but the last version.
this flag there.
`,
Advanced: true,
}, {
Name: "hard_delete",
Help: `Permanently delete files on removal.
Normally files will get sent to the recycle bin on deletion. Setting
this flag causes them to be permanently deleted. Use with care.
OneDrive personal accounts do not support the permanentDelete API,
it only applies to OneDrive for Business and SharePoint document libraries.
`,
Advanced: true,
Default: false,
}, {
Name: "link_scope",
Default: "anonymous",
@@ -695,6 +707,7 @@ type Options struct {
ServerSideAcrossConfigs bool `config:"server_side_across_configs"`
ListChunk int64 `config:"list_chunk"`
NoVersions bool `config:"no_versions"`
HardDelete bool `config:"hard_delete"`
LinkScope string `config:"link_scope"`
LinkType string `config:"link_type"`
LinkPassword string `config:"link_password"`
@@ -1479,7 +1492,12 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
// deleteObject removes an object by ID
func (f *Fs) deleteObject(ctx context.Context, id string) error {
opts := f.newOptsCall(id, "DELETE", "")
var opts rest.Opts
if f.opt.HardDelete {
opts = f.newOptsCall(id, "POST", "/permanentDelete")
} else {
opts = f.newOptsCall(id, "DELETE", "")
}
opts.NoResponse = true
return f.pacer.Call(func() (bool, error) {
+25 -15
View File
@@ -50,7 +50,7 @@ func (f *Fs) TestWritePermissions(t *testing.T, r *fstest.Run) {
file1 := r.WriteFile(randomFilename(), content, t2)
// add a permission with "read" role
permissions := defaultPermissions()
permissions := defaultPermissions(f.driveType)
permissions[0].Roles[0] = api.ReadRole
expectedMeta, actualMeta := f.putWithMeta(ctx, t, &file1, permissions)
f.compareMeta(t, expectedMeta, actualMeta, false)
@@ -59,7 +59,7 @@ func (f *Fs) TestWritePermissions(t *testing.T, r *fstest.Run) {
found, num := false, 0
foundCount := 0
for i, p := range actualP {
for _, identity := range p.GrantedToIdentities {
for _, identity := range p.GetGrantedToIdentities(f.driveType) {
if identity.User.DisplayName == testUserID {
// note: expected will always be element 0 here, but actual may be variable based on org settings
assert.Equal(t, expectedP[0].Roles, p.Roles)
@@ -68,7 +68,7 @@ func (f *Fs) TestWritePermissions(t *testing.T, r *fstest.Run) {
}
}
if f.driveType == driveTypePersonal {
if p.GrantedTo != nil && p.GrantedTo.User != (api.Identity{}) && p.GrantedTo.User.ID == testUserID { // shows up in a different place on biz vs. personal
if p.GetGrantedTo(f.driveType) != nil && p.GetGrantedTo(f.driveType).User != (api.Identity{}) && p.GetGrantedTo(f.driveType).User.ID == testUserID { // shows up in a different place on biz vs. personal
assert.Equal(t, expectedP[0].Roles, p.Roles)
found, num = true, i
foundCount++
@@ -106,7 +106,7 @@ func (f *Fs) TestWritePermissions(t *testing.T, r *fstest.Run) {
found = false
var foundP *api.PermissionsType
for _, p := range actualP {
if p.GrantedTo == nil || p.GrantedTo.User == (api.Identity{}) || p.GrantedTo.User.ID != testUserID {
if p.GetGrantedTo(f.driveType) == nil || p.GetGrantedTo(f.driveType).User == (api.Identity{}) || p.GetGrantedTo(f.driveType).User.ID != testUserID {
continue
}
found = true
@@ -134,7 +134,7 @@ func (f *Fs) TestReadPermissions(t *testing.T, r *fstest.Run) {
// test that what we got before vs. after is the same
_ = f.opt.MetadataPermissions.Set("read")
_, expectedMeta := f.putWithMeta(ctx, t, &file1, []*api.PermissionsType{}) // return var intentionally switched here
permissions := defaultPermissions()
permissions := defaultPermissions(f.driveType)
_, actualMeta := f.putWithMeta(ctx, t, &file1, permissions)
if f.driveType == driveTypePersonal {
perms, ok := actualMeta["permissions"]
@@ -150,7 +150,7 @@ func (f *Fs) TestReadMetadata(t *testing.T, r *fstest.Run) {
ctx, ci := fs.AddConfig(ctx)
ci.Metadata = true
file1 := r.WriteFile(randomFilename(), "hello", t2)
permissions := defaultPermissions()
permissions := defaultPermissions(f.driveType)
_ = f.opt.MetadataPermissions.Set("read,write")
_, actualMeta := f.putWithMeta(ctx, t, &file1, permissions)
@@ -174,7 +174,7 @@ func (f *Fs) TestDirectoryMetadata(t *testing.T, r *fstest.Run) {
ctx, ci := fs.AddConfig(ctx)
ci.Metadata = true
_ = f.opt.MetadataPermissions.Set("read,write")
permissions := defaultPermissions()
permissions := defaultPermissions(f.driveType)
permissions[0].Roles[0] = api.ReadRole
expectedMeta := fs.Metadata{
@@ -288,7 +288,7 @@ func (f *Fs) TestServerSideCopyMove(t *testing.T, r *fstest.Run) {
file1 := r.WriteFile(randomFilename(), content, t2)
// add a permission with "read" role
permissions := defaultPermissions()
permissions := defaultPermissions(f.driveType)
permissions[0].Roles[0] = api.ReadRole
expectedMeta, actualMeta := f.putWithMeta(ctx, t, &file1, permissions)
f.compareMeta(t, expectedMeta, actualMeta, false)
@@ -331,7 +331,10 @@ func (f *Fs) TestMetadataMapper(t *testing.T, r *fstest.Run) {
_ = f.opt.MetadataPermissions.Set("read,write")
file1 := r.WriteFile(randomFilename(), content, t2)
const blob = `{"Metadata":{"permissions":"[{\"grantedToIdentities\":[{\"user\":{\"id\":\"ryan@contoso.com\"}}],\"roles\":[\"read\"]}]"}}`
blob := `{"Metadata":{"permissions":"[{\"grantedToIdentities\":[{\"user\":{\"id\":\"ryan@contoso.com\"}}],\"roles\":[\"read\"]}]"}}`
if f.driveType != driveTypePersonal {
blob = `{"Metadata":{"permissions":"[{\"grantedToIdentitiesV2\":[{\"user\":{\"id\":\"ryan@contoso.com\"}}],\"roles\":[\"read\"]}]"}}`
}
// Copy
ci.MetadataMapper = []string{"echo", blob}
@@ -347,7 +350,7 @@ func (f *Fs) TestMetadataMapper(t *testing.T, r *fstest.Run) {
found := false
foundCount := 0
for _, p := range actualP {
for _, identity := range p.GrantedToIdentities {
for _, identity := range p.GetGrantedToIdentities(f.driveType) {
if identity.User.DisplayName == testUserID {
assert.Equal(t, []api.Role{api.ReadRole}, p.Roles)
found = true
@@ -355,7 +358,7 @@ func (f *Fs) TestMetadataMapper(t *testing.T, r *fstest.Run) {
}
}
if f.driveType == driveTypePersonal {
if p.GrantedTo != nil && p.GrantedTo.User != (api.Identity{}) && p.GrantedTo.User.ID == testUserID { // shows up in a different place on biz vs. personal
if p.GetGrantedTo(f.driveType) != nil && p.GetGrantedTo(f.driveType).User != (api.Identity{}) && p.GetGrantedTo(f.driveType).User.ID == testUserID { // shows up in a different place on biz vs. personal
assert.Equal(t, []api.Role{api.ReadRole}, p.Roles)
found = true
foundCount++
@@ -449,11 +452,18 @@ func indent(t *testing.T, s string) string {
return marshalPerms(t, p)
}
func defaultPermissions() []*api.PermissionsType {
func defaultPermissions(driveType string) []*api.PermissionsType {
if driveType == driveTypePersonal {
return []*api.PermissionsType{{
GrantedTo: &api.IdentitySet{User: api.Identity{}},
GrantedToIdentities: []*api.IdentitySet{{User: api.Identity{ID: testUserID}}},
Roles: []api.Role{api.WriteRole},
}}
}
return []*api.PermissionsType{{
GrantedTo: &api.IdentitySet{User: api.Identity{}},
GrantedToIdentities: []*api.IdentitySet{{User: api.Identity{ID: testUserID}}},
Roles: []api.Role{api.WriteRole},
GrantedToV2: &api.IdentitySet{User: api.Identity{}},
GrantedToIdentitiesV2: []*api.IdentitySet{{User: api.Identity{ID: testUserID}}},
Roles: []api.Role{api.WriteRole},
}}
}
+12 -4
View File
@@ -53,7 +53,7 @@ const (
PhaseTypePending = "PHASE_TYPE_PENDING"
UploadTypeForm = "UPLOAD_TYPE_FORM"
UploadTypeResumable = "UPLOAD_TYPE_RESUMABLE"
ListLimit = 100
ListLimit = 500
)
// ------------------------------------------------------------
@@ -156,6 +156,7 @@ type FileList struct {
NextPageToken string `json:"next_page_token"`
Version string `json:"version,omitempty"`
VersionOutdated bool `json:"version_outdated,omitempty"`
SyncTime Time `json:"sync_time"`
}
// File is a basic element representing a single file object
@@ -165,14 +166,14 @@ type FileList struct {
// 2) the other from File.Medias[].Link.URL.
// Empirically, 2) is less restrictive to multiple concurrent range-requests
// for a single file, i.e. supports for higher `--multi-thread-streams=N`.
// However, it is not generally applicable as it is only for meadia.
// However, it is not generally applicable as it is only for media.
type File struct {
Apps []*FileApp `json:"apps,omitempty"`
Audit *FileAudit `json:"audit,omitempty"`
Collection string `json:"collection,omitempty"` // TODO
CreatedTime Time `json:"created_time,omitempty"`
DeleteTime Time `json:"delete_time,omitempty"`
FileCategory string `json:"file_category,omitempty"`
FileCategory string `json:"file_category,omitempty"` // "AUDIO", "VIDEO"
FileExtension string `json:"file_extension,omitempty"`
FolderType string `json:"folder_type,omitempty"`
Hash string `json:"hash,omitempty"` // sha1 but NOT a valid file hash. looks like a torrent hash
@@ -191,11 +192,14 @@ type File struct {
ParentID string `json:"parent_id,omitempty"`
Phase string `json:"phase,omitempty"`
Revision int `json:"revision,omitempty,string"`
ReferenceEvents []interface{} `json:"reference_events"`
ReferenceResource interface{} `json:"reference_resource"`
Size int64 `json:"size,omitempty,string"`
SortName string `json:"sort_name,omitempty"`
Space string `json:"space,omitempty"`
SpellName []interface{} `json:"spell_name,omitempty"` // TODO maybe list of something?
Starred bool `json:"starred,omitempty"`
Tags []interface{} `json:"tags"`
ThumbnailLink string `json:"thumbnail_link,omitempty"`
Trashed bool `json:"trashed,omitempty"`
UserID string `json:"user_id,omitempty"`
@@ -241,15 +245,18 @@ type Media struct {
IsOrigin bool `json:"is_origin,omitempty"`
ResolutionName string `json:"resolution_name,omitempty"`
IsVisible bool `json:"is_visible,omitempty"`
Category string `json:"category,omitempty"`
Category string `json:"category,omitempty"` // "category_origin"
Audio interface{} `json:"audio"` // TODO: undiscovered yet
}
// FileParams includes parameters for instant open
type FileParams struct {
DeviceID string `json:"device_id,omitempty"`
Duration int64 `json:"duration,omitempty,string"` // in seconds
Height int `json:"height,omitempty,string"`
Platform string `json:"platform,omitempty"` // "Upload"
PlatformIcon string `json:"platform_icon,omitempty"`
TaskID string `json:"task_id"`
URL string `json:"url,omitempty"`
Width int `json:"width,omitempty,string"`
}
@@ -395,6 +402,7 @@ type Quota struct {
UsageInTrash int64 `json:"usage_in_trash,omitempty,string"` // bytes in trash but this seems not working
PlayTimesLimit string `json:"play_times_limit,omitempty"` // maybe in seconds
PlayTimesUsage string `json:"play_times_usage,omitempty"` // maybe in seconds
IsUnlimited bool `json:"is_unlimited,omitempty"`
}
// Share is a response to RequestShare
+43 -3
View File
@@ -9,7 +9,9 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"github.com/rclone/rclone/backend/pikpak/api"
"github.com/rclone/rclone/lib/rest"
@@ -141,9 +143,8 @@ func (f *Fs) getFile(ctx context.Context, ID string) (info *api.File, err error)
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.rst.CallJSON(ctx, &opts, nil, &info)
if err == nil && info.Phase != api.PhaseTypeComplete {
// could be pending right after file is created/uploaded.
return true, errors.New("not PHASE_TYPE_COMPLETE")
if err == nil && !info.Links.ApplicationOctetStream.Valid() {
return true, errors.New("no link")
}
return f.shouldRetry(ctx, resp, err)
})
@@ -167,6 +168,45 @@ func (f *Fs) patchFile(ctx context.Context, ID string, req *api.File) (info *api
return
}
// getTask gets api.Task from API for the ID passed
func (f *Fs) getTask(ctx context.Context, ID string, checkPhase bool) (info *api.Task, err error) {
opts := rest.Opts{
Method: "GET",
Path: "/drive/v1/tasks/" + ID,
}
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.rst.CallJSON(ctx, &opts, nil, &info)
if checkPhase {
if err == nil && info.Phase != api.PhaseTypeComplete {
// could be pending right after file is created/uploaded.
return true, errors.New(info.Phase)
}
}
return f.shouldRetry(ctx, resp, err)
})
return
}
// deleteTask remove a task having the specified ID
func (f *Fs) deleteTask(ctx context.Context, ID string, deleteFiles bool) (err error) {
params := url.Values{}
params.Set("delete_files", strconv.FormatBool(deleteFiles))
params.Set("task_ids", ID)
opts := rest.Opts{
Method: "DELETE",
Path: "/drive/v1/tasks",
Parameters: params,
NoResponse: true,
}
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
resp, err = f.rst.CallJSON(ctx, &opts, nil, nil)
return f.shouldRetry(ctx, resp, err)
})
return
}
// getAbout gets drive#quota information from server
func (f *Fs) getAbout(ctx context.Context) (info *api.About, err error) {
opts := rest.Opts{
+103 -49
View File
@@ -18,7 +18,6 @@ package pikpak
// ------------------------------------------------------------
// * List() with options starred-only
// * uploadByResumable() with configurable chunk-size
// * user-configurable list chunk
// * backend command: untrash, iscached
// * api(event,task)
@@ -47,12 +46,14 @@ import (
"github.com/rclone/rclone/backend/pikpak/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/chunksize"
"github.com/rclone/rclone/fs/config"
"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/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/atexit"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/oauthutil"
@@ -66,10 +67,13 @@ import (
const (
rcloneClientID = "YNxT9w7GMdWvEOKa"
rcloneEncryptedClientSecret = "aqrmB6M1YJ1DWCBxVxFSjFo7wzWEky494YMmkqgAl1do1WKOe2E"
minSleep = 10 * time.Millisecond
minSleep = 100 * time.Millisecond
maxSleep = 2 * time.Second
waitTime = 500 * time.Millisecond
decayConstant = 2 // bigger for slower decay, exponential
rootURL = "https://api-drive.mypikpak.com"
minChunkSize = fs.SizeSuffix(s3manager.MinUploadPartSize)
defaultUploadConcurrency = s3manager.DefaultUploadConcurrency
)
// Globals
@@ -191,6 +195,42 @@ Fill in for rclone to use a non root folder as its starting point.
Help: "Files bigger than this will be cached on disk to calculate hash if required.",
Default: fs.SizeSuffix(10 * 1024 * 1024),
Advanced: true,
}, {
Name: "chunk_size",
Help: `Chunk size for multipart uploads.
Large files will be uploaded in chunks of this size.
Note that this is stored in memory and there may be up to
"--transfers" * "--pikpak-upload-concurrency" chunks stored at once
in memory.
If you are transferring large files over high-speed links and you have
enough memory, then increasing this will speed up the transfers.
Rclone will automatically increase the chunk size when uploading a
large file of known size to stay below the 10,000 chunks limit.
Increasing the chunk size decreases the accuracy of the progress
statistics displayed with "-P" flag.`,
Default: minChunkSize,
Advanced: true,
}, {
Name: "upload_concurrency",
Help: `Concurrency for multipart uploads.
This is the number of chunks of the same file that are uploaded
concurrently for multipart uploads.
Note that chunks are stored in memory and there may be up to
"--transfers" * "--pikpak-upload-concurrency" chunks stored at once
in memory.
If you are uploading small numbers of large files over high-speed links
and these uploads do not fully utilize your bandwidth, then increasing
this may help to speed up the transfers.`,
Default: defaultUploadConcurrency,
Advanced: true,
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
@@ -221,6 +261,8 @@ type Options struct {
UseTrash bool `config:"use_trash"`
TrashedOnly bool `config:"trashed_only"`
HashMemoryThreshold fs.SizeSuffix `config:"hash_memory_limit"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
UploadConcurrency int `config:"upload_concurrency"`
Enc encoder.MultiEncoder `config:"encoding"`
}
@@ -430,6 +472,9 @@ func newFs(ctx context.Context, name, path string, m configmap.Mapper) (*Fs, err
if err := configstruct.Set(m, opt); err != nil {
return nil, err
}
if opt.ChunkSize < minChunkSize {
return nil, fmt.Errorf("chunk size must be at least %s", minChunkSize)
}
root := parsePath(path)
@@ -1016,21 +1061,24 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
dstObj.id = srcObj.id
var info *api.File
if srcLeaf != dstLeaf {
// Rename
info, err = f.renameObject(ctx, srcObj.id, dstLeaf)
info, err := f.renameObject(ctx, srcObj.id, dstLeaf)
if err != nil {
return nil, fmt.Errorf("move: couldn't rename moved file: %w", err)
}
err = dstObj.setMetaData(info)
if err != nil {
return nil, err
}
} else {
// Update info
info, err = f.getFile(ctx, dstObj.id)
err = dstObj.readMetaData(ctx)
if err != nil {
return nil, fmt.Errorf("move: couldn't update moved file: %w", err)
return nil, fmt.Errorf("move: couldn't locate moved file: %w", err)
}
}
return dstObj, dstObj.setMetaData(info)
return dstObj, nil
}
// copy objects
@@ -1143,7 +1191,7 @@ func (f *Fs) uploadByForm(ctx context.Context, in io.Reader, name string, size i
return
}
func (f *Fs) uploadByResumable(ctx context.Context, in io.Reader, resumable *api.Resumable, options ...fs.OpenOption) (err error) {
func (f *Fs) uploadByResumable(ctx context.Context, in io.Reader, name string, size int64, resumable *api.Resumable) (err error) {
p := resumable.Params
endpoint := strings.Join(strings.Split(p.Endpoint, ".")[1:], ".") // "mypikpak.com"
@@ -1156,28 +1204,31 @@ func (f *Fs) uploadByResumable(ctx context.Context, in io.Reader, resumable *api
if err != nil {
return
}
partSize := chunksize.Calculator(name, size, s3manager.MaxUploadParts, f.opt.ChunkSize)
uploader := s3manager.NewUploader(sess)
// Create an uploader with the session and custom options
uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) {
u.PartSize = int64(partSize)
u.Concurrency = f.opt.UploadConcurrency
})
// Upload input parameters
uParams := &s3manager.UploadInput{
Bucket: &p.Bucket,
Key: &p.Key,
Body: in,
}
// Perform upload with options different than the those in the Uploader.
_, err = uploader.UploadWithContext(ctx, uParams, func(u *s3manager.Uploader) {
// TODO can be user-configurable
u.PartSize = 10 * 1024 * 1024 // 10MB part size
})
// Perform an upload
_, err = uploader.UploadWithContext(ctx, uParams)
return
}
func (f *Fs) upload(ctx context.Context, in io.Reader, leaf, dirID, sha1Str string, size int64, options ...fs.OpenOption) (*api.File, error) {
func (f *Fs) upload(ctx context.Context, in io.Reader, leaf, dirID, sha1Str string, size int64, options ...fs.OpenOption) (info *api.File, err error) {
// determine upload type
uploadType := api.UploadTypeResumable
if size >= 0 && size < int64(5*fs.Mebi) {
uploadType = api.UploadTypeForm
}
// if size >= 0 && size < int64(5*fs.Mebi) {
// uploadType = api.UploadTypeForm
// }
// stop using uploadByForm() cause it is not as reliable as uploadByResumable() for a large number of small files
// request upload ticket to API
req := api.RequestNewFile{
@@ -1192,32 +1243,46 @@ func (f *Fs) upload(ctx context.Context, in io.Reader, leaf, dirID, sha1Str stri
if uploadType == api.UploadTypeResumable {
req.Resumable = map[string]string{"provider": "PROVIDER_ALIYUN"}
}
newfile, err := f.requestNewFile(ctx, &req)
new, err := f.requestNewFile(ctx, &req)
if err != nil {
return nil, fmt.Errorf("failed to create a new file: %w", err)
}
if newfile.File == nil {
return nil, fmt.Errorf("invalid response: %+v", newfile)
} else if newfile.File.Phase == api.PhaseTypeComplete {
if new.File == nil {
return nil, fmt.Errorf("invalid response: %+v", new)
} else if new.File.Phase == api.PhaseTypeComplete {
// early return; in case of zero-byte objects
return newfile.File, nil
return new.File, nil
}
if uploadType == api.UploadTypeForm && newfile.Form != nil {
err = f.uploadByForm(ctx, in, req.Name, size, newfile.Form, options...)
} else if uploadType == api.UploadTypeResumable && newfile.Resumable != nil {
err = f.uploadByResumable(ctx, in, newfile.Resumable, options...)
defer atexit.OnError(&err, func() {
fs.Debugf(leaf, "canceling upload: %v", err)
if cancelErr := f.deleteObjects(ctx, []string{new.File.ID}, false); cancelErr != nil {
fs.Logf(leaf, "failed to cancel upload: %v", cancelErr)
}
if cancelErr := f.deleteTask(ctx, new.Task.ID, false); cancelErr != nil {
fs.Logf(leaf, "failed to cancel upload: %v", cancelErr)
}
fs.Debugf(leaf, "waiting %v for the cancellation to be effective", waitTime)
time.Sleep(waitTime)
})()
if uploadType == api.UploadTypeForm && new.Form != nil {
err = f.uploadByForm(ctx, in, req.Name, size, new.Form, options...)
} else if uploadType == api.UploadTypeResumable && new.Resumable != nil {
err = f.uploadByResumable(ctx, in, leaf, size, new.Resumable)
} else {
return nil, fmt.Errorf("unable to proceed upload: %+v", newfile)
err = fmt.Errorf("no method available for uploading: %+v", new)
}
if err != nil {
return nil, fmt.Errorf("failed to upload: %w", err)
}
// refresh uploaded file info
// Compared to `newfile.File` this upgrades several fields...
// audit, links, modified_time, phase, revision, and web_content_link
return f.getFile(ctx, newfile.File.ID)
fs.Debugf(leaf, "sleeping for %v before checking upload status", waitTime)
time.Sleep(waitTime)
if _, err = f.getTask(ctx, new.Task.ID, true); err != nil {
return nil, fmt.Errorf("unable to complete the upload: %w", err)
}
return new.File, nil
}
// Put the object
@@ -1470,22 +1535,11 @@ func (o *Object) setMetaDataWithLink(ctx context.Context) error {
return nil
}
// fetch download link with retry scheme
// 1 initial attempt and 2 retries are reasonable based on empirical analysis
retries := 2
for i := 1; i <= retries+1; i++ {
info, err := o.fs.getFile(ctx, o.id)
if err != nil {
return fmt.Errorf("can't fetch download link: %w", err)
}
if err = o.setMetaData(info); err == nil && o.link.Valid() {
return nil
}
if i <= retries {
time.Sleep(time.Duration(200*i) * time.Millisecond)
}
info, err := o.fs.getFile(ctx, o.id)
if err != nil {
return err
}
return errors.New("can't download - no link to download")
return o.setMetaData(info)
}
// readMetaData gets the metadata if it hasn't already been fetched
@@ -1619,14 +1673,14 @@ func (o *Object) open(ctx context.Context, url string, options ...fs.OpenOption)
// Open an object for read
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.ReadCloser, err error) {
if o.id == "" {
return nil, errors.New("can't download - no id")
return nil, errors.New("can't download: no id")
}
if o.size == 0 {
// zero-byte objects may have no download link
return io.NopCloser(bytes.NewBuffer([]byte(nil))), nil
}
if err = o.setMetaDataWithLink(ctx); err != nil {
return nil, err
return nil, fmt.Errorf("can't download: %w", err)
}
return o.open(ctx, o.link.URL, options...)
}
+3
View File
@@ -285,6 +285,9 @@ func getConfigMap(m configmap.Mapper) (uid, accessToken, refreshToken, saltedKey
}
_saltedKeyPass = saltedKeyPass
// empty strings are considered "ok" by m.Get, which is not true business-wise
ok = accessToken != "" && uid != "" && refreshToken != "" && saltedKeyPass != ""
return
}
+1 -1
View File
@@ -349,7 +349,7 @@ func (f *Fs) Root() string {
// String converts this Fs to a string
func (f *Fs) String() string {
return f.description
return f.description + " at " + f.root
}
// Precision return the precision of this Fs
+45 -6
View File
@@ -129,6 +129,9 @@ var providerOption = fs.Option{
}, {
Value: "Linode",
Help: "Linode Object Storage",
}, {
Value: "Magalu",
Help: "Magalu Object Storage",
}, {
Value: "Minio",
Help: "Minio Object Storage",
@@ -530,7 +533,7 @@ func init() {
}, {
Name: "region",
Help: "Region to connect to.\n\nLeave blank if you are using an S3 clone and you don't have a region.",
Provider: "!AWS,Alibaba,ArvanCloud,ChinaMobile,Cloudflare,IONOS,Petabox,Liara,Linode,Qiniu,RackCorp,Scaleway,Storj,Synology,TencentCOS,HuaweiOBS,IDrive",
Provider: "!AWS,Alibaba,ArvanCloud,ChinaMobile,Cloudflare,IONOS,Petabox,Liara,Linode,Magalu,Qiniu,RackCorp,Scaleway,Storj,Synology,TencentCOS,HuaweiOBS,IDrive",
Examples: []fs.OptionExample{{
Value: "",
Help: "Use this if unsure.\nWill use v4 signatures and an empty region.",
@@ -933,6 +936,19 @@ func init() {
Value: "us-iad-1.linodeobjects.com",
Help: "Washington, DC, (USA), us-iad-1",
}},
}, {
// Magalu endpoints: https://docs.magalu.cloud/docs/object-storage/how-to/copy-url
Name: "endpoint",
Help: "Endpoint for Magalu Object Storage API.",
Provider: "Magalu",
Examples: []fs.OptionExample{{
Value: "br-se1.magaluobjects.com",
Help: "São Paulo, SP (BR), br-se1",
}, {
Value: "br-ne1.magaluobjects.com",
Help: "Fortaleza, CE (BR), br-ne1",
},
},
}, {
// oss endpoints: https://help.aliyun.com/document_detail/31837.html
Name: "endpoint",
@@ -1285,7 +1301,7 @@ func init() {
}, {
Name: "endpoint",
Help: "Endpoint for S3 API.\n\nRequired when using an S3 clone.",
Provider: "!AWS,ArvanCloud,IBMCOS,IDrive,IONOS,TencentCOS,HuaweiOBS,Alibaba,ChinaMobile,GCS,Liara,Linode,Scaleway,StackPath,Storj,Synology,RackCorp,Qiniu,Petabox",
Provider: "!AWS,ArvanCloud,IBMCOS,IDrive,IONOS,TencentCOS,HuaweiOBS,Alibaba,ChinaMobile,GCS,Liara,Linode,MagaluCloud,Scaleway,StackPath,Storj,Synology,RackCorp,Qiniu,Petabox",
Examples: []fs.OptionExample{{
Value: "objects-us-east-1.dream.io",
Help: "Dream Objects endpoint",
@@ -1394,6 +1410,14 @@ func init() {
Value: "s3.ir-tbz-sh1.arvanstorage.ir",
Help: "ArvanCloud Tabriz Iran (Shahriar) endpoint",
Provider: "ArvanCloud",
}, {
Value: "br-se1.magaluobjects.com",
Help: "Magalu BR Southeast 1 endpoint",
Provider: "Magalu",
}, {
Value: "br-se1.magaluobjects.com",
Help: "Magalu BR Northest 1 endpoint",
Provider: "Magalu",
}},
}, {
Name: "location_constraint",
@@ -1776,7 +1800,7 @@ func init() {
}, {
Name: "location_constraint",
Help: "Location constraint - must be set to match the Region.\n\nLeave blank if not sure. Used when creating buckets only.",
Provider: "!AWS,Alibaba,ArvanCloud,HuaweiOBS,ChinaMobile,Cloudflare,IBMCOS,IDrive,IONOS,Leviia,Liara,Linode,Qiniu,RackCorp,Scaleway,StackPath,Storj,TencentCOS,Petabox",
Provider: "!AWS,Alibaba,ArvanCloud,HuaweiOBS,ChinaMobile,Cloudflare,IBMCOS,IDrive,IONOS,Leviia,Liara,Linode,Magalu,Qiniu,RackCorp,Scaleway,StackPath,Storj,TencentCOS,Petabox",
}, {
Name: "acl",
Help: `Canned ACL used when creating buckets and storing or copying objects.
@@ -2031,6 +2055,15 @@ If you leave it blank, this is calculated automatically from the sse_customer_ke
Value: "STANDARD",
Help: "Standard storage class",
}},
}, {
// Mapping from here: #todo
Name: "storage_class",
Help: "The storage class to use when storing new objects in Magalu.",
Provider: "Magalu",
Examples: []fs.OptionExample{{
Value: "STANDARD",
Help: "Standard storage class",
}},
}, {
// Mapping from here: https://intl.cloud.tencent.com/document/product/436/30925
Name: "storage_class",
@@ -3127,7 +3160,7 @@ func setQuirks(opt *Options) {
listObjectsV2 = false
virtualHostStyle = false
urlEncodeListings = false
useAlreadyExists = false // untested
useAlreadyExists = true
case "ChinaMobile":
listObjectsV2 = false
virtualHostStyle = false
@@ -3173,6 +3206,12 @@ func setQuirks(opt *Options) {
case "LyveCloud":
useMultipartEtag = false // LyveCloud seems to calculate multipart Etags differently from AWS
useAlreadyExists = false // untested
case "Magalu":
listObjectsV2 = false
virtualHostStyle = false
urlEncodeListings = false
useMultipartEtag = false
useAlreadyExists = false
case "Minio":
virtualHostStyle = false
case "Netease":
@@ -4026,7 +4065,7 @@ func (f *Fs) list(ctx context.Context, opt listOpt, fn listFn) error {
isDirectory = false
} else {
// Don't insert the root directory
if remote == opt.directory {
if remote == f.opt.Enc.ToStandardPath(opt.directory) {
continue
}
}
@@ -5383,7 +5422,7 @@ func (f *Fs) headObject(ctx context.Context, req *s3.HeadObjectInput) (resp *s3.
})
if err != nil {
if awsErr, ok := err.(awserr.RequestFailure); ok {
if awsErr.StatusCode() == http.StatusNotFound {
if awsErr.StatusCode() == http.StatusNotFound || awsErr.StatusCode() == http.StatusMethodNotAllowed {
return nil, fs.ErrorObjectNotFound
}
}
+31
View File
@@ -332,6 +332,25 @@ cost of using more memory.
`,
Default: 64,
Advanced: true,
}, {
Name: "connections",
Help: strings.Replace(`Maximum number of SFTP simultaneous connections, 0 for unlimited.
Note that setting this is very likely to cause deadlocks so it should
be used with care.
If you are doing a sync or copy then make sure concurrency is one more
than the sum of |--transfers| and |--checkers|.
If you use |--check-first| then it just needs to be one more than the
maximum of |--checkers| and |--transfers|.
So for |concurrency 3| you'd use |--checkers 2 --transfers 2
--check-first| or |--checkers 1 --transfers 1|.
`, "|", "`", -1),
Default: 0,
Advanced: true,
}, {
Name: "set_env",
Default: fs.SpaceSepList{},
@@ -502,6 +521,7 @@ type Options struct {
IdleTimeout fs.Duration `config:"idle_timeout"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
Concurrency int `config:"concurrency"`
Connections int `config:"connections"`
SetEnv fs.SpaceSepList `config:"set_env"`
Ciphers fs.SpaceSepList `config:"ciphers"`
KeyExchange fs.SpaceSepList `config:"key_exchange"`
@@ -533,6 +553,7 @@ type Fs struct {
pacer *fs.Pacer // pacer for operations
savedpswd string
sessions atomic.Int32 // count in use sessions
tokens *pacer.TokenDispenser
}
// Object is a remote SFTP file that has been stat'd (so it exists, but is not necessarily open for reading)
@@ -695,6 +716,9 @@ func (f *Fs) newSftpClient(client sshClient, opts ...sftp.ClientOption) (*sftp.C
// Get an SFTP connection from the pool, or open a new one
func (f *Fs) getSftpConnection(ctx context.Context) (c *conn, err error) {
accounting.LimitTPS(ctx)
if f.opt.Connections > 0 {
f.tokens.Get()
}
f.poolMu.Lock()
for len(f.pool) > 0 {
c = f.pool[0]
@@ -717,6 +741,9 @@ func (f *Fs) getSftpConnection(ctx context.Context) (c *conn, err error) {
}
return false, nil
})
if f.opt.Connections > 0 && c == nil {
f.tokens.Put()
}
return c, err
}
@@ -727,6 +754,9 @@ func (f *Fs) getSftpConnection(ctx context.Context) (c *conn, err error) {
// if err is not nil then it checks the connection is alive using a
// Getwd request
func (f *Fs) putSftpConnection(pc **conn, err error) {
if f.opt.Connections > 0 {
defer f.tokens.Put()
}
c := *pc
if !c.sshClient.CanReuse() {
return
@@ -812,6 +842,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if len(opt.SSH) != 0 && ((opt.User != currentUser && opt.User != "") || opt.Host != "" || (opt.Port != "22" && opt.Port != "")) {
fs.Logf(name, "--sftp-ssh is in use - ignoring user/host/port from config - set in the parameters to --sftp-ssh (remove them from the config to silence this warning)")
}
f.tokens = pacer.NewTokenDispenser(opt.Connections)
if opt.User == "" {
opt.User = currentUser
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
+4 -1
View File
@@ -121,6 +121,9 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return nil, err
}
// Strip leading and trailing slashes, see https://github.com/rclone/rclone/issues/7796 for details.
root = strings.Trim(root, "/")
client := fshttp.NewClient(ctx)
f := &Fs{
@@ -1017,7 +1020,7 @@ func (f *Fs) CreateDir(ctx context.Context, parentSlug, leaf string) (newID stri
return folder.Slug, nil
}
func (f *Fs) newObjectWithInfo(ctx context.Context, remote string, info *api.File) (*Object, error) {
func (f *Fs) newObjectWithInfo(ctx context.Context, remote string, info *api.File) (fs.Object, error) {
o := &Object{
fs: f,
remote: remote,
+5
View File
@@ -127,6 +127,11 @@ func (f *Fs) Features() *fs.Features {
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
upstreams, err := f.action(ctx, dir)
if err != nil {
// If none of the backends can have empty directories then
// don't complain about directories not being found
if !f.features.CanHaveEmptyDirectories && err == fs.ErrorObjectNotFound {
return nil
}
return err
}
errs := Errors(make([]error, len(upstreams)))
+11
View File
@@ -322,6 +322,17 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
return do.Metadata(ctx)
}
// SetMetadata sets metadata for an Object
//
// It should return fs.ErrorNotImplemented if it can't set metadata
func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
do, ok := o.Object.(fs.SetMetadataer)
if !ok {
return fs.ErrorNotImplemented
}
return do.SetMetadata(ctx, metadata)
}
// Metadata returns metadata for an DirEntry
//
// It should return nil if there is no Metadata
+2 -2
View File
@@ -29,7 +29,7 @@ func prepareServer(t *testing.T) (configmap.Simple, func()) {
what := fmt.Sprintf("%s %s: Header ", r.Method, r.URL.Path)
assert.Equal(t, headers[1], r.Header.Get(headers[0]), what+headers[0])
assert.Equal(t, headers[3], r.Header.Get(headers[2]), what+headers[2])
fmt.Fprintf(w, `<d:multistatus xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
_, err := fmt.Fprintf(w, `<d:multistatus xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
<d:response>
<d:href>/remote.php/webdav/</d:href>
<d:propstat>
@@ -41,8 +41,8 @@ func prepareServer(t *testing.T) (configmap.Simple, func()) {
</d:propstat>
</d:response>
</d:multistatus>`)
require.NoError(t, err)
})
// Make the test server
ts := httptest.NewServer(handler)
+10 -1
View File
@@ -70,8 +70,17 @@ type ItemInfo struct {
Item Item `json:"data"`
}
// Links contains Cursor information
type Links struct {
Cursor struct {
HasNext bool `json:"has_next"`
Next string `json:"next"`
} `json:"cursor"`
}
// ItemList contains multiple Zoho Items
type ItemList struct {
Links Links `json:"links"`
Items []Item `json:"data"`
}
@@ -90,7 +99,7 @@ type UploadResponse struct {
Uploads []UploadInfo `json:"data"`
}
// WriteMetadataRequest is is used to write metadata for a
// WriteMetadataRequest is used to write metadata for a
// single item
type WriteMetadataRequest struct {
Data WriteMetadata `json:"data"`
+42 -80
View File
@@ -289,6 +289,10 @@ func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, err
authRetry = true
fs.Debugf(nil, "Should retry: %v", err)
}
if resp != nil && resp.StatusCode == 429 {
fs.Errorf(nil, "zoho: rate limit error received, sleeping for 60s: %v", err)
time.Sleep(60 * time.Second)
}
return authRetry || fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
}
@@ -332,7 +336,7 @@ func parsePath(path string) (root string) {
// readMetaDataForPath reads the metadata from the path
func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Item, err error) {
// defer fs.Trace(f, "path=%q", path)("info=%+v, err=%v", &info, &err)
// defer log.Trace(f, "path=%q", path)("info=%+v, err=%v", &info, &err)
leaf, directoryID, err := f.dirCache.FindPath(ctx, path, false)
if err != nil {
if err == fs.ErrorDirNotFound {
@@ -454,18 +458,18 @@ type listAllFn func(*api.Item) bool
//
// If the user fn ever returns true then it early exits with found = true
func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, filesOnly bool, fn listAllFn) (found bool, err error) {
const listItemsLimit = 1000
opts := rest.Opts{
Method: "GET",
Path: "/files/" + dirID + "/files",
ExtraHeaders: map[string]string{"Accept": "application/vnd.api+json"},
Parameters: url.Values{},
Parameters: url.Values{
"page[limit]": {strconv.Itoa(listItemsLimit)},
"page[next]": {"0"},
},
}
opts.Parameters.Set("page[limit]", strconv.Itoa(10))
offset := 0
OUTER:
for {
opts.Parameters.Set("page[offset]", strconv.Itoa(offset))
var result api.ItemList
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
@@ -495,7 +499,15 @@ OUTER:
break OUTER
}
}
offset += 10
if !result.Links.Cursor.HasNext {
break
}
// Fetch the next from the URL in the response
nextURL, err := url.Parse(result.Links.Cursor.Next)
if err != nil {
return found, fmt.Errorf("failed to parse next link as URL: %w", err)
}
opts.Parameters.Set("page[next]", nextURL.Query().Get("page[next]"))
}
return
}
@@ -631,33 +643,6 @@ func (f *Fs) createObject(ctx context.Context, remote string, size int64, modTim
return
}
// Put the object
//
// Copy the reader in to the new object which is returned.
//
// The new object may have been created if an error is returned
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
existingObj, err := f.newObjectWithInfo(ctx, src.Remote(), nil)
switch err {
case nil:
return existingObj, existingObj.Update(ctx, in, src, options...)
case fs.ErrorObjectNotFound:
// Not found so create it
return f.PutUnchecked(ctx, in, src)
default:
return nil, err
}
}
func isSimpleName(s string) bool {
for _, r := range s {
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && (r != '.') {
return false
}
}
return true
}
func (f *Fs) upload(ctx context.Context, name string, parent string, size int64, in io.Reader, options ...fs.OpenOption) (*api.Item, error) {
params := url.Values{}
params.Set("filename", name)
@@ -693,22 +678,32 @@ func (f *Fs) upload(ctx context.Context, name string, parent string, size int64,
return nil, errors.New("upload: invalid response")
}
// Received meta data is missing size so we have to read it again.
info, err := f.readMetaDataForID(ctx, uploadResponse.Uploads[0].Attributes.RessourceID)
if err != nil {
return nil, err
// It doesn't always appear on first read so try again if necessary
var info *api.Item
const maxTries = 10
sleepTime := 100 * time.Millisecond
for i := 0; i < maxTries; i++ {
info, err = f.readMetaDataForID(ctx, uploadResponse.Uploads[0].Attributes.RessourceID)
if err != nil {
return nil, err
}
if info.Attributes.StorageInfo.Size != 0 || size == 0 {
break
}
fs.Debugf(f, "Size not available yet for %q - try again in %v (try %d/%d)", name, sleepTime, i+1, maxTries)
time.Sleep(sleepTime)
sleepTime *= 2
}
return info, nil
}
// PutUnchecked the object into the container
//
// This will produce an error if the object already exists.
// Put the object into the container
//
// Copy the reader in to the new object which is returned.
//
// The new object may have been created if an error is returned
func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
size := src.Size()
remote := src.Remote()
@@ -718,25 +713,12 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
return nil, err
}
if isSimpleName(leaf) {
info, err := f.upload(ctx, f.opt.Enc.FromStandardName(leaf), directoryID, size, in, options...)
if err != nil {
return nil, err
}
return f.newObjectWithInfo(ctx, remote, info)
}
tempName := "rcloneTemp" + random.String(8)
info, err := f.upload(ctx, tempName, directoryID, size, in, options...)
// Upload the file
info, err := f.upload(ctx, f.opt.Enc.FromStandardName(leaf), directoryID, size, in, options...)
if err != nil {
return nil, err
}
o, err := f.newObjectWithInfo(ctx, remote, info)
if err != nil {
return nil, err
}
return o, o.(*Object).rename(ctx, leaf)
return f.newObjectWithInfo(ctx, remote, info)
}
// Mkdir creates the container if it doesn't exist
@@ -1200,32 +1182,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return err
}
if isSimpleName(leaf) {
// Simple name we can just overwrite the old file
info, err := o.fs.upload(ctx, o.fs.opt.Enc.FromStandardName(leaf), directoryID, size, in, options...)
if err != nil {
return err
}
return o.setMetaData(info)
}
// We have to fall back to upload + rename
tempName := "rcloneTemp" + random.String(8)
info, err := o.fs.upload(ctx, tempName, directoryID, size, in, options...)
// Overwrite the old file
info, err := o.fs.upload(ctx, o.fs.opt.Enc.FromStandardName(leaf), directoryID, size, in, options...)
if err != nil {
return err
}
// upload was successful, need to delete old object before rename
if err = o.Remove(ctx); err != nil {
return fmt.Errorf("failed to remove old object: %w", err)
}
if err = o.setMetaData(info); err != nil {
return err
}
// rename also updates metadata
return o.rename(ctx, leaf)
return o.setMetaData(info)
}
// Remove an object
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# This adds the version each backend was released to its docs page
set -e
for backend in $( find backend -maxdepth 1 -type d ); do
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# An example script to run when bisecting go with git bisect -run when
# looking for an rclone regression
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Example script for git bisect run
#
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
set -e
docker build -t rclone/xgo-cgofuse https://github.com/winfsp/cgofuse.git
docker images
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Insert the rc docs into docs/content/rc.md
set -e
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# Thrash the VFS tests
set -e
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
# defaults
buildflags=""
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
if [[ ! -z $(git status --short --untracked-files=no) ]]; then
echo "Detected uncommitted changes - commit before running this"
+7
View File
@@ -97,6 +97,8 @@ var logReplacements = []string{
`^NOTICE:.*?Files of unknown size \(such as Google Docs\) do not sync reliably with --checksum or --size-only\. Consider using modtime instead \(the default\) or --drive-skip-gdocs.*?$`, dropMe,
// ignore cache backend cache expired messages
`^INFO : .*cache expired.*$`, dropMe,
// ignore "Implicitly create directory" messages (TestnStorage:)
`^INFO : .*Implicitly create directory.*$`, dropMe,
// ignore differences in backend features
`^.*?"HashType1":.*?$`, dropMe,
`^.*?"HashType2":.*?$`, dropMe,
@@ -108,6 +110,8 @@ var logReplacements = []string{
`^(INFO : .*?: (Made directory with|Set directory) (metadata|modification time)).*$`, dropMe,
// ignore sizes in directory time updates
`^(NOTICE: .*?: Skipped set directory modification time as --dry-run is set).*$`, dropMe,
// ignore sizes in directory metadata updates
`^(NOTICE: .*?: Skipped update directory metadata as --dry-run is set).*$`, dropMe,
}
// Some dry-run messages differ depending on the particular remote.
@@ -937,6 +941,9 @@ func (b *bisyncTest) checkPreReqs(ctx context.Context, opt *bisync.Options) (con
b.fs2.Features().Disable("Copy") // API has longstanding bug for conflictBehavior=replace https://github.com/rclone/rclone/issues/4590
b.fs2.Features().Disable("Move")
}
if strings.Contains(strings.ToLower(fs.ConfigString(b.fs1)), "mailru") || strings.Contains(strings.ToLower(fs.ConfigString(b.fs2)), "mailru") {
fs.GetConfig(ctx).TPSLimit = 10 // https://github.com/rclone/rclone/issues/7768#issuecomment-2060888980
}
if (!b.fs1.Features().CanHaveEmptyDirectories || !b.fs2.Features().CanHaveEmptyDirectories) && (b.testCase == "createemptysrcdirs" || b.testCase == "rmdirs") {
b.t.Skip("skipping test as remote does not support empty dirs")
}
+1 -1
View File
@@ -64,7 +64,7 @@ func WhichCheck(ctx context.Context, opt *operations.CheckOpt) *operations.Check
}
}
// if we've gotten this far, niether check or cryptcheck will work, so use --download
// if we've gotten this far, neither check or cryptcheck will work, so use --download
fs.Infof(fdst, "Can't compare hashes, so using check --download for safety. (Use --size-only or --ignore-checksum to disable)")
opt.Check = DownloadCheckFn
return opt
+1 -1
View File
@@ -274,7 +274,7 @@ func (ri *renamesInfo) getNames(is1to2 bool) (srcOldName, srcNewName, dstOldName
return ri.path2.oldName, ri.path2.newName, ri.path1.oldName, ri.path1.newName
}
// work out the lowest number that niether side has, return it for suffix
// work out the lowest number that neither side has, return it for suffix
func (b *bisyncRun) numerate(ctx context.Context, startnum int, file, alias string) int {
for i := startnum; i < math.MaxInt; i++ {
iStr := fmt.Sprint(i)
+325 -86
View File
@@ -1,6 +1,7 @@
package gitannex
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@@ -8,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/stretchr/testify/require"
@@ -19,7 +21,7 @@ import (
// checkRcloneBinaryVersion runs whichever rclone is on the PATH and checks
// whether it reports a version that matches the test's expectations. Returns
// nil when the version is the expected version, otherwise returns an error.
func checkRcloneBinaryVersion() error {
func checkRcloneBinaryVersion(t *testing.T) error {
// versionInfo is a subset of information produced by "core/version".
type versionInfo struct {
Version string
@@ -40,16 +42,172 @@ func checkRcloneBinaryVersion() error {
if parsed.Version != fs.Version {
return fmt.Errorf("expected version %q, but got %q", fs.Version, parsed.Version)
}
if !parsed.IsGit {
if parsed.IsGit != strings.HasSuffix(fs.Version, "-DEV") {
return errors.New("expected rclone to be a dev build")
}
_, tagString := buildinfo.GetLinkingAndTags()
if parsed.GoTags != tagString {
return fmt.Errorf("expected tag string %q, but got %q", tagString, parsed.GoTags)
// TODO: Skip the test when tags do not match.
t.Logf("expected tag string %q, but got %q. Not skipping!", tagString, parsed.GoTags)
}
return nil
}
// countFilesRecursively returns the number of files nested underneath `dir`. It
// counts files only and excludes directories.
func countFilesRecursively(t *testing.T, dir string) int {
remoteFiles, err := os.ReadDir(dir)
require.NoError(t, err)
var count int
for _, f := range remoteFiles {
if f.IsDir() {
subdir := filepath.Join(dir, f.Name())
count += countFilesRecursively(t, subdir)
} else {
count++
}
}
return count
}
func findFileWithContents(t *testing.T, dir string, wantContents []byte) bool {
remoteFiles, err := os.ReadDir(dir)
require.NoError(t, err)
for _, f := range remoteFiles {
fPath := filepath.Join(dir, f.Name())
if f.IsDir() {
if findFileWithContents(t, fPath, wantContents) {
return true
}
} else {
contents, err := os.ReadFile(fPath)
require.NoError(t, err)
if bytes.Equal(contents, wantContents) {
return true
}
}
}
return false
}
type e2eTestingContext struct {
t *testing.T
tempDir string
binDir string
homeDir string
configDir string
rcloneConfigDir string
ephemeralRepoDir string
}
// makeE2eTestingContext sets up a new e2eTestingContext rooted under
// `t.TempDir()`. It creates the skeleton directory structure shown below in the
// temp directory without creating any files.
//
// .
// |-- bin
// | `-- git-annex-remote-rclone-builtin -> ${PATH_TO_RCLONE_BINARY}
// |-- ephemeralRepo
// `-- user
// `-- .config
// `-- rclone
// `-- rclone.conf
func makeE2eTestingContext(t *testing.T) e2eTestingContext {
tempDir := t.TempDir()
binDir := filepath.Join(tempDir, "bin")
homeDir := filepath.Join(tempDir, "user")
configDir := filepath.Join(homeDir, ".config")
rcloneConfigDir := filepath.Join(configDir, "rclone")
ephemeralRepoDir := filepath.Join(tempDir, "ephemeralRepo")
for _, dir := range []string{binDir, homeDir, configDir, rcloneConfigDir, ephemeralRepoDir} {
require.NoError(t, os.Mkdir(dir, 0700))
}
return e2eTestingContext{t, tempDir, binDir, homeDir, configDir, rcloneConfigDir, ephemeralRepoDir}
}
// Install the symlink that enables git-annex to invoke "rclone gitannex"
// without explicitly specifying the subcommand.
func (e *e2eTestingContext) installRcloneGitannexSymlink(t *testing.T) {
rcloneBinaryPath, err := exec.LookPath("rclone")
require.NoError(t, err)
require.NoError(t, os.Symlink(
rcloneBinaryPath,
filepath.Join(e.binDir, "git-annex-remote-rclone-builtin")))
}
// Install a rclone.conf file in an appropriate location in the fake home
// directory. The config defines an rclone remote named "MyRcloneRemote" using
// the local backend.
func (e *e2eTestingContext) installRcloneConfig(t *testing.T) {
// Install the rclone.conf file that defines the remote.
rcloneConfigPath := filepath.Join(e.rcloneConfigDir, "rclone.conf")
rcloneConfigContents := "[MyRcloneRemote]\ntype = local"
require.NoError(t, os.WriteFile(rcloneConfigPath, []byte(rcloneConfigContents), 0600))
}
// runInRepo runs the given command from within the ephemeral repo directory. To
// prevent accidental changes in the real home directory, it sets the HOME
// variable to a subdirectory of the temp directory. It also ensures that the
// git-annex-remote-rclone-builtin symlink will be found by extending the PATH.
func (e *e2eTestingContext) runInRepo(t *testing.T, command string, args ...string) {
if testing.Verbose() {
t.Logf("Running %s %v\n", command, args)
}
cmd := exec.Command(command, args...)
cmd.Dir = e.ephemeralRepoDir
cmd.Env = []string{
"HOME=" + e.homeDir,
"PATH=" + os.Getenv("PATH") + ":" + e.binDir,
}
buf, err := cmd.CombinedOutput()
require.NoError(t, err, fmt.Sprintf("+ %s %v failed:\n%s\n", command, args, buf))
}
// createGitRepo creates an empty git repository in the ephemeral repo
// directory. It makes "global" config changes that are ultimately scoped to the
// calling test thanks to runInRepo() overriding the HOME environment variable.
func (e *e2eTestingContext) createGitRepo(t *testing.T) {
e.runInRepo(t, "git", "annex", "version")
e.runInRepo(t, "git", "config", "--global", "user.name", "User Name")
e.runInRepo(t, "git", "config", "--global", "user.email", "user@example.com")
e.runInRepo(t, "git", "config", "--global", "init.defaultBranch", "main")
e.runInRepo(t, "git", "init")
e.runInRepo(t, "git", "annex", "init")
}
func skipE2eTestIfNecessary(t *testing.T) {
if testing.Short() {
t.Skip("Skipping due to short mode.")
}
// TODO: Support e2e tests on Windows. Need to evaluate the semantics of the
// HOME and PATH environment variables.
switch runtime.GOOS {
case "darwin",
"freebsd",
"linux",
"netbsd",
"openbsd",
"plan9",
"solaris":
default:
t.Skipf("GOOS %q is not supported.", runtime.GOOS)
}
if err := checkRcloneBinaryVersion(t); err != nil {
t.Skipf("Skipping due to rclone version: %s", err)
}
if _, err := exec.LookPath("git-annex"); err != nil {
t.Skipf("Skipping because git-annex was not found: %s", err)
}
}
// This end-to-end test runs `git annex testremote` in a temporary git repo.
// This test will be skipped unless the `rclone` binary on PATH reports the
// expected version.
@@ -64,96 +222,177 @@ func checkRcloneBinaryVersion() error {
// parameters like repo layouts, and runtime may suffer from a combinatorial
// explosion.
func TestEndToEnd(t *testing.T) {
if testing.Short() {
t.Skip("Skipping due to short mode.")
}
skipE2eTestIfNecessary(t)
// TODO: Support this test on Windows. Need to evaluate the semantics of the
// HOME and PATH environment variables.
switch runtime.GOOS {
case "darwin",
"freebsd",
"linux",
"netbsd",
"openbsd",
"plan9",
"solaris":
default:
t.Skipf("GOOS %q is not supported.", runtime.GOOS)
}
for _, mode := range allLayoutModes() {
mode := mode
t.Run(string(mode), func(t *testing.T) {
t.Parallel()
if err := checkRcloneBinaryVersion(); err != nil {
t.Skipf("Skipping due to rclone version: %s", err)
}
testingContext := makeE2eTestingContext(t)
testingContext.installRcloneGitannexSymlink(t)
testingContext.installRcloneConfig(t)
testingContext.createGitRepo(t)
if _, err := exec.LookPath("git-annex"); err != nil {
t.Skipf("Skipping because git-annex was not found: %s", err)
}
testingContext.runInRepo(t, "git", "annex", "initremote", "MyTestRemote",
"type=external", "externaltype=rclone-builtin", "encryption=none",
"rcloneremotename=MyRcloneRemote", "rcloneprefix="+testingContext.ephemeralRepoDir,
"rclonelayout="+string(mode))
// Create a temp directory and chdir there, just in case.
originalWd, err := os.Getwd()
require.NoError(t, err)
tempDir := t.TempDir()
require.NoError(t, os.Chdir(tempDir))
defer func() { require.NoError(t, os.Chdir(originalWd)) }()
// Flesh out subdirectories of the temp directory:
//
// .
// |-- bin
// | `-- git-annex-remote-rclone-builtin -> ${PATH_TO_RCLONE_BINARY}
// |-- ephemeralRepo
// `-- user
// `-- .config
// `-- rclone
// `-- rclone.conf
binDir := filepath.Join(tempDir, "bin")
homeDir := filepath.Join(tempDir, "user")
configDir := filepath.Join(homeDir, ".config")
rcloneConfigDir := filepath.Join(configDir, "rclone")
ephemeralRepoDir := filepath.Join(tempDir, "ephemeralRepo")
for _, dir := range []string{binDir, homeDir, configDir, rcloneConfigDir, ephemeralRepoDir} {
require.NoError(t, os.Mkdir(dir, 0700))
testingContext.runInRepo(t, "git", "annex", "testremote", "MyTestRemote")
})
}
}
// Install the symlink that enables git-annex to invoke "rclone gitannex"
// without explicitly specifying the subcommand.
rcloneBinaryPath, err := exec.LookPath("rclone")
require.NoError(t, err)
require.NoError(t, os.Symlink(
rcloneBinaryPath,
filepath.Join(binDir, "git-annex-remote-rclone-builtin")))
// Install the rclone.conf file that defines the remote.
rcloneConfigPath := filepath.Join(rcloneConfigDir, "rclone.conf")
rcloneConfigContents := "[MyRcloneRemote]\ntype = local"
require.NoError(t, os.WriteFile(rcloneConfigPath, []byte(rcloneConfigContents), 0600))
// NOTE: These commands must be run with HOME pointing at an ephemeral
// directory, rather than the real home directory.
cmds := [][]string{
{"git", "annex", "version"},
{"git", "config", "--global", "user.name", "User Name"},
{"git", "config", "--global", "user.email", "user@example.com"},
{"git", "init"},
{"git", "annex", "init"},
{"git", "annex", "initremote", "MyTestRemote",
"type=external", "externaltype=rclone-builtin", "encryption=none",
"rcloneremotename=MyRcloneRemote", "rcloneprefix=" + ephemeralRepoDir},
{"git", "annex", "testremote", "MyTestRemote"},
// For each layout mode, migrate a single remote from git-annex-remote-rclone to
// git-annex-remote-rclone-builtin and run `git annex testremote`.
func TestEndToEndMigration(t *testing.T) {
skipE2eTestIfNecessary(t)
if _, err := exec.LookPath("git-annex-remote-rclone"); err != nil {
t.Skipf("Skipping because git-annex-remote-rclone was not found: %s", err)
}
for _, mode := range allLayoutModes() {
mode := mode
t.Run(string(mode), func(t *testing.T) {
t.Parallel()
tc := makeE2eTestingContext(t)
tc.installRcloneGitannexSymlink(t)
tc.installRcloneConfig(t)
tc.createGitRepo(t)
remoteStorage := filepath.Join(tc.tempDir, "remotePrefix")
require.NoError(t, os.Mkdir(remoteStorage, 0777))
tc.runInRepo(t,
"git", "annex", "initremote", "MigratedRemote",
"type=external", "externaltype=rclone", "encryption=none",
"target=MyRcloneRemote",
"rclone_layout="+string(mode),
"prefix="+remoteStorage,
)
fooFileContents := []byte{1, 2, 3, 4}
fooFilePath := filepath.Join(tc.ephemeralRepoDir, "foo")
require.NoError(t, os.WriteFile(fooFilePath, fooFileContents, 0700))
tc.runInRepo(t, "git", "annex", "add", "foo")
tc.runInRepo(t, "git", "commit", "-m", "Add foo file")
// Git-annex objects are not writable, which prevents `testing` from
// cleaning up the temp directory. We can work around this by
// explicitly dropping any files we add to the annex.
t.Cleanup(func() { tc.runInRepo(t, "git", "annex", "drop", "--force", "foo") })
tc.runInRepo(t, "git", "annex", "copy", "--to=MigratedRemote", "foo")
tc.runInRepo(t, "git", "annex", "fsck", "--from=MigratedRemote", "foo")
tc.runInRepo(t,
"git", "annex", "enableremote", "MigratedRemote",
"externaltype=rclone-builtin",
"rcloneremotename=MyRcloneRemote",
"rclonelayout="+string(mode),
"rcloneprefix="+remoteStorage,
)
tc.runInRepo(t, "git", "annex", "fsck", "--from=MigratedRemote", "foo")
tc.runInRepo(t, "git", "annex", "testremote", "MigratedRemote")
})
}
}
// For each layout mode, create two git-annex remotes with externaltype=rclone
// and externaltype=rclone-builtin respectively. Test that files copied to one
// remote are present on the other. Similarly, test that files deleted from one
// are removed on the other.
func TestEndToEndRepoLayoutCompat(t *testing.T) {
skipE2eTestIfNecessary(t)
if _, err := exec.LookPath("git-annex-remote-rclone"); err != nil {
t.Skipf("Skipping because git-annex-remote-rclone was not found: %s", err)
}
for _, mode := range allLayoutModes() {
mode := mode
t.Run(string(mode), func(t *testing.T) {
t.Parallel()
tc := makeE2eTestingContext(t)
tc.installRcloneGitannexSymlink(t)
tc.installRcloneConfig(t)
tc.createGitRepo(t)
remoteStorage := filepath.Join(tc.tempDir, "remotePrefix")
require.NoError(t, os.Mkdir(remoteStorage, 0777))
tc.runInRepo(t,
"git", "annex", "initremote", "Control",
"type=external", "externaltype=rclone", "encryption=none",
"target=MyRcloneRemote",
"rclone_layout="+string(mode),
"prefix="+remoteStorage)
tc.runInRepo(t,
"git", "annex", "initremote", "Experiment",
"type=external", "externaltype=rclone-builtin", "encryption=none",
"rcloneremotename=MyRcloneRemote",
"rclonelayout="+string(mode),
"rcloneprefix="+remoteStorage)
fooFileContents := []byte{1, 2, 3, 4}
fooFilePath := filepath.Join(tc.ephemeralRepoDir, "foo")
require.NoError(t, os.WriteFile(fooFilePath, fooFileContents, 0700))
tc.runInRepo(t, "git", "annex", "add", "foo")
tc.runInRepo(t, "git", "commit", "-m", "Add foo file")
// Git-annex objects are not writable, which prevents `testing` from
// cleaning up the temp directory. We can work around this by
// explicitly dropping any files we add to the annex.
t.Cleanup(func() { tc.runInRepo(t, "git", "annex", "drop", "--force", "foo") })
require.Equal(t, 0, countFilesRecursively(t, remoteStorage))
require.False(t, findFileWithContents(t, remoteStorage, fooFileContents))
// Copy the file to Control and verify it's present on Experiment.
tc.runInRepo(t, "git", "annex", "copy", "--to=Control", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
tc.runInRepo(t, "git", "annex", "fsck", "--from=Experiment", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
// Drop the file locally and verify we can copy it back from Experiment.
tc.runInRepo(t, "git", "annex", "drop", "--force", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
tc.runInRepo(t, "git", "annex", "copy", "--from=Experiment", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
// Drop the file from Experiment, copy it back to Experiment, and
// verify it's still present on Control.
tc.runInRepo(t, "git", "annex", "drop", "--from=Experiment", "--force", "foo")
require.Equal(t, 0, countFilesRecursively(t, remoteStorage))
require.False(t, findFileWithContents(t, remoteStorage, fooFileContents))
tc.runInRepo(t, "git", "annex", "copy", "--to=Experiment", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
tc.runInRepo(t, "git", "annex", "fsck", "--from=Control", "foo")
require.Equal(t, 1, countFilesRecursively(t, remoteStorage))
require.True(t, findFileWithContents(t, remoteStorage, fooFileContents))
// Drop the file from Control.
for _, args := range cmds {
fmt.Printf("+ %v\n", args)
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = ephemeralRepoDir
cmd.Env = []string{
"HOME=" + homeDir,
"PATH=" + os.Getenv("PATH") + ":" + binDir,
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
require.NoError(t, cmd.Run())
tc.runInRepo(t, "git", "annex", "drop", "--from=Control", "--force", "foo")
require.Equal(t, 0, countFilesRecursively(t, remoteStorage))
require.False(t, findFileWithContents(t, remoteStorage, fooFileContents))
})
}
}
+142 -44
View File
@@ -96,23 +96,44 @@ func (m *messageParser) nextSpaceDelimitedParameter() (string, error) {
}
// finalParameter consumes the final parameter, which may contain spaces.
func (m *messageParser) finalParameter() (string, error) {
func (m *messageParser) finalParameter() string {
m.line = strings.TrimRight(m.line, "\r\n")
if len(m.line) == 0 {
return "", errors.New("nothing remains to parse")
return ""
}
param := m.line
m.line = ""
return param, nil
return param
}
// configDefinition describes a configuration value required by this command. We
// use "GETCONFIG" messages to query git-annex for these values at runtime.
type configDefinition struct {
name string
description string
destination *string
names []string
description string
destination *string
defaultValue *string
}
func (c *configDefinition) getCanonicalName() string {
if len(c.names) < 1 {
panic(fmt.Errorf("configDefinition must have at least one name: %v", c))
}
return c.names[0]
}
// fullDescription returns a single-line, human-readable description for this
// config. The returned string begins with a list of synonyms and ends with
// `c.description`.
func (c *configDefinition) fullDescription() string {
if len(c.names) <= 1 {
return c.description
}
// Exclude the canonical name from the list of synonyms.
synonyms := c.names[1:len(c.names)]
commaSeparatedSynonyms := strings.Join(synonyms, ", ")
return fmt.Sprintf("(synonyms: %s) %s", commaSeparatedSynonyms, c.description)
}
// server contains this command's current state.
@@ -132,6 +153,7 @@ type server struct {
configsDone bool
configPrefix string
configRcloneRemoteName string
configRcloneLayout string
}
func (s *server) sendMsg(msg string) {
@@ -203,11 +225,7 @@ func (s *server) run() error {
case "REMOVE":
err = s.handleRemove(message)
case "ERROR":
errorMessage, parseErr := message.finalParameter()
if parseErr != nil {
err = fmt.Errorf("error while parsing ERROR message from git-annex: %w", parseErr)
break
}
errorMessage := message.finalParameter()
err = fmt.Errorf("received error message from git-annex: %s", errorMessage)
//
@@ -271,20 +289,33 @@ func (s *server) handleInitRemote() error {
// Get a list of configs with pointers to fields of `s`.
func (s *server) getRequiredConfigs() []configDefinition {
defaultRclonePrefix := "git-annex-rclone"
defaultRcloneLayout := "nodir"
return []configDefinition{
{
"rcloneremotename",
[]string{"rcloneremotename", "target"},
"Name of the rclone remote to use. " +
"Must match a remote known to rclone. " +
"(Note that rclone remotes are a distinct concept from git-annex remotes.)",
&s.configRcloneRemoteName,
nil,
},
{
"rcloneprefix",
[]string{"rcloneprefix", "prefix"},
"Directory where rclone will write git-annex content. " +
"If not specified, defaults to \"git-annex-rclone\". " +
"This directory be created on init if it does not exist.",
fmt.Sprintf("If not specified, defaults to %q. ", defaultRclonePrefix) +
"This directory will be created on init if it does not exist.",
&s.configPrefix,
&defaultRclonePrefix,
},
{
[]string{"rclonelayout", "rclone_layout"},
"Defines where, within the rcloneprefix directory, rclone will write git-annex content. " +
fmt.Sprintf("Must be one of %v. ", allLayoutModes()) +
fmt.Sprintf("If empty, defaults to %q.", defaultRcloneLayout),
&s.configRcloneLayout,
&defaultRcloneLayout,
},
}
}
@@ -298,24 +329,35 @@ func (s *server) queryConfigs() error {
// Send a "GETCONFIG" message for each required config and parse git-annex's
// "VALUE" response.
for _, config := range s.getRequiredConfigs() {
s.sendMsg(fmt.Sprintf("GETCONFIG %s", config.name))
var valueReceived bool
// Try each of the config's names in sequence, starting with the
// canonical name.
for _, configName := range config.names {
s.sendMsg(fmt.Sprintf("GETCONFIG %s", configName))
message, err := s.getMsg()
if err != nil {
return err
message, err := s.getMsg()
if err != nil {
return err
}
valueKeyword, err := message.nextSpaceDelimitedParameter()
if err != nil || valueKeyword != "VALUE" {
return fmt.Errorf("failed to parse config value: %s %s", valueKeyword, message.line)
}
value := message.finalParameter()
if value != "" {
*config.destination = value
valueReceived = true
break
}
}
valueKeyword, err := message.nextSpaceDelimitedParameter()
if err != nil || valueKeyword != "VALUE" {
return fmt.Errorf("failed to parse config value: %s %s", valueKeyword, message.line)
if !valueReceived {
if config.defaultValue == nil {
return fmt.Errorf("did not receive a non-empty config value for %q", config.getCanonicalName())
}
*config.destination = *config.defaultValue
}
value, err := message.finalParameter()
if err != nil || value == "" {
return fmt.Errorf("config value of %q must not be empty", config.name)
}
*config.destination = value
}
s.configsDone = true
@@ -335,7 +377,7 @@ func (s *server) handlePrepare() error {
// in sync with `handlePrepare()`.
func (s *server) handleListConfigs() {
for _, config := range s.getRequiredConfigs() {
s.sendMsg(fmt.Sprintf("CONFIG %s %s", config.name, config.description))
s.sendMsg(fmt.Sprintf("CONFIG %s %s", config.getCanonicalName(), config.fullDescription()))
}
s.sendMsg("CONFIGEND")
}
@@ -351,10 +393,10 @@ func (s *server) handleTransfer(message *messageParser) error {
s.sendMsg("TRANSFER-FAILURE failed to parse key")
return fmt.Errorf("malformed arguments for TRANSFER: %w", err)
}
argFile, err := message.finalParameter()
if err != nil {
s.sendMsg("TRANSFER-FAILURE failed to parse file")
return fmt.Errorf("malformed arguments for TRANSFER: %w", err)
argFile := message.finalParameter()
if argFile == "" {
s.sendMsg("TRANSFER-FAILURE failed to parse file path")
return errors.New("failed to parse file path")
}
if err := s.queryConfigs(); err != nil {
@@ -362,7 +404,19 @@ func (s *server) handleTransfer(message *messageParser) error {
return fmt.Errorf("error getting configs: %w", err)
}
remoteFs, err := cache.Get(context.TODO(), fmt.Sprintf("%s:%s", s.configRcloneRemoteName, s.configPrefix))
layout := parseLayoutMode(s.configRcloneLayout)
if layout == layoutModeUnknown {
s.sendMsg(fmt.Sprintf("TRANSFER-FAILURE %s", argKey))
return fmt.Errorf("error parsing layout mode: %q", s.configRcloneLayout)
}
remoteFsString, err := buildFsString(s.queryDirhash, layout, argKey, s.configRcloneRemoteName, s.configPrefix)
if err != nil {
s.sendMsg(fmt.Sprintf("TRANSFER-FAILURE %s", argKey))
return fmt.Errorf("error building fs string: %w", err)
}
remoteFs, err := cache.Get(context.TODO(), remoteFsString)
if err != nil {
s.sendMsg(fmt.Sprintf("TRANSFER-FAILURE %s %s failed to get remote fs", argMode, argKey))
return err
@@ -409,9 +463,9 @@ func (s *server) handleTransfer(message *messageParser) error {
}
func (s *server) handleCheckPresent(message *messageParser) error {
argKey, err := message.finalParameter()
if err != nil {
return err
argKey := message.finalParameter()
if argKey == "" {
return errors.New("failed to parse response for CHECKPRESENT")
}
if err := s.queryConfigs(); err != nil {
@@ -419,7 +473,19 @@ func (s *server) handleCheckPresent(message *messageParser) error {
return fmt.Errorf("error getting configs: %s", err)
}
remoteFs, err := cache.Get(context.TODO(), fmt.Sprintf("%s:%s", s.configRcloneRemoteName, s.configPrefix))
layout := parseLayoutMode(s.configRcloneLayout)
if layout == layoutModeUnknown {
s.sendMsg(fmt.Sprintf("CHECKPRESENT-FAILURE %s", argKey))
return fmt.Errorf("error parsing layout mode: %q", s.configRcloneLayout)
}
remoteFsString, err := buildFsString(s.queryDirhash, layout, argKey, s.configRcloneRemoteName, s.configPrefix)
if err != nil {
s.sendMsg(fmt.Sprintf("CHECKPRESENT-FAILURE %s", argKey))
return fmt.Errorf("error building fs string: %w", err)
}
remoteFs, err := cache.Get(context.TODO(), remoteFsString)
if err != nil {
s.sendMsg(fmt.Sprintf("CHECKPRESENT-UNKNOWN %s failed to get remote fs", argKey))
return err
@@ -439,13 +505,45 @@ func (s *server) handleCheckPresent(message *messageParser) error {
return nil
}
func (s *server) handleRemove(message *messageParser) error {
argKey, err := message.finalParameter()
func (s *server) queryDirhash(msg string) (string, error) {
s.sendMsg(msg)
parser, err := s.getMsg()
if err != nil {
return err
return "", err
}
keyword, err := parser.nextSpaceDelimitedParameter()
if err != nil {
return "", err
}
if keyword != "VALUE" {
return "", fmt.Errorf("expected VALUE keyword, but got %q", keyword)
}
dirhash, err := parser.nextSpaceDelimitedParameter()
if err != nil {
return "", fmt.Errorf("failed to parse dirhash: %w", err)
}
return dirhash, nil
}
func (s *server) handleRemove(message *messageParser) error {
argKey := message.finalParameter()
if argKey == "" {
return errors.New("failed to parse key for REMOVE")
}
remoteFs, err := cache.Get(context.TODO(), fmt.Sprintf("%s:%s", s.configRcloneRemoteName, s.configPrefix))
layout := parseLayoutMode(s.configRcloneLayout)
if layout == layoutModeUnknown {
s.sendMsg(fmt.Sprintf("REMOVE-FAILURE %s", argKey))
return fmt.Errorf("error parsing layout mode: %q", s.configRcloneLayout)
}
remoteFsString, err := buildFsString(s.queryDirhash, layout, argKey, s.configRcloneRemoteName, s.configPrefix)
if err != nil {
s.sendMsg(fmt.Sprintf("REMOVE-FAILURE %s", argKey))
return fmt.Errorf("error building fs string: %w", err)
}
remoteFs, err := cache.Get(context.TODO(), remoteFsString)
if err != nil {
s.sendMsg(fmt.Sprintf("REMOVE-FAILURE %s", argKey))
return fmt.Errorf("error getting remote fs: %w", err)
+52 -21
View File
@@ -1,38 +1,69 @@
Rclone's gitannex subcommand enables git-annex to store and retrieve content
from an rclone remote. It expects to be run by git-annex, not directly by users.
It is an "external special remote program" as defined by git-annex.
Rclone's `gitannex` subcommand enables [git-annex] to store and retrieve content
from an rclone remote. It is meant to be run by git-annex, not directly by
users.
[git-annex]: https://git-annex.branchable.com/
Installation on Linux
---------------------
1. Create a symlink and ensure it's on your PATH. For example:
1. Skip this step if your version of git-annex is [10.20240430] or newer.
Otherwise, you must create a symlink somewhere on your PATH with a particular
name. This symlink helps git-annex tell rclone it wants to run the "gitannex"
subcommand.
ln -s "$(realpath rclone)" "$HOME/bin/git-annex-remote-rclone-builtin"
```sh
# Create the helper symlink in "$HOME/bin".
ln -s "$(realpath rclone)" "$HOME/bin/git-annex-remote-rclone-builtin"
2. Add a new external remote to your git-annex repo.
# Verify the new symlink is on your PATH.
which git-annex-remote-rclone-builtin
```
The new remote's type should be "rclone-builtin". When git-annex interacts
with remotes of this type, it will try to run a command named
"git-annex-remote-rclone-builtin", so the symlink from the previous step
should be on your PATH.
[10.20240430]: https://git-annex.branchable.com/news/version_10.20240430/
2. Add a new remote to your git-annex repo. This new remote will connect
git-annex with the `rclone gitannex` subcommand.
Start by asking git-annex to describe the remote's available configuration
parameters.
```sh
# If you skipped step 1:
git annex initremote MyRemote type=rclone --whatelse
# If you created a symlink in step 1:
git annex initremote MyRemote type=external externaltype=rclone-builtin --whatelse
```
> **NOTE**: If you're porting an existing [git-annex-remote-rclone] remote to
> use `rclone gitannex`, you can probably reuse the configuration parameters
> verbatim without renaming them. Check parameter synonyms with `--whatelse`
> as shown above.
>
> [git-annex-remote-rclone]: https://github.com/git-annex-remote-rclone/git-annex-remote-rclone
The following example creates a new git-annex remote named "MyRemote" that
will use the rclone remote named "SomeRcloneRemote". This rclone remote must
be configured in your rclone.conf file, wherever that is located on your
system. The rcloneprefix value ensures that content is only written into the
rclone remote underneath the "git-annex-content" directory.
will use the rclone remote named "SomeRcloneRemote". That rclone remote must
be one configured in your rclone.conf file, which can be located with `rclone
config file`.
git annex initremote MyRemote \
type=external \
externaltype=rclone-builtin \
encryption=none \
rcloneremotename=SomeRcloneRemote \
rcloneprefix=git-annex-content
```sh
git annex initremote MyRemote \
type=external \
externaltype=rclone-builtin \
encryption=none \
rcloneremotename=SomeRcloneRemote \
rcloneprefix=git-annex-content \
rclonelayout=nodir
```
3. Before you trust this command with your precious data, be sure to **test the
remote**. This command is very new and has not been tested on many rclone
backends. Caveat emptor!
git annex testremote my-rclone-remote
```sh
git annex testremote MyRemote
```
Happy annexing!
+143 -17
View File
@@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
@@ -64,12 +65,10 @@ var messageParserTestCases = []messageParserTestCase{
assert.Error(t, err)
assert.Equal(t, param, "")
param, err = m.finalParameter()
assert.Error(t, err)
param = m.finalParameter()
assert.Equal(t, param, "")
param, err = m.finalParameter()
assert.Error(t, err)
param = m.finalParameter()
assert.Equal(t, param, "")
param, err = m.nextSpaceDelimitedParameter()
@@ -95,8 +94,7 @@ var messageParserTestCases = []messageParserTestCase{
assert.Error(t, err)
assert.Equal(t, param, "")
param, err = m.finalParameter()
assert.Error(t, err)
param = m.finalParameter()
assert.Equal(t, param, "")
},
},
@@ -118,8 +116,7 @@ var messageParserTestCases = []messageParserTestCase{
assert.Error(t, err)
assert.Equal(t, param, "")
param, err = m.finalParameter()
assert.Error(t, err)
param = m.finalParameter()
assert.Equal(t, param, "")
},
},
@@ -136,8 +133,7 @@ var messageParserTestCases = []messageParserTestCase{
assert.NoError(t, err)
assert.Equal(t, param, "secondparam")
param, err = m.finalParameter()
assert.NoError(t, err)
param = m.finalParameter()
assert.Equal(t, param, "final param with spaces")
},
},
@@ -151,12 +147,10 @@ var messageParserTestCases = []messageParserTestCase{
t.Run(testName, func(t *testing.T) {
m := messageParser{"one long final parameter" + lineEnding}
param, err := m.finalParameter()
assert.NoError(t, err)
param := m.finalParameter()
assert.Equal(t, param, "one long final parameter")
param, err = m.finalParameter()
assert.Error(t, err)
param = m.finalParameter()
assert.Equal(t, param, "")
})
@@ -199,6 +193,63 @@ func TestMessageParser(t *testing.T) {
}
}
func TestConfigDefinitionOneName(t *testing.T) {
var parsed string
var defaultValue = "abc"
configFoo := configDefinition{
names: []string{"foo"},
description: "The foo config is utterly useless.",
destination: &parsed,
defaultValue: &defaultValue,
}
assert.Equal(t, "foo",
configFoo.getCanonicalName())
assert.Equal(t,
configFoo.description,
configFoo.fullDescription())
}
func TestConfigDefinitionTwoNames(t *testing.T) {
var parsed string
var defaultValue = "abc"
configFoo := configDefinition{
names: []string{"foo", "bar"},
description: "The foo config is utterly useless.",
destination: &parsed,
defaultValue: &defaultValue,
}
assert.Equal(t, "foo",
configFoo.getCanonicalName())
assert.Equal(t,
"(synonyms: bar) The foo config is utterly useless.",
configFoo.fullDescription())
}
func TestConfigDefinitionThreeNames(t *testing.T) {
var parsed string
var defaultValue = "abc"
configFoo := configDefinition{
names: []string{"foo", "bar", "baz"},
description: "The foo config is utterly useless.",
destination: &parsed,
defaultValue: &defaultValue,
}
assert.Equal(t, "foo",
configFoo.getCanonicalName())
assert.Equal(t,
`(synonyms: bar, baz) The foo config is utterly useless.`,
configFoo.fullDescription())
}
type testState struct {
t *testing.T
server *server
@@ -231,6 +282,12 @@ func (h *testState) requireReadLineExact(line string) {
require.Equal(h.t, line+"\n", receivedLine)
}
func (h *testState) requireReadLine() string {
receivedLine, err := h.mockStdoutReader.ReadString('\n')
require.NoError(h.t, err)
return receivedLine
}
func (h *testState) requireWriteLine(line string) {
_, err := h.mockStdinW.Write([]byte(line + "\n"))
require.NoError(h.t, err)
@@ -241,6 +298,7 @@ func (h *testState) requireWriteLine(line string) {
func (h *testState) preconfigureServer() {
h.server.configPrefix = h.localFsDir
h.server.configRcloneRemoteName = h.remoteName
h.server.configRcloneLayout = string(layoutModeNodir)
h.server.configsDone = true
}
@@ -275,6 +333,34 @@ var localBackendTestCases = []testCase{
require.NoError(t, h.mockStdinW.Close())
},
},
{
label: "HandlesListConfigs",
testProtocolFunc: func(t *testing.T, h *testState) {
h.preconfigureServer()
h.requireReadLineExact("VERSION 1")
h.requireWriteLine("INITREMOTE")
h.requireReadLineExact("INITREMOTE-SUCCESS")
h.requireWriteLine("LISTCONFIGS")
require.Regexp(t,
regexp.MustCompile(`^CONFIG rcloneremotename \(synonyms: target\) (.|\n)*$`),
h.requireReadLine(),
)
require.Regexp(t,
regexp.MustCompile(`^CONFIG rcloneprefix \(synonyms: prefix\) (.|\n)*$`),
h.requireReadLine(),
)
require.Regexp(t,
regexp.MustCompile(`^CONFIG rclonelayout \(synonyms: rclone_layout\) (.|\n)*$`),
h.requireReadLine(),
)
h.requireReadLineExact("CONFIGEND")
require.NoError(t, h.mockStdinW.Close())
},
},
{
label: "HandlesPrepare",
testProtocolFunc: func(t *testing.T, h *testState) {
@@ -292,6 +378,40 @@ var localBackendTestCases = []testCase{
h.requireWriteLine("VALUE " + h.remoteName)
h.requireReadLineExact("GETCONFIG rcloneprefix")
h.requireWriteLine("VALUE " + h.localFsDir)
h.requireReadLineExact("GETCONFIG rclonelayout")
h.requireWriteLine("VALUE foo")
h.requireReadLineExact("PREPARE-SUCCESS")
require.Equal(t, h.server.configRcloneRemoteName, h.remoteName)
require.Equal(t, h.server.configPrefix, h.localFsDir)
require.True(t, h.server.configsDone)
require.NoError(t, h.mockStdinW.Close())
},
},
{
label: "HandlesPrepareWithSynonyms",
testProtocolFunc: func(t *testing.T, h *testState) {
h.requireReadLineExact("VERSION 1")
h.requireWriteLine("EXTENSIONS INFO") // Advertise that we support the INFO extension
h.requireReadLineExact("EXTENSIONS")
if !h.server.extensionInfo {
t.Errorf("expected INFO extension to be enabled")
return
}
h.requireWriteLine("PREPARE")
h.requireReadLineExact("GETCONFIG rcloneremotename")
// TODO check what git-annex does when asked for a config value it does not have.
h.requireWriteLine("VALUE")
h.requireReadLineExact("GETCONFIG target")
h.requireWriteLine("VALUE " + h.remoteName)
h.requireReadLineExact("GETCONFIG rcloneprefix")
h.requireWriteLine("VALUE " + h.localFsDir)
h.requireReadLineExact("GETCONFIG rclonelayout")
h.requireWriteLine("VALUE foo")
h.requireReadLineExact("PREPARE-SUCCESS")
require.Equal(t, h.server.configRcloneRemoteName, h.remoteName)
@@ -320,9 +440,15 @@ var localBackendTestCases = []testCase{
localFsDirWithSpaces := fmt.Sprintf(" %s\t", h.localFsDir)
h.requireWriteLine(fmt.Sprintf("VALUE %s", remoteNameWithSpaces))
h.requireReadLineExact("GETCONFIG rcloneprefix")
h.requireReadLineExact("GETCONFIG rcloneprefix")
h.requireWriteLine(fmt.Sprintf("VALUE %s", localFsDirWithSpaces))
h.requireReadLineExact("GETCONFIG rclonelayout")
h.requireWriteLine("VALUE")
h.requireReadLineExact("GETCONFIG rclone_layout")
h.requireWriteLine("VALUE")
h.requireReadLineExact("PREPARE-SUCCESS")
require.Equal(t, h.server.configRcloneRemoteName, remoteNameWithSpaces)
@@ -374,11 +500,11 @@ var localBackendTestCases = []testCase{
// Note the whitespace following the key.
h.requireWriteLine("TRANSFER STORE Key ")
h.requireReadLineExact("TRANSFER-FAILURE failed to parse file")
h.requireReadLineExact("TRANSFER-FAILURE failed to parse file path")
require.NoError(t, h.mockStdinW.Close())
},
expectedError: "malformed arguments for TRANSFER: nothing remains to parse",
expectedError: "failed to parse file",
},
// Repeated EXTENSIONS messages add to each other rather than overriding
// prior advertised extensions. This behavior is not mandated by the
+72
View File
@@ -0,0 +1,72 @@
package gitannex
import (
"fmt"
"strings"
)
type layoutMode string
// All layout modes from git-annex-remote-rclone are supported.
const (
layoutModeLower layoutMode = "lower"
layoutModeDirectory layoutMode = "directory"
layoutModeNodir layoutMode = "nodir"
layoutModeMixed layoutMode = "mixed"
layoutModeFrankencase layoutMode = "frankencase"
layoutModeUnknown layoutMode = ""
)
func allLayoutModes() []layoutMode {
return []layoutMode{
layoutModeLower,
layoutModeDirectory,
layoutModeNodir,
layoutModeMixed,
layoutModeFrankencase,
}
}
func parseLayoutMode(mode string) layoutMode {
for _, knownMode := range allLayoutModes() {
if mode == string(knownMode) {
return knownMode
}
}
return layoutModeUnknown
}
type queryDirhashFunc func(msg string) (string, error)
func buildFsString(queryDirhash queryDirhashFunc, mode layoutMode, key, remoteName, prefix string) (string, error) {
if mode == layoutModeNodir {
return fmt.Sprintf("%s:%s", remoteName, prefix), nil
}
var dirhash string
var err error
switch mode {
case layoutModeLower, layoutModeDirectory:
dirhash, err = queryDirhash("DIRHASH-LOWER " + key)
case layoutModeMixed, layoutModeFrankencase:
dirhash, err = queryDirhash("DIRHASH " + key)
default:
panic("unreachable")
}
if err != nil {
return "", fmt.Errorf("buildFsString failed to query dirhash: %w", err)
}
switch mode {
case layoutModeLower:
return fmt.Sprintf("%s:%s/%s", remoteName, prefix, dirhash), nil
case layoutModeDirectory:
return fmt.Sprintf("%s:%s/%s%s", remoteName, prefix, dirhash, key), nil
case layoutModeMixed:
return fmt.Sprintf("%s:%s/%s", remoteName, prefix, dirhash), nil
case layoutModeFrankencase:
return fmt.Sprintf("%s:%s/%s", remoteName, prefix, strings.ToLower(dirhash)), nil
default:
panic("unreachable")
}
}
+4 -1
View File
@@ -289,7 +289,10 @@ func (cds *contentDirectoryService) Handle(action string, argsXML []byte, r *htt
return nil, err
}
return map[string]string{
"Result": didlLite(string(result)),
"TotalMatches": "1",
"NumberReturned": "1",
"Result": didlLite(string(result)),
"UpdateID": cds.updateIDString(),
}, nil
default:
return nil, upnp.Errorf(upnp.ArgumentValueInvalidErrorCode, "unhandled browse flag: %v", browse.BrowseFlag)
+1 -1
View File
@@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
#
# Test all the remotes against restic integration test
# Run with: screen -S restic-test -L ./restic-test.sh
+13
View File
@@ -213,6 +213,14 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
}, nil
}
// storeModtime sets both "mtime" and "X-Amz-Meta-Mtime" to val in b.meta.
// Call this whenever modtime is updated.
func (b *s3Backend) storeModtime(fp string, meta map[string]string, val string) {
meta["X-Amz-Meta-Mtime"] = val
meta["mtime"] = val
b.meta.Store(fp, meta)
}
// TouchObject creates or updates meta on specified object.
func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]string) (result gofakes3.PutObjectResult, err error) {
_, err = b.vfs.Stat(fp)
@@ -237,6 +245,7 @@ func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]
if val, ok := meta["X-Amz-Meta-Mtime"]; ok {
ti, err := swift.FloatStringToTime(val)
if err == nil {
b.storeModtime(fp, meta, val)
return result, b.vfs.Chtimes(fp, ti, ti)
}
// ignore error since the file is successfully created
@@ -245,6 +254,7 @@ func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]
if val, ok := meta["mtime"]; ok {
ti, err := swift.FloatStringToTime(val)
if err == nil {
b.storeModtime(fp, meta, val)
return result, b.vfs.Chtimes(fp, ti, ti)
}
// ignore error since the file is successfully created
@@ -307,6 +317,7 @@ func (b *s3Backend) PutObject(
if val, ok := meta["X-Amz-Meta-Mtime"]; ok {
ti, err := swift.FloatStringToTime(val)
if err == nil {
b.storeModtime(fp, meta, val)
return result, b.vfs.Chtimes(fp, ti, ti)
}
// ignore error since the file is successfully created
@@ -315,6 +326,7 @@ func (b *s3Backend) PutObject(
if val, ok := meta["mtime"]; ok {
ti, err := swift.FloatStringToTime(val)
if err == nil {
b.storeModtime(fp, meta, val)
return result, b.vfs.Chtimes(fp, ti, ti)
}
// ignore error since the file is successfully created
@@ -425,6 +437,7 @@ func (b *s3Backend) CopyObject(ctx context.Context, srcBucket, srcKey, dstBucket
if err != nil {
return result, nil
}
b.storeModtime(fp, meta, val)
return result, b.vfs.Chtimes(fp, ti, ti)
}
+6 -1
View File
@@ -139,7 +139,12 @@ func Touch(ctx context.Context, f fs.Fs, remote string) error {
return err
}
fs.Debugf(nil, "Touch time %v", t)
file, err := f.NewObject(ctx, remote)
var file fs.Object
if remote == "" {
err = fs.ErrorIsDir
} else {
file, err = f.NewObject(ctx, remote)
}
if err != nil {
if errors.Is(err, fs.ErrorObjectNotFound) {
// Touching non-existent path, possibly creating it as new file
+1 -2
View File
@@ -9,8 +9,7 @@
"description": "rclone - rsync for cloud storage: google drive, s3, gcs, azure, dropbox, box...",
"canonifyurls": false,
"disableKinds": [
"taxonomy",
"taxonomyTerm"
"taxonomy"
],
"ignoreFiles": [
"~$",
+2 -1
View File
@@ -109,7 +109,7 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Akamai Netstorage" home="https://www.akamai.com/us/en/products/media-delivery/netstorage.jsp" config="/netstorage/" >}}
{{< provider name="Alibaba Cloud (Aliyun) Object Storage System (OSS)" home="https://www.alibabacloud.com/product/oss/" config="/s3/#alibaba-oss" >}}
{{< provider name="Amazon S3" home="https://aws.amazon.com/s3/" config="/s3/" >}}
{{< provider name="Backblaze B2" home="https://www.backblaze.com/b2/cloud-storage.html" config="/b2/" >}}
{{< provider name="Backblaze B2" home="https://www.backblaze.com/cloud-storage" config="/b2/" >}}
{{< provider name="Box" home="https://www.box.com/" config="/box/" >}}
{{< provider name="Ceph" home="http://ceph.com/" config="/s3/#ceph" >}}
{{< provider name="China Mobile Ecloud Elastic Object Storage (EOS)" home="https://ecloud.10086.cn/home/product-introduction/eos/" config="/s3/#china-mobile-ecloud-eos" >}}
@@ -141,6 +141,7 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Liara Object Storage" home="https://liara.ir/landing/object-storage" config="/s3/#liara-object-storage" >}}
{{< provider name="Linkbox" home="https://linkbox.to/" config="/linkbox/" >}}
{{< provider name="Linode Object Storage" home="https://www.linode.com/products/object-storage/" config="/s3/#linode" >}}
{{< provider name="Magalu" home="https://magalu.cloud/object-storage/" config="/s3/#magalu" >}}
{{< provider name="Mail.ru Cloud" home="https://cloud.mail.ru/" config="/mailru/" >}}
{{< provider name="Memset Memstore" home="https://www.memset.com/cloud/storage/" config="/swift/" >}}
{{< provider name="Mega" home="https://mega.nz/" config="/mega/" >}}
+1 -1
View File
@@ -118,7 +118,7 @@ Here are the Advanced options specific to alias (Alias for an existing remote).
#### --alias-description
Description of the remote
Description of the remote.
Properties:
+14
View File
@@ -851,3 +851,17 @@ put them back in again.` >}}
* Katia Esposito <katia@linux.com>
* pawsey-kbuckley <36438302+pawsey-kbuckley@users.noreply.github.com>
* hidewrong <167099254+hidewrong@users.noreply.github.com>
* Michael Terry <mike@mterry.name>
* Sunny <25066078+LoSunny@users.noreply.github.com>
* overallteach <cricis@foxmail.com>
* JT Olio <jt@olio.lol>
* Evan McBeth <64177332+AtomicRobotMan0101@users.noreply.github.com>
* Dominik Joe Pantůček <dominik.pantucek@trustica.cz>
* yumeiyin <155420652+yumeiyin@users.noreply.github.com>
* Bruno Fernandes <54373093+folkzb@users.noreply.github.com>
* Thomas Schneider <tspam.github@brainfuck.space>
* Charles Hamilton <52973156+chamilton-ccn@users.noreply.github.com>
* Tomasz Melcer <tomasz@melcer.pl>
* Michał Dzienisiewicz <michal.piotr.dz@gmail.com>
* Florian Klink <flokli@flokli.de>
* Bill Fraser <bill@wfraser.dev>
+1 -1
View File
@@ -851,7 +851,7 @@ Properties:
#### --azureblob-description
Description of the remote
Description of the remote.
Properties:
+1 -1
View File
@@ -689,7 +689,7 @@ Properties:
#### --azurefiles-description
Description of the remote
Description of the remote.
Properties:
+5 -5
View File
@@ -6,7 +6,7 @@ versionIntroduced: "v1.26"
# {{< icon "fa fa-fire" >}} Backblaze B2
B2 is [Backblaze's cloud storage system](https://www.backblaze.com/b2/).
B2 is [Backblaze's cloud storage system](https://www.backblaze.com/cloud-storage).
Paths are specified as `remote:bucket` (or `remote:` for the `lsd`
command.) You may put subdirectories in too, e.g. `remote:bucket/path/to/dir`.
@@ -77,7 +77,7 @@ excess files in the bucket.
### Application Keys
B2 supports multiple [Application Keys for different access permission
to B2 Buckets](https://www.backblaze.com/b2/docs/application_keys.html).
to B2 Buckets](https://www.backblaze.com/docs/cloud-storage-application-keys).
You can use these with rclone too; you will need to use rclone version 1.43
or later.
@@ -165,7 +165,7 @@ used.
### Versions
When rclone uploads a new version of a file it creates a [new version
of it](https://www.backblaze.com/b2/docs/file_versions.html).
of it](https://www.backblaze.com/docs/cloud-storage-file-versions).
Likewise when you delete a file, the old version will be marked hidden
and still be available. Conversely, you may opt in to a "hard delete"
of files with the `--b2-hard-delete` flag which would permanently remove
@@ -416,7 +416,7 @@ below will cause b2 to return specific errors:
* "force_cap_exceeded"
These will be set in the "X-Bz-Test-Mode" header which is documented
in the [b2 integrations checklist](https://www.backblaze.com/b2/docs/integration_checklist.html).
in the [b2 integrations checklist](https://www.backblaze.com/docs/cloud-storage-integration-checklist).
Properties:
@@ -647,7 +647,7 @@ Properties:
#### --b2-description
Description of the remote
Description of the remote.
Properties:
+1 -1
View File
@@ -475,7 +475,7 @@ Properties:
#### --box-description
Description of the remote
Description of the remote.
Properties:
+1 -1
View File
@@ -666,7 +666,7 @@ Properties:
#### --cache-description
Description of the remote
Description of the remote.
Properties:
+153
View File
@@ -5,6 +5,159 @@ description: "Rclone Changelog"
# Changelog
## v1.67.0 - 2024-06-14
[See commits](https://github.com/rclone/rclone/compare/v1.66.0...v1.67.0)
* New backends
* [uloz.to](/ulozto/) (iotmaestro)
* New S3 providers
* [Magalu Object Storage](/s3/#magalu) (Bruno Fernandes)
* New commands
* [gitannex](/commands/rclone_gitannex/): Enables git-annex to store and retrieve content from an rclone remote (Dan McArdle)
* New Features
* accounting: Add deleted files total size to status summary line (Kyle Reynolds)
* build
* Fix `CVE-2023-45288` by upgrading `golang.org/x/net` (Nick Craig-Wood)
* Fix `CVE-2024-35255` by upgrading `github.com/Azure/azure-sdk-for-go/sdk/azidentity` to 1.6.0 (dependabot)
* Convert source files with CRLF to LF (albertony)
* Update all dependencies (Nick Craig-Wood)
* doc updates (albertony, Alex Garel, Dave Nicolson, Dominik Joe Pantůček, Eric Wolf, Erisa A, Evan Harris, Evan McBeth, Gachoud Philippe, hidewrong, jakzoe, jumbi77, kapitainsky, Kyle Reynolds, Lewis Hook, Nick Craig-Wood, overallteach, pawsey-kbuckley, Pieter van Oostrum, psychopatt, racerole, static-moonlight, Warrentheo, yudrywet, yumeiyin )
* ncdu: Do not quit on Esc to aid usability (Katia Esposito)
* rcserver: Set `ModTime` for dirs and files served by `--rc-serve` (Nikita Shoshin)
* Bug Fixes
* bisync: Add integration tests against all backends and fix many many problems (nielash)
* config: Fix default value for `description` (Nick Craig-Wood)
* copy: Fix `nil` pointer dereference when corrupted on transfer with `nil` dst (nielash)
* fs
* Improve JSON Unmarshalling for `Duration` types (Kyle Reynolds)
* Close the CPU profile on exit (guangwu)
* Replace `/bin/bash` with `/usr/bin/env bash` (Florian Klink)
* oauthutil: Clear client secret if client ID is set (Michael Terry)
* operations
* Rework `rcat` so that it doesn't call the `--metadata-mapper` twice (Nick Craig-Wood)
* Ensure `SrcFsType` is set correctly when using `--metadata-mapper` (Nick Craig-Wood)
* Fix "optional feature not implemented" error with a crypted sftp bug (Nick Craig-Wood)
* Fix very long file names when using copy with `--partial` (Nick Craig-Wood)
* Fix retries downloading too much data with certain backends (Nick Craig-Wood)
* Fix move when dst is nil and fdst is case-insensitive (nielash)
* Fix lsjson `--encrypted` when using `--crypt-XXX` parameters (Nick Craig-Wood)
* Fix missing metadata for multipart transfers to local disk (Nick Craig-Wood)
* Fix incorrect modtime on some multipart transfers (Nick Craig-Wood)
* Fix hashing problem in integration tests (Nick Craig-Wood)
* rc
* Fix stats groups being ignored in `operations/check` (Nick Craig-Wood)
* Fix incorrect `Content-Type` in HTTP API (Kyle Reynolds)
* serve s3
* Fix `Last-Modified` header format (Butanediol)
* Fix in-memory metadata storing wrong modtime (nielash)
* Fix XML of error message (Nick Craig-Wood)
* serve webdav: Fix webdav with `--baseurl` under Windows (Nick Craig-Wood)
* serve dlna: Make `BrowseMetadata` more compliant (albertony)
* serve http: Added `Content-Length` header when HTML directory is served (Sunny)
* sync
* Don't sync directories if they haven't been modified (Nick Craig-Wood)
* Don't test reading metadata if we can't write it (Nick Craig-Wood)
* Fix case normalisation (problem on on s3) (Nick Craig-Wood)
* Fix management of empty directories to make it more accurate (Nick Craig-Wood)
* Fix creation of empty directories when `--create-empty-src-dirs=false` (Nick Craig-Wood)
* Fix directory modification times not being set (Nick Craig-Wood)
* Fix "failed to update directory timestamp or metadata: directory not found" (Nick Craig-Wood)
* Fix expecting SFTP to have MkdirMetadata method: optional feature not implemented (Nick Craig-Wood)
* test info: Improve cleanup of temp files (Kyle Reynolds)
* touch: Fix using `-R` on certain backends (Nick Craig-Wood)
* Mount
* Add `--direct-io` flag to force uncached access (Nick Craig-Wood)
* VFS
* Fix download loop when file size shrunk (Nick Craig-Wood)
* Fix renaming a directory (nielash)
* Local
* Add `--local-time-type` to use `mtime`/`atime`/`btime`/`ctime` as the time (Nick Craig-Wood)
* Allow `SeBackupPrivilege` and/or `SeRestorePrivilege` to work on Windows (Charles Hamilton)
* Azure Blob
* Fix encoding issue with dir path comparison (nielash)
* B2
* Add new [cleanup](/b2/#cleanup) and [cleanup-hidden](/b2/#cleanup-hidden) backend commands. (Pat Patterson)
* Update B2 URLs to new home (Nick Craig-Wood)
* Chunker
* Fix startup when root points to composite multi-chunk file without metadata (nielash)
* Fix case-insensitive comparison on local without metadata (nielash)
* Fix "finalizer already set" error (nielash)
* Drive
* Add [backend query](/drive/#query) command for general purpose querying of files (John-Paul Smith)
* Stop sending notification emails when setting permissions (Nick Craig-Wood)
* Fix server side copy with metadata from my drive to shared drive (Nick Craig-Wood)
* Set all metadata permissions and return error summary instead of stopping on the first error (Nick Craig-Wood)
* Make errors setting permissions into no retry errors (Nick Craig-Wood)
* Fix description being overwritten on server side moves (Nick Craig-Wood)
* Allow setting metadata to fail if `failok` flag is set (Nick Craig-Wood)
* Fix panic when using `--metadata-mapper` on large google doc files (Nick Craig-Wood)
* Dropbox
* Add `--dropbox-root-namespace` to override the root namespace (Bill Fraser)
* Google Cloud Storage
* Fix encoding issue with dir path comparison (nielash)
* Hdfs
* Fix f.String() not including subpath (nielash)
* Http
* Add `--http-no-escape` to not escape URL metacharacters in path names (Kyle Reynolds)
* Jottacloud
* Set metadata on server side copy and move (albertony)
* Linkbox
* Fix working with names longer than 8-25 Unicode chars. (Vitaly)
* Fix list paging and optimized synchronization. (gvitali)
* Mailru
* Attempt to fix throttling by increasing min sleep to 100ms (Nick Craig-Wood)
* Memory
* Fix dst mutating src after server-side copy (nielash)
* Fix deadlock in operations.Purge (nielash)
* Fix incorrect list entries when rooted at subdirectory (nielash)
* Onedrive
* Add `--onedrive-hard-delete` to permanently delete files (Nick Craig-Wood)
* Make server-side copy work in more scenarios (YukiUnHappy)
* Fix "unauthenticated: Unauthenticated" errors when downloading (Nick Craig-Wood)
* Fix `--metadata-mapper` being called twice if writing permissions (nielash)
* Set all metadata permissions and return error summary instead of stopping on the first error (nielash)
* Make errors setting permissions into no retry errors (Nick Craig-Wood)
* Skip writing permissions with 'owner' role (nielash)
* Fix references to deprecated permissions properties (nielash)
* Add support for group permissions (nielash)
* Allow setting permissions to fail if `failok` flag is set (Nick Craig-Wood)
* Pikpak
* Make getFile() usage more efficient to avoid the download limit (wiserain)
* Improve upload reliability and resolve potential file conflicts (wiserain)
* Implement configurable chunk size for multipart upload (wiserain)
* Protondrive
* Don't auth with an empty access token (Michał Dzienisiewicz)
* Qingstor
* Disable integration tests as test account suspended (Nick Craig-Wood)
* Quatrix
* Fix f.String() not including subpath (nielash)
* S3
* Add new AWS region `il-central-1` Tel Aviv (yoelvini)
* Update Scaleway's configuration options (Alexandre Lavigne)
* Ceph: fix quirks when creating buckets to fix trying to create an existing bucket (Thomas Schneider)
* Fix encoding issue with dir path comparison (nielash)
* Fix 405 error on HEAD for delete marker with versionId (nielash)
* Validate `--s3-copy-cutoff` size before copy (hoyho)
* SFTP
* Add `--sftp-connections` to limit the maximum number of connections (Tomasz Melcer)
* Storj
* Update `storj.io/uplink` to latest release (JT Olio)
* Update bio on request (Nick Craig-Wood)
* Swift
* Implement `--swift-use-segments-container` to allow >5G files on Blomp (Nick Craig-Wood)
* Union
* Fix deleting dirs when all remotes can't have empty dirs (Nick Craig-Wood)
* WebDAV
* Fix setting modification times erasing checksums on owncloud and nextcloud (nielash)
* owncloud: Add `--webdav-owncloud-exclude-mounts` which allows excluding mounted folders when listing remote resources (Thomas Müller)
* Zoho
* Fix throttling problem when uploading files (Nick Craig-Wood)
* Use cursor listing for improved performance (Nick Craig-Wood)
* Retry reading info after upload if size wasn't returned (Nick Craig-Wood)
* Remove simple file names complication which is no longer needed (Nick Craig-Wood)
* Sleep for 60 seconds if rate limit error received (Nick Craig-Wood)
## v1.66.0 - 2024-03-10
[See commits](https://github.com/rclone/rclone/compare/v1.65.0...v1.66.0)
+1 -1
View File
@@ -479,7 +479,7 @@ Properties:
#### --chunker-description
Description of the remote
Description of the remote.
Properties:
+1 -1
View File
@@ -160,7 +160,7 @@ Here are the Advanced options specific to combine (Combine several remotes into
#### --combine-description
Description of the remote
Description of the remote.
Properties:
+21 -3
View File
@@ -257,6 +257,7 @@ rclone [flags]
--dropbox-encoding Encoding The encoding for the backend (default Slash,BackSlash,Del,RightSpace,InvalidUtf8,Dot)
--dropbox-impersonate string Impersonate this user when using a business account
--dropbox-pacer-min-sleep Duration Minimum time to sleep between API calls (default 10ms)
--dropbox-root-namespace string Specify a different Dropbox namespace ID to use as the root for all paths
--dropbox-shared-files Instructs rclone to work on individual shared files
--dropbox-shared-folders Instructs rclone to work on shared folders
--dropbox-token string OAuth Access Token as a JSON blob
@@ -384,6 +385,7 @@ rclone [flags]
--hidrive-upload-cutoff SizeSuffix Cutoff/Threshold for chunked uploads (default 96Mi)
--http-description string Description of the remote
--http-headers CommaSepList Set HTTP headers for all transactions
--http-no-escape Do not escape URL metacharacters in path names
--http-no-head Don't use HEAD requests
--http-no-slash Set this if the site doesn't end directories with /
--http-url string URL of HTTP host to connect to
@@ -432,7 +434,7 @@ rclone [flags]
--koofr-encoding Encoding The encoding for the backend (default Slash,BackSlash,Del,Ctl,InvalidUtf8,Dot)
--koofr-endpoint string The Koofr API endpoint to use
--koofr-mountid string Mount ID of the mount to use
--koofr-password string Your password for rclone (generate one at https://app.koofr.net/app/admin/preferences/password) (obscured)
--koofr-password string Your password for rclone generate one at https://app.koofr.net/app/admin/preferences/password (obscured)
--koofr-provider string Choose your storage provider
--koofr-setmtime Does the backend support setting modification time (default true)
--koofr-user string Your user name
@@ -449,6 +451,7 @@ rclone [flags]
--local-no-set-modtime Disable setting modtime
--local-no-sparse Disable sparse files for multi-thread downloads
--local-nounc Disable UNC (long path names) conversion on Windows
--local-time-type mtime|atime|btime|ctime Set what kind of time is returned (default mtime)
--local-unicode-normalization Apply unicode NFC normalization to paths and filenames
--local-zero-size-links Assume the Stat size of links is zero (and read them instead) (deprecated)
--log-file string Log everything to this file
@@ -530,6 +533,7 @@ rclone [flags]
--onedrive-drive-type string The type of the drive (personal | business | documentLibrary)
--onedrive-encoding Encoding The encoding for the backend (default Slash,LtGt,DoubleQuote,Colon,Question,Asterisk,Pipe,BackSlash,Del,Ctl,LeftSpace,LeftTilde,RightSpace,RightPeriod,InvalidUtf8,Dot)
--onedrive-expose-onenote-files Set to make OneNote files show up in directory listings
--onedrive-hard-delete Permanently delete files on removal
--onedrive-hash-type string Specify the hash in use for the backend (default "auto")
--onedrive-link-password string Set the password for links created by the link command
--onedrive-link-scope string Set the scope of the links created by the link command (default "anonymous")
@@ -587,6 +591,7 @@ rclone [flags]
--pcloud-token-url string Token server url
--pcloud-username string Your pcloud username
--pikpak-auth-url string Auth server URL
--pikpak-chunk-size SizeSuffix Chunk size for multipart uploads (default 5Mi)
--pikpak-client-id string OAuth Client Id
--pikpak-client-secret string OAuth Client Secret
--pikpak-description string Description of the remote
@@ -597,6 +602,7 @@ rclone [flags]
--pikpak-token string OAuth Access Token as a JSON blob
--pikpak-token-url string Token server url
--pikpak-trashed-only Only show files that are in the trash
--pikpak-upload-concurrency int Concurrency for multipart uploads (default 5)
--pikpak-use-trash Send files to the trash instead of deleting permanently (default true)
--pikpak-user string Pikpak username
--premiumizeme-auth-url string Auth server URL
@@ -665,6 +671,7 @@ rclone [flags]
--rc-realm string Realm for authentication
--rc-salt string Password hashing salt (default "dlPL2MqE")
--rc-serve Enable the serving of remote objects
--rc-serve-no-modtime Don't read the modification time (can speed things up)
--rc-server-read-timeout Duration Timeout for server reading data (default 1h0m0s)
--rc-server-write-timeout Duration Timeout for server writing data (default 1h0m0s)
--rc-template string User-specified template
@@ -745,6 +752,7 @@ rclone [flags]
--sftp-chunk-size SizeSuffix Upload and download chunk size (default 32Ki)
--sftp-ciphers SpaceSepList Space separated list of ciphers to be used for session encryption, ordered by preference
--sftp-concurrency int The maximum number of outstanding requests for one file (default 64)
--sftp-connections int Maximum number of SFTP simultaneous connections, 0 for unlimited
--sftp-copy-is-hardlink Set to enable server side copies using hardlinks
--sftp-description string Description of the remote
--sftp-disable-concurrent-reads If set don't use concurrent reads
@@ -840,7 +848,7 @@ rclone [flags]
--swift-auth string Authentication URL for server (OS_AUTH_URL)
--swift-auth-token string Auth Token from alternate authentication - optional (OS_AUTH_TOKEN)
--swift-auth-version int AuthVersion - optional - set to (1,2,3) if your auth URL has no version (ST_AUTH_VERSION)
--swift-chunk-size SizeSuffix Above this size files will be chunked into a _segments container (default 5Gi)
--swift-chunk-size SizeSuffix Above this size files will be chunked (default 5Gi)
--swift-description string Description of the remote
--swift-domain string User domain - optional (v3 auth) (OS_USER_DOMAIN_NAME)
--swift-encoding Encoding The encoding for the backend (default Slash,InvalidUtf8)
@@ -856,6 +864,7 @@ rclone [flags]
--swift-tenant string Tenant name - optional for v1 auth, this or tenant_id required otherwise (OS_TENANT_NAME or OS_PROJECT_NAME)
--swift-tenant-domain string Tenant domain - optional (v3 auth) (OS_PROJECT_DOMAIN_NAME)
--swift-tenant-id string Tenant ID - optional for v1 auth, this or tenant required otherwise (OS_TENANT_ID)
--swift-use-segments-container Tristate Choose destination for large object segments (default unset)
--swift-user string User name to log in (OS_USERNAME)
--swift-user-id string User ID to log in - optional - most swift systems use user and leave this blank (v3 auth) (OS_USER_ID)
--syslog Use Syslog for logging
@@ -867,6 +876,13 @@ rclone [flags]
--track-renames When synchronizing, track file renames and do a server-side move if possible
--track-renames-strategy string Strategies to use when synchronizing using track-renames hash|modtime|leaf (default "hash")
--transfers int Number of file transfers to run in parallel (default 4)
--ulozto-app-token string The application token identifying the app. An app API key can be either found in the API
--ulozto-description string Description of the remote
--ulozto-encoding Encoding The encoding for the backend (default Slash,BackSlash,Del,Ctl,InvalidUtf8,Dot)
--ulozto-list-page-size int The size of a single page for list commands. 1-500 (default 500)
--ulozto-password string The password for the user (obscured)
--ulozto-root-folder-slug string If set, rclone will use this folder as the root folder for all operations. For example,
--ulozto-username string The username of the principal to operate as
--union-action-policy string Policy to choose upstream on ACTION category (default "epall")
--union-cache-time int Cache time of usage and free space (in seconds) (default 120)
--union-create-policy string Policy to choose upstream on CREATE category (default "epmfs")
@@ -883,7 +899,7 @@ rclone [flags]
--use-json-log Use json log format
--use-mmap Use mmap allocator (see docs)
--use-server-modtime Use server modified time instead of object metadata
--user-agent string Set the user-agent to a specified string (default "rclone/v1.66.0")
--user-agent string Set the user-agent to a specified string (default "rclone/v1.67.0")
-v, --verbose count Print lots more stuff (repeat for more)
-V, --version Print the version number
--webdav-bearer-token string Bearer token instead of user/pass (e.g. a Macaroon)
@@ -892,6 +908,7 @@ rclone [flags]
--webdav-encoding string The encoding for the backend
--webdav-headers CommaSepList Set HTTP headers for all transactions
--webdav-nextcloud-chunk-size SizeSuffix Nextcloud upload chunk size (default 10Mi)
--webdav-owncloud-exclude-mounts Exclude ownCloud mounted storages
--webdav-owncloud-exclude-shares Exclude ownCloud shares
--webdav-pacer-min-sleep Duration Minimum time to sleep between API calls (default 10ms)
--webdav-pass string Password (obscured)
@@ -937,6 +954,7 @@ rclone [flags]
* [rclone delete](/commands/rclone_delete/) - Remove the files in path.
* [rclone deletefile](/commands/rclone_deletefile/) - Remove a single file from remote.
* [rclone gendocs](/commands/rclone_gendocs/) - Output markdown docs for rclone to the directory supplied.
* [rclone gitannex](/commands/rclone_gitannex/) - Speaks with git-annex over stdin/stdout.
* [rclone hashsum](/commands/rclone_hashsum/) - Produces a hashsum file for all the objects in the path.
* [rclone link](/commands/rclone_link/) - Generate public link to file/folder.
* [rclone listremotes](/commands/rclone_listremotes/) - List all the remotes in the config file and defined in environment variables.
@@ -14,21 +14,32 @@ Output bash completion script for rclone.
Generates a bash shell autocompletion script for rclone.
This writes to /etc/bash_completion.d/rclone by default so will
probably need to be run with sudo or as root, e.g.
By default, when run without any arguments,
sudo rclone genautocomplete bash
rclone genautocomplete bash
Logout and login again to use the autocompletion scripts, or source
them directly
the generated script will be written to
. /etc/bash_completion
/etc/bash_completion.d/rclone
If you supply a command line argument the script will be written
there.
and so rclone will probably need to be run as root, or with sudo.
If you supply a path to a file as the command line argument, then
the generated script will be written to that file, in which case
you should not need root privileges.
If output_file is "-", then the output will be written to stdout.
If you have installed the script into the default location, you
can logout and login again to use the autocompletion script.
Alternatively, you can source the script directly
. /path/to/my_bash_completion_scripts/rclone
and the autocompletion functionality will be added to your
current shell.
```
rclone completion bash [output_file] [flags]
+102
View File
@@ -0,0 +1,102 @@
---
title: "rclone gitannex"
description: "Speaks with git-annex over stdin/stdout."
slug: rclone_gitannex
url: /commands/rclone_gitannex/
versionIntroduced: v1.67.0
# autogenerated - DO NOT EDIT, instead edit the source code in cmd/gitannex/ and as part of making a release run "make commanddocs"
---
# rclone gitannex
Speaks with git-annex over stdin/stdout.
## Synopsis
Rclone's `gitannex` subcommand enables [git-annex] to store and retrieve content
from an rclone remote. It is meant to be run by git-annex, not directly by
users.
[git-annex]: https://git-annex.branchable.com/
Installation on Linux
---------------------
1. Skip this step if your version of git-annex is [10.20240430] or newer.
Otherwise, you must create a symlink somewhere on your PATH with a particular
name. This symlink helps git-annex tell rclone it wants to run the "gitannex"
subcommand.
```sh
# Create the helper symlink in "$HOME/bin".
ln -s "$(realpath rclone)" "$HOME/bin/git-annex-remote-rclone-builtin"
# Verify the new symlink is on your PATH.
which git-annex-remote-rclone-builtin
```
[10.20240430]: https://git-annex.branchable.com/news/version_10.20240430/
2. Add a new remote to your git-annex repo. This new remote will connect
git-annex with the `rclone gitannex` subcommand.
Start by asking git-annex to describe the remote's available configuration
parameters.
```sh
# If you skipped step 1:
git annex initremote MyRemote type=rclone --whatelse
# If you created a symlink in step 1:
git annex initremote MyRemote type=external externaltype=rclone-builtin --whatelse
```
> **NOTE**: If you're porting an existing [git-annex-remote-rclone] remote to
> use `rclone gitannex`, you can probably reuse the configuration parameters
> verbatim without renaming them. Check parameter synonyms with `--whatelse`
> as shown above.
>
> [git-annex-remote-rclone]: https://github.com/git-annex-remote-rclone/git-annex-remote-rclone
The following example creates a new git-annex remote named "MyRemote" that
will use the rclone remote named "SomeRcloneRemote". That rclone remote must
be one configured in your rclone.conf file, which can be located with `rclone
config file`.
```sh
git annex initremote MyRemote \
type=external \
externaltype=rclone-builtin \
encryption=none \
rcloneremotename=SomeRcloneRemote \
rcloneprefix=git-annex-content \
rclonelayout=nodir
```
3. Before you trust this command with your precious data, be sure to **test the
remote**. This command is very new and has not been tested on many rclone
backends. Caveat emptor!
```sh
git annex testremote MyRemote
```
Happy annexing!
```
rclone gitannex [flags]
```
## Options
```
-h, --help help for gitannex
```
See the [global flags page](/flags/) for global options not listed here.
# SEE ALSO
* [rclone](/commands/rclone/) - Show help for rclone commands, flags and backends.
+2 -2
View File
@@ -37,7 +37,7 @@ The output is an array of Items, where each Item looks like this
"Tier" : "hot",
}
If `--hash` is not specified the Hashes property won't be emitted. The
If `--hash` is not specified, the Hashes property will be omitted. The
types of hash can be specified with the `--hash-type` parameter (which
may be repeated). If `--hash-type` is set then it implies `--hash`.
@@ -49,7 +49,7 @@ If `--no-mimetype` is specified then MimeType will be blank. This can
speed things up on remotes where reading the MimeType takes an extra
request (e.g. s3, swift).
If `--encrypted` is not specified the Encrypted won't be emitted.
If `--encrypted` is not specified the Encrypted will be omitted.
If `--dirs-only` is not specified files in addition to directories are
returned
+4 -3
View File
@@ -13,9 +13,8 @@ Mount the remote as file system on a mountpoint.
## Synopsis
rclone mount allows Linux, FreeBSD, macOS and Windows to
mount any of Rclone's cloud storage systems as a file system with
FUSE.
Rclone mount allows Linux, FreeBSD, macOS and Windows to
mount any of Rclone's cloud storage systems as a file system with FUSE.
First set up your remote using `rclone config`. Check it works with `rclone ls` etc.
@@ -830,6 +829,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone mount remote:path /path/to/mountpoint [flags]
```
@@ -850,6 +850,7 @@ rclone mount remote:path /path/to/mountpoint [flags]
--devname string Set the device name - default is remote:path
--dir-cache-time Duration Time to cache directory entries for (default 5m0s)
--dir-perms FileMode Directory permissions (default 0777)
--direct-io Use Direct IO, disables caching of data
--file-perms FileMode File permissions (default 0666)
--fuse-flag stringArray Flags or arguments to be passed direct to libfuse/WinFsp (repeat if required)
--gid uint32 Override the gid field set by the filesystem (not supported on Windows) (default 1000)
+2 -1
View File
@@ -46,7 +46,8 @@ press '?' to toggle the help on and off. The supported keys are:
^L refresh screen (fix screen corruption)
r recalculate file sizes
? to toggle help on and off
q/ESC/^c to quit
ESC to close the menu box
q/^c to quit
Listed files/directories may be prefixed by a one-character flag,
some of them combined with a description in brackets at end of line.
+4 -3
View File
@@ -14,9 +14,8 @@ Mount the remote as file system on a mountpoint.
## Synopsis
rclone nfsmount allows Linux, FreeBSD, macOS and Windows to
mount any of Rclone's cloud storage systems as a file system with
FUSE.
Rclone nfsmount allows Linux, FreeBSD, macOS and Windows to
mount any of Rclone's cloud storage systems as a file system with FUSE.
First set up your remote using `rclone config`. Check it works with `rclone ls` etc.
@@ -831,6 +830,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone nfsmount remote:path /path/to/mountpoint [flags]
```
@@ -852,6 +852,7 @@ rclone nfsmount remote:path /path/to/mountpoint [flags]
--devname string Set the device name - default is remote:path
--dir-cache-time Duration Time to cache directory entries for (default 5m0s)
--dir-perms FileMode Directory permissions (default 0777)
--direct-io Use Direct IO, disables caching of data
--file-perms FileMode File permissions (default 0666)
--fuse-flag stringArray Flags or arguments to be passed direct to libfuse/WinFsp (repeat if required)
--gid uint32 Override the gid field set by the filesystem (not supported on Windows) (default 1000)
+3 -2
View File
@@ -13,7 +13,6 @@ Run rclone listening to remote control commands only.
## Synopsis
This runs rclone so that it only listens to remote control commands.
This is useful if you are controlling rclone via the rc API.
@@ -67,7 +66,7 @@ of that with the CA certificate. `--krc-ey` should be the PEM encoded
private key and `--rc-client-ca` should be the PEM encoded client
certificate authority certificate.
--rc-min-tls-version is minimum TLS version that is acceptable. Valid
`--rc-min-tls-version` is minimum TLS version that is acceptable. Valid
values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
"tls1.0").
@@ -135,6 +134,7 @@ Use `--rc-realm` to set the authentication realm.
Use `--rc-salt` to change the password hashing salt from the default.
```
rclone rcd <path to files to serve>* [flags]
```
@@ -170,6 +170,7 @@ Flags to control the Remote Control API.
--rc-realm string Realm for authentication
--rc-salt string Password hashing salt (default "dlPL2MqE")
--rc-serve Enable the serving of remote objects
--rc-serve-no-modtime Don't read the modification time (can speed things up)
--rc-server-read-timeout Duration Timeout for server reading data (default 1h0m0s)
--rc-server-write-timeout Duration Timeout for server writing data (default 1h0m0s)
--rc-template string User-specified template
+1 -1
View File
@@ -24,7 +24,6 @@ based on media formats or file extensions. Additionally, there is no
media transcoding support. This means that some players might show
files that they are not able to play back correctly.
## Server options
Use `--addr` to specify which IP address and port the server should
@@ -391,6 +390,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone serve dlna remote:path [flags]
```
@@ -406,6 +406,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone serve docker [flags]
```
@@ -427,6 +428,7 @@ rclone serve docker [flags]
--devname string Set the device name - default is remote:path
--dir-cache-time Duration Time to cache directory entries for (default 5m0s)
--dir-perms FileMode Directory permissions (default 0777)
--direct-io Use Direct IO, disables caching of data
--file-perms FileMode File permissions (default 0666)
--forget-state Skip restoring previous state
--fuse-flag stringArray Flags or arguments to be passed direct to libfuse/WinFsp (repeat if required)
+1 -1
View File
@@ -13,7 +13,6 @@ Serve remote:path over FTP.
## Synopsis
Run a basic FTP server to serve a remote over FTP protocol.
This can be viewed with a FTP client or you can make a remote of
type FTP to read and write it.
@@ -469,6 +468,7 @@ This can be used to build general purpose proxies to any kind of
backend that rclone supports.
```
rclone serve ftp remote:path [flags]
```
+2 -1
View File
@@ -68,7 +68,7 @@ of that with the CA certificate. `--key` should be the PEM encoded
private key and `--client-ca` should be the PEM encoded client
certificate authority certificate.
--min-tls-version is minimum TLS version that is acceptable. Valid
`--min-tls-version` is minimum TLS version that is acceptable. Valid
values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
"tls1.0").
@@ -570,6 +570,7 @@ This can be used to build general purpose proxies to any kind of
backend that rclone supports.
```
rclone serve http remote:path [flags]
```
@@ -399,6 +399,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone serve nfs remote:path [flags]
```
+2 -1
View File
@@ -137,7 +137,7 @@ of that with the CA certificate. `--key` should be the PEM encoded
private key and `--client-ca` should be the PEM encoded client
certificate authority certificate.
--min-tls-version is minimum TLS version that is acceptable. Valid
`--min-tls-version` is minimum TLS version that is acceptable. Valid
values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
"tls1.0").
@@ -169,6 +169,7 @@ Use `--realm` to set the authentication realm.
Use `--salt` to change the password hashing salt from the default.
```
rclone serve restic remote:path [flags]
```
+23 -2
View File
@@ -53,7 +53,27 @@ like this:
rclone serve s3 --auth-key ACCESS_KEY_ID,SECRET_ACCESS_KEY remote:path
```
This will be compatible with an rclone remote which is defined like this:
For example, to use a simple folder in the filesystem, run the server
with a command like this:
```
rclone serve s3 --auth-key ACCESS_KEY_ID,SECRET_ACCESS_KEY local:/path/to/folder
```
The `rclone.conf` for the server could look like this:
```
[local]
type = local
```
The `local` configuration is optional though. If you run the server with a
`remote:path` like `/path/to/folder` (without the `local:` prefix and without an
`rclone.conf` file), rclone will fall back to a default configuration, which
will be visible as a warning in the logs. But it will run nonetheless.
This will be compatible with an rclone (client) remote configuration which
is defined like this:
```
[serves3]
@@ -173,7 +193,7 @@ of that with the CA certificate. `--key` should be the PEM encoded
private key and `--client-ca` should be the PEM encoded client
certificate authority certificate.
--min-tls-version is minimum TLS version that is acceptable. Valid
`--min-tls-version` is minimum TLS version that is acceptable. Valid
values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
"tls1.0").
@@ -531,6 +551,7 @@ result is accurate. However, this is very inefficient and may cost lots of API
calls resulting in extra charges. Use it as a last resort and only with caching.
```
rclone serve s3 remote:path [flags]
```
@@ -500,6 +500,7 @@ This can be used to build general purpose proxies to any kind of
backend that rclone supports.
```
rclone serve sftp remote:path [flags]
```
+4 -2
View File
@@ -30,6 +30,7 @@ supported hash on the backend or you can use a named hash such as
to see the full list.
## Access WebDAV on Windows
WebDAV shared folder can be mapped as a drive on Windows, however the default settings prevent it.
Windows will fail to connect to the server using insecure Basic authentication.
It will not even display any login dialog. Windows requires SSL / HTTPS connection to be used with Basic.
@@ -45,6 +46,7 @@ If required, increase the FileSizeLimitInBytes to a higher value.
Navigate to the Services interface, then restart the WebClient service.
## Access Office applications on WebDAV
Navigate to following registry HKEY_CURRENT_USER\Software\Microsoft\Office\[14.0/15.0/16.0]\Common\Internet
Create a new DWORD BasicAuthLevel with value 2.
0 - Basic authentication disabled
@@ -53,7 +55,6 @@ Create a new DWORD BasicAuthLevel with value 2.
https://learn.microsoft.com/en-us/office/troubleshoot/powerpoint/office-opens-blank-from-sharepoint
## Server options
Use `--addr` to specify which IP address and port the server should
@@ -97,7 +98,7 @@ of that with the CA certificate. `--key` should be the PEM encoded
private key and `--client-ca` should be the PEM encoded client
certificate authority certificate.
--min-tls-version is minimum TLS version that is acceptable. Valid
`--min-tls-version` is minimum TLS version that is acceptable. Valid
values are "tls1.0", "tls1.1", "tls1.2" and "tls1.3" (default
"tls1.0").
@@ -599,6 +600,7 @@ This can be used to build general purpose proxies to any kind of
backend that rclone supports.
```
rclone serve webdav remote:path [flags]
```
@@ -34,6 +34,7 @@ rclone test info [remote:path]+ [flags]
--check-normalization Check UTF-8 Normalization
--check-streaming Check uploads with indeterminate file size
-h, --help help for info
--keep-test-files Keep test files after execution
--upload-wait Duration Wait after writing a file (default 0s)
--write-json string Write results to file
```
+1 -1
View File
@@ -160,7 +160,7 @@ Properties:
#### --compress-description
Description of the remote
Description of the remote.
Properties:
+2 -2
View File
@@ -182,7 +182,7 @@ A long passphrase is recommended, or `rclone config` can generate a
random one.
The obscured password is created using AES-CTR with a static key. The
salt is stored verbatim at the beginning of the obscured password. This
IV (nonce) is stored verbatim at the beginning of the obscured password. This
static key is shared between all versions of rclone.
If you reconfigure rclone with the same passwords/passphrases
@@ -634,7 +634,7 @@ Properties:
#### --crypt-description
Description of the remote
Description of the remote.
Properties:
+5 -1
View File
@@ -1943,6 +1943,10 @@ with the `--stats` flag.
This can be used with the `--stats-one-line` flag for a simpler
display.
To change the display length of filenames (for different terminal widths),
see the `--stats-file-name-length` option. The default output is formatted
for 80 character wide terminals.
Note: On Windows until [this bug](https://github.com/Azure/go-ansiterm/issues/26)
is fixed all non-ASCII characters will be replaced with `.` when
`--progress` is in use.
@@ -2781,7 +2785,7 @@ it will log a high priority message if the retry was successful.
* `6` - Less serious errors (like 461 errors from dropbox) (NoRetry errors)
* `7` - Fatal error (one that more retries won't fix, like account suspended) (Fatal errors)
* `8` - Transfer exceeded - limit set by --max-transfer reached
* `9` - Operation successful, but no files transferred
* `9` - Operation successful, but no files transferred (Requires [`--error-on-no-transfer`](#error-on-no-transfer))
* `10` - Duration exceeded - limit set by --max-duration reached
Environment Variables
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more