Compare commits

..
360 Commits
Author SHA1 Message Date
kalyan f6b8187e10 doc: explain new/changed/unmodified in the backup summary (#22244) 2026-12-02 21:31:55 +00:00
Michael Eischer b21617d3dc Merge pull request #22236 from g4lb/perf/tree-node-marshal
data: call Node.MarshalJSON directly when building a tree
2026-12-02 22:28:21 +01:00
g4lb ed922942fc data: call Node.MarshalJSON directly when building a tree 2026-12-02 10:22:25 +02:00
dependabot[bot] 9a2accfdde build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azcore from 1.23.3 to 1.24.0 (#22240)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 21:30:25 +00:00
dependabot[bot] 337b8f15ab build(deps): bump github.com/spf13/pflag from 1.0.10 to 1.1.0 (#22239)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 21:28:58 +00:00
dependabot[bot] 06ac4df5a9 build(deps): bump docker/login-action from 4.7.0 to 4.8.0 (#22237)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 22:12:13 +01:00
dependabot[bot] 1c55b6cec7 build(deps): bump the golang-x-deps group with 3 updates (#22238)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 22:11:48 +01:00
dependabot[bot] 71f804a929 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/storage/azblob from 1.8.1 to 1.8.3 (#22241)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 22:08:32 +01:00
dependabot[bot] 3f52603ef2 build(deps): bump github.com/pkg/sftp from 1.13.11 to 1.13.13 (#22242)
Signed-off-by: dependabot[bot] <support@github.com>
2026-12-01 22:07:55 +01:00
g4lb 33b2785d90 data: keep node names sorted in BenchmarkBuildTree 2026-11-30 22:02:30 +02:00
Michael Eischer 12073885f7 Merge pull request #22212 from theobarrague/fix/blobset-string-off-by-one
fix: correct blob count in BlobSet.String summary
2026-11-29 15:45:53 +01:00
Théo BARRAGUÉ 4a9941c1e1 restic: correct blob count in BlobSet.String summary
The "(N more)" summary printed when a BlobSet is truncated to ten
elements was computed as len(s)-n-1 instead of len(s)-n, so it undercounted
the unlisted elements by one and even became negative ("(-1 more)") when
exactly ten elements were present. This is user-visible in the 'not found in
the index' error printed by prune when the index is incomplete.
2026-11-29 15:34:29 +01:00
Michael Eischer 0cd0df6346 Merge pull request #22216 from MichaelEischer/quote-ui-output
Ensure paths etc. are quoted in terminal output
2026-11-28 20:53:43 +01:00
Michael Eischer 7a1ac9bda0 properly encode JSON everywhere 2026-11-28 20:41:09 +01:00
Michael Eischer 03e4060791 fix invalid verbs passed to sprintf 2026-11-28 20:27:06 +01:00
Michael Eischer 1227b2ab7e fix debug logs with missing parameters 2026-11-28 20:27:06 +01:00
Michael Eischer 152c2720bb don't quote repository open error by default 2026-11-28 20:27:06 +01:00
Michael Eischer d156f3b5f1 backup: fix missing error if vss snapshot properties cannot be read 2026-11-28 20:27:06 +01:00
Michael Eischer ab38c42497 archiver: fix double path injection after quoting 2026-11-28 20:27:06 +01:00
Michael Eischer fc85e9eb9b find: fix printing of paths containing % (format verbs) 2026-11-28 20:27:06 +01:00
Michael Eischer 79b676aa98 cat: always use raw output
This avoids quoting of JSON data.
2026-11-28 20:27:06 +01:00
Michael Eischer 057a5c65d2 add changelog 2026-11-28 20:27:06 +01:00
Michael Eischer 84a75fc09e generically sanitize output 2026-11-28 20:27:06 +01:00
Michael Eischer 76925aeb63 always quote paths in error messages 2026-11-28 20:27:06 +01:00
Michael Eischer 2518cd4a75 data / repository: quote fields in String() methods 2026-11-28 20:24:37 +01:00
Michael Eischer 584ec23160 quote paths in direct command output 2026-11-28 18:18:59 +01:00
Michael Eischer 15e1e33a19 Merge pull request #22221 from MichaelEischer/index-jsontext-decode
Speed up index decoding using Go 1.27's jsontext
2026-11-28 12:36:24 +01:00
Michael Eischer 0e50a959d5 ui: add helper to quote slices 2026-11-28 12:30:00 +01:00
Michael Eischer 43f00195bd add index speedup changelog 2026-11-28 12:27:03 +01:00
Michael Eischer 5769abd0ea index: use custom duplicate field check 2026-11-28 12:27:02 +01:00
Michael Eischer 93ed73cdd2 index: test error handling of hand-rolled decoder 2026-11-28 12:26:24 +01:00
Michael Eischer 1f76eb6a2e index: speed up index decoding
Stream index JSON with encoding/json/jsontext on Go 1.27 and later.
Go 1.26 keeps the encoding/json decoder.
2026-11-28 00:11:31 +01:00
Michael Eischer e63cb63ba6 Merge pull request #22209 from MichaelEischer/enforce-ordering
Also enforce node ordering for check, dump and mount
2026-11-28 00:09:25 +01:00
flinteger-code 1d0668f656 Enhancement: snapshots: Add --reverse option to reverse sort order (#5677) 2026-11-27 22:24:36 +00:00
Michael Eischer 4ea95e8de3 Merge pull request #22215 from MichaelEischer/better-debug-redact
Improve credentials redaction in debug log
2026-11-27 23:23:49 +01:00
Michael Eischer 2f0fbaa136 fix crash for parameter 2026-11-27 23:13:19 +01:00
Michael Eischer 780cb97523 debug: redact Azure SAS and short-lived S3 tokens 2026-11-27 23:01:00 +01:00
Michael Eischer 00ab2da0e4 redact CLI parameters in debug log 2026-11-27 23:01:00 +01:00
Michael Eischer d7b184f4ce repository: validate id in repo config (#22214) 2026-11-27 22:58:39 +01:00
Michael Eischer 00b2f19c3d repository: enforce limits for small file types (#22213) 2026-11-27 22:48:52 +01:00
Michael Eischer 814ef968d9 repository: refactor ListBlobs to be iterator based (#22208) 2026-11-27 22:46:12 +01:00
Merlin 4797768ba9 backend/sftp: Add sftp.server-alive-interval and sftp.server-alive-count-max options (#5314) 2026-11-27 22:16:04 +01:00
Arpit Jain 885519b1ba data: require an empty tag to be the only tag in a filter (#22222)
Signed-off-by: Arpit Jain <arpitjain099@gmail.com>
2026-11-27 21:12:19 +01:00
Michael Eischer f25ec9a5ab ui: allow timeformat without space between time and timezone (#22220) 2026-11-24 19:58:09 +01:00
Winfried Plappert 8f4873d5d7 CLI date/time related options - allow different time formats (#21867) 2026-11-22 18:12:38 +00:00
Michael Eischer 1d80020e28 Move buffer pool into the repository (#21942)
* restic: add BlobBuffer pool types

Based on the buffer type used by the archiver. The main change is that
`Get()` now always returns a slice with length zero.

* repository: add BlobBufferPool to BlobSaverAsync

* repository: change SaveBlobAsync to take a BlobBuffer

Ownership of the buffer transfers to SaveBlobAsync. Callers can now take
a buffer from the buffer pool.

Internally saveAndEncrypt now reuses pooled buffers.

* archiver: switch fileSaver to repository BlobBufferPool
2026-11-22 18:08:20 +01:00
Michael Eischer 79f17ac895 archiver: switch fileSaver to repository BlobBufferPool 2026-11-22 17:54:09 +01:00
Michael Eischer 30de2d9211 repository: change SaveBlobAsync to take a BlobBuffer
Ownership of the buffer transfers to SaveBlobAsync. Callers can now take
a buffer from the buffer pool.

Internally saveAndEncrypt now reuses pooled buffers.
2026-11-22 17:54:09 +01:00
Michael Eischer 4718be1aee repository: add BlobBufferPool to BlobSaverAsync 2026-11-22 17:54:09 +01:00
Ion 2991718398 repository: save config before key file during init (#21944)
restic init generated and uploaded the key file first and only saved the
config afterwards. If two clients ran init against the same empty
repository location at nearly the same time, the backend could end up
with two key files but only one config file, since backends that reject
overwrites let only one of the two config writes succeed. The losing
client's key file stayed in the repository without ever belonging to a
valid config, so clients picking that key later would fail with a
"config or key ... is damaged" error instead of a clear diagnostic.

Reorder Repository.init so the config is saved before the key file is
uploaded. To make that possible, AddKey no longer generates a random
master key internally; callers now supply the master key to encrypt and
store. The two other callers of AddKey (key add, key passwd) already had
an existing key available and pass that through unchanged.
2026-11-22 16:49:09 +00:00
Michael Eischer 3446754c41 restic: add BlobBuffer pool types
Based on the buffer type used by the archiver. The main change is that
`Get()` now always returns a slice with length zero.
2026-11-22 17:48:20 +01:00
Brook SeyoumandMichael Eischer b7e20f3aa2 Enhancement: add version-specific docs URLs to help output (#21795)
---------

Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-11-22 16:43:44 +00:00
Hugo 8af83234f2 Add benchmark with concurrent archivers (#5764)
Current benchmarks all work with a single archiver, and are not suitable
for testing changes which might affect contention.

Add a benchmark with multiple small files and multiple concurrent
archivers.
2026-11-22 16:35:59 +00:00
Fabien ea9a3f6801 docs: clarify backup scheduling scope and common patterns (#5651) 2026-11-22 16:28:59 +00:00
Michael Eischer 69ddfc4676 add basic changelog 2026-11-22 10:28:54 +01:00
Michael Eischer a8492c778e deduplicate test tree setup 2026-11-22 10:28:54 +01:00
Michael Eischer e6a3b7b299 mount: report unordered directory entries 2026-11-22 10:28:54 +01:00
Michael Eischer d7cdb55ebf dump: report unordered directory entries 2026-11-22 10:28:54 +01:00
Michael Eischer 25751a5856 check: report unordered directory entries 2026-11-22 10:28:54 +01:00
Michael Eischer 7745986c6d repair snapshots: warn when unordered directory entries are skipped 2026-11-22 10:28:54 +01:00
Michael Eischer b35ef9c203 walker: skip unordered directory entries while rewriting
This only applies if AllowUnstableSerialization is set, such that only
the `repair snapshots` command adopts this behavior.
2026-11-22 10:28:54 +01:00
Michael Eischer 09cf44557e data: refactor tree order check into EnforceTreeOrder
The restorer test now also thoroughly checks that later files are still
restored.
2026-11-22 10:28:54 +01:00
joyhsia 4729a99ebf tests: allow more time for REST server startup (#22205)
The macOS failure in #22146 reaches the two-second readiness deadline. Give the test server ten seconds to start while retaining immediate readiness and context cancellation handling.
2026-11-21 13:59:31 +00:00
Berk D. Demir db81226395 build(deps): bump golang.org/x/sys from 0.49.0 to 0.50.0 (#22204)
Unit tests fail on ppc64le due to a bug in golang.org/x/sys

Upstream fix[^1] is included in the v0.50.0 release.

Came across packaging for Alpine, which defaults to building PIE
binaries, when ppc64le build was segfaulting[^2] in the unit tests.

e.g.
```
--- FAIL: TestBackup (0.01s)
    testing.go:30: using low-security KDF parameters for test
    config.go:59: disabling check of the chunker polynomial
    testing.go:30: using low-security KDF parameters for test
    config.go:59: disabling check of the chunker polynomial
    lock_file.go:93: setting lock timeout to 0s
panic: runtime error: invalid memory address or nil pointer dereference [recovered, repanicked]
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10a1daf38]
```

[^1]: https://github.com/golang/go/issues/82324
[^2]: https://gitlab.alpinelinux.org/bdd/aports/-/jobs/2617025
2026-11-21 13:29:39 +00:00
Leo R. Lundgren e2a3f7bd75 Correct order of credits for issue #22180 2026-11-19 16:16:49 +01:00
Alexander Neumann d66a3f4fe7 Set development version for 0.20.0 2026-11-19 12:22:31 +01:00
Alexander Neumann 9c88ff768f Add version for 0.20.0 2026-11-19 12:22:02 +01:00
Alexander Neumann 9d1ea09e86 Update manpages and auto-completion 2026-11-19 12:22:02 +01:00
Alexander Neumann 6a63ee1d11 Generate CHANGELOG.md for 0.20.0 2026-11-19 12:21:18 +01:00
Alexander Neumann 7bed534cd1 Prepare changelog for 0.20.0 2026-11-19 12:21:18 +01:00
Alexander Neumann bae91697d3 Update changelogs 2026-11-19 12:09:12 +01:00
Michael EischerandLeo R. Lundgren 74f00280e2 Polish changelogs (#22195)
---------

Co-authored-by: Leo R. Lundgren <leo@finalresort.org>
2026-11-17 19:29:42 +01:00
dependabot[bot] 55abaa6de8 build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.4 to 4.1.6 (#22191)
Bumps [github.com/go-jose/go-jose/v4](https://github.com/go-jose/go-jose) from 4.1.4 to 4.1.6.
- [Release notes](https://github.com/go-jose/go-jose/releases)
- [Commits](https://github.com/go-jose/go-jose/compare/v4.1.4...v4.1.6)

---
updated-dependencies:
- dependency-name: github.com/go-jose/go-jose/v4
  dependency-version: 4.1.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-15 21:22:01 +00:00
dependabot[bot] 0a7e093006 build(deps): bump google.golang.org/api from 0.291.0 to 0.313.0 (#22156)
Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.291.0 to 0.313.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.291.0...v0.313.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-version: 0.310.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-15 22:08:42 +01:00
dependabot[bot] 10aab6465e build(deps): bump github.com/minio/minio-go/v7 from 7.3.0 to 7.4.1 (#22157)
Bumps [github.com/minio/minio-go/v7](https://github.com/minio/minio-go) from 7.3.0 to 7.4.1.
- [Release notes](https://github.com/minio/minio-go/releases)
- [Commits](https://github.com/minio/minio-go/compare/v7.3.0...v7.4.1)

---
updated-dependencies:
- dependency-name: github.com/minio/minio-go/v7
  dependency-version: 7.4.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-15 21:35:30 +01:00
00f12ea705 build(deps): bump the golang-x-deps group across 1 directory with 8 updates (#22066)
* build(deps): bump the golang-x-deps group across 1 directory with 8 updates

Bumps the golang-x-deps group with 8 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [golang.org/x/crypto](https://github.com/golang/crypto) | `0.55.0` | `0.58.0` |
| [golang.org/x/net](https://github.com/golang/net) | `0.58.0` | `0.60.0` |
| [golang.org/x/oauth2](https://github.com/golang/oauth2) | `0.36.0` | `0.37.0` |
| [golang.org/x/sync](https://github.com/golang/sync) | `0.22.0` | `0.24.0` |
| [golang.org/x/sys](https://github.com/golang/sys) | `0.47.0` | `0.49.0` |
| [golang.org/x/term](https://github.com/golang/term) | `0.45.0` | `0.47.0` |
| [golang.org/x/text](https://github.com/golang/text) | `0.41.0` | `0.43.0` |
| [golang.org/x/time](https://github.com/golang/time) | `0.15.0` | `0.16.0` |



Updates `golang.org/x/crypto` from 0.55.0 to 0.58.0
- [Commits](https://github.com/golang/crypto/compare/v0.55.0...v0.58.0)

Updates `golang.org/x/net` from 0.58.0 to 0.60.0
- [Commits](https://github.com/golang/net/compare/v0.58.0...v0.60.0)

Updates `golang.org/x/oauth2` from 0.36.0 to 0.37.0
- [Commits](https://github.com/golang/oauth2/compare/v0.36.0...v0.37.0)

Updates `golang.org/x/sync` from 0.22.0 to 0.24.0
- [Commits](https://github.com/golang/sync/compare/v0.22.0...v0.24.0)

Updates `golang.org/x/sys` from 0.47.0 to 0.49.0
- [Commits](https://github.com/golang/sys/compare/v0.47.0...v0.49.0)

Updates `golang.org/x/term` from 0.45.0 to 0.47.0
- [Commits](https://github.com/golang/term/compare/v0.45.0...v0.47.0)

Updates `golang.org/x/text` from 0.41.0 to 0.43.0
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.41.0...v0.43.0)

Updates `golang.org/x/time` from 0.15.0 to 0.16.0
- [Commits](https://github.com/golang/time/compare/v0.15.0...v0.16.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.57.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/net
  dependency-version: 0.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/oauth2
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/sync
  dependency-version: 0.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/sys
  dependency-version: 0.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/term
  dependency-version: 0.46.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/text
  dependency-version: 0.42.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/time
  dependency-version: 0.16.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
...

Signed-off-by: dependabot[bot] <support@github.com>

* Resolve deprecations

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-11-15 21:19:58 +01:00
Michael Eischer d991764a22 Resolve deprecations 2026-11-15 21:08:57 +01:00
Dean Chen 5cda063cbb fs: fall back to numeric ids when --ownership-by-name lookup fails (#22185)
Signed-off-by: Dean Chen <862469039@qq.com>
2026-11-15 19:30:21 +00:00
xh123637andMichael Eischer 2126756613 restorer: reject trees with duplicate or out-of-order node names (#22190)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
Signed-off-by: xh123637 <3324733895@qq.com>
2026-11-15 20:16:32 +01:00
JUSHUANGHUI LI d7aa4145e0 global: reject empty repository location files (#22052)
Return a fatal error before opening or creating a repository when its location file is empty after decoding and trimming whitespace.
2026-11-15 19:03:50 +00:00
Michael Eischer 335d7e38aa Merge pull request #22130 from junkerderprovinz/fix/issue-22112
stats: keep progress counters across snapshots
2026-11-15 20:01:16 +01:00
ump45nose edd3654c0a doc/cache: document the cache command (#22139) 2026-11-15 20:00:00 +01:00
Rob MartinandMichael Eischer 2c9b353cbf repository: do not delete config on atomic backends during upgrade rollback (#22136)
In UpgradeRepo, if upgradeRepository fails, the error handler attempts
contingency rollback by re-uploading the original config file.

However, the contingency path unconditionally executed repo.be.Remove(ctx, h)
before calling repo.be.Save. On backends supporting atomic replacement (such
as local filesystems), a failed upgrade (e.g. out-of-disk-space or permissions
error while writing the temporary file) leaves the original, valid version 1
configuration file completely intact on disk.

Unconditionally removing the config file during rollback actively deletes
the working configuration. If the subsequent Save call also fails, the
repository is left permanently corrupted without a config file.

Condition the pre-removal on !repo.be.Properties().HasAtomicReplace, matching
the forward upgrade path in upgradeRepository. Add a unit test asserting that
aborted upgrades on atomic backends preserve the intact original configuration.

---------

Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-11-15 18:57:01 +00:00
ump45nose c904b78998 prune: list all size suffixes accepted by --repack-smaller-than (#22137) 2026-11-15 19:55:41 +01:00
Dean Chen 4dfa381b9f restorer: don't delete files when a directory tree can't be loaded (#22189)
When loading or iterating a directory tree failed, traverseTreeInner
returned a nil file list together with the error. If the error handler
ignored the error, the caller still called leaveDir with that nil list,
and restore --delete removed every existing entry of the directory in
the target, even though the expected content was simply unknown.

Force disable deletion in that case, the same way it is already done
for invalid node names.

Signed-off-by: Dean Chen <862469039@qq.com>
2026-11-15 19:50:17 +01:00
Younes Beriane c4f9e50609 restorer: rewrite partially matching hard-linked files in full (#22086) 2026-11-15 18:40:11 +00:00
Michael Eischer 516c8d32e0 Merge pull request #22117 from Grivn/fix/legacy-null-tree
data: read empty trees from older repaired snapshots
2026-11-15 19:27:39 +01:00
Michael Eischer 6619ac9620 prune: drop test already covered by unit test 2026-11-15 19:14:35 +01:00
Michael Eischer 354f6aeed6 Untangle and clarify the contributing guide (#22169)
* Small typos and clarification in contributing guide

* cross-link contributing guide and issue/pr template

* drop GOPATH mention

* don't include merge commits in PRs

* make high review delays explicit

* explicitly ask for link to current PR in changelog template

* clarify docs changes

* use bug template as authoritative place'

* consolidate development information in 090_participating

Also move issue / PR creation relevant information into contributing.md.

* clarify meaning of assigning to a pull request

* link to minimum go version

* minor typos

* golanci-lint is always applied in full

* add micro summary

* more typo fixes

* always run golangci-lint

* Simplify issue/pr template

* Fix IRC webchat link

* Move security policy to SECURITY.md

* address review comments
2026-11-15 17:40:08 +01:00
Michael Eischer c734245fd3 repair snapshots: fix missing error message on unreadable snapshot (#22166) 2026-11-06 21:42:11 +01:00
Michael Eischer 0a2b084306 CI: disable swift tests (#22167) 2026-11-06 21:41:45 +01:00
Junker der Provinz e9a07fd773 changelog: link the pull request 2026-11-06 01:09:05 +01:00
omrzk c2c046c7b1 docs: keep S3 credentials out of Docker arguments (#22118) 2026-11-05 21:18:24 +00:00
ump45nose 0039a14381 global: mention the cache dir and user agent environment defaults (#22135) 2026-11-05 21:12:18 +00:00
John Maguire 7f6d8acb85 backend/b2: Support Multi-Bucket Application Keys (#22104) 2026-11-05 20:52:49 +00:00
Michael Eischer 068a324dcd Merge pull request #22124 from pujitha24/auto/issue-22120
prune: report failure to list pack files as a fatal error
2026-11-05 21:24:23 +01:00
Michael Eischer f515b862de prune: simplify test setup 2026-11-05 21:15:09 +01:00
Winfried Plappert 4619a31716 rewrite - more error exit tests (#22142) 2026-11-05 21:08:01 +01:00
Wei-Lun Li 9a0b9e0eb5 data: return an error for too large numbers in ParseDuration (#22163) 2026-11-05 19:36:49 +00:00
alexcastgonz b5d0152014 doc: list RESTIC_HTTP_USER_AGENT in the environment variables (#22123) 2026-11-05 19:26:31 +00:00
subomiandMichael Eischer 83a2726a30 s3: add option to disable AWS dual-stack endpoints (#22060)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-11-05 19:07:43 +00:00
dependabot[bot] b5463d900d build(deps): bump github.com/klauspost/compress from 1.20.0 to 1.20.3 (#22159)
Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 20:06:09 +01:00
dependabot[bot] 4416b9fa09 build(deps): bump docker/login-action from 4.6.0 to 4.7.0 (#22155) 2026-11-05 20:03:54 +01:00
dependabot[bot] 29fecdbd40 build(deps): bump the golang-x-deps group across 1 directory with 8 updates
Bumps the golang-x-deps group with 8 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [golang.org/x/crypto](https://github.com/golang/crypto) | `0.55.0` | `0.58.0` |
| [golang.org/x/net](https://github.com/golang/net) | `0.58.0` | `0.60.0` |
| [golang.org/x/oauth2](https://github.com/golang/oauth2) | `0.36.0` | `0.37.0` |
| [golang.org/x/sync](https://github.com/golang/sync) | `0.22.0` | `0.24.0` |
| [golang.org/x/sys](https://github.com/golang/sys) | `0.47.0` | `0.49.0` |
| [golang.org/x/term](https://github.com/golang/term) | `0.45.0` | `0.47.0` |
| [golang.org/x/text](https://github.com/golang/text) | `0.41.0` | `0.43.0` |
| [golang.org/x/time](https://github.com/golang/time) | `0.15.0` | `0.16.0` |



Updates `golang.org/x/crypto` from 0.55.0 to 0.58.0
- [Commits](https://github.com/golang/crypto/compare/v0.55.0...v0.58.0)

Updates `golang.org/x/net` from 0.58.0 to 0.60.0
- [Commits](https://github.com/golang/net/compare/v0.58.0...v0.60.0)

Updates `golang.org/x/oauth2` from 0.36.0 to 0.37.0
- [Commits](https://github.com/golang/oauth2/compare/v0.36.0...v0.37.0)

Updates `golang.org/x/sync` from 0.22.0 to 0.24.0
- [Commits](https://github.com/golang/sync/compare/v0.22.0...v0.24.0)

Updates `golang.org/x/sys` from 0.47.0 to 0.49.0
- [Commits](https://github.com/golang/sys/compare/v0.47.0...v0.49.0)

Updates `golang.org/x/term` from 0.45.0 to 0.47.0
- [Commits](https://github.com/golang/term/compare/v0.45.0...v0.47.0)

Updates `golang.org/x/text` from 0.41.0 to 0.43.0
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.41.0...v0.43.0)

Updates `golang.org/x/time` from 0.15.0 to 0.16.0
- [Commits](https://github.com/golang/time/compare/v0.15.0...v0.16.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.57.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/net
  dependency-version: 0.59.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/oauth2
  dependency-version: 0.37.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/sync
  dependency-version: 0.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/sys
  dependency-version: 0.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/term
  dependency-version: 0.46.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/text
  dependency-version: 0.42.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
- dependency-name: golang.org/x/time
  dependency-version: 0.16.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang-x-deps
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-01 01:42:51 +00:00
Junker der ProvinzandWinfried Plappert 84c2d0223f stats: keep progress counters across snapshots
The file, blob and size counters were reset for every snapshot, so the
progress line only reflected the last processed snapshot.

Co-authored-by: Winfried Plappert <18740761+wplapper@users.noreply.github.com>
2026-10-21 22:44:24 +02:00
Pujitha Paladugu bba1b68082 prune: report failure to list pack files as a fatal error
Motivation: when listing pack files fails during prune (for example due
to a request timeout), the error was returned unwrapped and main printed
it with "%+v", which dumps a stack trace. As discussed in the issue, the
error needs one more level of wrapping before it can be treated as a
fatal error.

Approach: in decidePackAction, wrap an error from listing pack files
with errors.Fatalf("failed to list pack files: %v"). Errors that are
already fatal (e.g. ErrSizeNotMatching) and errors after context
cancellation are returned unchanged. The underlying error is preserved
via Unwrap. Retry log messages are unchanged; only the final error
output is shortened and says where the failure occurred.

Validation: `go test ./internal/repository/ -run Prune` and
`go test ./cmd/restic/ -run Prune` pass. The new test
TestPrunePackListError (backend whose pack list fails) fails without
the change and passes with it. I did not reproduce a real REST backend
timeout.

Report: https://github.com/restic/restic/issues/22120
Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
Assisted-by: claude-sonnet-5-5 (via Claude Code)
2026-10-18 12:58:49 -07:00
wjc dd09b6bd01 docs: add FAQ for shared versus separate repositories (#22106) 2026-10-18 14:23:55 +00:00
MikeeI adc0284113 copy: avoid a full index scan for disabled debug output (#22103) 2026-10-18 13:50:05 +00:00
Michael Eischer 25aa69dbc7 Merge pull request #22089 from restic/dependabot/go_modules/cloud.google.com/go/storage-1.68.0
build(deps): bump cloud.google.com/go/storage from 1.64.0 to 1.69.0
2026-10-18 15:37:57 +02:00
Nicolai Scheer b4be15a7d9 cmd/restic: fix repair snapshots test on 32-bit platforms (#22098) 2026-10-18 13:36:23 +00:00
dependabot[bot] b1d146035a build(deps): bump cloud.google.com/go/storage from 1.64.0 to 1.69.0
Bumps [cloud.google.com/go/storage](https://github.com/googleapis/google-cloud-go) from 1.64.0 to 1.69.0.
- [Release notes](https://github.com/googleapis/google-cloud-go/releases)
- [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-cloud-go/compare/compute/v1.64.0...compute/v1.69.0)

---
updated-dependencies:
- dependency-name: cloud.google.com/go/storage
  dependency-version: 1.68.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-18 13:18:42 +00:00
Michael Eischer 885e6b6e71 Merge pull request #22121 from MichaelEischer/go-1.27
bump minimum go version to 1.26
2026-10-18 15:16:28 +02:00
Michael Eischer cb1d66a398 add changelog go version bump 2026-10-17 22:57:11 +02:00
Michael Eischer 5d745e2ead windows: use os.OpenFile with O_FILE_FLAG_* instead of low-level API 2026-10-17 22:57:11 +02:00
Michael Eischer 2497d99f9f fix linter error 2026-10-17 22:57:11 +02:00
Michael Eischer 35f15c398a apply go fix ./... 2026-10-17 22:57:11 +02:00
Michael Eischer a9d74f178e bump minimum go version to 1.26 2026-10-17 22:37:36 +02:00
dependabot[bot] e40a4a165e build(deps): bump github.com/ProtonMail/go-crypto from 1.4.1 to 1.5.2 (#22090)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-17 21:40:50 +02:00
Grivn d714e22605 data: read empty trees from older repaired snapshots
Older repair snapshots versions serialized missing subtrees as nodes:null.
The streaming decoder rejects these trees, preventing prune and other
commands from traversing snapshots that previous releases could read.

Accept null as an empty node list. Add decoder coverage and a regression
that prunes, checks and restores a snapshot with a legacy empty subtree.
2026-10-16 01:58:41 +08:00
Winfried Plappert 9da3b87b07 forget - missing lock for 'failedSnIDs' (#22100) 2026-10-11 22:15:25 +02:00
JayandMichael Eischer 519a979107 ci: update golangci-lint to v2.14 (#22111)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-10-11 16:33:41 +00:00
dependabot[bot] ca1c625227 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/storage/azblob from 1.8.0 to 1.8.1 (#22088)
Signed-off-by: dependabot[bot] <support@github.com>
2026-10-11 17:49:52 +02:00
Michael Eischer 5127c4abf9 Fix tar extraction errors in sandboxes (#22071) 2026-09-25 22:08:18 +02:00
Michael Eischer 8e917cf0bd Merge pull request #22069 from MichaelEischer/go-1.27
CI: Add go 1.27
2026-09-25 22:05:52 +02:00
Michael Eischer 818dd21a4f index: hash blob IDs with maphash.Bytes (#22070)
Avoid constructing a maphash.Hash on every lookup and insert.
2026-09-25 22:05:12 +02:00
Michael Eischer 6adedec6b4 repository: use synctest for lock tests (#22038)
Replace select based on context/timer with deterministic pattern.
The tests depend on timing. Thus, use synctest which provides
deterministic clock updates and also speeds up test execution by
skipping sleep times.
2026-09-20 22:05:21 +02:00
Michael Eischer 9d17700830 update golangci-lint ignore 2026-09-20 22:01:08 +02:00
Michael Eischer 1cce3790f4 gofmt 2026-09-20 21:28:55 +02:00
Michael Eischer 1765e36f95 CI: Add go 1.27 2026-09-20 21:28:40 +02:00
dependabot[bot] 9c86adb783 build(deps): bump google.golang.org/grpc from 1.82.1 to 1.83.2 (#22068)
Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 18:38:57 +00:00
Sergey Kolomiichuk ab17711e31 selfupdate: replace deprecated golang.org/x/crypto/openpgp with ProtonMail/go-crypto (#21997) 2026-09-20 18:33:24 +00:00
dependabot[bot] 444c1cb221 build(deps): bump github.com/klauspost/compress from 1.19.2 to 1.20.0 (#22044)
Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 20:19:54 +02:00
Michael Eischer c0acea6d75 Merge pull request #22054 from user01010111/docs/env-option-precedence
doc: clarify environment variable precedence
2026-09-20 20:18:07 +02:00
dependabot[bot] 7710556df1 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azidentity from 1.14.0 to 1.14.1 (#22043)
Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 18:14:39 +00:00
jf nz a428df74c9 doc: clarify environment variable precedence 2026-09-20 20:07:48 +02:00
Michael Eischer 96188e33a3 backend/s3: switch tests from minio to seaweedfs (#22067) 2026-09-20 20:03:48 +02:00
dependabot[bot] f35acc2421 build(deps): bump github.com/minio/minio-go/v7 from 7.2.1 to 7.3.0 (#22046)
Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 16:23:30 +02:00
dependabot[bot] ca33201335 build(deps): bump re-actors/alls-green from 1.2.2 to 1.3.0 (#22047)
Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 16:20:15 +02:00
Etienne D ba802d42b7 fix(swift): store APIKey as SecretString to prevent debug log leak (#22007) 2026-08-29 20:11:48 +00:00
CAOShurong 46ea365629 docs: fix two dead links (PGP key URL, MinIO docs URL) (#22028) 2026-08-29 19:07:37 +00:00
CAOShurong fb5e9df357 docs: fix contradiction about which files are encrypted (#22029) 2026-08-29 19:07:11 +00:00
Michael Eischer b593ba305b Apply go fix ./... (#22037) 2026-08-29 21:02:05 +02:00
Buggfix42 28d802df8c [Documentation] A few minor improvements (#21998) 2026-08-29 17:47:29 +00:00
GuitarBilly 0946f45de6 Update 110_talks.rst (#21989) 2026-08-29 19:44:43 +02:00
dependabot[bot] 5895e6d059 build(deps): bump cloud.google.com/go/storage from 1.63.0 to 1.64.0 (#21996)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-29 19:43:41 +02:00
Michael Eischer e982b6e7b5 CI: add size labels to PRs (#22036) 2026-08-29 19:39:04 +02:00
Jörn Bethune 479cf1fb3d documentation: Fix incorrect snapshot ID (#22017) 2026-08-29 17:33:20 +00:00
Ricardo Mendonça Ferreira dbaa8cf124 Update documentation for environment variable syntax (#22026) 2026-08-29 17:30:52 +00:00
dependabot[bot] a80be1478a build(deps): bump google.golang.org/api from 0.285.0 to 0.291.0 (#21995)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:24:27 +02:00
dependabot[bot] 7bfa32a90a build(deps): bump github.com/pkg/sftp from 1.13.10 to 1.13.11 (#21994)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:23:52 +02:00
dependabot[bot] 63b583c4ea build(deps): bump github.com/minio/minio-go/v7 from 7.1.0 to 7.2.1 (#21993)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:22:40 +02:00
dependabot[bot] 85bf4430b8 build(deps): bump actions/setup-go from 6 to 7 (#21992)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:21:34 +02:00
dependabot[bot] e2b43a5f1f build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/storage/azblob from 1.7.0 to 1.8.0 (#21991)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:21:07 +02:00
dependabot[bot] 607aba3809 build(deps): bump docker/login-action from 4.2.0 to 4.6.0 (#21990)
Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 22:20:40 +02:00
Michael Eischer c6074f82fb Merge pull request #21978 from MichaelEischer/go-fix2
Run `go fix ./...`
2026-08-01 22:17:53 +02:00
Arpit Jain 8baffc4027 repository: reject key and config files that are too short (#21977)
Signed-off-by: Arpit Jain <arpitjain099@gmail.com>
2026-07-22 20:38:07 +00:00
Michael Eischer f215365af9 Apply go fix -waitgroup ./... 2026-07-22 22:27:21 +02:00
Michael Eischer 14e523a1d9 Apply go fix -testingcontext ./... 2026-07-22 22:27:15 +02:00
Michael Eischer 58f92708c2 Apply go fix -stringsseq ./... 2026-07-22 22:27:07 +02:00
Michael Eischer 31e96f4ec9 Apply go fix -stringsbuilder ./... 2026-07-22 22:26:50 +02:00
Michael Eischer a2cb015591 Apply go fix -slicescontains ./... 2026-07-22 22:26:33 +02:00
Michael Eischer e2495b72bb Apply go fix -reflecttypefor ./... 2026-07-22 22:26:27 +02:00
Michael Eischer 2c169edad4 Apply go fix -rangeint ./... 2026-07-22 22:26:19 +02:00
Michael Eischer fb36a7f59b Apply go fix -omitzero ./... 2026-07-22 22:26:07 +02:00
Michael Eischer 8ed263c6dd Apply go fix -minmax ./... 2026-07-22 22:25:56 +02:00
Michael Eischer 0e4f288e83 Apply go fix -mapsloop ./... 2026-07-22 22:25:47 +02:00
Michael Eischer da4d8f5851 Apply go fix -fmtappendf ./... 2026-07-22 22:25:26 +02:00
Michael Eischer 32e9869cc8 Apply go fix -any ./... 2026-07-22 22:25:18 +02:00
Junker der Provinz d4088aa09b doc: describe the cadence of JSON status messages (#21954) 2026-07-15 20:38:38 +00:00
schrumpelnase 35dcda418c docs(README.md): fixed label of the link to the mastodon profile (#21958) 2026-07-15 20:32:26 +00:00
Michael Eischer af4f50223e ls: only keep fields required for sorting in memory (#21949) 2026-07-15 22:22:55 +02:00
Michael Eischer 9e007fa3cc Merge pull request #21937 from brainexe/reduce-index-memory-packindex-uint32
Reduce in-memory index entry size by storing packIndex as uint32
2026-07-15 22:16:40 +02:00
dependabot[bot] a4d85ce299 build(deps): bump the golang-x-deps group across 1 directory with 6 updates (#21923)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 21:32:37 +02:00
dependabot[bot] 9b0ee37697 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azidentity from 1.13.1 to 1.14.0 (#21925)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 21:31:44 +02:00
Matthias Dötsch 905ca56ee8 Address review feedback on #21937:
- addToPacks now returns uint32 directly and the value is passed through
  store() to indexMap.add unchanged, instead of casting between int and
  uint32.
- merge() appends idx2.packs to idx.packs without going through
  addToPacks, so it now checks the pack count against the uint32 limit
  itself + error if exceeded.
- optimize changelog message
2026-07-13 07:25:08 +02:00
dependabot[bot] 987caba408 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azcore from 1.21.1 to 1.22.0 (#21926)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-10 22:46:11 +02:00
dependabot[bot] bfca18c1b0 build(deps): bump actions/checkout from 6 to 7 (#21922)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-10 22:20:22 +02:00
dependabot[bot] dba493cb6c build(deps): bump github.com/klauspost/compress from 1.18.6 to 1.18.7 (#21924)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-10 22:17:43 +02:00
dependabot[bot] 512d0577d6 build(deps): bump cloud.google.com/go/storage from 1.62.2 to 1.63.0 (#21927)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-10 22:16:48 +02:00
Matthias Dötsch e428de5f84 Reduce in-memory index entry size by storing packIndex as uint32
Each blob in a repository requires one index entry in memory, which is one
of the largest contributors to restic's memory usage. The indexEntry.packIndex
field, an index into the per-Index packs slice, was stored as a machine-word
int (8 bytes on amd64) although the value is always a small array index.

Store it as a uint32 instead. This shrinks indexEntry from 64 to 56 bytes on
64-bit platforms (56 % 8 == 0, so no padding is added), reducing index memory
by roughly 12% -- about 100 MB for a repository with ~13 million blobs, as
confirmed by profiling. uint32 allows 4.29 billion packs (>30 billion blobs at
the assumed 8 blobs/pack), far beyond any real repository; addToPacks guards
against overflow defensively. The on-disk repository format is unaffected.
2026-07-08 06:01:15 +00:00
Michael Eischer d8ef26afa4 Merge branch 'patch-release' 2026-07-05 16:27:43 +02:00
astro-stan cc93a94e15 feat: Add support for setting --ignore-ctime and --ignore-inode via environment variables (#5730) 2026-06-28 15:36:58 +02:00
Winfried PlappertandMichael Eischer 62991338ea replace FindFilteredSnapshots() with (*data.SnapshotFilter).FindAll() (#21912)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-28 13:31:06 +00:00
Winfried PlappertandMichael Eischer 75de8b54e6 restic check and restic repair packs: treat missing packfiles the same as damaged and truncated packfiles (#21845)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-28 12:09:42 +02:00
Michael Eischer e4056e70a8 Merge pull request #21888 from MichaelEischer/chunker-factory
Move chunker construction to repository and switch to BaseChunker
2026-06-27 22:56:07 +02:00
Michael Eischer 8cc69782b5 repository: expose ZeroChunk via chunker factory 2026-06-27 22:23:59 +02:00
Michael Eischer ccb828e87b repository: add ChunkerFactory and decouple archiver from chunker
Introduce restic.Chunker and ChunkerFactory interfaces with a
repository-backed implementation. The archiver obtains chunkers via
ChunkerFactory() from the repository.
2026-06-27 22:13:41 +02:00
Michael Eischer 70a45791b2 archiver: switch file saver from Chunker to BaseChunker
Update the chunker dependency. Move the chunk memory handling into the
fileSaver. This minimizes the logic required in a chunker
implementation.

readNextChunk is a direct derivative of Chunker.Next.
2026-06-27 22:13:41 +02:00
Winfried PlappertandMichael Eischer 9e1a526611 Fix broken snapshots via restic repair snapshots --forget (#21907)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-27 22:09:10 +02:00
Michael Eischer aa94be2dbd Merge pull request #21883 from MichaelEischer/fix-find-pack
find: improve blob resolution for broken pack files
2026-06-26 22:33:38 +02:00
Michael Eischer 804ff4bc95 find: add test for listing blobs from corrupt pack files 2026-06-26 22:16:55 +02:00
Michael Eischer 9670cd7459 find: fix fallback to index if pack cannot be listed
`find` would only look up completely missing pack files in the index. A
still existing but broken pack file would result in an error.
2026-06-26 22:16:55 +02:00
Michael Eischer 634e9b2411 find: check blobIDs/treeIDs presence by length
Depending on the code path, the map could be initialized but stay empty.
2026-06-26 21:46:30 +02:00
Gilbert Gilb's db03aed816 feat(backends/s3): add warmup support for check command (#5248) 2026-06-25 20:46:55 +02:00
Michael Eischer 4e8eea7ab4 Merge pull request #21902 from restic/speedup-test
Cut local test suite execution time in half
2026-06-24 21:34:55 +02:00
Michael Eischer 981adc47ac snapshots: improve wording for timezone information (#21913) 2026-06-24 19:49:07 +02:00
Michael Eischer 7134577c56 use constants from cobra for shell completion helper names (#21905) 2026-06-22 22:58:26 +02:00
Ricardo Sawir 55e335ec6c fuse: reset treeCache on snapshot reload to fix stale latest symlink (#21873)
The treeCache in SnapshotsDir was never cleared when snapshots were
reloaded. This caused the "latest" symlink to keep pointing to the
previous snapshot even after new snapshots were added.

Add a generation counter to SnapshotsDirStructure that is incremented
whenever the directory structure is rebuilt (in makeDirs). The
treeCache checks this generation on each lookup and resets itself
when the generation changes, ensuring cached nodes (including symlinks)
are refreshed after a snapshot reload.
2026-06-22 18:31:51 +00:00
Winfried Plappert d30d6b6281 backup - show excluded files and directories in verbose mode - text/JSON (#21887) 2026-06-21 16:11:42 +00:00
Eyüp Can Akman 8d7679c831 backup: skip source paths that cannot be accessed (#21852) 2026-06-21 17:16:16 +02:00
Michael Eischer d9dd1b7534 archiver: ignore duplicate but excluded directory entry (#21900) 2026-06-21 15:49:08 +02:00
Michael Eischer 1151d70655 Merge pull request #21875 from MichaelEischer/fix-snapshots-latest-group-by
Fix default grouping of `snapshots --latest <n>`
2026-06-21 15:46:49 +02:00
Michael Eischer 369da8a770 snapshots: revert default --lastest behavior to pre-0.19.0
the changed behavior now only applies when using `--group-by`.
2026-06-21 15:28:22 +02:00
Michael Eischer 9f84c80056 snapshots: cleanup handling of deprecated --last option 2026-06-21 15:28:22 +02:00
Michael Eischer 6070462465 backup: move options finalization to BackupOptions.Finalize 2026-06-21 15:28:22 +02:00
Michael Eischer 1029fe6dd0 list packs snapshot: include actual error in error message (#21903) 2026-06-21 15:27:19 +02:00
Michael Eischer 8f00b335b4 rclone/fs: parallelize tests 2026-06-20 22:43:03 +02:00
Michael Eischer c6a064b68b mount: disable debug log for test
I don't recall any recent problems with that test.
2026-06-20 22:04:07 +02:00
Michael Eischer 8d191c19a5 archiver: decrease sleeps for TestFileChanged test
Modern filesystems provide microsecond granularity or better. The old
special case for macOS is removed as Go 1.25 (minimum for restic)
requires at least macOS 12, which uses APFS instead of the old HFS+.
2026-06-20 21:55:46 +02:00
Michael Eischer d5267f03e0 use fastest compression in integration tests 2026-06-20 20:00:17 +02:00
Michael Eischer 5683224a3c layout: skip creation of pack subdirectories in integration tests
Each time a local backend is created, the local backend also creates all
shard subdirectories. For the integration tests this has the downside
that this results in ~120 (number of test) * 256 (number of directories)
= 30k directories that are created unnecessarily. This significantly
slows down test execution and cleanup.
2026-06-20 20:00:17 +02:00
Michael Eischer 71064fac10 mount: decrease sleep to speed up test 2026-06-20 20:00:17 +02:00
Michael Eischer 52cde35aea try deleting a directory before resetting the readonly status in tests 2026-06-20 20:00:17 +02:00
Michael Eischer f394723aa2 inject crypto keys for integration tests 2026-06-20 20:00:17 +02:00
Michael Eischer 072305c5b3 repository: run version sub-tests of TestAllVersions in parallel
TestRepositoryIncrementalIndex no longer modified index.Full as this
modified global state and also had no effect on the test result.
2026-06-20 19:59:37 +02:00
Michael Eischer a1420ea6c7 repository: use separate rand instance per test
Use separate instances to prevent data races when executing tests in
parallel.
2026-06-20 19:50:10 +02:00
Michael Eischer a3be3bd9e1 backend/test: gradually increase timeout for TestListCancel to speed up fast backends 2026-06-20 19:46:22 +02:00
Michael Eischer b24d05bcb4 skip key decryption in tests 2026-06-20 19:46:22 +02:00
Michael Eischer c021b8cde0 decrease test data sizes 2026-06-20 19:46:22 +02:00
Michael Eischer 18e5c446e0 data/fs: faster comparison in tests 2026-06-20 19:46:22 +02:00
Michael Eischer f91afb2fa8 repository: run TestPruneSmall in parallel to other tests 2026-06-20 19:46:22 +02:00
Michael Eischer 2148508050 repository/checker: speed up test repo creation
data.TestCreateSnapshot is much faster than archiver.TestSnapshot
2026-06-20 19:46:22 +02:00
Michael Eischer 37e8f50aeb repository: decrease test data size for streamPack 2026-06-20 19:46:22 +02:00
Michael Eischer 7e5eaf1ead crypto: decrease parameters for calibrate test 2026-06-20 19:46:22 +02:00
Michael Eischer aae0985673 index: decrease depth of test repos 2026-06-20 19:46:22 +02:00
Michael Eischer f9d953d4cd index: test ForAllIndex with generated repo 2026-06-20 19:46:22 +02:00
Michael Eischer 69a3ba5b33 index: speed up oversized test data generation 2026-06-20 19:46:22 +02:00
Michael Eischer c183fe2035 restore: speed up test data generation in newTestRepo 2026-06-20 19:46:22 +02:00
Michael Eischer 1174e97b30 restic: speed up repository config initialization in tests
Avoid redundant polynomial generation, which takes a millisecond or so.
2026-06-20 19:46:22 +02:00
Michael Eischer 440d925467 repository: default to fastest compression in tests 2026-06-20 19:46:22 +02:00
Michael Eischer 28521d27c1 Merge pull request #21897 from MichaelEischer/sftp-fix-chmod
backend/sftp: fix removing files on windows sftp
2026-06-20 19:29:49 +02:00
Michael Eischer af64caf5d9 Merge pull request #21885 from MichaelEischer/separate-backend-restic-filetype
Separate backend.FileType from restic.FileType
2026-06-20 19:24:51 +02:00
Michael Eischer 9ab5fc59c2 restic: split FileType for backend.FileType
Equality of constants is enforced via internal/repository/filetype.go
using compile time checks.
2026-06-20 19:15:40 +02:00
Michael Eischer 6c509f7ac1 Correctly pair backend/restic.FileType with APIs
Use backend.FileType to interact with the backend. And restic.FileType
to interact with the repository.
2026-06-20 19:15:40 +02:00
Michael Eischer ea699bb0ba backend/rest: fix flaky test cleanup (#21901) 2026-06-20 19:14:54 +02:00
Michael Eischer 532f36a5a8 archiver: pass ItemAction to progress reporter instead of data.Node (#21886) 2026-06-20 19:06:45 +02:00
Michael Eischer 57ac5d107c Merge pull request #21882 from MichaelEischer/untangle-imports
Untangle imports of repository, restorer, fs
2026-06-20 18:24:50 +02:00
Michael Eischer 2f31cde517 internal/restorer: invert dependency direction to ui/restorer
The restorer imported ui/restorer which leaks ui logic into the restorer
core. Swap the direction by letting the restorer use a ProgressReporter
interface + associated constants.
2026-06-20 17:49:20 +02:00
Michael Eischer 5cd39d01c1 internal/data: extract HardlinkIndex from restorer
The HardlinkIndex is also used by `cmd_stats`, thus place it in a shared
package.
2026-06-20 17:49:20 +02:00
Michael Eischer 61708772a2 mount: use existing HasPathPrefix helper
replaces the custom isInside helper to check path nesting
2026-06-20 17:49:20 +02:00
Michael Eischer d9d54a505e restic: move Printer interface from internal/ui/progress
Move Printer and NewNoopPrinter to internal/restic so repository does
not have to import the ui packages.
2026-06-20 17:49:20 +02:00
Michael Eischer 0f4236cb39 repository: return unlock func from LockRepo
Drop the Unlocker interface and return the unlock callback directly
from LockRepo, simplifying callers that only need to defer unlock().
2026-06-20 17:48:35 +02:00
Michael Eischer 4d1b9cef63 internal/fileio: extract low-level file I/O from internal/fs
Move TempFile and PreallocateFile into internal/fileio. internal/fs
primarily focuses on converting between data.Node and the actual
filesystem state. Extract the two methods to not pull in unnecessary
dependencies.
2026-06-20 17:48:35 +02:00
Winfried PlappertandMichael Eischer 284daaf0b4 restic list pack snapshotID - create lists of packfiles for a given snapshot as text (#5396)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-20 15:46:44 +00:00
Michael Eischer 980f194360 fs: print missing error if xattr cannot be read (#21896) 2026-06-20 17:11:16 +02:00
Michael Eischer d795988fa8 Misc error handling fixes (#21884)
* forget: fix error handling if snapshot key cannot be marshaled

* backend/b2: correctly close file if too short

* backend/rest: correctly close body on out of bounds read

* backend/sftp: fix file handle leak if chmod for a file fails

* backend/util: fix errorhandling in DefaultDelete test helper

* prune/repair pack: document ignored errors

* selfupdate: improve error handling

* repository: show correct error if zstd decoder cannot be initialized
2026-06-20 17:09:02 +02:00
Michael Eischer 203e595ccb backend/sftp: fix removing files on windows sftp 2026-06-19 23:23:01 +02:00
Michael Eischer 6c67a095dc backend/sftp: fix error reporting of Save method 2026-06-19 23:09:59 +02:00
Michael Eischer 1a9decf03e repository: show correct error if zstd decoder cannot be initialized 2026-06-14 16:52:40 +02:00
Michael Eischer 718f09e02d selfupdate: improve error handling 2026-06-14 16:51:56 +02:00
Michael Eischer 82708ff7f7 prune/repair pack: document ignored errors 2026-06-14 16:51:56 +02:00
Michael Eischer 18c47c5bf9 backend/util: fix errorhandling in DefaultDelete test helper 2026-06-14 16:40:09 +02:00
Michael Eischer faea0d677a backend/sftp: fix file handle leak if chmod for a file fails 2026-06-14 16:39:42 +02:00
Michael Eischer ae8fdb08fa backend/rest: correctly close body on out of bounds read 2026-06-14 16:38:54 +02:00
Michael Eischer 5c8c048c1a backend/b2: correctly close file if too short 2026-06-14 16:38:21 +02:00
Michael Eischer 6b88b072e0 forget: fix error handling if snapshot key cannot be marshaled 2026-06-14 16:37:58 +02:00
Michael Eischer 7d36449ea8 repository: change LoadBlob, LookupBlob and LookupBlobSize to BlobHandles (#21857) 2026-06-14 15:30:00 +02:00
Michael Eischer 71f38d266c ensure reliable cleanup of test repository (#21880) 2026-06-14 14:25:00 +02:00
Michael Eischer 0536e15bbf snapshots: show location name instead of current timezone (#21877) 2026-06-14 14:02:20 +02:00
Michael Eischer 650f658244 repository/index: ensure progress bar cancelation on early index load failure (#21881) 2026-06-14 13:56:24 +02:00
Michael Eischer ae96b2a0f8 mount: fix crash in mountpoint validation (#21879) 2026-06-14 13:55:26 +02:00
Michael Eischer ce9b6ceea1 Merge pull request #21862 from MichaelEischer/lock-cleanup
Move Lock type to repository package and clean it up a bit
2026-06-13 21:46:26 +02:00
Michael Eischer 406dec29a7 repository: remove redundant mutex in checkForOtherLocks
forAllLocks already serializes the callback calls. Still has to create a
copy of checkedIDs to prevent a data race between forAllLocks and the
callback.
2026-06-13 21:37:24 +02:00
Michael Eischer 6fe10a72eb repository: drop mutex from lockHandle 2026-06-13 21:37:06 +02:00
Michael Eischer 1a6d43286a repository: comment cleanups 2026-06-13 21:36:36 +02:00
Michael Eischer 151903d4d4 repository: fix goroutine leak due to delayedCancelContext in tests 2026-06-13 21:35:51 +02:00
Michael Eischer b86568b790 repository: merge Unlocker and lockContext 2026-06-13 21:35:41 +02:00
Michael Eischer a5f3256626 repository: partially deduplicate refresh and refreshStaleLock 2026-06-13 21:33:58 +02:00
Michael Eischer 5989671f87 repository: deduplicate error handling in checkForOtherLocks 2026-06-13 21:33:43 +02:00
Michael Eischer b7f3a1367a repository: add SIGHUP handler only on Unix systems 2026-06-13 21:33:27 +02:00
Michael Eischer 4838b0ae3e repository: cleanup naming of lockCtx 2026-06-13 21:33:19 +02:00
Michael Eischer c87da70af9 repository: separate Lock in-repository from lock handle
Reduce Lock to a pure data transfer object and move the logic to
lockHandle.
2026-06-13 21:33:03 +02:00
Michael Eischer 81b6414c55 repository: hide Lock methods
Unexport lock file methods except String. Lock file operations are only
used within the repository package.
2026-06-13 21:32:13 +02:00
Michael Eischer 637c1cfb66 repository: unexport internal lock file helpers
Unexport UnlockCancelDelay, IsInvalidLock, ErrRemovedLock, NewLock,
StaleLockTimeout and ForAllLocks
2026-06-13 21:31:27 +02:00
Michael Eischer b892b1a150 repository: move lock file handling from restic package 2026-06-13 21:31:23 +02:00
Michael Eischer 7015da44ad restic: extract UidGidInt into separate files
Extract UidGidInt to simplify moving the locking code to the repository.
2026-06-13 21:24:38 +02:00
Michael Eischer 3ee465d363 repository: rename Lock function to LockRepo
Rename `Lock()` to `LockRepo()` to make room for the `Lock` struct.
2026-06-13 21:24:37 +02:00
Michael Eischer 8e11f5747d restic: introduce Counter interface to decouple from ui/progress (#21861)
decouple restic and ui/progress packages
2026-06-13 21:08:18 +02:00
Michael Eischer 22a304af7e Merge pull request #21849 from restic/internal-crypto-package
repository: move crypto package to internal/repository/crypto
2026-06-13 20:33:24 +02:00
Michael Eischer c8a0bc2c5e repository: move crypto package to internal/repository/crypto 2026-06-13 20:05:06 +02:00
Michael Eischer 35e60dc2c7 restic: remove Key() from repository interface
All callers use the concrete Repository type
2026-06-13 20:05:06 +02:00
Michael Eischer 8e93172bf8 cache: remove dependency on crypto package for truncation checks
The cache backend + repository can by now properly recover from damaged
files stored in the cache. Thus, remove the legacy sanity check.
2026-06-13 20:05:05 +02:00
Michael Eischer b94ef4831d repository: add PackBlob.UncompressedCiphertextLength() 2026-06-13 20:05:05 +02:00
Michael Eischer 952b310d62 Merge pull request #21851 from MichaelEischer/misc-cleanups2
Unexport lots of methods and structs
2026-06-13 20:03:18 +02:00
Michael Eischer 3eb5f83db3 fs: more vss related unexports 2026-06-13 19:54:32 +02:00
Michael Eischer d3ef21f870 archiver: unexport BackupTarget type 2026-06-13 19:54:12 +02:00
Michael Eischer 31df7508c4 archiver: unexport Options.ApplyDefaults 2026-06-13 19:53:51 +02:00
Michael Eischer 87c9ed4573 archiver: unexport toNoder 2026-06-13 19:53:31 +02:00
Michael Eischer eedba12968 bloblru: unexport add and get 2026-06-13 19:53:13 +02:00
Michael Eischer 264cfbcff2 data: remove unused Nodes type 2026-06-13 19:52:49 +02:00
Michael Eischer 7f3c9eb749 data: unexport fixTime 2026-06-13 19:52:27 +02:00
Michael Eischer 347cac780d data: unexport osType 2026-06-13 19:52:07 +02:00
Michael Eischer 23d6946fc9 fs: unexport CommandReader type 2026-06-13 19:51:49 +02:00
Michael Eischer 2db654533b fs: unexport Reader type 2026-06-13 19:51:33 +02:00
Michael Eischer f5843a7d97 fs: unexport more vss types 2026-06-13 19:51:14 +02:00
Michael Eischer e1e7fc8fb2 fs: unexport Local and expose via NewLocal 2026-06-13 19:50:49 +02:00
Michael Eischer 1acc19dac5 repository: unexport SearchKey 2026-06-13 19:49:03 +02:00
Michael Eischer 79e92b3bc6 repository: change Unlocker to interface 2026-06-13 19:48:47 +02:00
Michael Eischer 766d9f9f1e repository: unexport openKey 2026-06-13 19:48:31 +02:00
Michael Eischer 131abbb4f0 repository: unexport WarmupJob 2026-06-13 19:48:15 +02:00
Michael Eischer d62e42e620 repository: unexport NewChecker 2026-06-13 19:48:02 +02:00
Michael Eischer 35caceace4 restore: unexport HardlinkIndex.Index and hardlinkKey 2026-06-13 19:12:05 +02:00
Michael Eischer f2ff05f840 Merge pull request #21848 from restic/shrink-repository-interface
move restic.{Blob,Blobs,PackedBlob} types to `./internal/repository/pack` package
2026-06-13 19:11:33 +02:00
Michael Eischer c062a78dcd repository: move Blob, Blobs and PackedBlob to pack package
This removes them from the public interface. The latter now only
provides the PackBlob interface, without being bound to the type used
internally by the pack package.
2026-06-13 18:58:37 +02:00
Michael Eischer 35af104749 restic: change LookupBlob to return []PackBlob 2026-06-13 17:54:58 +02:00
Michael Eischer ccb5ae1592 restic: change ListBlobs to return PackBlob
PackBlob is a limited interface that only exposes a part of the
information provided by PackedBlob. Most of the changes are switches
from direct value lookups to the interface methods, with a few larger
changes to let the tests still work.
2026-06-13 17:54:38 +02:00
Michael Eischer 97f1e99ed9 restic: add PackBlob interface and implement it on PackedBlob
The PackBlob interface will allow hiding details from the public
interface, in particular, the offset of a blob within a pack file.
2026-06-13 17:54:18 +02:00
Michael Eischer c060c317d3 repository: unexport listPacksFromIndex
`ListPacksFromIndex` only has repository-internal callers left (besides
test code).
2026-06-13 17:54:03 +02:00
Michael Eischer a9e0b46358 restic: list pack header via ListPackHandles
Replace ListPack with ListPackHandles so callers only receive blob
handles from pack headers, not layout fields.
2026-06-13 17:50:21 +02:00
Michael Eischer 8169814b38 restic: switch LoadBlobsFromPack to BlobHandles
LoadBlobsFromPack now resolves the handles to Blobs. Repository internal
code can still use the Blob-based method.

The loader used in the filerestorer test now has to implement sorting
the blobs by offset itself as it no longer has access to the repository-internal
dataypes.
2026-06-13 17:50:21 +02:00
Michael Eischer f186e1e458 repository: require *Repository for CopyBlobs
Prepare `CopyBlobs` to allow access to unexported methods of the
Repository struct. This requires changing the test to inject the number
of backend connections via a wrapped backend instead of a wrapped
repository.
2026-06-13 17:50:21 +02:00
Winfried PlappertandMichael Eischer 0938f52f38 tests - more test cases for internal/repository/check.go (#21830)
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-13 15:35:48 +00:00
Michael Eischer 9f9a3472aa Merge pull request #21850 from MichaelEischer/misc-cleanups
Cleanup `ui/*` package and minor cleanups in `test` and `walker`
2026-06-13 17:12:14 +02:00
Michael Eischer 14f86a462a stats: refactor ui progress printer into ui/stats 2026-06-13 17:00:11 +02:00
Michael Eischer 825d67ba4b backup,restore: move CalculateProgressInterval call to their ui package 2026-06-13 16:53:57 +02:00
Michael Eischer 3b8b77e54d test: remove unused exports 2026-06-13 16:53:57 +02:00
Michael Eischer 0bbfb072af ui/progress: unexport NoopPrinter and add New* function 2026-06-13 16:53:57 +02:00
Michael Eischer e8ed2434cd ui: move NewProgressPrinter to ui/progress.NewTerminalPrinter 2026-06-13 16:53:54 +02:00
Michael Eischer c04f3e9d6c ui: unexport json and text progress 2026-06-13 16:53:30 +02:00
Michael Eischer 37fdbe5779 ui: inline Message into progressPrinter 2026-06-13 16:53:30 +02:00
Michael Eischer 47328afb2e ui/progress: remove unused test helper 2026-06-13 16:53:30 +02:00
Michael Eischer e6d054d896 walker: remove empty testing.go 2026-06-13 16:53:30 +02:00
Michael Eischer fc81a0b6ad ui/terminal: unexport Terminal type 2026-06-13 16:53:30 +02:00
Michael Eischer dee28f5b0e ui/terminal: unexport New function 2026-06-13 16:53:30 +02:00
Michael Eischer 2d02a1ad39 doc: clarify forget --prune --json output (#21878) 2026-06-13 16:47:15 +02:00
Michael Eischer bae49d00ee stats: hide progress bar for json output (#21871) 2026-06-13 15:13:26 +02:00
e5dba15367 Json prune (#5239)
Co-authored-by: Alexander Weiss <alex@weissfam.de>
Co-authored-by: Michael Eischer <michael.eischer@fau.de>
2026-06-13 10:38:57 +00:00
Michael Eischer bf56d71b09 Merge pull request #21876 from MichaelEischer/cleanup-mount-validation
mount: refactor mountpoint validation
2026-06-12 23:34:44 +02:00
Michael Eischer e94ec65efb mount: unify mountpoint validation error messages 2026-06-12 22:30:53 +02:00
Michael Eischer 49f9e67520 mount: factor out mountpoint validation into helper 2026-06-12 22:29:45 +02:00
Michael Eischer 3a4b0e3b8c Merge pull request #5348 from zmanda/fix-gh-5234-prevent-mount-command-over-repository
mount: prevent mounting over repository
2026-06-12 22:27:50 +02:00
Michael Eischer abfc9bbdff Merge pull request #21868 from MichaelEischer/fix-zero-sized-blobs
repository: fix zero-sized blobs in v2 repos
2026-06-11 20:43:38 +02:00
Michael Eischer 784812361e Merge pull request #21858 from MichaelEischer/unexport-backends
Unexport several backend types
2026-06-10 22:51:32 +02:00
Michael Eischer c745f810b3 backend/cache: use backend types not restic types (#21860) 2026-06-10 22:45:39 +02:00
Michael Eischer 721411e04c backend/azure/gs/s3: remove unused Path() method 2026-06-10 22:37:07 +02:00
Michael Eischer b07ff6cd34 backends: remove unused SetListMax method
It was never used. Remove the dead code.
2026-06-10 22:37:07 +02:00
Michael Eischer 8b3bbb527c backend/s3: unexport 2026-06-10 22:37:07 +02:00
Michael Eischer 4a2d8e04aa backend/rclone: unexport 2026-06-10 22:37:07 +02:00
Michael Eischer a36488b706 backend/gs: unexport 2026-06-10 22:37:07 +02:00
Michael Eischer cfb506a77a backend/cache: unexport 2026-06-10 22:37:07 +02:00
Michael Eischer a15b1579ff Merge pull request #21846 from restic/repository-cleanups
Cleanup repository package
2026-06-10 22:36:04 +02:00
Michael Eischer ff95080f36 restic: move test helpers and drop unused JSONUnpackedLoader 2026-06-10 22:20:28 +02:00
Michael Eischer 119bb9d9a8 repository: require *Repository for ExaminePack
The function wouldn't work with a different Repository implementation
anyways.
2026-06-10 22:20:28 +02:00
Michael Eischer 8c6ee42d17 debug: move DumpPacks into repository package
Processing pack file internals belongs into the repository package.
2026-06-10 22:20:28 +02:00
Michael Eischer ccddc1914d repository: rename PackError to ErrPackMetadata 2026-06-10 22:20:28 +02:00
Michael Eischer 4bc5eca7ea repository: merge check.go into checker.go 2026-06-10 22:20:28 +02:00
Michael Eischer 17ff3aa5f9 Merge pull request #21841 from MichaelEischer/isolate-repository
prevent imports of repository internals
2026-06-10 22:19:24 +02:00
Michael Eischer 5683180a3b upgrade compress library 2026-06-10 22:03:56 +02:00
Michael Eischer 0fc7444e32 repository: fix zero-sized blobs in v2 repos 2026-06-10 22:03:40 +02:00
Michael Eischer 81571775d5 fix version set by helper after release (#21865) 2026-06-09 22:43:18 +02:00
Alexander Neumann 16b8b8cda0 Set development version for 0.19.0 2026-06-09 18:49:09 +02:00
Michael Eischer 7d25ca9d67 repository: omit unused headerSize from ListPack() 2026-05-31 22:53:00 +02:00
Michael Eischer cc546b71e3 debug: move code requring internal access to repository package 2026-05-31 22:48:38 +02:00
Michael Eischer 3cb49556f5 repair index: replace full index handling integration test with unit test 2026-05-31 22:39:16 +02:00
Michael Eischer f625190393 check: simplify index damage test 2026-05-31 22:19:15 +02:00
Michael Eischer 620f5986f8 list index: use helper in repository package 2026-05-31 22:14:01 +02:00
Michael Eischer 49c7364e79 add golangci-lint rule to prevent imports of repository internals 2026-05-31 18:20:37 +02:00
Srigovind Nayak e1e36ed848 doc: note that mountpoint must not overlap the repository
Document the new restriction added so users encountering the error
message have a reference, and so the constraint is visible before they
hit it.
2026-05-16 18:07:42 +05:30
Srigovind Nayak a37010a825 chore: update changelog for issue 5234 2026-05-16 18:06:14 +05:30
Srigovind Nayak a0d7745e8b mount: refuse mountpoints that overlap the local repository
Mounting a local repository onto its own directory caused the FUSE
  server to read its own backend files through the mount it had just
  created, deadlocking the kernel. `umount` then reported "Device or
  resource busy" and recovery required a reboot that took several
  minutes. The same shape occurs when the mountpoint is nested inside
  the repository directory, or when the repository directory is nested
  inside the mountpoint.

  The mount command now resolves both paths via filepath.Abs and
  filepath.EvalSymlinks and refuses with a fatal error if either path
  equals or contains the other. The check runs before the repository
  lock is acquired so an overlap fails fast. Only the local backend is
  checked; remote backends cannot shadow the mountpoint directory.
2026-05-16 18:03:49 +05:30
439 changed files with 10631 additions and 5576 deletions

No files matched your search

+9 -16
View File
@@ -10,18 +10,10 @@ Welcome! - We kindly ask that you:
1. Fill out the issue template below - not doing so needs a good reason.
2. Use the forum if you have a question rather than a bug or feature request.
The forum is at: https://forum.restic.net
NOTE: Not filling out the issue template needs a good reason, as otherwise it
may take a lot longer to find the problem, not to mention it can take up a lot
more time which can otherwise be spent on development. Please also take the
time to help us debug the issue by collecting relevant information, even if
it doesn't seem to be relevant to you. Thanks!
The forum is a better place for questions about restic or general suggestions
and topics, e.g. usage or documentation questions! This issue tracker is mainly
for tracking bugs and feature requests directly relating to the development of
the software itself, rather than the project.
The forum is at https://forum.restic.net and is a better place for questions
about restic or general suggestions and topics, e.g. usage or documentation
questions! This issue tracker is mainly for tracking bugs and feature requests
directly relating to the development of the software itself.
Thanks for understanding, and for contributing to the project!
@@ -49,11 +41,12 @@ This section should include at least:
* The complete command line and any environment variables you used to
configure restic's backend access. Make sure to replace sensitive values!
* The output of the commands, what restic prints gives may give us much
information to diagnose the problem!
* The output of the commands – what restic prints often provides a clue.
* The more time you spend describing an easy way to reproduce the behavior (if
this is possible), the easier it is for the project developers to fix it!
* Clear and concise steps describing how to reproduce the behavior (if possible).
See https://github.com/restic/restic/blob/master/CONTRIBUTING.md#reporting-bugs
for ways to collect debug information if necessary.
-->
+5 -7
View File
@@ -10,12 +10,10 @@ Welcome! - We kindly ask that you:
1. Fill out the issue template below - not doing so needs a good reason.
2. Use the forum if you have a question rather than a bug or feature request.
The forum is at: https://forum.restic.net
The forum is a better place for questions about restic or general suggestions
and topics, e.g. usage or documentation questions! This issue tracker is mainly
for tracking bugs and feature requests directly relating to the development of
the software itself, rather than the project.
The forum is at https://forum.restic.net and is a better place for questions
about restic or general suggestions and topics, e.g. usage or documentation
questions! This issue tracker is mainly for tracking bugs and feature requests
directly relating to the development of the software itself.
Thanks for understanding, and for contributing to the project!
@@ -43,7 +41,7 @@ What are you trying to do? What problem would this solve?
---------------------------------------------------------
<!--
This section should contain a brief description what you're trying to do, which
This section should contain a brief description of what you're trying to do, which
would be possible after implementing the new feature.
-->
+4 -4
View File
@@ -8,7 +8,7 @@ What does this PR change? What problem does it solve?
-----------------------------------------------------
<!--
Describe the changes and their purpose here, as detailed as needed.
Describe the changes and their purpose here in as much detail as needed.
-->
Was the change previously discussed in an issue or on the forum?
@@ -32,11 +32,11 @@ check the last box. Enable a checkbox by replacing [ ] with [x].
Please always follow these steps:
- Read the [contribution guidelines](https://github.com/restic/restic/blob/master/CONTRIBUTING.md#providing-patches).
- Enable [maintainer edits](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
- Run `gofmt` on the code in all commits.
- Run `gofmt -w **/*.go` on the code in all commits. Use `golangci-lint run` to lint the code. The CI pipeline also runs those checks.
- Format all commit messages in the same style as [the other commits in the repository](https://github.com/restic/restic/blob/master/CONTRIBUTING.md#git-commits).
-->
- [ ] I have added tests for all code changes, see [writing tests](https://restic.readthedocs.io/en/stable/090_participating.html#writing-tests)
- [ ] I have added documentation for relevant changes (in the manual).
- [ ] There's a new file in `changelog/unreleased/` that describes the changes for our users (see [template](https://github.com/restic/restic/blob/master/changelog/TEMPLATE)).
- [ ] I have added documentation for relevant changes (in the manual). NOTE: Do not edit files in `doc/man`, as they are auto-generated.
- [ ] There's a new file in `changelog/unreleased/` describing the changes for our users if relevant (see [template](https://github.com/restic/restic/blob/master/changelog/TEMPLATE)).
- [ ] I'm done! This pull request is ready for review.
+1 -1
View File
@@ -22,6 +22,6 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Codespell
uses: codespell-project/actions-codespell@8f01853be192eb0f849a5c7d721450e7a467c579 # v2.2
+2 -2
View File
@@ -26,10 +26,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Log in to the Container registry
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
+13
View File
@@ -0,0 +1,13 @@
name: size-label
on: pull_request_target
jobs:
size-label:
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
steps:
- name: size-label
uses: "pascalgn/size-label-action@56b489b027932ec0cf60438a1a5f1a19c8fc71ff" # v0.5.7
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
+33 -29
View File
@@ -13,7 +13,7 @@ permissions:
contents: read
env:
latest_go: "1.26.x"
latest_go: "1.27.x"
GO111MODULE: on
jobs:
@@ -23,29 +23,29 @@ jobs:
# list of jobs to run:
include:
- job_name: Windows
go: 1.26.x
go: 1.27.x
os: windows-latest
- job_name: macOS
go: 1.26.x
go: 1.27.x
os: macOS-latest
test_fuse: false
- job_name: Linux
go: 1.26.x
go: 1.27.x
os: ubuntu-latest
test_cloud_backends: true
test_fuse: true
check_changelog: true
- job_name: Linux (race)
go: 1.26.x
go: 1.27.x
os: ubuntu-latest
test_fuse: true
test_opts: "-race"
- job_name: Linux
go: 1.25.x
go: 1.26.x
os: ubuntu-latest
test_fuse: true
@@ -57,10 +57,10 @@ jobs:
steps:
- name: Check out code
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Set up Go ${{ matrix.go }}
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: ${{ matrix.go }}
@@ -69,14 +69,21 @@ jobs:
echo "build Go tools"
go install github.com/restic/rest-server/cmd/rest-server@master
echo "install minio server"
echo "install seaweedfs"
SEAWEEDFS_VERSION=4.47
mkdir $HOME/bin
case "$(uname -m)" in
x86_64) seaweed_arch=amd64 ;;
arm64|aarch64) seaweed_arch=arm64 ;;
*) echo "unsupported architecture $(uname -m)"; exit 1 ;;
esac
if [ "$RUNNER_OS" == "macOS" ]; then
wget --no-verbose -O $HOME/bin/minio https://dl.minio.io/server/minio/release/darwin-amd64/minio
seaweed_os=darwin
else
wget --no-verbose -O $HOME/bin/minio https://dl.minio.io/server/minio/release/linux-amd64/minio
seaweed_os=linux
fi
chmod 755 $HOME/bin/minio
wget --no-verbose -O- "https://github.com/seaweedfs/seaweedfs/releases/download/${SEAWEEDFS_VERSION}/${seaweed_os}_${seaweed_arch}.tar.gz" \
| tar -xzf - -C $HOME/bin weed
echo "install rclone"
if [ "$RUNNER_OS" == "macOS" ]; then
@@ -101,9 +108,13 @@ jobs:
echo "build Go tools"
go install github.com/restic/rest-server/cmd/rest-server@master
echo "install minio server"
echo "install seaweedfs"
$seaweedVersion = "4.47"
mkdir $Env:USERPROFILE/bin
Invoke-WebRequest https://dl.minio.io/server/minio/release/windows-amd64/minio.exe -OutFile $Env:USERPROFILE/bin/minio.exe
Invoke-WebRequest "https://github.com/seaweedfs/seaweedfs/releases/download/$seaweedVersion/windows_amd64.zip" -OutFile seaweedfs.zip
unzip seaweedfs.zip
move weed.exe $Env:USERPROFILE/bin
rm seaweedfs.zip
echo "install rclone"
Invoke-WebRequest https://downloads.rclone.org/rclone-current-windows-amd64.zip -OutFile rclone.zip
@@ -172,14 +183,12 @@ jobs:
RESTIC_TEST_OS_USERNAME: ${{ secrets.RESTIC_TEST_OS_USERNAME }}
RESTIC_TEST_OS_PASSWORD: ${{ secrets.RESTIC_TEST_OS_PASSWORD }}
RESTIC_TEST_OS_REGION_NAME: ${{ secrets.RESTIC_TEST_OS_REGION_NAME }}
RESTIC_TEST_SWIFT: ${{ secrets.RESTIC_TEST_SWIFT }}
# fail if any of the following tests cannot be run
RESTIC_TEST_DISALLOW_SKIP: "restic/backend/rest.TestBackendREST,\
restic/backend/sftp.TestBackendSFTP,\
restic/backend/s3.TestBackendMinio,\
restic/backend/s3.TestBackendSeaweedFS,\
restic/backend/rclone.TestBackendRclone,\
restic/backend/s3.TestBackendS3,\
restic/backend/swift.TestBackendSwift,\
restic/backend/b2.TestBackendB2,\
restic/backend/gs.TestBackendGS,\
restic/backend/azure.TestBackendAzure"
@@ -222,10 +231,10 @@ jobs:
steps:
- name: Check out code
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Set up Go ${{ env.latest_go }}
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: ${{ env.latest_go }}
@@ -244,10 +253,10 @@ jobs:
checks: write
steps:
- name: Check out code
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Set up Go ${{ env.latest_go }}
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: ${{ env.latest_go }}
@@ -255,14 +264,9 @@ jobs:
uses: golangci/golangci-lint-action@v9
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v2.12
version: v2.14
args: --verbose --timeout 5m
# only run golangci-lint for pull requests, otherwise ALL hints get
# reported. We need to slowly address all issues until we can enable
# linting the master branch :)
if: github.event_name == 'pull_request'
- name: Check go.mod/go.sum
run: |
echo "check if go.mod and go.sum are up to date"
@@ -280,7 +284,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe
uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35
with:
jobs: ${{ toJSON(needs) }}
@@ -289,7 +293,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Docker meta
id: meta
+8 -4
View File
@@ -32,7 +32,6 @@ linters:
backend-imports:
files:
- "**/internal/backend/**"
- "!**/internal/backend/cache/**"
- "!**/internal/backend/test/**"
- "!**/*_test.go"
deny:
@@ -40,6 +39,13 @@ linters:
desc: "internal/restic should not be imported to keep the architectural layers intact"
- pkg: "github.com/restic/restic/internal/repository"
desc: "internal/repository should not be imported to keep the architectural layers intact"
repository-internals:
files:
- "**"
- "!**/internal/repository/**"
deny:
- pkg: "github.com/restic/restic/internal/repository/"
desc: "packages below internal/repository should not be imported to not depend on repository internals"
importas:
alias:
- pkg: github.com/restic/restic/internal/test
@@ -72,9 +78,7 @@ linters:
text: "package-comments: should have a package comment"
# staticcheck: there's no easy way to replace these packages
- path: (.+)\.go$
text: 'SA1019: "golang.org/x/crypto/poly1305" is deprecated'
- path: (.+)\.go$
text: 'SA1019: "golang.org/x/crypto/openpgp" is deprecated'
text: 'SA1019: golang.org/x/crypto/poly1305 is deprecated'
- path: (.+)\.go$
text: "redefines-builtin-id:"
# revive: collection of helpers to implement a backend, more descriptive names would be too repetitive
+262
View File
@@ -1,5 +1,6 @@
# Table of Contents
* [Changelog for 0.20.0](#changelog-for-restic-0200-2026-11-19)
* [Changelog for 0.19.1](#changelog-for-restic-0191-2026-07-05)
* [Changelog for 0.19.0](#changelog-for-restic-0190-2026-06-09)
* [Changelog for 0.18.1](#changelog-for-restic-0181-2025-09-21)
@@ -42,6 +43,267 @@
* [Changelog for 0.6.0](#changelog-for-restic-060-2017-05-29)
# Changelog for restic 0.20.0 (2026-11-19)
The following sections list the changes in restic 0.20.0 relevant to
restic users. The changes are ordered by importance.
## Summary
* Sec #22178: Fix ownership when `restore --ownership-by-name` cannot resolve names
* Sec #22180: Reject duplicate or out-of-order node names during `restore`
* Fix #21977: Don't crash on truncated key or config file
* Fix #22007: Redact `swift` backend password in debug log output
* Fix #22051: Reject empty repository location files
* Fix #22085: Restore partially matching hard-linked files correctly
* Fix #22092: Handle empty directories from older repaired snapshots
* Fix #22112: Don't reset `stats` progress bar counters for every snapshot
* Fix #22120: Improve error message when `prune` fails to list pack files
* Fix #22136: Improve resilience of repository v2 upgrade rollback
* Fix #22163: Error on too large numbers in `--keep-within*` durations
* Fix #22181: Do not delete files in directories whose tree cannot be loaded
* Chg #22104: Require Go 1.26.10 or newer
* Enh #3129: Add JSON support to `prune` command
* Enh #5189: Add option to disable AWS S3 dual-stack endpoints
* Enh #5248: Add warmup support for `check` on the S3 backend
* Enh #5372: Support specifying snapshot ID in `list packs` command
* Enh #5741: Support Multi-Bucket Application Keys in the `b2` backend
* Enh #21845: Handle missing pack files in `repair packs`
* Enh #21870: Show excluded items during `backup` in verbose mode
* Enh #21883: Handle corrupted pack files in `find --pack`
* Enh #21892: Make `repair snapshots --forget` remove broken snapshots
* Enh #21937: Reduce memory usage of the in-memory index
## Details
* Security #22178: Fix ownership when `restore --ownership-by-name` cannot resolve names
When restoring with `--ownership-by-name`, user or group names that could not be
resolved on the restore host (or were not recorded in the snapshot) caused
restic to change the owner of the restored file to UID/GID 0. Combined with
restored setuid/setgid bits this could produce unintentional setuid-root files.
Restic now instead falls back to the numeric UID/GID stored in the snapshot and
prints a warning when a name cannot be resolved.
https://github.com/restic/restic/issues/22178
https://github.com/restic/restic/pull/22185
* Security #22180: Reject duplicate or out-of-order node names during `restore`
A tree containing a symlink and a directory with the same name could let
`restore` write through the symlink to files outside the restore target.
Restic now rejects trees whose node names are not strictly increasing during
restore and reports an error instead of restoring such a snapshot.
Thanks to Mario Ramos (@marrionesa), calif.io, Zachariah Mithani (AploSec) and
Manuel Riel (@m3nu) for reporting this.
https://github.com/restic/restic/issues/22180
https://github.com/restic/restic/pull/22190
* Bugfix #21977: Don't crash on truncated key or config file
Restic previously crashed with a slice bounds panic when the repository
contained a key or config file that was shorter than the encryption overhead,
for example after an upload was interrupted. Since every command has to read a
key file, the whole repository became unusable until the file was removed.
This has now been fixed, and restic instead reports that the file is too short.
https://github.com/restic/restic/pull/21977
* Bugfix #22007: Redact `swift` backend password in debug log output
Restic could previously write the OpenStack Swift backend password in clear text
to the debug log when debug logging was enabled. The password came from the
environment variables `OS_PASSWORD` and `ST_KEY`. It is now redacted.
https://github.com/restic/restic/pull/22007
* Bugfix #22051: Reject empty repository location files
Previously, if the `--repository-file` option or `RESTIC_REPOSITORY_FILE`
environment variable referred to a file that was either empty or contained only
whitespace, restic used the current directory for the repository.
This has now been fixed, and restic instead reports an error in this case.
https://github.com/restic/restic/issues/22051
https://github.com/restic/restic/pull/22052
* Bugfix #22085: Restore partially matching hard-linked files correctly
When restoring over an existing file which had hard links and was partially
different from the file in the snapshot, restic used to replace the file with an
empty one but only restored the changed parts. The restored file then contained
zero bytes in the unchanged parts. Restic now instead rewrites the whole file in
this case.
https://github.com/restic/restic/issues/22085
https://github.com/restic/restic/pull/22086
* Bugfix #22092: Handle empty directories from older repaired snapshots
Since restic 0.19.0, snapshots containing empty directories written by older
versions of `repair snapshots` could fail with `error decoding tree: expected [,
got <nil>`.
This has now been fixed, allowing `prune`, `check` and `restore` to process the
affected snapshots successfully.
https://github.com/restic/restic/issues/22092
https://github.com/restic/restic/pull/22117
* Bugfix #22112: Don't reset `stats` progress bar counters for every snapshot
The progress bar of the `stats` command previously reset its file, blob and size
counters at the start of each snapshot, so the final progress line only showed
the numbers for the last processed snapshot. These numbers varied between runs
depending on the order in which snapshots were processed.
The progress bar now instead counts across all selected snapshots.
https://github.com/restic/restic/issues/22112
https://github.com/restic/restic/pull/22130
* Bugfix #22120: Improve error message when `prune` fails to list pack files
When listing the pack files of a repository failed during `prune`, for example
due to a request timeout, restic printed the error together with a stack trace.
Restic now instead reports a short error message stating that listing the pack
files failed.
https://github.com/restic/restic/issues/22120
https://github.com/restic/restic/pull/22124
* Bugfix #22136: Improve resilience of repository v2 upgrade rollback
When an upgrade from repository version 1 to version 2 failed, restic deleted
the configuration file before writing the previous version of it back. If
writing the old configuration file back also failed, the repository no longer
had a configuration file and could not be opened.
Restic now writes the previous configuration back without deleting the file
first on relevant backends.
https://github.com/restic/restic/pull/22136
* Bugfix #22163: Error on too large numbers in `--keep-within*` durations
Restic used to crash with a stack trace when a number in a duration such as the
one passed to `forget --keep-within` did not fit into an integer. It now reports
an invalid argument instead.
https://github.com/restic/restic/pull/22163
* Bugfix #22181: Do not delete files in directories whose tree cannot be loaded
When `restore --delete` failed to load or read the tree of a directory, for
example because a pack file was missing, restic reported an error but then
deleted all existing content of that directory in the target. Restic now
disables deletion for the rest of the restore when a tree cannot be loaded.
https://github.com/restic/restic/issues/22181
https://github.com/restic/restic/pull/22189
* Change #22104: Require Go 1.26.10 or newer
Restic now requires Go 1.26.10 or newer to build, as the library used to access
the B2 backend requires it.
https://github.com/restic/restic/pull/22104
https://github.com/restic/restic/pull/22121
* Enhancement #3129: Add JSON support to `prune` command
The `prune` command now supports the `--json` option for JSON output.
https://github.com/restic/restic/issues/3129
https://github.com/restic/restic/pull/5239
* Enhancement #5189: Add option to disable AWS S3 dual-stack endpoints
Restic used dual-stack endpoints for AWS regions that have them, with no way to
opt out. VPC interface and gateway endpoints do not support dual-stack, so a
repository reachable over a VPC endpoint could not be used.
Passing `-o s3.disable-dualstack=true` now keeps restic on the single-stack
endpoint.
https://github.com/restic/restic/issues/5189
https://github.com/restic/restic/pull/22060
* Enhancement #5248: Add warmup support for `check` on the S3 backend
The `check` command can now warm up pack files from cold storage on S3 and
S3-compatible providers before reading them. Like the other cold storage
features, this remains experimental and is gated behind the `s3-restore` feature
flag.
https://github.com/restic/restic/issues/3202
https://github.com/restic/restic/issues/2504
https://github.com/restic/restic/pull/5248
* Enhancement #5372: Support specifying snapshot ID in `list packs` command
The `list packs` command now accepts a snapshot ID and lists the pack files used
by that snapshot.
https://github.com/restic/restic/issues/5372
https://github.com/restic/restic/pull/5396
* Enhancement #5741: Support Multi-Bucket Application Keys in the `b2` backend
The `b2` backend now supports Backblaze B2 Multi-Bucket Application Keys,
including single-bucket keys created through the multi-bucket API (for example
by the Backblaze Terraform provider).
https://github.com/restic/restic/issues/5741
https://github.com/restic/restic/pull/22104
* Enhancement #21845: Handle missing pack files in `repair packs`
Missing and damaged pack files previously required separate approaches to fix a
repository. Both cases can now be handled by the `repair packs` command, which
removes missing pack files from the repository index.
https://github.com/restic/restic/pull/21845
* Enhancement #21870: Show excluded items during `backup` in verbose mode
The `backup -vv` command (backup in verbose mode) now shows excluded files and
directories. Both text and JSON output are supported.
https://github.com/restic/restic/issues/21870
https://github.com/restic/restic/pull/21887
* Enhancement #21883: Handle corrupted pack files in `find --pack`
The `find --pack <id>` command can now also report snapshots in which a pack
file is corrupted but still present in the repository index.
https://github.com/restic/restic/pull/21883
* Enhancement #21892: Make `repair snapshots --forget` remove broken snapshots
The `repair snapshots --forget` command will now remove broken snapshot files
reported by `check` or by earlier error messages from restic.
https://github.com/restic/restic/issues/21892
https://github.com/restic/restic/pull/21907
* Enhancement #21937: Reduce memory usage of the in-memory index
Restic keeps an index of the repository contents in memory during most
operations. This index now requires roughly 12% less memory, which is especially
noticeable for large repositories with many snapshots, where a lot of index data
has to be loaded.
https://github.com/restic/restic/pull/21937
# Changelog for restic 0.19.1 (2026-07-05)
The following sections list the changes in restic 0.19.1 relevant to
restic users. The changes are ordered by importance.
+57 -101
View File
@@ -1,28 +1,27 @@
This document describes the way you can contribute to the restic project.
This document describes how to report security issues and bugs, and how to provide
patches for restic.
Ways to Help Out
================
Thank you for your contribution! Please **open an issue first** (or add a
comment to an existing issue) if you plan to work on any code or add a new
feature. This way, duplicate work is prevented and we can discuss your ideas
and design first. Small bugfixes are an exception to this rule, just open a
Thank you for your contribution! Always check if there is an existing issue and
add a comment there or otherwise **open an issue first** if you plan to work
on any larger amount of code or add a new significant feature.
This way, duplicate work is prevented and we can discuss your ideas and
design first. Small bugfixes are an exception to this rule, just open a
pull request in this case.
There are several ways you can help us out. First of all code contributions and
bug fixes are most welcome. However even "minor" details as fixing spelling
errors, improving documentation or pointing out usability issues are a great
help also.
Contributions are welcome in general, but expect long review times due to
a general overload of the maintainers.
The restic project uses the GitHub infrastructure (see the
[project page](https://github.com/restic/restic)) for all related discussions
as well as the [forum](https://forum.restic.net/) and the `#restic` channel
on [irc.libera.chat](https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:6697/#restic).
on [irc.libera.chat](https://web.libera.chat/#restic).
If you want to find an area that currently needs improving have a look at the
open issues listed at the
[issues page](https://github.com/restic/restic/issues). This is also the place
for discussing enhancement to the restic tools.
If you want to find an area that currently needs improving, have a look at the
open issues listed at the [issues page](https://github.com/restic/restic/issues).
This is also the place for discussing enhancements to the restic tools.
If you are unsure what to do, please have a look at the issues, especially
those tagged
@@ -35,19 +34,11 @@ at the issues tagged as [help wanted](https://github.com/restic/restic/labels/he
Reporting Bugs
==============
You've found a bug? Thanks for letting us know so we can fix it! It is a good
idea to describe in detail how to reproduce the bug (when you know how), what
environment was used and so on. Please tell us at least the following things:
* What's the version of restic you used? Please include the output of
`restic version` in your bug report.
* What commands did you execute to get to where the bug occurred?
* What did you expect?
* What happened instead?
* Are you aware of a way to reproduce the bug?
Remember, the easier it is for us to reproduce the bug, the earlier it will be
corrected!
You've found a bug? Thanks for letting us know so we can fix it! Please fill out
the [Bug issue template](https://github.com/restic/restic/blob/master/.github/ISSUE_TEMPLATE/Bug.md?plain=1),
but refer to [Security Policy](./SECURITY.md) for critical security issues.
We need the information to reproduce and investigate bugs. Remember, the easier
it is for us to reproduce the bug, the earlier it will be corrected!
In addition, you can instruct restic to create a debug log by setting the
environment variable `DEBUG_LOG` to a file, e.g. like this:
@@ -66,64 +57,20 @@ and then exit immediately. This will not damage your repository, however,
it might be necessary to manually clean up stale lock files using
`restic unlock`.
On Windows, please set the environment variable `RESTIC_DEBUG_STACKTRACE_SIGINT`
to `true` and press `Ctrl-C` to create a stacktrace.
On Windows, please run restic with the environment variable
`RESTIC_DEBUG_STACKTRACE_SIGINT` set to `true` and press `Ctrl-C` to
create a stacktrace.
If you think restic uses too much memory or a too large cache directory, then
please include the output of `restic stats --mode debug`.
If you think restic uses too much memory or the cache directory is too large,
then please include the output of `restic stats --mode debug`.
Development Environment
=======================
Restic Development
==================
The repository contains the code written for restic in the directories
`cmd/` and `internal/`.
Make sure you have the minimum required Go version installed. Clone the repo
(without having `$GOPATH` set) and `cd` into the directory:
$ unset GOPATH
$ git clone https://github.com/restic/restic
$ cd restic
Then use the `go` tool to build restic:
$ go build ./cmd/restic
$ ./restic version
restic 0.14.0-dev (compiled manually) compiled with go1.19 on linux/amd64
To create a debug build use:
$ go build -tags debug ./cmd/restic
You can run all tests with the following command:
$ go test ./...
Performance and Memory Usage Issues
===================================
Debug builds of restic support the `--block-profile`, `--cpu-profile`,
`--mem-profile`, and `--trace-profile` options which collect performance data
that later on can be analyzed using the go tools:
$ restic --cpu-profile . [...]
$ go tool pprof -http localhost:12345 cpu.pprof
To analyze a trace profile use `go tool trace -http=localhost:12345 trace.out`.
As the memory usage of restic changes over time, it may be useful to capture a
snapshot of the current heap. This is possible using then `--listen-profile`
option. Then while restic runs you can query and afterwards analyze the heap statistics.
$ restic --listen-profile localhost:12345 [...]
$ curl http://localhost:12345/debug/pprof/heap -o heap.pprof
$ go tool pprof -http localhost:12345 heap.pprof
Further useful tools are setting the environment variable `GODEBUG=gctrace=1`,
which provides information about garbage collector runs. For a graphical variant
combine this with gcvis.
The [development environment](doc/090_participating.rst#development-environment)
section describes how to build restic and run the tests. The documentation also
contains guidance on debugging and writing tests.
Providing Patches
@@ -136,7 +83,8 @@ down to the following steps:
0. If you want to work on something, please add a comment to the issue on
GitHub. For a new feature, please add an issue before starting to work on
it, so that duplicate work is prevented.
it, so that duplicate work is prevented. Small bugfixes are an exception
to this rule, just open a pull request in this case.
1. Next, fork our project on GitHub if you haven't done so already.
@@ -144,30 +92,38 @@ down to the following steps:
your changes. If you are working on the code itself, please set up the
development environment as described in the previous section.
3. Commit your changes to the new branch as fine grained as possible, as
smaller patches, for individual changes, are easier to discuss and merge.
3. Commit in small, cohesive pieces. Smaller patches are easier to discuss and merge.
4. Push the new branch with your changes to your fork of the repository.
5. Create a pull request by visiting the GitHub website, it will guide you
through the process. Please [allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
5. Create a pull request by visiting the GitHub website. It will guide you
through the process. You **must** fill out the [Pull Request template](https://github.com/restic/restic/blob/master/.github/PULL_REQUEST_TEMPLATE.md?plain=1).
Please also [allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
6. You will receive comments on your code and the feature or bug that they
6. You will receive comments on your commits and the feature or bug that they
address. Maybe you need to rework some minor things, in this case push new
commits to the branch you created for the pull request (or amend the
existing commit, use common sense to decide which is better), they will be
automatically added to the pull request.
existing commit; use common sense to decide which is better), they will be
automatically added to the pull request. Do not include merge commits.
Please note that it may take a while until a maintainer finds time to review
your pull request. Please refrain from pinging maintainers for a review after
a few days, unless the fix is critical.
Maintainers may assign themselves to your pull request to simplify tracking
of pull requests to review, but you are still responsible for addressing review
comments.
7. If your pull request changes anything that users should be aware of
(a bugfix, a new feature, ...) please add an entry as a new file in
`changelog/unreleased` including the issue number in the filename (e.g.
`issue-8756`). Use the template in `changelog/TEMPLATE` for the content.
`pull-1234` or `issue-8756`). Use the template in `changelog/TEMPLATE` for the content.
It will be used in the announcement of the next stable release. While
writing, ask yourself: If I were the user, what would I need to be aware
of with this change?
of with this change? Documentation-only changes do not get a changelog entry.
8. Do not edit the man pages under `doc/man` or `doc/manual_rest.rst` -
these are autogenerated before new releases.
8. Do not edit the man pages under `doc/man` or the generated completion files
at `doc/*-completion.*` - these are autogenerated before new releases.
9. Once your code looks good and passes all the tests, we'll merge it. Thanks
a lot for your contribution!
@@ -190,17 +146,14 @@ The project is using the program
[`golangci-lint`](https://github.com/golangci/golangci-lint) to run a list of
linters and checkers. It will be run on the code when you submit a PR. In order
to check your code beforehand, you can run `golangci-lint run` manually.
Eventually, we will enable `golangci-lint` for the whole code base. For now,
you can ignore warnings printed for lines you did not modify, those will be
ignored by the CI.
For each pull request, several different systems run the integration tests on
Linux, macOS and Windows. We won't merge any code that does not pass all tests
for all systems, so when a tests fails, try to find out what's wrong and fix
for all systems, so when a test fails, try to find out what's wrong and fix
it. If you need help on this, please leave a comment in the pull request, and
we'll be glad to assist. Having a PR with failing integration tests is nothing
to be ashamed of. In contrast, that happens regularly for all of us. That's
what the tests are there for.
to be ashamed of. That happens regularly for all of us. That's what the tests
are there for.
More details of how to structure tests can be found here at
[writing tests](https://restic.readthedocs.io/en/stable/090_participating.html#writing-tests).
@@ -214,13 +167,16 @@ history and triaging bugs much easier.
Git commit messages have a very terse summary in the first line of the commit
message, followed by an empty line, followed by a more verbose description or a
List of changed things. For examples, please refer to the excellent [How to
list of changed things. For examples, please refer to the excellent [How to
Write a Git Commit Message](https://chris.beams.io/posts/git-commit/).
If you change/add multiple different things that aren't related at all, try to
make several smaller commits. This is much easier to review. Using `git add -p`
allows staging and committing only some changes.
Do not add merge commits in pull requests. Instead rebase your pull request
onto the master branch if there are merge conflicts.
Code Review
===========
@@ -228,7 +184,7 @@ The restic project encourages actively reviewing the code, as it will store
your precious data, so it's common practice to receive comments on provided
patches.
If you are reviewing other contributor's code please consider the following
If you are reviewing another contributor's code please consider the following
when reviewing:
* Be nice. Please make the review comment as constructive as possible so all
+9 -5
View File
@@ -46,7 +46,7 @@ Therefore, restic supports the following backends for storing backups natively:
- [Local directory](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#local)
- [sftp server (via SSH)](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#sftp)
- [HTTP REST server](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#rest-server) ([protocol](https://restic.readthedocs.io/en/latest/100_references.html#rest-backend), [rest-server](https://github.com/restic/rest-server))
- [Amazon S3](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#amazon-s3) (either from Amazon or using the [Minio](https://minio.io) server)
- [Amazon S3](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#amazon-s3) (or any other S3-compatible storage)
- [OpenStack Swift](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#openstack-swift)
- [BackBlaze B2](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#backblaze-b2)
- [Microsoft Azure Blob Storage](https://restic.readthedocs.io/en/latest/030_preparing_a_new_repo.html#microsoft-azure-blob-storage)
@@ -91,17 +91,21 @@ reproduce a byte identical version from the source code for that
release. Instructions on how to do that are contained in the
[builder repository](https://github.com/restic/builder).
## News
# News
You can follow the restic project on Mastodon [@resticbackup](https://fosstodon.org/@restic) or subscribe to
You can follow the restic project on Mastodon [@restic](https://fosstodon.org/@restic) or subscribe to
the [project blog](https://restic.net/blog/).
## License
# License
Restic is licensed under [BSD 2-Clause License](https://opensource.org/licenses/BSD-2-Clause). You can find the
complete text in [`LICENSE`](LICENSE).
## Sponsorship
# Contributing
See our [contributing guide](CONTRIBUTING.md) and [documentation for restic development](doc/090_participating.rst).
# Sponsorship
Backend integration tests for Google Cloud Storage and Microsoft Azure Blob
Storage are sponsored by [AppsCode](https://appscode.com)!
+15
View File
@@ -0,0 +1,15 @@
Security
========
**Important**: If you discover something that you believe to be a
possible critical security issue, please do *not* open a GitHub issue
but send an email directly to alexander@bumpern.de. If possible, please
encrypt your email using the following PGP key
([0x91A6868BD3F7A907](https://restic.net/gpg-key-alex.asc)):
```
pub 4096R/91A6868BD3F7A907 2014-11-01
Key fingerprint = CF8F 18F2 8445 7597 3F79 D4E1 91A6 868B D3F7 A907
uid Alexander Neumann <alexander@bumpern.de>
sub 4096R/D5FC2ACF4043FDF1 2014-11-01
```
+1 -1
View File
@@ -1 +1 @@
0.19.1-dev
0.20.0-dev
+1 -1
View File
@@ -59,7 +59,7 @@ var config = Config{
// see https://github.com/googleapis/google-cloud-go/issues/11448
DefaultBuildTags: []string{"selfupdate", "disable_grpc_modules"}, // specify build tags which are always used
Tests: []string{"./..."}, // tests to run
MinVersion: GoVersion{Major: 1, Minor: 25, Patch: 0}, // minimum Go version supported
MinVersion: GoVersion{Major: 1, Minor: 26, Patch: 10}, // minimum Go version supported
}
// Config configures the build.
+7
View File
@@ -0,0 +1,7 @@
Enhancement: Show excluded items during `backup` in verbose mode
The `backup -vv` command (backup in verbose mode) now shows excluded
files and directories. Both text and JSON output are supported.
https://github.com/restic/restic/issues/21870
https://github.com/restic/restic/pull/21887
+7
View File
@@ -0,0 +1,7 @@
Enhancement: Make `repair snapshots --forget` remove broken snapshots
The `repair snapshots --forget` command will now remove broken snapshot
files reported by `check` or by earlier error messages from restic.
https://github.com/restic/restic/issues/21892
https://github.com/restic/restic/pull/21907
+10
View File
@@ -0,0 +1,10 @@
Bugfix: Reject empty repository location files
Previously, if the `--repository-file` option or `RESTIC_REPOSITORY_FILE`
environment variable referred to a file that was either empty or contained
only whitespace, restic used the current directory for the repository.
This has now been fixed, and restic instead reports an error in this case.
https://github.com/restic/restic/issues/22051
https://github.com/restic/restic/pull/22052
+11
View File
@@ -0,0 +1,11 @@
Bugfix: Restore partially matching hard-linked files correctly
When restoring over an existing file which had hard links and
was partially different from the file in the snapshot, restic
used to replace the file with an empty one but only restored
the changed parts. The restored file then contained zero bytes
in the unchanged parts. Restic now instead rewrites the whole
file in this case.
https://github.com/restic/restic/issues/22085
https://github.com/restic/restic/pull/22086
+11
View File
@@ -0,0 +1,11 @@
Bugfix: Handle empty directories from older repaired snapshots
Since restic 0.19.0, snapshots containing empty directories written by older
versions of `repair snapshots` could fail with `error decoding tree: expected
[, got <nil>`.
This has now been fixed, allowing `prune`, `check` and `restore` to process
the affected snapshots successfully.
https://github.com/restic/restic/issues/22092
https://github.com/restic/restic/pull/22117
+12
View File
@@ -0,0 +1,12 @@
Bugfix: Don't reset `stats` progress bar counters for every snapshot
The progress bar of the `stats` command previously reset its file,
blob and size counters at the start of each snapshot, so the final
progress line only showed the numbers for the last processed snapshot.
These numbers varied between runs depending on the order in which
snapshots were processed.
The progress bar now instead counts across all selected snapshots.
https://github.com/restic/restic/issues/22112
https://github.com/restic/restic/pull/22130
+11
View File
@@ -0,0 +1,11 @@
Bugfix: Improve error message when `prune` fails to list pack files
When listing the pack files of a repository failed during `prune`, for
example due to a request timeout, restic printed the error together with
a stack trace.
Restic now instead reports a short error message stating that listing
the pack files failed.
https://github.com/restic/restic/issues/22120
https://github.com/restic/restic/pull/22124
+11
View File
@@ -0,0 +1,11 @@
Bugfix: Improve resilience of repository v2 upgrade rollback
When an upgrade from repository version 1 to version 2 failed, restic
deleted the configuration file before writing the previous version of
it back. If writing the old configuration file back also failed, the
repository no longer had a configuration file and could not be opened.
Restic now writes the previous configuration back without deleting
the file first on relevant backends.
https://github.com/restic/restic/pull/22136
+12
View File
@@ -0,0 +1,12 @@
Security: Fix ownership when `restore --ownership-by-name` cannot resolve names
When restoring with `--ownership-by-name`, user or group names that could not
be resolved on the restore host (or were not recorded in the snapshot) caused
restic to change the owner of the restored file to UID/GID 0. Combined with
restored setuid/setgid bits this could produce unintentional setuid-root files.
Restic now instead falls back to the numeric UID/GID stored in the snapshot and
prints a warning when a name cannot be resolved.
https://github.com/restic/restic/issues/22178
https://github.com/restic/restic/pull/22185
+13
View File
@@ -0,0 +1,13 @@
Security: Reject duplicate or out-of-order node names during `restore`
A tree containing a symlink and a directory with the same name could let
`restore` write through the symlink to files outside the restore target.
Restic now rejects trees whose node names are not strictly increasing
during restore and reports an error instead of restoring such a snapshot.
Thanks to Mario Ramos (@marrionesa), calif.io, Zachariah Mithani (AploSec) and
Manuel Riel (@m3nu) for reporting this.
https://github.com/restic/restic/issues/22180
https://github.com/restic/restic/pull/22190
+9
View File
@@ -0,0 +1,9 @@
Bugfix: Do not delete files in directories whose tree cannot be loaded
When `restore --delete` failed to load or read the tree of a directory, for
example because a pack file was missing, restic reported an error but then
deleted all existing content of that directory in the target. Restic now
disables deletion for the rest of the restore when a tree cannot be loaded.
https://github.com/restic/restic/issues/22181
https://github.com/restic/restic/pull/22189
+6
View File
@@ -0,0 +1,6 @@
Enhancement: Add JSON support to `prune` command
The `prune` command now supports the `--json` option for JSON output.
https://github.com/restic/restic/issues/3129
https://github.com/restic/restic/pull/5239
+10
View File
@@ -0,0 +1,10 @@
Enhancement: Add warmup support for `check` on the S3 backend
The `check` command can now warm up pack files from cold storage on S3
and S3-compatible providers before reading them. Like the other cold
storage features, this remains experimental and is gated behind the
`s3-restore` feature flag.
https://github.com/restic/restic/pull/5248
https://github.com/restic/restic/issues/3202
https://github.com/restic/restic/issues/2504
+11
View File
@@ -0,0 +1,11 @@
Enhancement: Add option to disable AWS S3 dual-stack endpoints
Restic used dual-stack endpoints for AWS regions that have them, with no way to
opt out. VPC interface and gateway endpoints do not support dual-stack, so a
repository reachable over a VPC endpoint could not be used.
Passing `-o s3.disable-dualstack=true` now keeps restic on the single-stack
endpoint.
https://github.com/restic/restic/issues/5189
https://github.com/restic/restic/pull/22060
+7
View File
@@ -0,0 +1,7 @@
Enhancement: Support specifying snapshot ID in `list packs` command
The `list packs` command now accepts a snapshot ID and lists the pack
files used by that snapshot.
https://github.com/restic/restic/issues/5372
https://github.com/restic/restic/pull/5396
+8
View File
@@ -0,0 +1,8 @@
Enhancement: Support Multi-Bucket Application Keys in the `b2` backend
The `b2` backend now supports Backblaze B2 Multi-Bucket Application Keys,
including single-bucket keys created through the multi-bucket API (for
example by the Backblaze Terraform provider).
https://github.com/restic/restic/issues/5741
https://github.com/restic/restic/pull/22104
+7
View File
@@ -0,0 +1,7 @@
Enhancement: Handle missing pack files in `repair packs`
Missing and damaged pack files previously required separate approaches
to fix a repository. Both cases can now be handled by the `repair packs`
command, which removes missing pack files from the repository index.
https://github.com/restic/restic/pull/21845
+6
View File
@@ -0,0 +1,6 @@
Enhancement: Handle corrupted pack files in `find --pack`
The `find --pack <id>` command can now also report snapshots in which
a pack file is corrupted but still present in the repository index.
https://github.com/restic/restic/pull/21883
+8
View File
@@ -0,0 +1,8 @@
Enhancement: Reduce memory usage of the in-memory index
Restic keeps an index of the repository contents in memory during most
operations. This index now requires roughly 12% less memory, which is
especially noticeable for large repositories with many snapshots, where
a lot of index data has to be loaded.
https://github.com/restic/restic/pull/21937
+10
View File
@@ -0,0 +1,10 @@
Bugfix: Don't crash on truncated key or config file
Restic previously crashed with a slice bounds panic when the repository
contained a key or config file that was shorter than the encryption overhead,
for example after an upload was interrupted. Since every command has to read
a key file, the whole repository became unusable until the file was removed.
This has now been fixed, and restic instead reports that the file is too short.
https://github.com/restic/restic/pull/21977
+7
View File
@@ -0,0 +1,7 @@
Bugfix: Redact `swift` backend password in debug log output
Restic could previously write the OpenStack Swift backend password in clear
text to the debug log when debug logging was enabled. The password came from
the environment variables `OS_PASSWORD` and `ST_KEY`. It is now redacted.
https://github.com/restic/restic/pull/22007
+7
View File
@@ -0,0 +1,7 @@
Change: Require Go 1.26.10 or newer
Restic now requires Go 1.26.10 or newer to build, as the library used to
access the B2 backend requires it.
https://github.com/restic/restic/pull/22104
https://github.com/restic/restic/pull/22121
+7
View File
@@ -0,0 +1,7 @@
Bugfix: Error on too large numbers in `--keep-within*` durations
Restic used to crash with a stack trace when a number in a duration such as
the one passed to `forget --keep-within` did not fit into an integer. It now
reports an invalid argument instead.
https://github.com/restic/restic/pull/22163
+2
View File
@@ -25,6 +25,8 @@ the default.
# The first issue ID determines the filename for the changelog entry:
# changelog/unreleased/issue-1234. If there are no relevant issue links,
# use the PR ID and call the file pull-55555.
#
# Make sure to always include a link to the PR that introduces the change.
https://github.com/restic/restic/issues/1234
https://github.com/restic/restic/pull/55555
+32
View File
@@ -0,0 +1,32 @@
Enhancement: More flexible formats for backup and rewrite time related options
Restic backup --time allowed in the past only the format "2006-01-02 15:04:05".
`backup --time` and `rewrite --new-time` can now use the following range of date/time
formats:
```
y-m-d
y-m-d HH:MM
y-m-d HH:MM:SS
d.m.y
d.m.y HH:MM
d.m.y HH:MM:SS
```
With additional modifiers for timezone name and timezone offset:
```
y-m-d HH:MM:SS MST
y-m-d HH:MM:SS -0700
y-m-d HH:MM:SS-0700
d.m.y HH:MM:SS MST
d.m.y HH:MM:SS -0700
d.m.y HH:MM:SS-0700
```
https://github.com/restic/restic/issues/2065
https://github.com/restic/restic/pull/21867
https://github.com/restic/restic/pull/22220
+12
View File
@@ -0,0 +1,12 @@
Enhancement: Add options to configure SSH keepalive for SFTP backend
SFTP connections could be interrupted when no data was sent for a long time,
for example while restic processes large amounts of unchanged data. The new
`sftp.server-alive-interval` and `sftp.server-alive-count-max` options set the
corresponding `ServerAliveInterval` and `ServerAliveCountMax` SSH options to
keep the connection alive. If unset, the values from the SSH configuration
are used.
https://github.com/restic/restic/issues/5313
https://github.com/restic/restic/pull/5314
https://forum.restic.net/t/robustness-of-repository-issue-resolved/1475
+12
View File
@@ -0,0 +1,12 @@
Bugfix: Fix damaged repository after concurrent `init` on REST backend
When two `restic init` runs raced against the same empty repository on
the REST backend, the repository could end up with a leftover key file
that did not belong to the stored config. Clients that happened to pick
that key failed with a "config or key ... is damaged" error.
Restic now stores the config file before the key file during `init`, so
the losing run no longer leaves a key file behind.
https://github.com/restic/restic/issues/5717
https://github.com/restic/restic/pull/21944
+5
View File
@@ -0,0 +1,5 @@
Enhancement: Add version-specific docs URLs to help output
Updated the help message to use version-specific documentation URLs or else just use latest.
https://github.com/restic/restic/pull/21795
+9
View File
@@ -0,0 +1,9 @@
Enhancement: Filter out-of-order entries in `check`, `dump` and `mount`
Only the `restore` command filtered out-of-order directory entries. Now,
also the `dump` and `mount` commands filter out-of-order directory entries.
The `check` command warns about such damaged directories. The `repair snapshots`
command can now remove such invalid directory entries while keeping the
remaining snapshot.
https://github.com/restic/restic/pull/22209
+13
View File
@@ -0,0 +1,13 @@
Bugfix: Quote non-printable characters in text output
Filenames and other printed text, such as hostnames, tags, and error
messages, could contain newlines or terminal control characters. Restic
printed many of those strings verbatim, which could mangle the status output
or change the terminal state.
Text output now quotes strings that contain non-printable or invalid UTF-8
characters. JSON output escapes control and format characters using standard
JSON escape sequences so it remains valid and decodes identically. The `cat`
command and `dump` commands still output data verbatim.
https://github.com/restic/restic/pull/22216
+5
View File
@@ -0,0 +1,5 @@
Enhancement: Speed up index decoding by 50%
Loading the repository index is now roughly 50% faster.
https://github.com/restic/restic/pull/22221
+15
View File
@@ -0,0 +1,15 @@
Bugfix: Correctly apply a `--tag` filter that contains an empty tag
The empty tag in a `--tag` or `--keep-tag` list selects snapshots without
any tags. Restic stopped looking at a tag list once it reached the empty
tag, so a list like `,foo` matched every untagged snapshot instead of
matching nothing, while the equivalent `foo,` matched nothing. For
`forget` that meant snapshots outside the filter were considered for
removal.
Restic now requires an empty tag to be the only tag in its list. A list
that combines it with another tag, such as `,foo` or `foo,`, is rejected
when the command line is parsed, instead of quietly selecting either the
wrong snapshots or none at all.
https://github.com/restic/restic/pull/22222
+6
View File
@@ -0,0 +1,6 @@
Enhancement: snapshots: Add --reverse option to reverse sort order
The `snapshots` command now supports a `--reverse` option, which lists
snapshots newest first instead of the default oldest first.
https://github.com/restic/restic/pull/5677
+43 -36
View File
@@ -10,6 +10,7 @@ import (
"path"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
@@ -53,22 +54,7 @@ Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
PreRunE: func(_ *cobra.Command, _ []string) error {
if envVal := os.Getenv("RESTIC_READ_CONCURRENCY"); envVal != "" && !opts.readConcurrencyFlag.Changed {
n, err := strconv.ParseUint(envVal, 10, 32)
if err != nil {
return errors.Fatalf("invalid value for RESTIC_READ_CONCURRENCY %q: %v", envVal, err)
}
opts.ReadConcurrency = uint(n)
}
if opts.Host == "" {
hostname, err := os.Hostname()
if err != nil {
debug.Log("os.Hostname() returned err: %v", err)
return nil
}
opts.Host = hostname
}
return nil
return opts.Finalize()
},
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
@@ -143,8 +129,8 @@ func (opts *BackupOptions) AddFlags(f *pflag.FlagSet) {
f.StringArrayVar(&opts.FilesFromRaw, "files-from-raw", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)")
f.StringVar(&opts.TimeStamp, "time", "", "`time` of the backup (ex. '2012-11-01 22:08:41') (default: now)")
f.BoolVar(&opts.WithAtime, "with-atime", false, "store the atime for all files and directories")
f.BoolVar(&opts.IgnoreInode, "ignore-inode", false, "ignore inode number and ctime changes when checking for modified files")
f.BoolVar(&opts.IgnoreCtime, "ignore-ctime", false, "ignore ctime changes when checking for modified files")
f.BoolVar(&opts.IgnoreInode, "ignore-inode", false, "ignore inode number and ctime changes when checking for modified files (default: $RESTIC_IGNORE_INODE or false)")
f.BoolVar(&opts.IgnoreCtime, "ignore-ctime", false, "ignore ctime changes when checking for modified files (default: $RESTIC_IGNORE_CTIME or false)")
f.BoolVarP(&opts.DryRun, "dry-run", "n", false, "do not upload or write any data, just show what would be done")
f.BoolVar(&opts.NoScan, "no-scan", false, "do not run scanner to estimate size of backup")
if runtime.GOOS == "windows" {
@@ -157,12 +143,35 @@ func (opts *BackupOptions) AddFlags(f *pflag.FlagSet) {
opts.readConcurrencyFlag = f.Lookup("read-concurrency")
// parse read inode and ctime from env, on error the default value will be used
opts.IgnoreInode, _ = strconv.ParseBool(os.Getenv("RESTIC_IGNORE_INODE"))
opts.IgnoreCtime, _ = strconv.ParseBool(os.Getenv("RESTIC_IGNORE_CTIME"))
// parse host from env, if not exists or empty the default value will be used
if host := os.Getenv("RESTIC_HOST"); host != "" {
opts.Host = host
}
}
func (opts *BackupOptions) Finalize() error {
if envVal := os.Getenv("RESTIC_READ_CONCURRENCY"); envVal != "" && !opts.readConcurrencyFlag.Changed {
n, err := strconv.ParseUint(envVal, 10, 32)
if err != nil {
return errors.Fatalf("invalid value for RESTIC_READ_CONCURRENCY %q: %v", envVal, err)
}
opts.ReadConcurrency = uint(n)
}
if opts.Host == "" {
hostname, err := os.Hostname()
if err != nil {
debug.Log("os.Hostname() returned err: %v", err)
return nil
}
opts.Host = hostname
}
return nil
}
var backupFSTestHook func(fs fs.FS) fs.FS
// ErrInvalidSourceData is used to report an incomplete backup
@@ -173,14 +182,14 @@ var ErrNoSourceData = errors.Fatal("all source directories/files do not exist")
// filterExisting returns the items that exist and can be accessed. It returns
// ErrNoSourceData if none remain, or ErrInvalidSourceData if some were skipped.
func filterExisting(items []string, warnf func(msg string, args ...interface{})) (result []string, err error) {
func filterExisting(items []string, warnf func(msg string, args ...any)) (result []string, err error) {
for _, item := range items {
_, err := fs.Lstat(item)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
warnf("%v does not exist, skipping\n", item)
warnf("%v does not exist, skipping\n", ui.Quote(item))
} else {
warnf("%v cannot be accessed, skipping\n", item)
warnf("%v cannot be accessed, skipping\n", ui.Quote(item))
}
continue
}
@@ -296,10 +305,8 @@ func (opts BackupOptions) Check(gopts global.Options, args []string) error {
}
filesFrom := append(append(opts.FilesFrom, opts.FilesFromVerbatim...), opts.FilesFromRaw...)
for _, filename := range filesFrom {
if filename == "-" {
return errors.Fatal("unable to read password from stdin when data is to be read from stdin, use --password-file or $RESTIC_PASSWORD")
}
if slices.Contains(filesFrom, "-") {
return errors.Fatal("unable to read password from stdin when data is to be read from stdin, use --password-file or $RESTIC_PASSWORD")
}
}
@@ -324,7 +331,7 @@ func (opts BackupOptions) Check(gopts global.Options, args []string) error {
// collectRejectByNameFuncs returns a list of all functions which may reject data
// from being saved in a snapshot based on path only
func collectRejectByNameFuncs(opts BackupOptions, repo *repository.Repository, warnf func(msg string, args ...interface{})) (fs []archiver.RejectByNameFunc, err error) {
func collectRejectByNameFuncs(opts BackupOptions, repo *repository.Repository, warnf func(msg string, args ...any)) (fs []archiver.RejectByNameFunc, err error) {
// exclude restic cache
if repo.Cache() != nil {
f, err := rejectResticCache(repo)
@@ -348,7 +355,7 @@ func collectRejectByNameFuncs(opts BackupOptions, repo *repository.Repository, w
// collectRejectFuncs returns a list of all functions which may reject data
// from being saved in a snapshot based on path and file info
func collectRejectFuncs(opts BackupOptions, targets []string, fs fs.FS, warnf func(msg string, args ...interface{})) (funcs []archiver.RejectFunc, err error) {
func collectRejectFuncs(opts BackupOptions, targets []string, fs fs.FS, warnf func(msg string, args ...any)) (funcs []archiver.RejectFunc, err error) {
// allowed devices
if opts.ExcludeOtherFS && !opts.Stdin && !opts.StdinCommand {
f, err := archiver.RejectByDevice(targets, fs)
@@ -396,7 +403,7 @@ func collectRejectFuncs(opts BackupOptions, targets []string, fs fs.FS, warnf fu
}
// collectTargets returns a list of target files/dirs from several sources.
func collectTargets(opts BackupOptions, args []string, warnf func(msg string, args ...interface{}), stdin io.ReadCloser) (targets []string, err error) {
func collectTargets(opts BackupOptions, args []string, warnf func(msg string, args ...any), stdin io.ReadCloser) (targets []string, err error) {
if opts.Stdin || opts.StdinCommand {
return nil, nil
}
@@ -417,7 +424,7 @@ func collectTargets(opts BackupOptions, args []string, warnf func(msg string, ar
var expanded []string
expanded, err := filepath.Glob(line)
if err != nil {
return nil, fmt.Errorf("pattern: %s: %w", line, err)
return nil, fmt.Errorf("pattern: %q: %w", line, err)
}
if len(expanded) == 0 {
warnf("pattern %q does not match any files, skipping\n", line)
@@ -521,7 +528,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
timeStamp := time.Now()
backupStart := timeStamp
if opts.TimeStamp != "" {
timeStamp, err = time.ParseInLocation(global.TimeFormat, opts.TimeStamp, time.Local)
timeStamp, err = ui.ParseTime(opts.TimeStamp)
if err != nil {
return errors.Fatalf("error in time option: %v", err)
}
@@ -537,8 +544,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
}
defer unlock()
progressReporter := backup.NewProgress(printer,
ui.CalculateProgressInterval(!gopts.Quiet, gopts.JSON, term.CanUpdateStatus()))
progressReporter := backup.NewProgress(printer, gopts.Quiet, gopts.JSON, term.CanUpdateStatus())
defer progressReporter.Done()
// rejectByNameFuncs collect functions that can reject items from the backup based on path only
@@ -572,7 +578,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
return err
}
var targetFS fs.FS = fs.Local{}
targetFS := fs.NewLocal()
if runtime.GOOS == "windows" && opts.UseFsSnapshot {
if err = fs.HasSufficientPrivilegesForVSS(); err != nil {
return err
@@ -582,7 +588,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
_ = progressReporter.Error(item, err)
}
messageHandler := func(msg string, args ...interface{}) {
messageHandler := func(msg string, args ...any) {
if !gopts.JSON {
printer.P(msg, args...)
}
@@ -640,7 +646,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
sc.Result = progressReporter.ReportTotal
if !gopts.JSON {
printer.V("start scan on %v", targets)
printer.V("start scan on %v", ui.QuoteSlice(targets))
}
wg.Go(func() error { return sc.Scan(cancelCtx, targets) })
}
@@ -663,6 +669,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
arch.CompleteItem = progressReporter.CompleteItem
arch.StartFile = progressReporter.StartFile
arch.CompleteBlob = progressReporter.CompleteBlob
arch.ExcludedItem = progressReporter.ExcludedItem
if opts.IgnoreInode {
// --ignore-inode implies --ignore-ctime: on FUSE, the ctime is not
@@ -685,7 +692,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
}
if !gopts.JSON {
printer.V("start backup on %v", targets)
printer.V("start backup on %v", ui.QuoteSlice(targets))
}
_, id, summary, err := arch.Snapshot(ctx, targets, snapshotOpts)
+56 -9
View File
@@ -1,11 +1,15 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
@@ -13,8 +17,10 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui/backup"
)
func testRunBackupAssumeFailure(t testing.TB, dir string, target []string, opts BackupOptions, gopts global.Options) error {
@@ -30,6 +36,13 @@ func testRunBackupAssumeFailure(t testing.TB, dir string, target []string, opts
})
}
func testRunBackupOutput(t testing.TB, opts BackupOptions, gopts global.Options, target []string) ([]byte, error) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runBackup(ctx, opts, gopts, gopts.Term, target)
})
return buf.Bytes(), err
}
func testRunBackup(t testing.TB, dir string, target []string, opts BackupOptions, gopts global.Options) {
err := testRunBackupAssumeFailure(t, dir, target, opts, gopts)
rtest.Assert(t, err == nil, "Error while backing up: %v", err)
@@ -49,6 +62,9 @@ func testBackup(t *testing.T, useFsSnapshot bool) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
// Use auto compression to ensure coverage in the integration tests
// All other tests use fastest compression for faster execution
env.gopts.Compression = repository.CompressionAuto
testSetupBackupData(t, env)
opts := BackupOptions{UseFsSnapshot: useFsSnapshot}
@@ -139,7 +155,7 @@ func (f *vssDeleteOriginalFS) Lstat(name string) (*fs.ExtendedFileInfo, error) {
_, _ = f.FS.Lstat(name)
// nuke testdata
var err error
for i := 0; i < 3; i++ {
for range 3 {
// The CI sometimes runs into "The process cannot access the file because it is being used by another process" errors
// thus try a few times to remove the data
err = os.RemoveAll(f.testdata)
@@ -615,13 +631,7 @@ func linkEqual(source, dest []string) bool {
}
for i := range source {
found := false
for j := range dest {
if source[i] == dest[j] {
found = true
break
}
}
found := slices.Contains(dest, source[i])
if !found {
return false
}
@@ -723,10 +733,47 @@ func TestBackupSkipIfUnchanged(t *testing.T) {
testSetupBackupData(t, env)
opts := BackupOptions{SkipIfUnchanged: true}
for i := 0; i < 3; i++ {
for range 3 {
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
}
testRunCheck(t, env.gopts)
}
func TestBackupExcludeWithOutput(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
backupOptions := BackupOptions{}
backupOptions.Excludes = []string{"*.py"}
env.gopts.JSON = true
env.gopts.Verbosity = 2
output, err := testRunBackupOutput(t, backupOptions, env.gopts, []string{filepath.Join(env.testdata, "0", "for_cmd_ls")})
rtest.OK(t, err)
foundExclude := false
for line := range bytes.SplitSeq(output, []byte("\n")) {
if len(line) == 0 {
continue
}
type MessageType struct {
MessageType string `json:"message_type"` // any
}
var mType MessageType
rtest.OK(t, json.Unmarshal(line, &mType))
if mType.MessageType != "excluded_item" {
continue
}
var excludeLine backup.VerboseExclude
rtest.OK(t, json.Unmarshal(line, &excludeLine))
rtest.Assert(t, strings.Contains(excludeLine.Item, ".py"), "expected excluded pathname to be ending in .py, but contains %q",
excludeLine.Item)
foundExclude = true
}
rtest.Assert(t, foundExclude, "expected at least one excluded item, but found none")
}
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@@ -57,7 +58,7 @@ func (opts *CacheOptions) AddFlags(f *pflag.FlagSet) {
}
func runCache(opts CacheOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
if len(args) > 0 {
return errors.Fatal("the cache command expects no arguments, only options - please see `restic help cache` for usage and flags")
+29 -24
View File
@@ -3,6 +3,8 @@ package main
import (
"context"
"encoding/json"
"io"
"slices"
"strings"
"github.com/spf13/cobra"
@@ -13,6 +15,7 @@ import (
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
var catAllowedCmds = []string{"config", "index", "snapshot", "key", "masterkey", "lock", "pack", "blob", "tree"}
@@ -48,13 +51,7 @@ func validateCatArgs(args []string) error {
return errors.Fatal("type not specified")
}
validType := false
for _, v := range catAllowedCmds {
if v == args[0] {
validType = true
break
}
}
validType := slices.Contains(catAllowedCmds, args[0])
if !validType {
return errors.Fatalf("invalid type %q, must be one of [%s]", args[0], strings.Join(catAllowedCmds, "|"))
}
@@ -67,7 +64,7 @@ func validateCatArgs(args []string) error {
}
func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
if err := validateCatArgs(args); err != nil {
return err
@@ -96,16 +93,17 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return err
}
printer.S(string(buf))
return nil
return writeWithNewline(term.OutputRaw(), buf)
case "index":
buf, err := repo.LoadUnpacked(ctx, restic.IndexFile, id)
if err != nil {
return err
}
printer.S(string(buf))
return nil
_, err = term.OutputRaw().Write(buf)
return err
case "snapshot":
sn, _, err := data.FindSnapshot(ctx, repo, repo, args[1])
if err != nil {
@@ -117,8 +115,8 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return err
}
printer.S(string(buf))
return nil
return writeWithNewline(term.OutputRaw(), buf)
case "key":
key, err := repository.LoadKey(ctx, repo, id)
if err != nil {
@@ -130,18 +128,18 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return err
}
printer.S(string(buf))
return nil
return writeWithNewline(term.OutputRaw(), buf)
case "masterkey":
buf, err := json.MarshalIndent(repo.Key(), "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
return writeWithNewline(term.OutputRaw(), buf)
case "lock":
lock, err := restic.LoadLock(ctx, repo, id)
lock, err := repository.LoadLock(ctx, repo, id)
if err != nil {
return err
}
@@ -151,8 +149,7 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return err
}
printer.S(string(buf))
return nil
return writeWithNewline(term.OutputRaw(), buf)
case "pack":
buf, err := repo.LoadRaw(ctx, restic.PackFile, id)
@@ -176,11 +173,11 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
}
for _, t := range []restic.BlobType{restic.DataBlob, restic.TreeBlob} {
if _, ok := repo.LookupBlobSize(t, id); !ok {
if _, ok := repo.LookupBlobSize(restic.BlobHandle{Type: t, ID: id}); !ok {
continue
}
buf, err := repo.LoadBlob(ctx, t, id, nil)
buf, err := repo.LoadBlob(ctx, restic.BlobHandle{Type: t, ID: id}, nil)
if err != nil {
return err
}
@@ -207,7 +204,7 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return err
}
buf, err := repo.LoadBlob(ctx, restic.TreeBlob, *sn.Tree, nil)
buf, err := repo.LoadBlob(ctx, restic.BlobHandle{Type: restic.TreeBlob, ID: *sn.Tree}, nil)
if err != nil {
return err
}
@@ -218,3 +215,11 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
return errors.Fatal("invalid type")
}
}
func writeWithNewline(w io.Writer, buf []byte) error {
if _, err := w.Write(buf); err != nil {
return err
}
_, err := w.Write([]byte{'\n'})
return err
}
+33 -26
View File
@@ -179,7 +179,7 @@ func parsePercentage(s string) (float64, error) {
// - if the user explicitly requested --no-cache, we don't use any cache
// - if the user provides --cache-dir, we use a cache in a temporary sub-directory of the specified directory and the sub-directory is deleted after the check
// - by default, we use a cache in a temporary directory that is deleted after the check
func prepareCheckCache(opts CheckOptions, gopts *global.Options, printer progress.Printer) (cleanup func()) {
func prepareCheckCache(opts CheckOptions, gopts *global.Options, printer restic.Printer) (cleanup func()) {
cleanup = func() {}
if opts.WithCache {
// use the default cache, no setup needed
@@ -229,9 +229,9 @@ func prepareCheckCache(opts CheckOptions, gopts *global.Options, printer progres
func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args []string, term ui.Terminal) (checkSummary, error) {
summary := checkSummary{MessageType: "summary"}
var printer progress.Printer
var printer restic.Printer
if !gopts.JSON {
printer = ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer = progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
} else {
printer = newJSONErrorPrinter(term)
}
@@ -307,13 +307,13 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
go chkr.Packs(ctx, errChan)
for err := range errChan {
var packErr *repository.PackError
var packErr *repository.ErrPackMetadata
if errors.As(err, &packErr) {
if packErr.Orphaned {
orphanedPacks++
printer.V("%v\n", err)
} else {
if packErr.Truncated {
if packErr.Truncated || packErr.Missing {
salvagePacks.Insert(packErr.ID)
}
errorsFound = true
@@ -339,25 +339,28 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
printer.P("check snapshots, trees and blobs\n")
errChan = make(chan error)
var brokenSnapshots []string
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
bar := printer.NewCounter("snapshots")
defer bar.Done()
chkr.Structure(ctx, bar, errChan)
}()
})
for err := range errChan {
errorsFound = true
if e, ok := err.(*checker.TreeError); ok {
switch e := err.(type) {
case *checker.TreeError:
printer.E("error for tree %v:\n", e.ID.Str())
for _, treeErr := range e.Errors {
summary.NumErrors++
printer.E(" %v\n", treeErr)
}
} else {
case *checker.SnapshotError:
printer.E("snapshot error %v: %v", e.ID, e.Message)
brokenSnapshots = append(brokenSnapshots, e.ID)
default:
summary.NumErrors++
printer.E("error: %v\n", err)
}
@@ -389,10 +392,9 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
}
if readDataFilter != nil {
p := printer.NewCounter("packs")
errChan := make(chan error)
go chkr.ReadPacks(ctx, readDataFilter, p, errChan)
go chkr.ReadPacks(ctx, readDataFilter, printer, errChan)
for err := range errChan {
errorsFound = true
@@ -402,7 +404,6 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
salvagePacks.Insert(err.PackID)
}
}
p.Done()
}
if len(salvagePacks) > 0 {
@@ -414,12 +415,18 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
printer.E("Damaged pack files can be caused by backend problems, hardware problems or bugs in restic. Please open an issue at https://github.com/restic/restic/issues/new/choose for further troubleshooting!\n")
}
if len(brokenSnapshots) > 0 {
printer.E("\nThe repository contains damaged snapshot files. These damaged files must be removed to repair the repository. This can be done using the following commands. Please read the troubleshooting guide at https://restic.readthedocs.io/en/stable/077_troubleshooting.html first.\n\n")
printer.E("restic repair snapshots --forget %s\n\n", strings.Join(brokenSnapshots, " "))
printer.E("Damaged snapshot files can be caused by backend problems, hardware problems or bugs in restic. Please open an issue at https://github.com/restic/restic/issues/new/choose for further troubleshooting!\n")
}
if ctx.Err() != nil {
return summary, ctx.Err()
}
if errorsFound {
if len(salvagePacks) == 0 {
if len(salvagePacks) == 0 && len(brokenSnapshots) == 0 {
printer.E("\nThe repository is damaged and must be repaired. Please follow the troubleshooting guide at https://restic.readthedocs.io/en/stable/077_troubleshooting.html .\n\n")
}
return summary, errors.Fatal("repository contains errors")
@@ -428,7 +435,7 @@ func runCheck(ctx context.Context, opts CheckOptions, gopts global.Options, args
return summary, nil
}
func buildPacksFilter(opts CheckOptions, printer progress.Printer,
func buildPacksFilter(opts CheckOptions, printer restic.Printer,
filteredStatus bool) (func(packs map[restic.ID]int64) map[restic.ID]int64, error) {
typeData := ""
if filteredStatus {
@@ -553,23 +560,23 @@ func newJSONErrorPrinter(term ui.Terminal) *jsonErrorPrinter {
}
}
func (*jsonErrorPrinter) NewCounter(_ string) *progress.Counter {
return nil
func (*jsonErrorPrinter) NewCounter(_ string) restic.Counter {
return restic.NoopCounter
}
func (*jsonErrorPrinter) NewCounterTerminalOnly(_ string) *progress.Counter {
return nil
func (*jsonErrorPrinter) NewCounterTerminalOnly(_ string) restic.Counter {
return restic.NoopCounter
}
func (p *jsonErrorPrinter) E(msg string, args ...interface{}) {
func (p *jsonErrorPrinter) E(msg string, args ...any) {
status := checkError{
MessageType: "error",
Message: fmt.Sprintf(msg, args...),
}
p.term.Error(ui.ToJSONString(status))
}
func (*jsonErrorPrinter) S(_ string, _ ...interface{}) {}
func (*jsonErrorPrinter) P(_ string, _ ...interface{}) {}
func (*jsonErrorPrinter) PT(_ string, _ ...interface{}) {}
func (*jsonErrorPrinter) V(_ string, _ ...interface{}) {}
func (*jsonErrorPrinter) VV(_ string, _ ...interface{}) {}
func (*jsonErrorPrinter) S(_ string, _ ...any) {}
func (*jsonErrorPrinter) P(_ string, _ ...any) {}
func (*jsonErrorPrinter) PT(_ string, _ ...any) {}
func (*jsonErrorPrinter) V(_ string, _ ...any) {}
func (*jsonErrorPrinter) VV(_ string, _ ...any) {}
+9 -8
View File
@@ -11,35 +11,36 @@ import (
func testRunCheck(t testing.TB, gopts global.Options) {
t.Helper()
output, err := testRunCheckOutput(t, gopts, true)
stdout, stderr, err := testRunCheckOutput(t, gopts, true)
if err != nil {
t.Error(output)
t.Error(stdout)
t.Error(stderr)
t.Fatalf("unexpected error: %+v", err)
}
}
func testRunCheckMustFail(t testing.TB, gopts global.Options) {
t.Helper()
_, err := testRunCheckOutput(t, gopts, false)
_, _, err := testRunCheckOutput(t, gopts, false)
rtest.Assert(t, err != nil, "expected non nil error after check of damaged repository")
}
func testRunCheckOutput(t testing.TB, gopts global.Options, checkUnused bool) (string, error) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
func testRunCheckOutput(t testing.TB, gopts global.Options, checkUnused bool) (string, string, error) {
stdout, stderr, err := withCaptureStdoutStderr(t, gopts, func(ctx context.Context, gopts global.Options) error {
opts := CheckOptions{
ReadData: true,
CheckUnused: checkUnused,
}
_, err := runCheck(context.TODO(), opts, gopts, nil, gopts.Term)
_, err := runCheck(ctx, opts, gopts, nil, gopts.Term)
return err
})
return buf.String(), err
return stdout.String(), stderr.String(), err
}
func testRunCheckOutputWithOpts(t testing.TB, gopts global.Options, opts CheckOptions, args []string) (string, error) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.Verbosity = 2
_, err := runCheck(context.TODO(), opts, gopts, args, gopts.Term)
_, err := runCheck(ctx, opts, gopts, args, gopts.Term)
return err
})
return buf.String(), err
+2 -3
View File
@@ -12,7 +12,6 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui/progress"
)
func TestParsePercentage(t *testing.T) {
@@ -204,7 +203,7 @@ func TestPrepareCheckCache(t *testing.T) {
rtest.OK(t, err)
}
gopts := global.Options{CacheDir: tmpDirBase}
cleanup := prepareCheckCache(testCase.opts, &gopts, &progress.NoopPrinter{})
cleanup := prepareCheckCache(testCase.opts, &gopts, restic.NewNoopPrinter())
files, err := os.ReadDir(tmpDirBase)
rtest.OK(t, err)
@@ -234,7 +233,7 @@ func TestPrepareCheckCache(t *testing.T) {
func TestPrepareDefaultCheckCache(t *testing.T) {
gopts := global.Options{CacheDir: ""}
cleanup := prepareCheckCache(CheckOptions{}, &gopts, &progress.NoopPrinter{})
cleanup := prepareCheckCache(CheckOptions{}, &gopts, restic.NewNoopPrinter())
_, err := os.ReadDir(gopts.CacheDir)
rtest.OK(t, err)
+45 -26
View File
@@ -72,14 +72,22 @@ func (opts *CopyOptions) AddFlags(f *pflag.FlagSet) {
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
var errSentinelEndIteration = errors.New("end iteration")
// collectAllSnapshots: select all snapshot trees to be copied
func collectAllSnapshots(ctx context.Context, opts CopyOptions,
srcSnapshotLister restic.Lister, srcRepo restic.Repository,
dstSnapshotByOriginal map[restic.ID][]*data.Snapshot, args []string, printer progress.Printer,
) iter.Seq[*data.Snapshot] {
return func(yield func(*data.Snapshot) bool) {
for sn := range FindFilteredSnapshots(ctx, srcSnapshotLister, srcRepo, &opts.SnapshotFilter, args, printer) {
dstSnapshotByOriginal map[restic.ID][]*data.Snapshot, args []string, printer restic.Printer,
) iter.Seq2[*data.Snapshot, error] {
return func(yield func(*data.Snapshot, error) bool) {
err := opts.SnapshotFilter.FindAll(ctx, srcSnapshotLister, srcRepo, args, func(_ string, sn *data.Snapshot, err error) error {
// check whether the destination has a snapshot with the same persistent ID which has similar snapshot fields
if err != nil {
if !yield(nil, err) {
return errSentinelEndIteration
}
return nil
}
srcOriginal := *sn.ID()
if sn.Original != nil {
srcOriginal = *sn.Original
@@ -95,18 +103,22 @@ func collectAllSnapshots(ctx context.Context, opts CopyOptions,
}
}
if isCopy {
continue
return nil
}
}
if !yield(sn) {
return
if !yield(sn, nil) {
return errSentinelEndIteration
}
return nil
})
if err != nil && !errors.Is(err, errSentinelEndIteration) {
yield(nil, err)
}
}
}
func runCopy(ctx context.Context, opts CopyOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
secondaryGopts, isFromRepo, err := opts.SecondaryRepoOptions.FillGlobalOpts(ctx, gopts, "destination")
if err != nil {
return err
@@ -148,15 +160,19 @@ func runCopy(ctx context.Context, opts CopyOptions, gopts global.Options, args [
}
dstSnapshotByOriginal := make(map[restic.ID][]*data.Snapshot)
for sn := range FindFilteredSnapshots(ctx, dstSnapshotLister, dstRepo, &opts.SnapshotFilter, nil, printer) {
err = opts.SnapshotFilter.FindAll(ctx, dstSnapshotLister, dstRepo, nil, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
if sn.Original != nil && !sn.Original.IsNull() {
dstSnapshotByOriginal[*sn.Original] = append(dstSnapshotByOriginal[*sn.Original], sn)
}
// also consider identical snapshot copies
dstSnapshotByOriginal[*sn.ID()] = append(dstSnapshotByOriginal[*sn.ID()], sn)
}
if ctx.Err() != nil {
return ctx.Err()
return nil
})
if err != nil {
return err
}
selectedSnapshots := collectAllSnapshots(ctx, opts, srcSnapshotLister, srcRepo, dstSnapshotByOriginal, args, printer)
@@ -189,8 +205,8 @@ func similarSnapshots(sna *data.Snapshot, snb *data.Snapshot) bool {
// copyTreeBatched copies multiple snapshots in one go. Snapshots are written after
// data equivalent to at least 10 packfiles was written.
func copyTreeBatched(ctx context.Context, srcRepo restic.Repository, dstRepo restic.Repository,
selectedSnapshots iter.Seq[*data.Snapshot], printer progress.Printer) error {
func copyTreeBatched(ctx context.Context, srcRepo *repository.Repository, dstRepo restic.Repository,
selectedSnapshots iter.Seq2[*data.Snapshot, error], printer restic.Printer) error {
// remember already processed trees across all snapshots
visitedTrees := srcRepo.NewAssociatedBlobSet()
@@ -199,7 +215,7 @@ func copyTreeBatched(ctx context.Context, srcRepo restic.Repository, dstRepo res
minDuration := 1 * time.Minute
// use pull-based iterator to allow iteration in multiple steps
next, stop := iter.Pull(selectedSnapshots)
next, stop := iter.Pull2(selectedSnapshots)
defer stop()
for {
@@ -210,7 +226,10 @@ func copyTreeBatched(ctx context.Context, srcRepo restic.Repository, dstRepo res
// call WithBlobUploader() once and then loop over all selectedSnapshots
err := dstRepo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
for batchSize < targetSize || time.Since(startTime) < minDuration {
sn, ok := next()
sn, err, ok := next()
if err != nil {
return err
}
if !ok {
break
}
@@ -254,8 +273,8 @@ func copyTreeBatched(ctx context.Context, srcRepo restic.Repository, dstRepo res
return nil
}
func copyTree(ctx context.Context, srcRepo restic.Repository, dstRepo restic.Repository,
visitedTrees restic.AssociatedBlobSet, rootTreeID restic.ID, printer progress.Printer, uploader restic.BlobSaverWithAsync) (uint64, error) {
func copyTree(ctx context.Context, srcRepo *repository.Repository, dstRepo restic.Repository,
visitedTrees restic.AssociatedBlobSet, rootTreeID restic.ID, printer restic.Printer, uploader restic.BlobSaverWithAsync) (uint64, error) {
copyBlobs := srcRepo.NewAssociatedBlobSet()
packList := restic.NewIDSet()
@@ -264,16 +283,16 @@ func copyTree(ctx context.Context, srcRepo restic.Repository, dstRepo restic.Rep
enqueue := func(h restic.BlobHandle) {
lock.Lock()
defer lock.Unlock()
if _, ok := dstRepo.LookupBlobSize(h.Type, h.ID); !ok {
pb := srcRepo.LookupBlob(h.Type, h.ID)
if _, ok := dstRepo.LookupBlobSize(h); !ok {
pb := srcRepo.LookupBlob(h)
copyBlobs.Insert(h)
for _, p := range pb {
packList.Insert(p.PackID)
packList.Insert(p.PackID())
}
}
}
err := data.StreamTrees(ctx, srcRepo, restic.IDs{rootTreeID}, nil, func(treeID restic.ID) bool {
err := data.StreamTrees(ctx, srcRepo, restic.IDs{rootTreeID}, restic.NoopCounter, func(treeID restic.ID) bool {
handle := restic.BlobHandle{ID: treeID, Type: restic.TreeBlob}
visited := visitedTrees.Has(handle)
visitedTrees.Insert(handle)
@@ -312,14 +331,14 @@ func copyTree(ctx context.Context, srcRepo restic.Repository, dstRepo restic.Rep
}
// copyStats: print statistics for the blobs to be copied
func copyStats(srcRepo restic.Repository, copyBlobs restic.AssociatedBlobSet, packList restic.IDSet, printer progress.Printer) uint64 {
func copyStats(srcRepo restic.Repository, copyBlobs restic.AssociatedBlobSet, packList restic.IDSet, printer restic.Printer) uint64 {
// count and size
countBlobs := 0
sizeBlobs := uint64(0)
for blob := range copyBlobs.Keys() {
for _, blob := range srcRepo.LookupBlob(blob.Type, blob.ID) {
for _, pb := range srcRepo.LookupBlob(blob) {
countBlobs++
sizeBlobs += uint64(blob.Length)
sizeBlobs += uint64(pb.CiphertextLength())
break
}
}
@@ -329,7 +348,7 @@ func copyStats(srcRepo restic.Repository, copyBlobs restic.AssociatedBlobSet, pa
return sizeBlobs
}
func copySaveSnapshot(ctx context.Context, sn *data.Snapshot, dstRepo restic.Repository, printer progress.Printer) error {
func copySaveSnapshot(ctx context.Context, sn *data.Snapshot, dstRepo restic.Repository, printer restic.Printer) error {
sn.Parent = nil // Parent does not have relevance in the new repo.
// Use Original as a persistent snapshot ID
if sn.Original == nil {
+6 -6
View File
@@ -9,7 +9,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func testRunCopy(t testing.TB, srcGopts global.Options, dstGopts global.Options) {
@@ -97,23 +97,23 @@ func TestCopy(t *testing.T) {
func testPackAndBlobCounts(t testing.TB, gopts global.Options) (countTreePacks int, countDataPacks int, countBlobs int) {
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
rtest.OK(t, repo.List(context.TODO(), restic.PackFile, func(id restic.ID, size int64) error {
blobs, _, err := repo.ListPack(context.TODO(), id, size)
handles, err := repo.ListPackHandles(context.TODO(), id, size)
rtest.OK(t, err)
rtest.Assert(t, len(blobs) > 0, "a packfile should contain at least one blob")
rtest.Assert(t, len(handles) > 0, "a packfile should contain at least one blob")
switch blobs[0].Type {
switch handles[0].Type {
case restic.TreeBlob:
countTreePacks++
case restic.DataBlob:
countDataPacks++
}
countBlobs += len(blobs)
countBlobs += len(handles)
return nil
}))
return nil
+12 -366
View File
@@ -4,28 +4,17 @@ package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/json"
"fmt"
"io"
"os"
"runtime"
"sync"
"time"
"github.com/klauspost/compress/zstd"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
"github.com/restic/restic/internal/crypto"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/repository/index"
"github.com/restic/restic/internal/repository/pack"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
@@ -128,63 +117,8 @@ func debugPrintSnapshots(ctx context.Context, repo *repository.Repository, wr io
})
}
// Pack is the struct used in printPacks.
type Pack struct {
Name string `json:"name"`
Blobs []Blob `json:"blobs"`
}
// Blob is the struct used in printPacks.
type Blob struct {
Type restic.BlobType `json:"type"`
Length uint `json:"length"`
ID restic.ID `json:"id"`
Offset uint `json:"offset"`
}
func printPacks(ctx context.Context, repo *repository.Repository, wr io.Writer, printer progress.Printer) error {
var m sync.Mutex
return restic.ParallelList(ctx, repo, restic.PackFile, repo.Connections(), func(ctx context.Context, id restic.ID, size int64) error {
blobs, _, err := repo.ListPack(ctx, id, size)
if err != nil {
printer.E("error for pack %v: %v", id.Str(), err)
return nil
}
p := Pack{
Name: id.String(),
Blobs: make([]Blob, len(blobs)),
}
for i, blob := range blobs {
p.Blobs[i] = Blob{
Type: blob.Type,
Length: blob.Length,
ID: blob.ID,
Offset: blob.Offset,
}
}
m.Lock()
defer m.Unlock()
return prettyPrintJSON(wr, p)
})
}
func dumpIndexes(ctx context.Context, repo restic.ListerLoaderUnpacked, wr io.Writer, printer progress.Printer) error {
return index.ForAllIndexes(ctx, repo, repo, func(id restic.ID, idx *index.Index, err error) error {
printer.S("index_id: %v", id)
if err != nil {
return err
}
return idx.Dump(wr)
})
}
func runDebugDump(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
if len(args) != 1 {
return errors.Fatal("type not specified")
@@ -200,11 +134,11 @@ func runDebugDump(ctx context.Context, gopts global.Options, args []string, term
switch tpe {
case "indexes":
return dumpIndexes(ctx, repo, gopts.Term.OutputWriter(), printer)
return repository.DumpIndexes(ctx, repo, gopts.Term.OutputWriter(), printer)
case "snapshots":
return debugPrintSnapshots(ctx, repo, gopts.Term.OutputWriter())
case "packs":
return printPacks(ctx, repo, gopts.Term.OutputWriter(), printer)
return repository.DumpPacks(ctx, repo, gopts.Term.OutputWriter(), printer)
case "all":
printer.S("snapshots:")
err := debugPrintSnapshots(ctx, repo, gopts.Term.OutputWriter())
@@ -213,7 +147,7 @@ func runDebugDump(ctx context.Context, gopts global.Options, args []string, term
}
printer.S("indexes:")
err = dumpIndexes(ctx, repo, gopts.Term.OutputWriter(), printer)
err = repository.DumpIndexes(ctx, repo, gopts.Term.OutputWriter(), printer)
if err != nil {
return err
}
@@ -224,227 +158,8 @@ func runDebugDump(ctx context.Context, gopts global.Options, args []string, term
}
}
func tryRepairWithBitflip(key *crypto.Key, input []byte, bytewise bool, printer progress.Printer) []byte {
if bytewise {
printer.S(" trying to repair blob by finding a broken byte")
} else {
printer.S(" trying to repair blob with single bit flip")
}
ch := make(chan int)
var wg errgroup.Group
done := make(chan struct{})
var fixed []byte
var found bool
workers := runtime.GOMAXPROCS(0)
printer.S(" spinning up %d worker functions", runtime.GOMAXPROCS(0))
for i := 0; i < workers; i++ {
wg.Go(func() error {
// make a local copy of the buffer
buf := make([]byte, len(input))
copy(buf, input)
testFlip := func(idx int, pattern byte) bool {
// flip bits
buf[idx] ^= pattern
nonce, plaintext := buf[:key.NonceSize()], buf[key.NonceSize():]
plaintext, err := key.Open(plaintext[:0], nonce, plaintext, nil)
if err == nil {
printer.S("")
printer.S(" blob could be repaired by XORing byte %v with 0x%02x", idx, pattern)
printer.S(" hash is %v", restic.Hash(plaintext))
close(done)
found = true
fixed = plaintext
return true
}
// flip bits back
buf[idx] ^= pattern
return false
}
for i := range ch {
if bytewise {
for j := 0; j < 255; j++ {
if testFlip(i, byte(j)) {
return nil
}
}
} else {
for j := 0; j < 7; j++ {
// flip each bit once
if testFlip(i, (1 << uint(j))) {
return nil
}
}
}
}
return nil
})
}
wg.Go(func() error {
defer close(ch)
start := time.Now()
info := time.Now()
for i := range input {
select {
case ch <- i:
case <-done:
printer.S(" done after %v", time.Since(start))
return nil
}
if time.Since(info) > time.Second {
secs := time.Since(start).Seconds()
gps := float64(i) / secs
remaining := len(input) - i
eta := time.Duration(float64(remaining)/gps) * time.Second
printer.S("\r%d byte of %d done (%.2f%%), %.0f byte per second, ETA %v",
i, len(input), float32(i)/float32(len(input))*100, gps, eta)
info = time.Now()
}
}
return nil
})
err := wg.Wait()
if err != nil {
panic("all go routines can only return nil")
}
if !found {
printer.S("\n blob could not be repaired")
}
return fixed
}
func decryptUnsigned(k *crypto.Key, buf []byte) []byte {
// strip signature at the end
l := len(buf)
nonce, ct := buf[:16], buf[16:l-16]
out := make([]byte, len(ct))
c, err := aes.NewCipher(k.EncryptionKey[:])
if err != nil {
panic(fmt.Sprintf("unable to create cipher: %v", err))
}
e := cipher.NewCTR(c, nonce)
e.XORKeyStream(out, ct)
return out
}
func loadBlobs(ctx context.Context, opts DebugExamineOptions, repo restic.Repository, packID restic.ID, list restic.Blobs, printer progress.Printer) error {
dec, err := zstd.NewReader(nil)
if err != nil {
panic(err)
}
pack, err := repo.LoadRaw(ctx, restic.PackFile, packID)
// allow processing broken pack files
if pack == nil {
return err
}
err = repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
for _, blob := range list {
printer.S(" loading blob %v at %v (length %v)", blob.ID, blob.Offset, blob.Length)
if int(blob.Offset+blob.Length) > len(pack) {
printer.E("skipping truncated blob")
continue
}
buf := pack[blob.Offset : blob.Offset+blob.Length]
key := repo.Key()
nonce, plaintext := buf[:key.NonceSize()], buf[key.NonceSize():]
plaintext, err = key.Open(plaintext[:0], nonce, plaintext, nil)
outputPrefix := ""
filePrefix := ""
if err != nil {
printer.E("error decrypting blob: %v", err)
if opts.TryRepair || opts.RepairByte {
plaintext = tryRepairWithBitflip(key, buf, opts.RepairByte, printer)
}
if plaintext != nil {
outputPrefix = "repaired "
filePrefix = "repaired-"
} else {
plaintext = decryptUnsigned(key, buf)
err = storePlainBlob(blob.ID, "damaged-", plaintext, printer)
if err != nil {
return err
}
continue
}
}
if blob.IsCompressed() {
decompressed, err := dec.DecodeAll(plaintext, nil)
if err != nil {
printer.S(" failed to decompress blob %v", blob.ID)
}
if decompressed != nil {
plaintext = decompressed
}
}
id := restic.Hash(plaintext)
var prefix string
if !id.Equal(blob.ID) {
printer.S(" successfully %vdecrypted blob (length %v), hash is %v, ID does not match, wanted %v", outputPrefix, len(plaintext), id, blob.ID)
prefix = "wrong-hash-"
} else {
printer.S(" successfully %vdecrypted blob (length %v), hash is %v, ID matches", outputPrefix, len(plaintext), id)
prefix = "correct-"
}
if opts.ExtractPack {
err = storePlainBlob(id, filePrefix+prefix, plaintext, printer)
if err != nil {
return err
}
}
if opts.ReuploadBlobs {
_, _, _, err := uploader.SaveBlob(ctx, blob.Type, plaintext, id, true)
if err != nil {
return err
}
printer.S(" uploaded %v %v", blob.Type, id)
}
}
return nil
})
return err
}
func storePlainBlob(id restic.ID, prefix string, plain []byte, printer progress.Printer) error {
filename := fmt.Sprintf("%s%s.bin", prefix, id)
f, err := os.Create(filename)
if err != nil {
return err
}
_, err = f.Write(plain)
if err != nil {
_ = f.Close()
return err
}
err = f.Close()
if err != nil {
return err
}
printer.S("decrypt of blob %v stored at %v", id, filename)
return nil
}
func runDebugExamine(ctx context.Context, gopts global.Options, opts DebugExamineOptions, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
if opts.ExtractPack && gopts.NoLock {
return fmt.Errorf("--extract-pack and --no-lock are mutually exclusive")
@@ -478,8 +193,14 @@ func runDebugExamine(ctx context.Context, gopts global.Options, opts DebugExamin
return err
}
examineOpts := repository.ExaminePackOptions{
TryRepair: opts.TryRepair,
RepairByte: opts.RepairByte,
ExtractPack: opts.ExtractPack,
ReuploadBlobs: opts.ReuploadBlobs,
}
for _, id := range ids {
err := examinePack(ctx, opts, repo, id, printer)
err := repository.ExaminePack(ctx, repo, id, examineOpts, printer)
if err != nil {
printer.E("error: %v", err)
}
@@ -489,78 +210,3 @@ func runDebugExamine(ctx context.Context, gopts global.Options, opts DebugExamin
}
return nil
}
func examinePack(ctx context.Context, opts DebugExamineOptions, repo restic.Repository, id restic.ID, printer progress.Printer) error {
printer.S("examine %v", id)
buf, err := repo.LoadRaw(ctx, restic.PackFile, id)
// also process damaged pack files
if buf == nil {
return err
}
printer.S(" file size is %v", len(buf))
gotID := restic.Hash(buf)
if !id.Equal(gotID) {
printer.S(" wanted hash %v, got %v", id, gotID)
} else {
printer.S(" hash for file content matches")
}
printer.S(" ========================================")
printer.S(" looking for info in the indexes")
blobsLoaded := false
// examine all data the indexes have for the pack file
for b := range repo.ListPacksFromIndex(ctx, restic.NewIDSet(id)) {
blobs := b.Blobs
if len(blobs) == 0 {
continue
}
checkPackSize(blobs, len(buf), printer)
err = loadBlobs(ctx, opts, repo, id, blobs, printer)
if err != nil {
printer.E("error: %v", err)
} else {
blobsLoaded = true
}
}
printer.S(" ========================================")
printer.S(" inspect the pack itself")
blobs, _, err := repo.ListPack(ctx, id, int64(len(buf)))
if err != nil {
return fmt.Errorf("pack %v: %v", id.Str(), err)
}
checkPackSize(blobs, len(buf), printer)
if !blobsLoaded {
return loadBlobs(ctx, opts, repo, id, blobs, printer)
}
return nil
}
func checkPackSize(blobs restic.Blobs, fileSize int, printer progress.Printer) {
// track current size and offset
var size, offset uint64
blobs.Sort()
for _, pb := range blobs {
printer.S(" %v blob %v, offset %-6d, raw length %-6d", pb.Type, pb.ID, pb.Offset, pb.Length)
if offset != uint64(pb.Offset) {
printer.S(" hole in file, want offset %v, got %v", offset, pb.Offset)
}
offset = uint64(pb.Offset + pb.Length)
size += uint64(pb.Length)
}
size += uint64(pack.CalculateHeaderSize(blobs))
if uint64(fileSize) != size {
printer.S(" file sizes do not match: computed %v, file size is %v", size, fileSize)
} else {
printer.S(" file sizes match")
}
}
+10 -5
View File
@@ -12,6 +12,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -83,7 +84,7 @@ type Comparer struct {
repo restic.BlobLoader
opts DiffOptions
printChange func(change *Change)
printError func(string, ...interface{})
printError func(string, ...any)
}
type Change struct {
@@ -96,6 +97,10 @@ func NewChange(path string, mode string) *Change {
return &Change{MessageType: "change", Path: path, Modifier: mode}
}
func printTextDiffChange(S func(string, ...any), change *Change) {
S("%-5s%v", change.Modifier, ui.Quote(change.Path))
}
// DiffStat collects stats for all types of items.
type DiffStat struct {
Files int `json:"files"`
@@ -157,7 +162,7 @@ type DiffStatsContainer struct {
}
// updateBlobs updates the blob counters in the stats struct.
func updateBlobs(repo restic.Loader, blobs restic.AssociatedBlobSet, stats *DiffStat, printError func(string, ...interface{})) {
func updateBlobs(repo restic.Loader, blobs restic.AssociatedBlobSet, stats *DiffStat, printError func(string, ...any)) {
for h := range blobs.Keys() {
switch h.Type {
case restic.DataBlob:
@@ -166,7 +171,7 @@ func updateBlobs(repo restic.Loader, blobs restic.AssociatedBlobSet, stats *Diff
stats.TreeBlobs++
}
size, found := repo.LookupBlobSize(h.Type, h.ID)
size, found := repo.LookupBlobSize(h)
if !found {
printError("unable to find blob size for %v", h)
continue
@@ -358,7 +363,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args [
return errors.Fatalf("specify two snapshot IDs")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
@@ -411,7 +416,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args [
opts: opts,
printError: printer.E,
printChange: func(change *Change) {
printer.S("%-5s%v", change.Modifier, change.Path)
printTextDiffChange(printer.S, change)
},
}
+21
View File
@@ -0,0 +1,21 @@
package main
import (
"strconv"
"testing"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func TestPrintTextDiffChangeQuotesPath(t *testing.T) {
term := &ui.MockTerminal{}
printer := progress.NewTerminalPrinter(false, 1, term)
printTextDiffChange(printer.S, NewChange("dir\nfile", "+"))
rtest.Equals(t, []string{"+ " + strconv.Quote("dir\nfile")}, term.Output)
term.Output = nil
printTextDiffChange(printer.S, NewChange("/ordinary/file", "+"))
rtest.Equals(t, []string{"+ /ordinary/file"}, term.Output)
}
+22 -2
View File
@@ -14,6 +14,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@@ -92,8 +93,16 @@ func printFromTree(ctx context.Context, tree data.TreeNodeIterator, repo restic.
item := filepath.Join(prefix, pathComponents[0])
l := len(pathComponents)
for it := range tree {
// Track the first out-of-order node for the requested name.
var skipped error
for it := range data.EnforceTreeOrder(tree) {
if it.Error != nil {
if errors.Is(it.Error, data.ErrTreeNotOrdered) {
if skipped == nil && it.Node.Name == pathComponents[0] {
skipped = it.Error
}
continue
}
return it.Error
}
if ctx.Err() != nil {
@@ -128,6 +137,9 @@ func printFromTree(ctx context.Context, tree data.TreeNodeIterator, repo restic.
}
}
}
if skipped != nil {
return fmt.Errorf("path %q not found in snapshot: %w", item, skipped)
}
return fmt.Errorf("path %q not found in snapshot", item)
}
@@ -136,7 +148,7 @@ func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args [
return errors.Fatal("no file and no snapshot ID specified")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
switch opts.Archive {
case "tar", "zip":
@@ -194,10 +206,18 @@ func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args [
}
d := dump.New(opts.Archive, repo, outputFileWriter)
totalErrors := 0
d.Error = func(nodePath string, err error) {
totalErrors++
printer.E("ignoring error for %s: %s\n", ui.Quote(nodePath), err)
}
err = printFromTree(ctx, tree, repo, "/", splittedPath, d, canWriteArchiveFunc)
if err != nil {
return errors.Fatalf("cannot dump file: %v", err)
}
if totalErrors > 0 {
return errors.Fatalf("ignored %d directory entries", totalErrors)
}
return nil
}
+47
View File
@@ -1,8 +1,15 @@
package main
import (
"bytes"
"context"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/dump"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
@@ -25,3 +32,43 @@ func TestDumpSplitPath(t *testing.T) {
rtest.Equals(t, path.result, parts)
}
}
func TestPrintFromTreeSkipsUnorderedNodes(t *testing.T) {
ctx := t.Context()
repo := repository.TestRepository(t)
var rootID restic.ID
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
rootID = data.TestSaveUnorderedSampleTree(t, ctx, uploader)
return nil
}))
load := func() data.TreeNodeIterator {
t.Helper()
tree, err := data.LoadTree(ctx, repo, rootID)
rtest.OK(t, err)
return tree
}
dumpFile := func(tree data.TreeNodeIterator, parts []string) (reported []string, err error) {
t.Helper()
d := dump.New("tar", repo, &bytes.Buffer{})
d.Error = func(nodePath string, err error) {
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "unexpected error %v", err)
reported = append(reported, nodePath)
}
err = printFromTree(ctx, tree, repo, "/", parts, d, func() error { return nil })
return reported, err
}
reported, err := dumpFile(load(), []string{"a"})
rtest.Assert(t, errors.Is(err, data.ErrTreeNotOrdered), "missing unordered file: %v", err)
rtest.Assert(t, len(reported) == 0, "lookup failure was reported via Error: %v", reported)
reported, err = dumpFile(load(), []string{"z"})
rtest.OK(t, err)
rtest.Assert(t, len(reported) == 0, "in-order match reported unordered siblings: %v", reported)
reported, err = dumpFile(load(), []string{"missing"})
rtest.Assert(t, err != nil && !errors.Is(err, data.ErrTreeNotOrdered), "missing path: %v", err)
rtest.Assert(t, len(reported) == 0, "unrelated unordered nodes were reported: %v", reported)
}
+64 -85
View File
@@ -19,6 +19,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/walker"
)
@@ -102,30 +103,6 @@ type findPattern struct {
ignoreCase bool
}
var timeFormats = []string{
"2006-01-02",
"2006-01-02 15:04",
"2006-01-02 15:04:05",
"2006-01-02 15:04:05 -0700",
"2006-01-02 15:04:05 MST",
"02.01.2006",
"02.01.2006 15:04",
"02.01.2006 15:04:05",
"02.01.2006 15:04:05 -0700",
"02.01.2006 15:04:05 MST",
"Mon Jan 2 15:04:05 -0700 MST 2006",
}
func parseTime(str string) (time.Time, error) {
for _, fmt := range timeFormats {
if t, err := time.ParseInLocation(fmt, str, time.Local); err == nil {
return t, nil
}
}
return time.Time{}, errors.Fatalf("unable to parse time: %q", str)
}
type statefulOutput struct {
ListLong bool
HumanReadable bool
@@ -135,9 +112,9 @@ type statefulOutput struct {
oldsn *data.Snapshot
hits int
printer interface {
S(string, ...interface{})
P(string, ...interface{})
E(string, ...interface{})
S(string, ...any)
P(string, ...any)
E(string, ...any)
}
stdout io.Writer
}
@@ -182,7 +159,7 @@ func (s *statefulOutput) PrintPatternJSON(path string, node *data.Node) {
if s.hits > 0 {
_, _ = s.stdout.Write([]byte(","))
}
_, _ = s.stdout.Write(b)
_, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b)))
s.hits++
}
@@ -194,7 +171,7 @@ func (s *statefulOutput) PrintPatternNormal(path string, node *data.Node) {
s.oldsn = s.newsn
s.printer.P("Found matching entries in snapshot %s from %s", s.oldsn.ID().Str(), s.oldsn.Time.Local().Format(global.TimeFormat))
}
s.printer.S(formatNode(path, node, s.ListLong, s.HumanReadable))
s.printer.S("%s", formatNode(path, node, s.ListLong, s.HumanReadable))
}
func (s *statefulOutput) PrintPattern(path string, node *data.Node) {
@@ -213,7 +190,7 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn *
Path string `json:"path"`
ParentTree string `json:"parent_tree,omitempty"`
SnapshotID string `json:"snapshot"`
Time time.Time `json:"time,omitempty"`
Time time.Time `json:"time"`
}{
ObjectType: kind,
ID: id,
@@ -233,17 +210,17 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn *
if s.hits > 0 {
_, _ = s.stdout.Write([]byte(","))
}
_, _ = s.stdout.Write(b)
_, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b)))
s.hits++
}
func (s *statefulOutput) PrintObjectNormal(kind, id, nodepath, treeID string, sn *data.Snapshot) {
s.printer.S("Found %s %s", kind, id)
if kind == "blob" {
s.printer.S(" ... in file %s", nodepath)
s.printer.S(" ... in file %s", ui.Quote(nodepath))
s.printer.S(" (tree %s)", treeID)
} else {
s.printer.S(" ... path %s", nodepath)
s.printer.S(" ... path %s", ui.Quote(nodepath))
}
s.printer.S(" ... in snapshot %s (%s)", sn.ID().Str(), sn.Time.Local().Format(global.TimeFormat))
}
@@ -280,9 +257,9 @@ type Finder struct {
treeIDs map[string]struct{}
itemsFound int
printer interface {
S(string, ...interface{})
P(string, ...interface{})
E(string, ...interface{})
S(string, ...any)
P(string, ...any)
E(string, ...any)
}
}
@@ -377,7 +354,7 @@ func (f *Finder) findTree(treeID restic.ID, nodepath string) error {
f.itemsFound++
// Terminate if we have found all trees (and we are not
// looking for blobs)
if f.itemsFound >= len(f.treeIDs) && f.blobIDs == nil {
if f.itemsFound >= len(f.treeIDs) && len(f.blobIDs) == 0 {
// Return an error to terminate the Walk
return errFindDone
}
@@ -412,13 +389,13 @@ func (f *Finder) findIDs(ctx context.Context, sn *data.Snapshot) error {
return nil
}
if node.Type == "dir" && f.treeIDs != nil {
if node.Type == "dir" && len(f.treeIDs) > 0 {
if err := f.findTree(*node.Subtree, nodepath); err != nil {
return err
}
}
if node.Type == data.NodeTypeFile && f.blobIDs != nil {
if node.Type == data.NodeTypeFile && len(f.blobIDs) > 0 {
for _, id := range node.Content {
if ctx.Err() != nil {
return ctx.Err()
@@ -444,6 +421,17 @@ func (f *Finder) findIDs(ctx context.Context, sn *data.Snapshot) error {
var errAllPacksFound = errors.New("all packs found")
func (f *Finder) addBlobHandle(h restic.BlobHandle) {
switch h.Type {
case restic.DataBlob:
f.blobIDs[h.ID.String()] = struct{}{}
case restic.TreeBlob:
f.treeIDs[h.ID.String()] = struct{}{}
default:
panic(fmt.Sprintf("unknown type %v in blob list", h.Type.String()))
}
}
// packsToBlobs converts the list of pack IDs to a list of blob IDs that
// belong to those packs.
func (f *Finder) packsToBlobs(ctx context.Context, packs []string) error {
@@ -467,37 +455,30 @@ func (f *Finder) packsToBlobs(ctx context.Context, packs []string) error {
return nil
}
delete(packIDs, id.Str())
} else {
// forget found id
delete(packIDs, idStr)
packIDs[idStr] = struct{}{}
}
debug.Log("Found pack %s", idStr)
blobs, _, err := f.repo.ListPack(ctx, id, size)
handles, err := f.repo.ListPackHandles(ctx, id, size)
if err != nil {
return err
// ignore error to allow fallback to index
return nil
}
for _, b := range blobs {
switch b.Type {
case restic.DataBlob:
f.blobIDs[b.ID.String()] = struct{}{}
case restic.TreeBlob:
f.treeIDs[b.ID.String()] = struct{}{}
default:
panic(fmt.Sprintf("unknown type %v in blob list", b.Type.String()))
}
for _, h := range handles {
f.addBlobHandle(h)
}
// forget successfully processed pack
delete(packIDs, idStr)
// Stop searching when all packs have been found
if len(packIDs) == 0 {
return errAllPacksFound
}
return nil
})
if err != nil && err != errAllPacksFound {
if err != nil && !errors.Is(err, errAllPacksFound) {
return err
}
if err != errAllPacksFound {
if len(packIDs) > 0 {
// try to resolve unknown pack ids from the index
packIDs, err = f.indexPacksToBlobs(ctx, packIDs)
if err != nil {
@@ -515,7 +496,7 @@ func (f *Finder) packsToBlobs(ctx context.Context, packs []string) error {
return errors.Fatalf("unable to find pack(s): %v", list)
}
debug.Log("%d blobs found", len(f.blobIDs))
debug.Log("%d blobs %v trees found", len(f.blobIDs), len(f.treeIDs))
return nil
}
@@ -525,40 +506,34 @@ func (f *Finder) indexPacksToBlobs(ctx context.Context, packIDs map[string]struc
// remember which packs were found in the index
indexPackIDs := make(map[string]struct{})
err := f.repo.ListBlobs(wctx, func(pb restic.PackedBlob) {
idStr := pb.PackID.String()
for pb := range f.repo.ListBlobs() {
if err := wctx.Err(); err != nil {
return nil, err
}
packID := pb.PackID()
idStr := packID.String()
// keep entry in packIDs as Each() returns individual index entries
matchingID := false
if _, ok := packIDs[idStr]; ok {
matchingID = true
} else {
if _, ok := packIDs[pb.PackID.Str()]; ok {
if _, ok := packIDs[packID.Str()]; ok {
// expand id
delete(packIDs, pb.PackID.Str())
delete(packIDs, packID.Str())
packIDs[idStr] = struct{}{}
matchingID = true
}
}
if matchingID {
f.blobIDs[pb.ID.String()] = struct{}{}
f.addBlobHandle(pb.Handle())
indexPackIDs[idStr] = struct{}{}
}
})
if err != nil {
return nil, err
}
for id := range indexPackIDs {
delete(packIDs, id)
}
if len(indexPackIDs) > 0 {
list := make([]string, 0, len(indexPackIDs))
for h := range indexPackIDs {
list = append(list, h)
}
f.printer.E("some pack files are missing from the repository, getting their blobs from the repository index: %v\n\n", list)
}
return packIDs, nil
}
@@ -569,16 +544,16 @@ func (f *Finder) findObjectPack(id string, t restic.BlobType) {
return
}
blobs := f.repo.LookupBlob(t, rid)
blobs := f.repo.LookupBlob(restic.BlobHandle{Type: t, ID: rid})
if len(blobs) == 0 {
f.printer.S("Object %s with type %s not found in the index", t.String(), rid.Str())
return
}
for _, b := range blobs {
if b.ID.Equal(rid) {
f.printer.S("Object belongs to pack %s", b.PackID)
f.printer.S(" ... Pack %s: %s", b.PackID.Str(), b.String())
if b.Handle().ID.Equal(rid) {
f.printer.S("Object belongs to pack %s", b.PackID())
f.printer.S(" ... Pack %s: %v", b.PackID().String(), b.Handle())
break
}
}
@@ -599,7 +574,7 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
return errors.Fatal("wrong number of arguments")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
var err error
pat := findPattern{pattern: args}
@@ -611,13 +586,13 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
}
if opts.Oldest != "" {
if pat.oldest, err = parseTime(opts.Oldest); err != nil {
if pat.oldest, err = ui.ParseTime(opts.Oldest); err != nil {
return err
}
}
if opts.Newest != "" {
if pat.newest, err = parseTime(opts.Newest); err != nil {
if pat.newest, err = ui.ParseTime(opts.Newest); err != nil {
return err
}
}
@@ -676,11 +651,15 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
}
var filteredSnapshots []*data.Snapshot
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, opts.Snapshots, printer) {
err = opts.SnapshotFilter.FindAll(ctx, snapshotLister, repo, opts.Snapshots, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
filteredSnapshots = append(filteredSnapshots, sn)
}
if ctx.Err() != nil {
return ctx.Err()
return nil
})
if err != nil {
return err
}
sort.Slice(filteredSnapshots, func(i, j int) bool {
@@ -691,7 +670,7 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
})
for _, sn := range filteredSnapshots {
if f.blobIDs != nil || f.treeIDs != nil {
if len(f.blobIDs) > 0 || len(f.treeIDs) > 0 {
if err = f.findIDs(ctx, sn); err != nil && !errors.Is(err, errFindDone) {
return err
}
@@ -703,7 +682,7 @@ func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args [
}
f.out.Finish()
if opts.ShowPackID && (f.blobIDs != nil || f.treeIDs != nil) {
if opts.ShowPackID && (len(f.blobIDs) > 0 || len(f.treeIDs) > 0) {
f.findObjectsPacks()
}
+41 -17
View File
@@ -9,10 +9,11 @@ import (
"testing"
"time"
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func testRunFind(t testing.TB, wantJSON bool, opts FindOptions, gopts global.Options, pattern string) []byte {
@@ -50,7 +51,7 @@ type testMatch struct {
Path string `json:"path,omitempty"`
Permissions string `json:"permissions,omitempty"`
Size uint64 `json:"size,omitempty"`
Date time.Time `json:"date,omitempty"`
Date time.Time `json:"date"`
UID uint32 `json:"uid,omitempty"`
GID uint32 `json:"gid,omitempty"`
}
@@ -153,7 +154,7 @@ type JSONOutput struct {
Path string `json:"path"`
ParentTree string `json:"parent_tree,omitempty"`
SnapshotID string `json:"snapshot"`
Time time.Time `json:"time,omitempty"`
Time time.Time `json:"time"`
}
func TestFindPackfile(t *testing.T) {
@@ -169,7 +170,7 @@ func TestFindPackfile(t *testing.T) {
// do all the testing wrapped inside withTermStatus()
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
@@ -179,14 +180,14 @@ func TestFindPackfile(t *testing.T) {
packID := restic.ID{}
done := false
err = repo.ListBlobs(ctx, func(pb restic.PackedBlob) {
if !done && pb.Type == restic.TreeBlob {
packID = pb.PackID
for pb := range repo.ListBlobs() {
rtest.OK(t, ctx.Err())
h := pb.Handle()
if !done && h.Type == restic.TreeBlob {
packID = pb.PackID()
done = true
}
})
rtest.OK(t, err)
}
rtest.Assert(t, !packID.IsNull(), "expected a tree packfile ID")
findOptions := FindOptions{PackID: true}
results := testRunFind(t, true, findOptions, env.gopts, packID.String())
@@ -228,22 +229,23 @@ func TestFindPackID(t *testing.T) {
dataPackID := restic.ID{}
treePackID := restic.ID{}
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
// load Index
rtest.OK(t, repo.LoadIndex(ctx, nil))
rtest.OK(t, repo.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
// go through all index entries and collect data and tree packfile(s)
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackedBlob) {
switch blob.Type {
for blob := range repo.ListBlobs() {
rtest.OK(t, ctx.Err())
switch blob.Handle().Type {
case restic.DataBlob:
dataPackID = blob.PackID
dataPackID = blob.PackID()
case restic.TreeBlob:
treePackID = blob.PackID
treePackID = blob.PackID()
}
}))
}
return nil
})
rtest.OK(t, err)
@@ -258,6 +260,28 @@ func TestFindPackID(t *testing.T) {
rtest.Assert(t, len(findRes) == numberOfFiles, "expected %d entries for this packfile, got %d",
numberOfFiles, len(findRes))
// corrupt the data pack file; find must fall back to the index
be := captureBackend(&env.gopts)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, _, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
h := backend.Handle{Type: backend.PackFile, Name: dataPackID.String()}
rtest.OK(t, be().Remove(ctx, h))
buf := make([]byte, 10)
rtest.OK(t, be().Save(ctx, h, backend.NewByteReader(buf, be().Hasher())))
return nil
})
rtest.OK(t, err)
out = testRunFind(t, true, FindOptions{PackID: true}, env.gopts, dataPackID.String())
findRes = []JSONOutput{}
rtest.OK(t, json.Unmarshal(out, &findRes))
rtest.Assert(t, len(findRes) == numberOfFiles, "expected %d entries for broken packfile, got %d",
numberOfFiles, len(findRes))
// look for tree packfile
rtest.Assert(t, !treePackID.IsNull(), "expected to find tree packfile in repo")
packID = treePackID.String()
+97
View File
@@ -0,0 +1,97 @@
package main
import (
"bytes"
"context"
"encoding/json"
"strconv"
"strings"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func TestPrintObjectQuotesPath(t *testing.T) {
term := &ui.MockTerminal{}
out := &statefulOutput{
printer: progress.NewTerminalPrinter(false, 1, term),
}
out.PrintObjectNormal("file", "abcd", "dir\nfile", "", &data.Snapshot{})
rtest.Equals(t, " ... path "+strconv.Quote("dir\nfile"), term.Output[1])
for _, line := range term.Output {
rtest.Assert(t, !strings.Contains(line, "\n"), "raw newline in %q", line)
}
term = &ui.MockTerminal{}
out.printer = progress.NewTerminalPrinter(false, 1, term)
out.PrintObjectNormal("blob", "abcd", "/ordinary/file", "tree", &data.Snapshot{})
rtest.Equals(t, " ... in file /ordinary/file", term.Output[1])
}
type fakeSnapshotLoader struct{}
func (fakeSnapshotLoader) Connections() uint { return 1 }
func (fakeSnapshotLoader) LoadUnpacked(_ context.Context, _ restic.FileType, _ restic.ID) ([]byte, error) {
return []byte("{}"), nil
}
func TestFindJSONEscapesControls(t *testing.T) {
hostilePath := "/dir/c1\u009b2J_del\x7f_tag\U000e0067"
sn, err := data.LoadSnapshot(t.Context(), fakeSnapshotLoader{}, restic.NewRandomID())
rtest.OK(t, err)
t.Run("pattern", func(t *testing.T) {
var buf bytes.Buffer
out := &statefulOutput{
JSON: true,
newsn: sn,
printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}),
stdout: &buf,
}
out.PrintPatternJSON(hostilePath, &data.Node{Name: "file"})
out.Finish()
got := buf.String()
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
var parsed []struct {
Matches []struct {
Path string `json:"path"`
} `json:"matches"`
}
rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed))
rtest.Equals(t, 1, len(parsed))
rtest.Equals(t, 1, len(parsed[0].Matches))
rtest.Equals(t, hostilePath, parsed[0].Matches[0].Path)
})
t.Run("object", func(t *testing.T) {
var buf bytes.Buffer
out := &statefulOutput{
JSON: true,
printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}),
stdout: &buf,
}
out.PrintObjectJSON("file", "abcd", hostilePath, "tree", sn)
out.Finish()
got := buf.String()
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
var parsed []struct {
Path string `json:"path"`
}
rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed))
rtest.Equals(t, 1, len(parsed))
rtest.Equals(t, hostilePath, parsed[0].Path)
})
}
+24 -7
View File
@@ -5,13 +5,16 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"sync"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -189,7 +192,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
return errors.Fatal("--no-lock is only applicable in combination with --dry-run for forget command")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun && gopts.NoLock, printer)
if err != nil {
return err
@@ -199,11 +202,15 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
var snapshots data.Snapshots
removeSnIDs := restic.NewIDSet()
for sn := range FindFilteredSnapshots(ctx, repo, repo, &opts.SnapshotFilter, args, printer) {
err = opts.SnapshotFilter.FindAll(ctx, repo, repo, args, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
snapshots = append(snapshots, sn)
}
if ctx.Err() != nil {
return ctx.Err()
return nil
})
if err != nil {
return err
}
var jsonGroups []*ForgetGroup
@@ -273,7 +280,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
keep, remove, reasons := data.ApplyPolicy(snapshotGroup, policy)
if !policy.Empty() && len(keep) == 0 {
return fmt.Errorf("refusing to delete last snapshot of snapshot group \"%v\"", key.String())
return fmt.Errorf("refusing to delete last snapshot of snapshot group [%s]", key.String())
}
if len(keep) != 0 && !gopts.Quiet && !gopts.JSON {
printer.P("keep %d snapshots:\n", len(keep))
@@ -312,10 +319,13 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
if len(removeSnIDs) > 0 {
if !opts.DryRun {
bar := printer.NewCounter("files deleted")
var lock sync.Mutex
err := restic.ParallelRemove(ctx, repo, removeSnIDs, restic.WriteableSnapshotFile, func(id restic.ID, err error) error {
if err != nil {
printer.E("unable to remove %v/%v from the repository\n", restic.SnapshotFile, id)
lock.Lock()
failedSnIDs.Insert(id)
lock.Unlock()
} else {
printer.VV("removed %v/%v\n", restic.SnapshotFile, id)
}
@@ -348,12 +358,19 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
printer.P("%d snapshots have been removed, running prune\n", len(removeSnIDs))
}
pruneOptions.DryRun = opts.DryRun
return runPruneWithRepo(ctx, pruneOptions, repo, removeSnIDs, printer)
return runPruneWithRepo(ctx, pruneOptions, gopts, repo, removeSnIDs, printer)
}
return nil
}
// PrintSnapshots prints a text table of the snapshots in list to stdout.
// The list is sorted so that the newest snapshot is listed last.
func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
sort.Stable(sort.Reverse(list))
return printSnapshotsTable(stdout, list, reasons, compact)
}
// ForgetGroup helps to print what is forgotten in JSON.
type ForgetGroup struct {
Tags []string `json:"tags"`
+1 -1
View File
@@ -42,7 +42,7 @@ func TestRunForgetSafetyNet(t *testing.T) {
KeepTags: data.TagLists{data.TagList{"invalid"}},
GroupBy: data.SnapshotGroupByOptions{Host: true, Path: true},
})
rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group "host example, path`), "wrong error message got %v", err)
rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group [host example, path`), "wrong error message got %v", err)
// disallow `forget --unsafe-allow-remove-all`
err = testRunForgetMayFail(t, env.gopts, ForgetOptions{
+4 -3
View File
@@ -7,6 +7,7 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
@@ -55,7 +56,7 @@ func (opts *generateOptions) AddFlags(f *pflag.FlagSet) {
f.StringVar(&opts.PowerShellCompletionFile, "powershell-completion", "", "write powershell completion `file` (`-` for stdout)")
}
func writeManpages(root *cobra.Command, dir string, printer progress.Printer) error {
func writeManpages(root *cobra.Command, dir string, printer restic.Printer) error {
// use a fixed date for the man pages so that generating them is deterministic
date, err := time.Parse("Jan 2006", "Jan 2017")
if err != nil {
@@ -73,7 +74,7 @@ func writeManpages(root *cobra.Command, dir string, printer progress.Printer) er
return doc.GenManTree(root, header, dir)
}
func writeCompletion(filename string, shell string, generate func(w io.Writer) error, printer progress.Printer, gopts global.Options) (err error) {
func writeCompletion(filename string, shell string, generate func(w io.Writer) error, printer restic.Printer, gopts global.Options) (err error) {
printer.PT("writing %s completion file to %v", shell, filename)
var outWriter io.Writer
if filename != "-" {
@@ -116,7 +117,7 @@ func runGenerate(opts generateOptions, gopts global.Options, args []string, term
return errors.Fatal("the generate command expects no arguments, only options - please see `restic help generate` for usage and flags")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
cmdRoot := newRootCommand(&global.Options{})
if opts.ManDir != "" {
+5 -4
View File
@@ -60,7 +60,7 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
return errors.Fatal("the init command expects no arguments, only options - please see `restic help init` for usage and flags")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
var version uint
switch opts.RepositoryVersion {
@@ -87,7 +87,8 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
}
if !gopts.JSON {
printer.P("created restic repository %v at %s", s.Config().ID[:10], location.StripPassword(gopts.Backends, gopts.Repo))
id := s.Config().ID
printer.P("created restic repository %v at %s", id.Str(), location.StripPassword(gopts.Backends, gopts.Repo))
if opts.CopyChunkerParameters && chunkerPolynomial != nil {
printer.P(" with chunker parameters copied from secondary repository")
}
@@ -99,7 +100,7 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
} else {
status := initSuccess{
MessageType: "initialized",
ID: s.Config().ID,
ID: s.Config().ID.String(),
Repository: location.StripPassword(gopts.Backends, gopts.Repo),
}
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(status)
@@ -108,7 +109,7 @@ func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args [
return nil
}
func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts global.Options, printer progress.Printer) (*chunker.Pol, error) {
func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts global.Options, printer restic.Printer) (*chunker.Pol, error) {
if opts.CopyChunkerParameters {
otherGopts, _, err := opts.SecondaryRepoOptions.FillGlobalOpts(ctx, gopts, "secondary")
if err != nil {
+4 -4
View File
@@ -10,13 +10,12 @@ import (
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui/progress"
)
func testRunInit(t testing.TB, gopts global.Options) {
repository.TestUseLowSecurityKDFParameters(t)
restic.TestDisableCheckPolynomial(t)
restic.TestSetLockTimeout(t, 0)
repository.TestSetLockTimeout(t, 0)
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runInit(ctx, InitOptions{}, gopts, nil, gopts.Term)
@@ -26,6 +25,7 @@ func testRunInit(t testing.TB, gopts global.Options) {
// create temporary junk files to verify that restic does not trip over them
for _, path := range []string{"index", "snapshots", "keys", "locks", filepath.Join("data", "00")} {
rtest.OK(t, os.MkdirAll(filepath.Join(gopts.Repo, path), 0700))
rtest.OK(t, os.WriteFile(filepath.Join(gopts.Repo, path, "tmp12345"), []byte("junk file"), 0o600))
}
}
@@ -57,14 +57,14 @@ func TestInitCopyChunkerParams(t *testing.T) {
var repo *repository.Repository
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
repo, err = global.OpenRepository(ctx, gopts, &progress.NoopPrinter{})
repo, err = global.OpenRepository(ctx, gopts, restic.NewNoopPrinter())
return err
})
rtest.OK(t, err)
var otherRepo *repository.Repository
err = withTermStatus(t, env2.gopts, func(ctx context.Context, gopts global.Options) error {
otherRepo, err = global.OpenRepository(ctx, gopts, &progress.NoopPrinter{})
otherRepo, err = global.OpenRepository(ctx, gopts, restic.NewNoopPrinter())
return err
})
rtest.OK(t, err)
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
@@ -60,7 +61,7 @@ func runKeyAdd(ctx context.Context, gopts global.Options, opts KeyAddOptions, ar
return fmt.Errorf("the key add command expects no arguments, only options - please see `restic help key add` for usage and flags")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithAppendLock(ctx, gopts, false, printer)
if err != nil {
return err
@@ -70,7 +71,7 @@ func runKeyAdd(ctx context.Context, gopts global.Options, opts KeyAddOptions, ar
return addKey(ctx, repo, gopts, opts, printer)
}
func addKey(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyAddOptions, printer progress.Printer) error {
func addKey(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyAddOptions, printer restic.Printer) error {
pw, err := getNewPassword(ctx, gopts, opts.NewPasswordFile, opts.InsecureNoPassword)
if err != nil {
return err
+9 -5
View File
@@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
"github.com/restic/restic/internal/restic"
"os"
"path/filepath"
"regexp"
@@ -13,7 +14,6 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui/progress"
)
func testRunKeyListOtherIDs(t testing.TB, gopts global.Options) []string {
@@ -63,11 +63,13 @@ func testRunKeyAddNewKeyUserHost(t testing.TB, gopts global.Options) {
rtest.OK(t, err)
_ = withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
repo, err := global.OpenRepository(ctx, gopts, &progress.NoopPrinter{})
repo, err := global.OpenRepository(ctx, gopts, restic.NewNoopPrinter())
rtest.OK(t, err)
key, err := repository.SearchKey(ctx, repo, testKeyNewPassword, 2, "")
err = repo.SearchKey(ctx, testKeyNewPassword, 2, "")
rtest.OK(t, err)
key, err := repository.LoadKey(ctx, repo, repo.KeyID())
rtest.OK(t, err)
rtest.Equals(t, "john", key.Username)
rtest.Equals(t, "example.com", key.Hostname)
return nil
@@ -105,11 +107,13 @@ func testRunKeyPasswdUserHost(t testing.TB, newPassword string, gopts global.Opt
gopts.Password = testKeyNewPassword
_ = withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
repo, err := global.OpenRepository(ctx, gopts, &progress.NoopPrinter{})
repo, err := global.OpenRepository(ctx, gopts, restic.NewNoopPrinter())
rtest.OK(t, err)
key, err := repository.SearchKey(ctx, repo, testKeyNewPassword, 1, "")
err = repo.SearchKey(ctx, testKeyNewPassword, 1, "")
rtest.OK(t, err)
key, err := repository.LoadKey(ctx, repo, repo.KeyID())
rtest.OK(t, err)
rtest.Equals(t, "john", key.Username)
rtest.Equals(t, "example.com", key.Hostname)
return nil
+7 -2
View File
@@ -46,7 +46,7 @@ func runKeyList(ctx context.Context, gopts global.Options, args []string, term u
return fmt.Errorf("the key list command expects no arguments, only options - please see `restic help key list` for usage and flags")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
@@ -56,7 +56,7 @@ func runKeyList(ctx context.Context, gopts global.Options, args []string, term u
return listKeys(ctx, repo, gopts, printer)
}
func listKeys(ctx context.Context, s *repository.Repository, gopts global.Options, printer progress.Printer) error {
func listKeys(ctx context.Context, s *repository.Repository, gopts global.Options, printer restic.Printer) error {
type keyInfo struct {
Current bool `json:"current"`
ID string `json:"id"`
@@ -99,6 +99,11 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts global.Option
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(keys)
}
for i := range keys {
keys[i].UserName = ui.Quote(keys[i].UserName)
keys[i].HostName = ui.Quote(keys[i].HostName)
}
tab := table.New()
tab.AddColumn(" ID", "{{if .Current}}*{{else}} {{end}}{{ .ShortID }}")
tab.AddColumn("User", "{{ .UserName }}")
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
@@ -55,7 +56,7 @@ func runKeyPasswd(ctx context.Context, gopts global.Options, opts KeyPasswdOptio
return fmt.Errorf("the key passwd command expects no arguments, only options - please see `restic help key passwd` for usage and flags")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
@@ -65,7 +66,7 @@ func runKeyPasswd(ctx context.Context, gopts global.Options, opts KeyPasswdOptio
return changePassword(ctx, repo, gopts, opts, printer)
}
func changePassword(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyPasswdOptions, printer progress.Printer) error {
func changePassword(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyPasswdOptions, printer restic.Printer) error {
pw, err := getNewPassword(ctx, gopts, opts.NewPasswordFile, opts.InsecureNoPassword)
if err != nil {
return err
+2 -2
View File
@@ -43,7 +43,7 @@ func runKeyRemove(ctx context.Context, gopts global.Options, args []string, term
return fmt.Errorf("key remove expects one argument as the key id")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
@@ -53,7 +53,7 @@ func runKeyRemove(ctx context.Context, gopts global.Options, args []string, term
return deleteKey(ctx, repo, args[0], printer)
}
func deleteKey(ctx context.Context, repo *repository.Repository, idPrefix string, printer progress.Printer) error {
func deleteKey(ctx context.Context, repo *repository.Repository, idPrefix string, printer restic.Printer) error {
id, err := restic.Find(ctx, repo, restic.KeyFile, idPrefix)
if err != nil {
return err
+59 -19
View File
@@ -2,13 +2,16 @@ package main
import (
"context"
"fmt"
"strings"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository/index"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
)
@@ -18,10 +21,12 @@ func newListCommand(globalOptions *global.Options) *cobra.Command {
var listAllowedArgsUseString = strings.Join(listAllowedArgs, "|")
cmd := &cobra.Command{
Use: "list [flags] [" + listAllowedArgsUseString + "]",
Use: "list [flags] [" + listAllowedArgsUseString + "|packs snapshotID]",
Short: "List objects in the repository",
Long: `
The "list" command allows listing objects in the repository based on type.
The "list packs snapshotID" variant accepts one snapshotID and lists all packfiles
used by this snapshot.
EXIT STATUS
===========
@@ -35,19 +40,18 @@ Exit status is 12 if the password is incorrect.
DisableAutoGenTag: true,
GroupID: cmdGroupDefault,
RunE: func(cmd *cobra.Command, args []string) error {
return runList(cmd.Context(), *globalOptions, args, globalOptions.Term)
return runList(cmd.Context(), *globalOptions, args, globalOptions.Term, listAllowedArgsUseString)
},
ValidArgs: listAllowedArgs,
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
}
return cmd
}
func runList(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
func runList(ctx context.Context, gopts global.Options, args []string, term ui.Terminal, listAllowedArgsUseString string) error {
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
if len(args) != 1 {
return errors.Fatal("type not specified")
if len(args) == 0 || (args[0] == "packs" && len(args) > 2) || (args[0] != "packs" && len(args) != 1) {
return errors.Fatal(fmt.Sprintf("too many parameters or type not specified. Must be one of [%s] or 'packs snapshotID'", listAllowedArgsUseString))
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock || args[0] == "locks", printer)
@@ -60,6 +64,10 @@ func runList(ctx context.Context, gopts global.Options, args []string, term ui.T
switch args[0] {
case "packs":
t = restic.PackFile
if len(args) == 2 {
// args[1] needs to be a snapshotID
return packfileList(ctx, repo, args[1], printer)
}
case "index":
t = restic.IndexFile
case "snapshots":
@@ -69,18 +77,13 @@ func runList(ctx context.Context, gopts global.Options, args []string, term ui.T
case "locks":
t = restic.LockFile
case "blobs":
return index.ForAllIndexes(ctx, repo, repo, func(_ restic.ID, idx *index.Index, err error) error {
if err != nil {
return err
for entry := range repository.AllIndexBlobs(ctx, repo, repo) {
if entry.Error != nil {
return entry.Error
}
for blobs := range idx.Values() {
if ctx.Err() != nil {
return ctx.Err()
}
printer.S("%v %v", blobs.Type, blobs.ID)
}
return nil
})
printer.S("%v %v", entry.Handle.Type, entry.Handle.ID)
}
return nil
default:
return errors.Fatal("invalid type")
}
@@ -90,3 +93,40 @@ func runList(ctx context.Context, gopts global.Options, args []string, term ui.T
return nil
})
}
// packfileList handles the list packs <snapshotID> variant.
// It prints a sorted list of packfiles belonging to this snapshot.
func packfileList(ctx context.Context, repo restic.Repository, snapshotID string, printer restic.Printer) error {
// ignore subpaths as this command is intended to list all packfiles necessary to restore the snapshot
// subpaths would require special handling and limit restorability
sn, _, err := (&data.SnapshotFilter{}).FindLatest(ctx, repo, repo, snapshotID)
if err != nil {
return fmt.Errorf("failed to find snapshot: %v", err)
}
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
usedBlobs := repo.NewAssociatedBlobSet()
bar := printer.NewCounter("snapshot")
bar.SetMax(uint64(1))
err = data.FindUsedBlobs(ctx, repo, []restic.ID{*sn.Tree}, usedBlobs, bar)
bar.Done()
if err != nil {
return err
}
snapPacks := restic.NewIDSet()
for bh := range usedBlobs.Keys() {
for _, blob := range repo.LookupBlob(bh) {
snapPacks.Insert(blob.PackID())
}
}
for _, packID := range snapPacks.List() {
printer.S("%v", packID)
}
return nil
}
+34 -8
View File
@@ -11,12 +11,12 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func testRunList(t testing.TB, gopts global.Options, tpe string) restic.IDs {
func testRunList(t testing.TB, gopts global.Options, params ...string) restic.IDs {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runList(ctx, gopts, []string{tpe}, gopts.Term)
return runList(ctx, gopts, params, gopts.Term, "")
})
rtest.OK(t, err)
return parseIDsFromReader(t, buf)
@@ -48,6 +48,10 @@ func parseIDsFromReader(t testing.TB, rd io.Reader) restic.IDs {
}
}
if err := sc.Err(); err != nil {
t.Fatalf("failed to scan list output (parsed %d IDs before error): %v", len(IDs), err)
}
return IDs
}
@@ -61,19 +65,20 @@ func testListSnapshots(t testing.TB, gopts global.Options, expected int) restic.
// extract blob set from repository index
func testListBlobs(t testing.TB, gopts global.Options) (blobSetFromIndex restic.IDSet) {
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
// make sure the index is loaded
rtest.OK(t, repo.LoadIndex(ctx, nil))
rtest.OK(t, repo.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
// get blobs from index
blobSetFromIndex = restic.NewIDSet()
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackedBlob) {
blobSetFromIndex.Insert(blob.ID)
}))
for blob := range repo.ListBlobs() {
rtest.OK(t, ctx.Err())
blobSetFromIndex.Insert(blob.Handle().ID)
}
return nil
})
rtest.OK(t, err)
@@ -102,3 +107,24 @@ func TestListBlobs(t *testing.T) {
rtest.Assert(t, blobSetFromIndex.Equals(testIDSet), "the set of restic.ID s should be equal")
}
func TestPackfileListWithSnapshot(t *testing.T) {
// setup
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
// 3 backups, single file each
opts := BackupOptions{}
testRunBackup(t, env.testdata, []string{filepath.Join(env.testdata, "0", "0", "9", "40")}, opts, env.gopts)
testRunBackup(t, env.testdata, []string{filepath.Join(env.testdata, "0", "0", "9", "41")}, opts, env.gopts)
testRunBackup(t, env.testdata, []string{filepath.Join(env.testdata, "0", "0", "9", "42")}, opts, env.gopts)
testListSnapshots(t, env.gopts, 3)
// run packfilelist
packfiles := testRunList(t, env.gopts, "packs")
rtest.Assert(t, len(packfiles) == 6, "expected 6 packfiles in repository, got %d", len(packfiles))
packfiles = testRunList(t, env.gopts, "packs", "latest")
rtest.Assert(t, len(packfiles) == 2, "expected 2 packfiles in snapshot, got %d", len(packfiles))
}
+79 -70
View File
@@ -21,6 +21,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/walker"
)
@@ -93,7 +94,7 @@ func (opts *LsOptions) AddFlags(f *pflag.FlagSet) {
type lsPrinter interface {
Snapshot(sn *data.Snapshot) error
Node(path string, node *data.Node, isPrefixDirectory bool) error
NodeOutput(n lsNodeOutput, isPrefixDirectory bool) error
LeaveDir(path string) error
Close() error
}
@@ -120,55 +121,68 @@ func (p *jsonLsPrinter) Snapshot(sn *data.Snapshot) error {
})
}
// Node formats node in our custom JSON format, followed by a newline.
func (p *jsonLsPrinter) Node(path string, node *data.Node, isPrefixDirectory bool) error {
if isPrefixDirectory {
return nil
}
return lsNodeJSON(p.enc, path, node)
type lsNodeOutput struct {
Name string `json:"name"`
Type data.NodeType `json:"type"`
Path string `json:"path"`
UID uint32 `json:"uid"`
GID uint32 `json:"gid"`
Size *uint64 `json:"size,omitempty"`
Mode os.FileMode `json:"mode,omitempty"`
Permissions string `json:"permissions,omitempty"`
ModTime time.Time `json:"mtime"`
AccessTime time.Time `json:"atime"`
ChangeTime time.Time `json:"ctime"`
Inode uint64 `json:"inode,omitempty"`
MessageType string `json:"message_type"`
StructType string `json:"struct_type"`
// Used for the ncdu output only
LinkTarget string `json:"-"`
DeviceID uint64 `json:"-"`
Links uint64 `json:"-"`
}
func lsNodeJSON(enc *json.Encoder, path string, node *data.Node) error {
n := &struct {
Name string `json:"name"`
Type string `json:"type"`
Path string `json:"path"`
UID uint32 `json:"uid"`
GID uint32 `json:"gid"`
Size *uint64 `json:"size,omitempty"`
Mode os.FileMode `json:"mode,omitempty"`
Permissions string `json:"permissions,omitempty"`
ModTime time.Time `json:"mtime,omitempty"`
AccessTime time.Time `json:"atime,omitempty"`
ChangeTime time.Time `json:"ctime,omitempty"`
Inode uint64 `json:"inode,omitempty"`
MessageType string `json:"message_type"` // "node"
StructType string `json:"struct_type"` // "node", deprecated
func (n lsNodeOutput) fileSize() uint64 {
if n.Size == nil {
return 0
}
return *n.Size
}
size uint64 // Target for Size pointer.
}{
func lsNodeOutputFrom(path string, node *data.Node) lsNodeOutput {
n := lsNodeOutput{
Name: node.Name,
Type: string(node.Type),
Type: node.Type,
Path: path,
UID: node.UID,
GID: node.GID,
size: node.Size,
Mode: node.Mode,
Permissions: node.Mode.String(),
ModTime: node.ModTime,
AccessTime: node.AccessTime,
ChangeTime: node.ChangeTime,
Inode: node.Inode,
LinkTarget: node.LinkTarget,
DeviceID: node.DeviceID,
Links: node.Links,
MessageType: "node",
StructType: "node",
}
// Always print size for regular files, even when empty,
// but never for other types.
if node.Type == data.NodeTypeFile {
n.Size = &n.size
size := node.Size
n.Size = &size
}
return n
}
return enc.Encode(n)
func (p *jsonLsPrinter) NodeOutput(n lsNodeOutput, isPrefixDirectory bool) error {
if isPrefixDirectory {
return nil
}
return p.enc.Encode(n)
}
func (p *jsonLsPrinter) LeaveDir(_ string) error { return nil }
@@ -195,7 +209,7 @@ func (p *ncduLsPrinter) Snapshot(sn *data.Snapshot) error {
return err
}
func lsNcduNode(_ string, node *data.Node) ([]byte, error) {
func lsNcduOutput(node lsNodeOutput) ([]byte, error) {
type NcduNode struct {
Name string `json:"name"`
Asize uint64 `json:"asize"`
@@ -212,11 +226,12 @@ func lsNcduNode(_ string, node *data.Node) ([]byte, error) {
const blockSize = 512
size := node.fileSize()
outNode := NcduNode{
Name: node.Name,
Asize: node.Size,
Asize: size,
// round up to nearest full blocksize
Dsize: (node.Size + blockSize - 1) / blockSize * blockSize,
Dsize: (size + blockSize - 1) / blockSize * blockSize,
Dev: node.DeviceID,
Ino: node.Inode,
NLink: node.Links,
@@ -244,8 +259,8 @@ func lsNcduNode(_ string, node *data.Node) ([]byte, error) {
return json.Marshal(outNode)
}
func (p *ncduLsPrinter) Node(path string, node *data.Node, _ bool) error {
out, err := lsNcduNode(path, node)
func (p *ncduLsPrinter) NodeOutput(node lsNodeOutput, _ bool) error {
out, err := lsNcduOutput(node)
if err != nil {
return err
}
@@ -275,18 +290,18 @@ type textLsPrinter struct {
ListLong bool
HumanReadable bool
termPrinter interface {
P(msg string, args ...interface{})
S(msg string, args ...interface{})
P(msg string, args ...any)
S(msg string, args ...any)
}
}
func (p *textLsPrinter) Snapshot(sn *data.Snapshot) error {
p.termPrinter.P("%v filtered by %v:", sn, p.dirs)
p.termPrinter.P("%v filtered by %v:", sn, ui.QuoteSlice(p.dirs))
return nil
}
func (p *textLsPrinter) Node(path string, node *data.Node, isPrefixDirectory bool) error {
func (p *textLsPrinter) NodeOutput(node lsNodeOutput, isPrefixDirectory bool) error {
if !isPrefixDirectory {
p.termPrinter.S("%s", formatNode(path, node, p.ListLong, p.HumanReadable))
p.termPrinter.S("%s", formatNodeOutput(node, p.ListLong, p.HumanReadable))
}
return nil
}
@@ -298,14 +313,8 @@ func (p *textLsPrinter) Close() error {
return nil
}
// for ls -l output sorting
type toSortOutput struct {
nodepath string
node *data.Node
}
func runLs(ctx context.Context, opts LsOptions, gopts global.Options, args []string, term ui.Terminal) error {
termPrinter := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
termPrinter := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
if len(args) == 0 {
return errors.Fatal("no snapshot ID specified, specify snapshot ID or use special ID 'latest'")
@@ -431,7 +440,7 @@ func runLs(ctx context.Context, opts LsOptions, gopts global.Options, args []str
printedDir := false
if withinDir(nodepath) {
// if we're within a target path, print the node
if err := printer.Node(nodepath, node, false); err != nil {
if err := printer.NodeOutput(lsNodeOutputFrom(nodepath, node), false); err != nil {
return err
}
printedDir = true
@@ -448,7 +457,7 @@ func runLs(ctx context.Context, opts LsOptions, gopts global.Options, args []str
if approachingMatchingTree(nodepath) {
// print node leading up to the target paths
if !printedDir {
return printer.Node(nodepath, node, true)
return printer.NodeOutput(lsNodeOutputFrom(nodepath, node), true)
}
return nil
}
@@ -487,7 +496,7 @@ func runLs(ctx context.Context, opts LsOptions, gopts global.Options, args []str
type sortedPrinter struct {
printer lsPrinter
collector []toSortOutput
collector []lsNodeOutput
sortMode SortMode
reverse bool
}
@@ -495,9 +504,9 @@ type sortedPrinter struct {
func (p *sortedPrinter) Snapshot(sn *data.Snapshot) error {
return p.printer.Snapshot(sn)
}
func (p *sortedPrinter) Node(path string, node *data.Node, isPrefixDirectory bool) error {
func (p *sortedPrinter) NodeOutput(node lsNodeOutput, isPrefixDirectory bool) error {
if !isPrefixDirectory {
p.collector = append(p.collector, toSortOutput{path, node})
p.collector = append(p.collector, node)
}
return nil
}
@@ -506,49 +515,49 @@ func (p *sortedPrinter) LeaveDir(_ string) error {
return nil
}
func (p *sortedPrinter) Close() error {
var comparator func(a, b toSortOutput) int
var comparator func(a, b lsNodeOutput) int
switch p.sortMode {
case SortModeName:
case SortModeSize:
comparator = func(a, b toSortOutput) int {
comparator = func(a, b lsNodeOutput) int {
return cmp.Or(
cmp.Compare(a.node.Size, b.node.Size),
cmp.Compare(a.nodepath, b.nodepath),
cmp.Compare(a.fileSize(), b.fileSize()),
cmp.Compare(a.Path, b.Path),
)
}
case SortModeMtime:
comparator = func(a, b toSortOutput) int {
comparator = func(a, b lsNodeOutput) int {
return cmp.Or(
a.node.ModTime.Compare(b.node.ModTime),
cmp.Compare(a.nodepath, b.nodepath),
a.ModTime.Compare(b.ModTime),
cmp.Compare(a.Path, b.Path),
)
}
case SortModeAtime:
comparator = func(a, b toSortOutput) int {
comparator = func(a, b lsNodeOutput) int {
return cmp.Or(
a.node.AccessTime.Compare(b.node.AccessTime),
cmp.Compare(a.nodepath, b.nodepath),
a.AccessTime.Compare(b.AccessTime),
cmp.Compare(a.Path, b.Path),
)
}
case SortModeCtime:
comparator = func(a, b toSortOutput) int {
comparator = func(a, b lsNodeOutput) int {
return cmp.Or(
a.node.ChangeTime.Compare(b.node.ChangeTime),
cmp.Compare(a.nodepath, b.nodepath),
a.ChangeTime.Compare(b.ChangeTime),
cmp.Compare(a.Path, b.Path),
)
}
case SortModeExt:
// map name to extension
mapExt := make(map[string]string, len(p.collector))
for _, item := range p.collector {
ext := filepath.Ext(item.nodepath)
mapExt[item.nodepath] = ext
ext := filepath.Ext(item.Path)
mapExt[item.Path] = ext
}
comparator = func(a, b toSortOutput) int {
comparator = func(a, b lsNodeOutput) int {
return cmp.Or(
cmp.Compare(mapExt[a.nodepath], mapExt[b.nodepath]),
cmp.Compare(a.nodepath, b.nodepath),
cmp.Compare(mapExt[a.Path], mapExt[b.Path]),
cmp.Compare(a.Path, b.Path),
)
}
}
@@ -560,7 +569,7 @@ func (p *sortedPrinter) Close() error {
slices.Reverse(p.collector)
}
for _, elem := range p.collector {
if err := p.printer.Node(elem.nodepath, elem.node, false); err != nil {
if err := p.printer.NodeOutput(elem, false); err != nil {
return err
}
}
+10 -10
View File
@@ -96,12 +96,12 @@ func TestLsNodeJSON(t *testing.T) {
c := lsTestNodes[i]
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
err := lsNodeJSON(enc, c.path, &c.Node)
err := enc.Encode(lsNodeOutputFrom(c.path, &c.Node))
rtest.OK(t, err)
rtest.Equals(t, expect+"\n", buf.String())
// Sanity check: output must be valid JSON.
var v interface{}
var v any
err = json.NewDecoder(buf).Decode(&v)
rtest.OK(t, err)
}
@@ -116,12 +116,12 @@ func TestLsNcduNode(t *testing.T) {
`{"name":"sticky","asize":0,"dsize":0,"dev":0,"ino":0,"nlink":0,"notreg":false,"uid":0,"gid":0,"mode":4077,"mtime":0}`,
} {
c := lsTestNodes[i]
out, err := lsNcduNode(c.path, &c.Node)
out, err := lsNcduOutput(lsNodeOutputFrom(c.path, &c.Node))
rtest.OK(t, err)
rtest.Equals(t, expect, string(out))
// Sanity check: output must be valid JSON.
var v interface{}
var v any
err = json.Unmarshal(out, &v)
rtest.OK(t, err)
}
@@ -138,24 +138,24 @@ func TestLsNcdu(t *testing.T) {
Hostname: "host",
Paths: []string{"/example"},
}))
rtest.OK(t, printer.Node("/directory", &data.Node{
rtest.OK(t, printer.NodeOutput(lsNodeOutputFrom("/directory", &data.Node{
Type: data.NodeTypeDir,
Name: "directory",
ModTime: modTime,
}, false))
rtest.OK(t, printer.Node("/directory/data", &data.Node{
}), false))
rtest.OK(t, printer.NodeOutput(lsNodeOutputFrom("/directory/data", &data.Node{
Type: data.NodeTypeFile,
Name: "data",
Size: 42,
ModTime: modTime,
}, false))
}), false))
rtest.OK(t, printer.LeaveDir("/directory"))
rtest.OK(t, printer.Node("/file", &data.Node{
rtest.OK(t, printer.NodeOutput(lsNodeOutputFrom("/file", &data.Node{
Type: data.NodeTypeFile,
Name: "file",
Size: 12345,
ModTime: modTime,
}, false))
}), false))
rtest.OK(t, printer.Close())
rtest.Equals(t, `[1, 2, {"time":"0001-01-01T00:00:00Z","tree":null,"paths":["/example"],"hostname":"host"}, [{"name":"/"},
+3 -3
View File
@@ -53,7 +53,7 @@ func (opts *MigrateOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVarP(&opts.Force, "force", "f", false, `apply a migration a second time`)
}
func checkMigrations(ctx context.Context, repo restic.Repository, printer progress.Printer) error {
func checkMigrations(ctx context.Context, repo restic.Repository, printer restic.Printer) error {
printer.P("available migrations:\n")
found := false
@@ -76,7 +76,7 @@ func checkMigrations(ctx context.Context, repo restic.Repository, printer progre
return nil
}
func applyMigrations(ctx context.Context, opts MigrateOptions, gopts global.Options, repo restic.Repository, args []string, term ui.Terminal, printer progress.Printer) error {
func applyMigrations(ctx context.Context, opts MigrateOptions, gopts global.Options, repo restic.Repository, args []string, term ui.Terminal, printer restic.Printer) error {
var firsterr error
for _, name := range args {
found := false
@@ -135,7 +135,7 @@ func applyMigrations(ctx context.Context, opts MigrateOptions, gopts global.Opti
}
func runMigrate(ctx context.Context, opts MigrateOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
+17 -29
View File
@@ -19,13 +19,15 @@ import (
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/fuse"
systemFuse "github.com/anacrolix/fuse"
"github.com/anacrolix/fuse/fs"
fusefs "github.com/anacrolix/fuse/fs"
)
func registerMountCommand(cmdRoot *cobra.Command, globalOptions *global.Options) {
@@ -119,7 +121,7 @@ func (opts *MountOptions) AddFlags(f *pflag.FlagSet) {
}
func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
if opts.TimeTemplate == "" {
return errors.Fatal("time template string cannot be empty")
@@ -152,7 +154,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
return err
}
fuseMountName := fmt.Sprintf("restic:%s", repo.Config().ID[:10])
fuseMountName := fmt.Sprintf("restic:%s", repo.Config().ID.String()[:10])
mountOptions := []systemFuse.MountOption{
systemFuse.ReadOnly(),
@@ -169,7 +171,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
}
}
systemFuse.Debug = func(msg interface{}) {
systemFuse.Debug = func(msg any) {
debug.Log("fuse: %v", msg)
}
@@ -196,10 +198,10 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
go func() {
defer close(done)
err = fs.Serve(c, root)
err = fusefs.Serve(c, root)
}()
printer.S("Now serving the repository at %s", mountpoint)
printer.S("Now serving the repository at %s", ui.Quote(mountpoint))
printer.S("Use another terminal or tool to browse the contents of this folder.")
printer.S("When finished, quit with Ctrl-c here or umount the mountpoint.")
debug.Log("serving mount at %v", mountpoint)
@@ -225,16 +227,16 @@ func validateMountpoint(mountpoint string, gopts global.Options) error {
// prevent unnecessary computations while opening the repository.
stat, err := os.Stat(mountpoint)
if errors.Is(err, os.ErrNotExist) {
return errors.Fatal(fmt.Sprintf("mountpoint %s does not exist", mountpoint))
return errors.Fatal(fmt.Sprintf("mountpoint %q does not exist", mountpoint))
} else if err != nil {
return errors.Fatal(fmt.Sprintf("mountpoint %s is inaccessible: %v", mountpoint, err))
return errors.Fatal(fmt.Sprintf("mountpoint %q is inaccessible: %v", mountpoint, err))
} else if !stat.IsDir() {
return errors.Fatal(fmt.Sprintf("mountpoint %s is not a directory", mountpoint))
return errors.Fatal(fmt.Sprintf("mountpoint %q is not a directory", mountpoint))
}
err = unix.Access(mountpoint, unix.W_OK|unix.X_OK)
if err != nil {
return errors.Fatal(fmt.Sprintf("mountpoint %s is not writeable or not executable", mountpoint))
return errors.Fatal(fmt.Sprintf("mountpoint %q is not writeable or not executable", mountpoint))
}
// Refuse to mount onto (or under, or over) the local repository directory.
@@ -269,11 +271,11 @@ func checkMountpointOverlap(repoPath, mountpoint string) error {
const tail = "; refusing to mount to avoid deadlocking the FUSE server"
switch {
case rp == mp:
return errors.Fatal(fmt.Sprintf("mountpoint %s is the local repository directory%s", mp, tail))
case isInside(rp, mp):
return errors.Fatal(fmt.Sprintf("mountpoint %s is inside the local repository directory %s%s", mp, rp, tail))
case isInside(mp, rp):
return errors.Fatal(fmt.Sprintf("local repository directory %s is inside the mountpoint %s%s", rp, mp, tail))
return errors.Fatal(fmt.Sprintf("mountpoint %q is the local repository directory%s", mp, tail))
case fs.HasPathPrefix(rp, mp):
return errors.Fatal(fmt.Sprintf("mountpoint %q is inside the local repository directory %q%s", mp, rp, tail))
case fs.HasPathPrefix(mp, rp):
return errors.Fatal(fmt.Sprintf("local repository directory %q is inside the mountpoint %q%s", rp, mp, tail))
}
return nil
}
@@ -293,17 +295,3 @@ func resolvePath(p string) (string, error) {
}
return resolved, nil
}
// isInside reports whether child is strictly nested inside parent. Both paths
// must already be cleaned and absolute. Equal paths return false; the caller
// handles equality separately so it can produce a distinct error message.
func isInside(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
if err != nil {
return false
}
if rel == "." || rel == ".." {
return false
}
return !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
+6 -12
View File
@@ -14,16 +14,15 @@ import (
systemFuse "github.com/anacrolix/fuse"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
const (
mountWait = 20
mountSleep = 100 * time.Millisecond
mountWait = 400
mountSleep = 5 * time.Millisecond
mountTestSubdir = "snapshots"
)
@@ -47,7 +46,7 @@ func snapshotsDirExists(t testing.TB, dir string) bool {
// waitForMount blocks (max mountWait * mountSleep) until the subdir
// "snapshots" appears in the dir.
func waitForMount(t testing.TB, dir string) {
for i := 0; i < mountWait; i++ {
for range mountWait {
if snapshotsDirExists(t, dir) {
t.Log("mounted directory is ready")
return
@@ -71,7 +70,7 @@ func testRunMount(t testing.TB, gopts global.Options, dir string, wg *sync.WaitG
func testRunUmount(t testing.TB, dir string) {
var err error
for i := 0; i < mountWait; i++ {
for range mountWait {
if err = systemFuse.Unmount(dir); err == nil {
t.Logf("directory %v umounted", dir)
return
@@ -131,7 +130,7 @@ func checkSnapshots(t testing.TB, gopts global.Options, mountpoint string, snaps
}
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
if err != nil {
return err
@@ -274,11 +273,6 @@ func TestMountSameTimestamps(t *testing.T) {
t.Skip("Skipping fuse tests")
}
debugEnabled := debug.TestLogToStderr(t)
if debugEnabled {
defer debug.TestDisableLog(t)
}
env, cleanup := withTestEnvironment(t)
// must list snapshots more than once
env.gopts.BackendTestHook = nil
+20 -21
View File
@@ -83,7 +83,7 @@ func (opts *PruneOptions) AddLimitedFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.RepackCacheableOnly, "repack-cacheable-only", false, "only repack packs which are cacheable")
f.BoolVar(&unused, "repack-small", false, "deprecated. Use --repack-smaller-than to specify a minimum size")
f.BoolVar(&opts.RepackUncompressed, "repack-uncompressed", false, "repack all uncompressed data")
f.StringVar(&opts.SmallPackSize, "repack-smaller-than", "", "pack `below-limit` packfiles (allowed suffixes: m/M)")
f.StringVar(&opts.SmallPackSize, "repack-smaller-than", "", "pack `below-limit` packfiles (allowed suffixes: k/K, m/M, g/G, t/T)")
err := f.MarkDeprecated("repack-small", "small files are automatically repacked. Use --repack-smaller-than to specify a minimum size")
if err != nil {
@@ -175,7 +175,7 @@ func runPrune(ctx context.Context, opts PruneOptions, gopts global.Options, term
return errors.Fatal("--no-lock is only applicable in combination with --dry-run for prune command")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun && gopts.NoLock, printer)
if err != nil {
return err
@@ -183,18 +183,18 @@ func runPrune(ctx context.Context, opts PruneOptions, gopts global.Options, term
defer unlock()
if opts.UnsafeNoSpaceRecovery != "" {
repoID := repo.Config().ID
repoID := repo.Config().ID.String()
if opts.UnsafeNoSpaceRecovery != repoID {
return errors.Fatalf("must pass id '%s' to --unsafe-recover-no-free-space", repoID)
}
opts.unsafeRecovery = true
}
return runPruneWithRepo(ctx, opts, repo, restic.NewIDSet(), printer)
return runPruneWithRepo(ctx, opts, gopts, repo, restic.NewIDSet(), printer)
}
func runPruneWithRepo(ctx context.Context, opts PruneOptions, repo *repository.Repository, ignoreSnapshots restic.IDSet, printer progress.Printer) error {
if repo.Cache() == nil {
func runPruneWithRepo(ctx context.Context, opts PruneOptions, gopts global.Options, repo *repository.Repository, ignoreSnapshots restic.IDSet, printer restic.Printer) error {
if repo.Cache() == nil && !gopts.JSON {
printer.S("warning: running prune without a cache, this may be very slow!")
}
@@ -230,9 +230,13 @@ func runPruneWithRepo(ctx context.Context, opts PruneOptions, repo *repository.R
printer.P("\nWould have made the following changes:")
}
err = printPruneStats(printer, plan.Stats())
if err != nil {
return err
if !gopts.JSON {
err = printPruneStats(printer, plan.Stats())
if err != nil {
return err
}
} else {
gopts.Term.Print(ui.ToJSONString(plan.Stats()))
}
// Trigger GC to reset garbage collection threshold
@@ -242,7 +246,7 @@ func runPruneWithRepo(ctx context.Context, opts PruneOptions, repo *repository.R
}
// printPruneStats prints out the statistics
func printPruneStats(printer progress.Printer, stats repository.PruneStats) error {
func printPruneStats(printer restic.Printer, stats repository.PruneStats) error {
printer.V("\nused: %10d blobs / %s", stats.Blobs.Used, ui.FormatBytes(stats.Size.Used))
if stats.Blobs.Duplicate > 0 {
printer.V("duplicates: %10d blobs / %s", stats.Blobs.Duplicate, ui.FormatBytes(stats.Size.Duplicate))
@@ -251,24 +255,19 @@ func printPruneStats(printer progress.Printer, stats repository.PruneStats) erro
if stats.Size.Unref > 0 {
printer.V("unreferenced: %s", ui.FormatBytes(stats.Size.Unref))
}
totalBlobs := stats.Blobs.Used + stats.Blobs.Unused + stats.Blobs.Duplicate
totalSize := stats.Size.Used + stats.Size.Duplicate + stats.Size.Unused + stats.Size.Unref
unusedSize := stats.Size.Duplicate + stats.Size.Unused
printer.V("total: %10d blobs / %s", totalBlobs, ui.FormatBytes(totalSize))
printer.V("unused size: %s of total size", ui.FormatPercent(unusedSize, totalSize))
printer.V("total: %10d blobs / %s", stats.Blobs.Total, ui.FormatBytes(stats.Size.Total))
printer.V("unused size: %s of total size", ui.FormatPercent(stats.Size.Duplicate+stats.Size.Unused, stats.Size.Total))
printer.P("\nto repack: %10d blobs / %s", stats.Blobs.Repack, ui.FormatBytes(stats.Size.Repack))
printer.P("this removes: %10d blobs / %s", stats.Blobs.Repackrm, ui.FormatBytes(stats.Size.Repackrm))
printer.P("to delete: %10d blobs / %s", stats.Blobs.Remove, ui.FormatBytes(stats.Size.Remove+stats.Size.Unref))
totalPruneSize := stats.Size.Remove + stats.Size.Repackrm + stats.Size.Unref
printer.P("total prune: %10d blobs / %s", stats.Blobs.Remove+stats.Blobs.Repackrm, ui.FormatBytes(totalPruneSize))
printer.P("total prune: %10d blobs / %s", stats.Blobs.RemoveTotal, ui.FormatBytes(stats.Size.RemoveTotal))
if stats.Size.Uncompressed > 0 {
printer.P("not yet compressed: %s", ui.FormatBytes(stats.Size.Uncompressed))
}
printer.P("remaining: %10d blobs / %s", totalBlobs-(stats.Blobs.Remove+stats.Blobs.Repackrm), ui.FormatBytes(totalSize-totalPruneSize))
unusedAfter := unusedSize - stats.Size.Remove - stats.Size.Repackrm
printer.P("remaining: %10d blobs / %s", stats.Blobs.Remain, ui.FormatBytes(stats.Size.Remain))
printer.P("unused size after prune: %s (%s of remaining size)",
ui.FormatBytes(unusedAfter), ui.FormatPercent(unusedAfter, totalSize-totalPruneSize))
ui.FormatBytes(stats.Size.RemainUnused), ui.FormatPercent(stats.Size.RemainUnused, stats.Size.Remain))
printer.P("")
printer.V("totally used packs: %10d", stats.Packs.Used)
printer.V("partly used packs: %10d", stats.Packs.PartlyUsed)
@@ -283,7 +282,7 @@ func printPruneStats(printer progress.Printer, stats repository.PruneStats) erro
return nil
}
func getUsedBlobs(ctx context.Context, repo restic.Repository, usedBlobs restic.FindBlobSet, ignoreSnapshots restic.IDSet, printer progress.Printer) error {
func getUsedBlobs(ctx context.Context, repo restic.Repository, usedBlobs restic.FindBlobSet, ignoreSnapshots restic.IDSet, printer restic.Printer) error {
var snapshotTrees restic.IDs
printer.P("loading all snapshots...")
err := data.ForAllSnapshots(ctx, repo, repo, ignoreSnapshots,
+25
View File
@@ -258,3 +258,28 @@ func TestPruneRepackSmallerThanSmoke(t *testing.T) {
MaxUnused: "5%",
})
}
func TestPruneJSON(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createPrunableRepo(t, env)
buf, err := withCaptureStdout(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = true
oldHook := gopts.BackendTestHook
gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) { return newListOnceBackend(r), nil }
defer func() {
gopts.BackendTestHook = oldHook
}()
return runPrune(ctx, pruneDefaultOptions, gopts, gopts.Term)
})
rtest.OK(t, err)
var stats repository.PruneStats
rtest.OK(t, json.Unmarshal(buf.Bytes(), &stats))
rtest.Equals(t, "summary", stats.MessageType)
rtest.Assert(t, stats.Blobs.Total > 0, "expected non-zero total blobs, got %v", stats.Blobs.Total)
rtest.Assert(t, stats.Packs.Total > 0, "expected non-zero total packs, got %v", stats.Packs.Total)
}
+9 -8
View File
@@ -48,7 +48,7 @@ func runRecover(ctx context.Context, gopts global.Options, term ui.Terminal) err
return err
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
@@ -75,13 +75,14 @@ func runRecover(ctx context.Context, gopts global.Options, term ui.Terminal) err
// tree. If it is not referenced, we have a root tree.
trees := make(map[restic.ID]bool)
err = repo.ListBlobs(ctx, func(blob restic.PackedBlob) {
if blob.Type == restic.TreeBlob {
trees[blob.Blob.ID] = false
for blob := range repo.ListBlobs() {
if err = ctx.Err(); err != nil {
return err
}
h := blob.Handle()
if h.Type == restic.TreeBlob {
trees[h.ID] = false
}
})
if err != nil {
return err
}
printer.P("load %d trees\n", len(trees))
@@ -173,7 +174,7 @@ func runRecover(ctx context.Context, gopts global.Options, term ui.Terminal) err
}
func createSnapshot(ctx context.Context, printer progress.Printer, name, hostname string, tags []string, repo restic.SaverUnpacked[restic.WriteableFileType], tree *restic.ID) error {
func createSnapshot(ctx context.Context, printer restic.Printer, name, hostname string, tags []string, repo restic.SaverUnpacked[restic.WriteableFileType], tree *restic.ID) error {
sn, err := data.NewSnapshot([]string{name}, tags, hostname, time.Now())
if err != nil {
return errors.Fatalf("unable to save snapshot: %v", err)
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -70,7 +71,7 @@ func newRebuildIndexCommand(globalOptions *global.Options) *cobra.Command {
}
func runRebuildIndex(ctx context.Context, opts RepairIndexOptions, gopts global.Options, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
@@ -11,7 +11,7 @@ import (
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository/index"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
@@ -24,13 +24,14 @@ func testRunRebuildIndex(t testing.TB, gopts global.Options) {
}
func testRebuildIndex(t *testing.T, backendTestHook global.BackendWrapper) {
repository.TestInjectKey(t, restic.TestParseID("b9883c60bed42db51be171ca52f055104b6ea7cfa2bc381c05b2b1f78231280c"), `{"mac":{"k":"maQ4ILA872XnDxHVEno94A==","r":"OptMBABwkgIsMQcHME8cBw=="},"encrypt":"janrR1efN7HyQ8kOZ9zhHixooZ/e+WelH0mT4v9WskQ="}`)
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("..", "..", "internal", "checker", "testdata", "duplicate-packs-in-index-test-repo.tar.gz")
rtest.SetupTarTestFixture(t, env.base, datafile)
out, err := testRunCheckOutput(t, env.gopts, false)
out, _, err := testRunCheckOutput(t, env.gopts, false)
if !strings.Contains(out, "contained in several indexes") {
t.Fatalf("did not find checker hint for packs in several indexes")
}
@@ -47,7 +48,7 @@ func testRebuildIndex(t *testing.T, backendTestHook global.BackendWrapper) {
testRunRebuildIndex(t, env.gopts)
env.gopts.BackendTestHook = nil
out, err = testRunCheckOutput(t, env.gopts, false)
out, _, err = testRunCheckOutput(t, env.gopts, false)
if len(out) != 0 {
t.Fatalf("expected no output from the checker, got: %v", out)
}
@@ -61,15 +62,6 @@ func TestRebuildIndex(t *testing.T) {
testRebuildIndex(t, nil)
}
func TestRebuildIndexAlwaysFull(t *testing.T) {
indexFull := index.Full
defer func() {
index.Full = indexFull
}()
index.Full = func(*index.Index) bool { return true }
testRebuildIndex(t, nil)
}
// indexErrorBackend modifies the first index after reading.
type indexErrorBackend struct {
backend.Backend
@@ -82,7 +74,7 @@ func (b *indexErrorBackend) Load(ctx context.Context, h backend.Handle, length i
// protect hasErred
b.lock.Lock()
defer b.lock.Unlock()
if !b.hasErred && h.Type == restic.IndexFile {
if !b.hasErred && h.Type == backend.IndexFile {
b.hasErred = true
return consumer(errorReadCloser{rd})
}
@@ -120,6 +112,7 @@ func (b *appendOnlyBackend) Remove(_ context.Context, h backend.Handle) error {
}
func TestRebuildIndexFailsOnAppendOnly(t *testing.T) {
repository.TestInjectKey(t, restic.TestParseID("b9883c60bed42db51be171ca52f055104b6ea7cfa2bc381c05b2b1f78231280c"), `{"mac":{"k":"maQ4ILA872XnDxHVEno94A==","r":"OptMBABwkgIsMQcHME8cBw=="},"encrypt":"janrR1efN7HyQ8kOZ9zhHixooZ/e+WelH0mT4v9WskQ="}`)
env, cleanup := withTestEnvironment(t)
defer cleanup()
+9 -4
View File
@@ -11,6 +11,7 @@ import (
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
)
@@ -52,7 +53,7 @@ func runRepairPacks(ctx context.Context, gopts global.Options, term ui.Terminal,
return errors.Fatal("no ids specified")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
@@ -68,9 +69,13 @@ func runRepairPacks(ctx context.Context, gopts global.Options, term ui.Terminal,
printer.P("saving backup copies of pack files to current folder")
for id := range ids {
buf, err := repo.LoadRaw(ctx, restic.PackFile, id)
// corrupted data is fine
if buf == nil {
return err
if ctx.Err() != nil {
return ctx.Err()
}
// only skip creating a local copy if no data at all could be loaded
if err != nil && buf == nil {
printer.E("will remove packfile %v due to failed download: %v", id, err)
continue
}
f, err := os.OpenFile("pack-"+id.String(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666)
@@ -0,0 +1,74 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui/progress"
)
// testRunRepairPacks runs `restic repair packs` with capturing stdout and stderr
func testRunRepairPacks(t testing.TB, gopts global.Options, args []string) (string, string, error) {
bufStdout, bufStderr, err := withCaptureStdoutStderr(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRepairPacks(ctx, gopts, gopts.Term, args)
})
return bufStdout.String(), bufStderr.String(), err
}
func TestRunRepairPackfiles(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
// backup of subtree 0/0/9/42
testRunBackup(t, env.testdata, []string{filepath.Join(env.testdata, "0", "0", "9", "42")}, BackupOptions{}, env.gopts)
testListSnapshots(t, env.gopts, 1)
packfileID := restic.ID{}
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
rtest.OK(t, repo.LoadIndex(ctx, printer))
// load packfiles from master index
for blob := range repo.ListBlobs() {
rtest.OK(t, ctx.Err())
if blob.Handle().Type == restic.DataBlob {
packfileID = blob.PackID()
}
}
return nil
})
rtest.OK(t, err)
rtest.Assert(t, !packfileID.IsNull(), "expected valid packfile ID")
packIDString := packfileID.String()
filename := filepath.Join(env.gopts.Repo, "data", packIDString[0:2], packIDString)
rtest.OK(t, os.Remove(filename))
_, outError, err := testRunCheckOutput(t, env.gopts, false)
rtest.Assert(t, err != nil, "expected check errors, got none")
rtest.Assert(t, strings.Contains(string(outError), packIDString), "expected mention of %q", packIDString)
// change to temporary directory to not pollute the repository with backup files
cleanupChdir := rtest.Chdir(t, env.base)
defer cleanupChdir()
// restic repair packs 'packIDString'
_, _, err = testRunRepairPacks(t, env.gopts, []string{packIDString})
rtest.OK(t, err)
// run restic repair snapshots --forget
testRunRepairSnapshot(t, env.gopts, true)
_, _, err = testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
+56 -7
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"path"
"slices"
"github.com/restic/restic/internal/data"
@@ -9,6 +10,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/walker"
"github.com/spf13/cobra"
@@ -77,8 +79,40 @@ func (opts *RepairOptions) AddFlags(f *pflag.FlagSet) {
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
// handleUnreadableSnapshotFile is called when FindAll returns an error for ID 'id'
func handleUnreadableSnapshotFile(
ctx context.Context,
be restic.Lister,
repo restic.Repository,
opts RepairOptions,
id string,
loadErr error,
args []string,
printer restic.Printer,
) (bool, error) {
brokenID, err := restic.Find(ctx, be, restic.SnapshotFile, id)
if err != nil {
return false, err
}
if opts.Forget && slices.Index(args, id) >= 0 {
if opts.DryRun {
printer.P("would remove unreadable snapshot %v", brokenID)
return true, nil
}
if err := repo.RemoveUnpacked(ctx, restic.WriteableSnapshotFile, brokenID); err != nil {
return false, errors.Wrapf(err, "unable to remove unreadable snapshot file %v", brokenID)
}
printer.P("removed unreadable snapshot %v", brokenID)
return true, nil
}
return false, errors.Fatalf("snapshot file %[1]s is unreadable, use `restic repair snapshots --forget %[1]s` to remove it. Original error: %v", brokenID, loadErr)
}
func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOptions, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun, printer)
if err != nil {
@@ -95,10 +129,11 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
return err
}
// Three error cases are checked:
// Four error cases are checked:
// - tree is a nil tree (-> will be replaced by an empty tree)
// - trees which cannot be loaded (-> the tree contents will be removed)
// - files whose contents are not fully available (-> file will be modified)
// - *checker.SnapshotError
rewriter := walker.NewTreeRewriter(walker.RewriteOpts{
RewriteNode: func(node *data.Node, path string) *data.Node {
if node.Type == data.NodeTypeIrregular || node.Type == data.NodeTypeInvalid {
@@ -114,7 +149,7 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
var newSize uint64
// check all contents and remove if not available
for _, id := range node.Content {
if size, found := repo.LookupBlobSize(restic.DataBlob, id); !found {
if size, found := repo.LookupBlobSize(restic.BlobHandle{Type: restic.DataBlob, ID: id}); !found {
ok = false
} else {
newContent = append(newContent, id)
@@ -142,10 +177,22 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
return slices.Values([]data.NodeOrError{}), nil
},
AllowUnstableSerialization: true,
ReportDroppedNode: func(parent string, node *data.Node, err error) {
target := path.Join(parent, node.Name)
printer.E("warning: dropping directory entry %q: %v", target, err)
},
})
changedCount := 0
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
errOuter := opts.SnapshotFilter.FindAll(ctx, snapshotLister, repo, args, func(id string, sn *data.Snapshot, err error) error {
if err != nil {
changed, err := handleUnreadableSnapshotFile(ctx, snapshotLister, repo, opts, id, err, args, printer)
if changed {
changedCount++
}
return err
}
printer.P("\n%v", sn)
changed, err := filterAndReplaceSnapshot(ctx, repo, sn,
func(ctx context.Context, sn *data.Snapshot, uploader restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error) {
@@ -158,9 +205,11 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
if changed {
changedCount++
}
}
if ctx.Err() != nil {
return ctx.Err()
return nil
})
if errOuter != nil {
return errOuter
}
printer.P("")
@@ -2,6 +2,8 @@ package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"hash/fnv"
"io"
"math/rand"
@@ -67,7 +69,7 @@ func TestRepairSnapshotsWithLostData(t *testing.T) {
// repository must be ok after removing the broken snapshots
testRunForget(t, env.gopts, ForgetOptions{}, snapshotIDs[0].String(), snapshotIDs[1].String())
testListSnapshots(t, env.gopts, 2)
_, err := testRunCheckOutput(t, env.gopts, false)
_, _, err := testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
@@ -96,7 +98,7 @@ func TestRepairSnapshotsWithLostTree(t *testing.T) {
testRunRebuildIndex(t, env.gopts)
testRunRepairSnapshot(t, env.gopts, true)
testListSnapshots(t, env.gopts, 1)
_, err := testRunCheckOutput(t, env.gopts, false)
_, _, err := testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
@@ -119,7 +121,7 @@ func TestRepairSnapshotsWithLostRootTree(t *testing.T) {
testRunRebuildIndex(t, env.gopts)
testRunRepairSnapshot(t, env.gopts, true)
testListSnapshots(t, env.gopts, 0)
_, err := testRunCheckOutput(t, env.gopts, false)
_, _, err := testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
@@ -136,3 +138,38 @@ func TestRepairSnapshotsIntact(t *testing.T) {
rtest.Assert(t, reflect.DeepEqual(oldSnapshotIDs, snapshotIDs), "unexpected snapshot id mismatch %v vs. %v", oldSnapshotIDs, snapshotIDs)
testRunCheck(t, env.gopts)
}
func TestRepairSnapshotsBrokenSnapshots(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
// create backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{}, env.gopts)
// create zero length file in snapshots/
// will fail with
// failed to load snapshot 1d204771: LoadRaw(<snapshot/1d20477115>): invalid data returned
handle, err := os.Create(filepath.Join(env.repo, "snapshots", "1d20477115fb872069a28a80ffb95a82cb8b1b1920de046a68c0195da63f30cf"))
rtest.OK(t, err)
rtest.OK(t, handle.Close())
// create some file with a correct sha256 name in snapshots/, will fail with
// failed to load snapshot abcd1234: ciphertext verification failed
contents := rtest.Random(1234567890, 42)
sha256Contents := sha256.Sum256(contents)
target := hex.EncodeToString(sha256Contents[:])
rtest.OK(t, os.WriteFile(filepath.Join(env.repo, "snapshots", target), contents, 0o600))
// run repair snapshots
repairOpts := RepairOptions{Forget: true}
env.gopts.BackendTestHook = nil
_, err = withCaptureStdout(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runRepairSnapshots(ctx, gopts, repairOpts, []string{"1d204771", target[:8]}, gopts.Term)
})
rtest.OK(t, err)
// verify that there are no snapshot errors
testRunCheck(t, env.gopts)
}
+6 -6
View File
@@ -11,9 +11,9 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/filter"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/restorer"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
restoreui "github.com/restic/restic/internal/ui/restore"
"github.com/spf13/cobra"
@@ -167,7 +167,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
return err
}
progress := restoreui.NewProgress(printer, ui.CalculateProgressInterval(!gopts.Quiet, gopts.JSON, term.CanUpdateStatus()))
progress := restoreui.NewProgress(printer, gopts.Quiet, gopts.JSON, term.CanUpdateStatus())
res := restorer.NewRestorer(repo, sn, restorer.Options{
DryRun: opts.DryRun,
Sparse: opts.Sparse,
@@ -243,7 +243,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
}
if !gopts.JSON {
printer.P("restoring %s to %s\n", res.Snapshot(), opts.Target)
printer.P("restoring %s to %s\n", res.Snapshot(), ui.Quote(opts.Target))
}
countRestoredFiles, err := res.RestoreTo(ctx, opts.Target)
@@ -259,7 +259,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
if opts.Verify {
if !gopts.JSON {
printer.P("verifying files in %s\n", opts.Target)
printer.P("verifying files in %s\n", ui.Quote(opts.Target))
}
var count int
t0 := time.Now()
@@ -273,7 +273,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
}
if !gopts.JSON {
printer.P("finished verifying %d files in %s (took %s)\n", count, opts.Target,
printer.P("finished verifying %d files in %s (took %s)\n", count, ui.Quote(opts.Target),
time.Since(t0).Round(time.Millisecond))
}
}
@@ -281,7 +281,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
return nil
}
func getXattrSelectFilter(opts RestoreOptions, printer progress.Printer) (func(xattrName string) bool, error) {
func getXattrSelectFilter(opts RestoreOptions, printer restic.Printer) (func(xattrName string) bool, error) {
hasXattrExcludes := len(opts.ExcludeXattrPattern) > 0
hasXattrIncludes := len(opts.IncludeXattrPattern) > 0
+3 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
@@ -242,7 +243,7 @@ func TestRestore(t *testing.T) {
testRunInit(t, env.gopts)
for i := 0; i < 10; i++ {
for i := range 10 {
p := filepath.Join(env.testdata, fmt.Sprintf("foo/bar/testfile%v", i))
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, uint(rand.Intn(2<<21))))
@@ -329,6 +330,7 @@ func TestRestoreLatest(t *testing.T) {
}
func TestRestoreWithPermissionFailure(t *testing.T) {
repository.TestInjectKey(t, restic.TestParseID("18493b1f93ad90b6bce7ed3afa93395a1f90e981f04145c03e5958cafa2ee33b"), `{"mac":{"k":"7ftgSq7jNM2HiGCyY9TYrg==","r":"o+1bB0wApwqoG7oAXOLyDw=="},"encrypt":"i57gVfyYp9HmXjzE0dSZyrkp2FN9LE75uWFjOuWze1M="}`)
env, cleanup := withTestEnvironment(t)
defer cleanup()
+17 -13
View File
@@ -92,7 +92,7 @@ func (sma snapshotMetadataArgs) convert() (*snapshotMetadata, error) {
var timeStamp *time.Time
if sma.Time != "" {
t, err := time.ParseInLocation(global.TimeFormat, sma.Time, time.Local)
t, err := ui.ParseTime(sma.Time)
if err != nil {
return nil, errors.Fatalf("error in time option: %v", err)
}
@@ -129,7 +129,7 @@ func (opts *RewriteOptions) AddFlags(f *pflag.FlagSet) {
// be updated accordingly.
type rewriteFilterFunc func(ctx context.Context, sn *data.Snapshot, uploader restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error)
func rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *data.Snapshot, opts RewriteOptions, printer progress.Printer) (bool, error) {
func rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *data.Snapshot, opts RewriteOptions, printer restic.Printer) (bool, error) {
if sn.Tree == nil {
return false, errors.Errorf("snapshot %v has nil tree", sn.ID().Str())
}
@@ -163,7 +163,7 @@ func rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *data.
rewriteNode = gatherExcludeFilters(rejectByNameFuncs, printer)
}
rewriter, querySize := walker.NewSnapshotSizeRewriter(rewriteNode, keepEmptyDirectoryFunc)
rewriter, querySize := walker.NewSnapshotSizeRewriter(rewriteNode, keepEmptyDirectoryFunc, nil)
filter = func(ctx context.Context, sn *data.Snapshot, uploader restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error) {
id, err := rewriter.RewriteTree(ctx, repo, uploader, "/", *sn.Tree)
@@ -191,7 +191,7 @@ func rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *data.
}
func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *data.Snapshot,
filter rewriteFilterFunc, dryRun bool, forget bool, newMetadata *snapshotMetadata, addTag string, printer progress.Printer,
filter rewriteFilterFunc, dryRun bool, forget bool, newMetadata *snapshotMetadata, addTag string, printer restic.Printer,
keepEmptySnapshot bool) (bool, error) {
var filteredTree restic.ID
@@ -245,7 +245,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("would set hostname to %s", newMetadata.Hostname)
printer.P("would set hostname to %s", ui.Quote(newMetadata.Hostname))
}
return true, nil
@@ -268,7 +268,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("setting host to %s", newMetadata.Hostname)
printer.P("setting host to %s", ui.Quote(newMetadata.Hostname))
sn.Hostname = newMetadata.Hostname
}
@@ -298,7 +298,7 @@ func runRewrite(ctx context.Context, opts RewriteOptions, gopts global.Options,
return errors.Fatal("exclude and include patterns are mutually exclusive")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
var (
repo *repository.Repository
@@ -327,7 +327,10 @@ func runRewrite(ctx context.Context, opts RewriteOptions, gopts global.Options,
}
changedCount := 0
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
err = opts.SnapshotFilter.FindAll(ctx, snapshotLister, repo, args, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
printer.P("\n%v", sn)
changed, err := rewriteSnapshot(ctx, repo, sn, opts, printer)
if err != nil {
@@ -336,9 +339,10 @@ func runRewrite(ctx context.Context, opts RewriteOptions, gopts global.Options,
if changed {
changedCount++
}
}
if ctx.Err() != nil {
return ctx.Err()
return nil
})
if err != nil {
return err
}
printer.P("")
@@ -359,7 +363,7 @@ func runRewrite(ctx context.Context, opts RewriteOptions, gopts global.Options,
return nil
}
func gatherIncludeFilters(includeByNameFuncs []filter.IncludeByNameFunc, printer progress.Printer) (rewriteNode walker.NodeRewriteFunc, keepEmptyDirectory walker.NodeKeepEmptyDirectoryFunc) {
func gatherIncludeFilters(includeByNameFuncs []filter.IncludeByNameFunc, printer restic.Printer) (rewriteNode walker.NodeRewriteFunc, keepEmptyDirectory walker.NodeKeepEmptyDirectoryFunc) {
inSelectByName := func(nodepath string, node *data.Node) bool {
for _, include := range includeByNameFuncs {
matched, childMayMatch := include(nodepath)
@@ -406,7 +410,7 @@ func gatherIncludeFilters(includeByNameFuncs []filter.IncludeByNameFunc, printer
return rewriteNode, keepEmptyDirectory
}
func gatherExcludeFilters(excludeByNameFuncs []filter.RejectByNameFunc, printer progress.Printer) (rewriteNode walker.NodeRewriteFunc) {
func gatherExcludeFilters(excludeByNameFuncs []filter.RejectByNameFunc, printer restic.Printer) (rewriteNode walker.NodeRewriteFunc) {
exSelectByName := func(nodepath string) bool {
for _, reject := range excludeByNameFuncs {
if reject(nodepath) {
+43 -4
View File
@@ -13,6 +13,7 @@ import (
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func testRunRewriteExclude(t testing.TB, gopts global.Options, excludes []string, forget bool, metadata snapshotMetadataArgs) {
@@ -42,7 +43,7 @@ func testLsOutputContainsCount(t testing.TB, gopts global.Options, lsOpts LsOpti
t.Helper()
out := testRunLsWithOpts(t, gopts, lsOpts, lsArgs)
count := 0
for _, line := range strings.Split(string(out), "\n") {
for line := range strings.SplitSeq(string(out), "\n") {
if strings.Contains(line, substring) {
count++
}
@@ -81,7 +82,7 @@ func getSnapshot(t testing.TB, snapshotID restic.ID, env *testEnvironment) *data
var snapshots []*data.Snapshot
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
@@ -157,7 +158,7 @@ func testRewriteMetadata(t *testing.T, metadata snapshotMetadataArgs) {
var snapshots []*data.Snapshot
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
@@ -205,7 +206,7 @@ func TestRewriteSnaphotSummary(t *testing.T) {
// replace snapshot by one without a summary
var oldSummary *data.SnapshotSummary
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
@@ -351,3 +352,41 @@ func TestRewriteIncludeNothing(t *testing.T) {
rtest.Assert(t, snapsBefore[0] == snapsAfter[0], "snapshots should be identical but are %s and %s",
snapsBefore[0].Str(), snapsAfter[0].Str())
}
func testRunRewriteOutput(t testing.TB, opts RewriteOptions, gopts global.Options, args []string) error {
t.Helper()
_, _, err := withCaptureStdoutStderr(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRewrite(ctx, opts, gopts, args, gopts.Term)
})
return err
}
func TestRewriteWrongMetadata(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createBasicRewriteRepo(t, env)
opts := RewriteOptions{
Metadata: snapshotMetadataArgs{
Time: "2026-10-10 1x:2y:3z",
},
}
err := testRunRewriteOutput(t, opts, env.gopts, []string{})
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "unable to parse time:"),
"expected time string related errors, got %v", err)
}
func TestRewriteWrongExcludePattern(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createBasicRewriteRepo(t, env)
opts := RewriteOptions{
ExcludePatternOptions: filter.ExcludePatternOptions{
Excludes: []string{"a["},
},
}
err := testRunRewriteOutput(t, opts, env.gopts, []string{})
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "--exclude: invalid pattern"),
"expected '--exclude: invalid pattern', got %v", err)
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/selfupdate"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
@@ -84,7 +85,7 @@ func runSelfUpdate(ctx context.Context, opts SelfUpdateOptions, gopts global.Opt
}
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(false, gopts.Verbosity, term)
printer.P("writing restic to %v", opts.Output)
v, err := selfupdate.DownloadLatestStableRelease(ctx, opts.Output, global.Version, printer.P)
+29 -20
View File
@@ -13,6 +13,7 @@ import (
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@@ -58,6 +59,7 @@ type SnapshotOptions struct {
last bool // Deprecated in favour of Latest.
Latest int
GroupBy data.SnapshotGroupByOptions
Reverse bool
}
func (opts *SnapshotOptions) AddFlags(f *pflag.FlagSet) {
@@ -71,6 +73,7 @@ func (opts *SnapshotOptions) AddFlags(f *pflag.FlagSet) {
}
f.IntVar(&opts.Latest, "latest", 0, "only show the last `n` snapshots for each host and path")
f.VarP(&opts.GroupBy, "group-by", "g", "`group` snapshots by host, paths and/or tags, separated by comma")
f.BoolVar(&opts.Reverse, "reverse", false, "reverse sort order of snapshots, newest first")
}
func (opts *SnapshotOptions) Finalize() error {
@@ -81,7 +84,7 @@ func (opts *SnapshotOptions) Finalize() error {
}
func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
@@ -89,12 +92,17 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Option
defer unlock()
var snapshots data.Snapshots
for sn := range FindFilteredSnapshots(ctx, repo, repo, &opts.SnapshotFilter, args, printer) {
err = opts.SnapshotFilter.FindAll(ctx, repo, repo, args, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
snapshots = append(snapshots, sn)
return nil
})
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
snapshotGroups, grouped, err := data.GroupSnapshots(snapshots, opts.GroupBy)
if err != nil {
return err
@@ -112,7 +120,11 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Option
list = filterLatestSnapshots(list, opts.Latest)
}
}
sort.Sort(sort.Reverse(list))
if opts.Reverse {
sort.Stable(list)
} else {
sort.Stable(sort.Reverse(list))
}
snapshotGroups[k] = list
}
@@ -135,7 +147,7 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Option
return err
}
}
err := PrintSnapshots(gopts.Term.OutputWriter(), list, nil, opts.Compact)
err := printSnapshotsTable(gopts.Term.OutputWriter(), list, nil, opts.Compact)
if err != nil {
return err
}
@@ -193,8 +205,9 @@ func filterLatestSnapshotsInGroup(list data.Snapshots, limit int) data.Snapshots
return list[:min(limit, len(list))]
}
// PrintSnapshots prints a text table of the snapshots in list to stdout.
func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
// printSnapshotsTable prints a text table of the snapshots in list to stdout,
// in the order the list is given. The caller is responsible for sorting it beforehand.
func printSnapshotsTable(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
// keep the reasons a snasphot is being kept in a map, so that it doesn't
// get lost when the list of snapshots is sorted
keepReasons := make(map[restic.ID]data.KeepReason, len(reasons))
@@ -210,11 +223,6 @@ func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepRe
hasSize = hasSize || (sn.Summary != nil)
}
// always sort the snapshots so that the newer ones are listed last
sort.SliceStable(list, func(i, j int) bool {
return list[i].Time.Before(list[j].Time)
})
// Determine the max widths for host and tag.
maxHost, maxTag := 10, 6
for _, sn := range list {
@@ -267,9 +275,9 @@ func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepRe
data := snapshot{
ID: sn.ID().Str(),
Timestamp: sn.Time.Local().Format(global.TimeFormat),
Hostname: sn.Hostname,
Tags: sn.Tags,
Paths: sn.Paths,
Hostname: ui.Quote(sn.Hostname),
Tags: ui.QuoteSlice(sn.Tags),
Paths: ui.QuoteSlice(sn.Paths),
}
if len(reasons) > 0 {
@@ -336,13 +344,13 @@ func PrintSnapshotGroupHeader(stdout io.Writer, groupKeyJSON string) error {
header := "snapshots"
var infoStrings []string
if key.Hostname != "" {
infoStrings = append(infoStrings, "host ["+key.Hostname+"]")
infoStrings = append(infoStrings, "host ["+ui.Quote(key.Hostname)+"]")
}
if key.Tags != nil {
infoStrings = append(infoStrings, "tags ["+strings.Join(key.Tags, ", ")+"]")
infoStrings = append(infoStrings, "tags ["+strings.Join(ui.QuoteSlice(key.Tags), ", ")+"]")
}
if key.Paths != nil {
infoStrings = append(infoStrings, "paths ["+strings.Join(key.Paths, ", ")+"]")
infoStrings = append(infoStrings, "paths ["+strings.Join(ui.QuoteSlice(key.Paths), ", ")+"]")
}
if infoStrings != nil {
header += " for (" + strings.Join(infoStrings, ", ") + ")"
@@ -367,6 +375,7 @@ type SnapshotGroup struct {
}
// printSnapshotGroupJSON writes the JSON representation of list to stdout.
// The snapshots in snGroups are expected to already be sorted; the order is preserved as-is.
func printSnapshotGroupJSON(stdout io.Writer, snGroups map[string]data.Snapshots, grouped bool) error {
if grouped {
snapshotGroups := []SnapshotGroup{}
@@ -93,3 +93,28 @@ func TestSnapshotsLatest(t *testing.T) {
rtest.Assert(t, len(snapshots) == 1, "expected only one snapshot, got %d", len(snapshots))
rtest.Equals(t, snapshots[0].ID.String(), secondSnapshotID, "unexpected snapshot ID")
}
func TestSnapshotsReverse(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
secondSnapshotID := snapshotsGroupTestData(t, env, true)
for _, reverse := range []bool{false, true} {
buf, err := withCaptureStdout(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = true
opts := SnapshotOptions{Reverse: reverse}
return runSnapshots(ctx, opts, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
snapshots := []Snapshot{}
rtest.OK(t, json.Unmarshal(buf.Bytes(), &snapshots))
rtest.Assert(t, len(snapshots) == 2, "expected two snapshots, got %d", len(snapshots))
if reverse {
rtest.Equals(t, secondSnapshotID, snapshots[0].ID.String(), "expected newest snapshot first with --reverse")
} else {
rtest.Equals(t, secondSnapshotID, snapshots[1].ID.String(), "expected newest snapshot last by default")
}
}
}
+31 -1
View File
@@ -1,14 +1,18 @@
package main
import (
"bytes"
"strings"
"testing"
"time"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
"github.com/spf13/pflag"
)
// Regression test for #2979: no snapshots should print as [], not null.
func TestEmptySnapshotGroupJSON(t *testing.T) {
func TestSnapshotsEmptySnapshotGroupJSON(t *testing.T) {
for _, grouped := range []bool{false, true} {
var w strings.Builder
err := printSnapshotGroupJSON(&w, nil, grouped)
@@ -17,3 +21,29 @@ func TestEmptySnapshotGroupJSON(t *testing.T) {
rtest.Equals(t, "[]", strings.TrimSpace(w.String()))
}
}
// TestSnapshotsPrintSnapshotsSortsAscending verifies that PrintSnapshots always sorts its
// input so that the oldest snapshot is listed first, regardless of the given order.
func TestSnapshotsPrintSnapshotsSortsAscending(t *testing.T) {
now := time.Now()
list := data.Snapshots{
{Time: now.Add(2 * time.Hour), Hostname: "host1", Paths: []string{"/data"}},
{Time: now, Hostname: "host1", Paths: []string{"/data"}},
{Time: now.Add(1 * time.Hour), Hostname: "host1", Paths: []string{"/data"}},
}
var buf bytes.Buffer
err := PrintSnapshots(&buf, list, nil, true)
rtest.OK(t, err)
rtest.Assert(t, list[0].Time.Equal(now), "expected oldest snapshot first, got %v", list[0].Time)
rtest.Assert(t, list[1].Time.Equal(now.Add(1*time.Hour)), "expected second-oldest snapshot second, got %v", list[1].Time)
rtest.Assert(t, list[2].Time.Equal(now.Add(2*time.Hour)), "expected newest snapshot last, got %v", list[2].Time)
}
// TestSnapshotsReverseFlag verifies that the --reverse flag defaults to false.
func TestSnapshotsReverseFlag(t *testing.T) {
var opts SnapshotOptions
opts.AddFlags(pflag.NewFlagSet("snapshots", pflag.ContinueOnError))
rtest.Equals(t, false, opts.Reverse)
}
+40 -111
View File
@@ -7,18 +7,15 @@ import (
"fmt"
"path/filepath"
"strings"
"sync"
"time"
"github.com/restic/chunker"
"github.com/restic/restic/internal/crypto"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/restorer"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
statsui "github.com/restic/restic/internal/ui/stats"
"github.com/restic/restic/internal/ui/table"
"github.com/restic/restic/internal/walker"
@@ -34,13 +31,13 @@ func newStatsCommand(globalOptions *global.Options) *cobra.Command {
Short: "Scan the repository and show basic statistics",
Long: `
The "stats" command walks one or multiple snapshots in a repository
and accumulates statistics about the data stored therein. It reports
and accumulates statistics about the data stored therein. It reports
on the number of unique files and their sizes, according to one of
the counting modes as given by the --mode flag.
It operates on all snapshots matching the selection criteria or all
snapshots if nothing is specified. The special snapshot ID "latest"
is also supported. Some modes make more sense over
is also supported. Some modes make more sense over
just a single snapshot, while others are useful across all snapshots,
depending on what you are trying to calculate.
@@ -104,7 +101,7 @@ func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args
return err
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
@@ -137,17 +134,19 @@ func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args
}
var snapshots data.Snapshots
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
err = opts.SnapshotFilter.FindAll(ctx, snapshotLister, repo, args, func(_ string, sn *data.Snapshot, err error) error {
if err != nil {
return err
}
snapshots = append(snapshots, sn)
return nil
})
if err != nil {
return err
}
statsProgress := newStatsProgress(term, !gopts.JSON, uint64(len(snapshots)))
updater := progress.NewUpdater(ui.CalculateProgressInterval(!gopts.Quiet, gopts.JSON, term.CanUpdateStatus()), func(runtime time.Duration, final bool) {
statsProgress.printProgress(runtime, final)
})
defer updater.Done()
statsProgress := statsui.NewProgress(term, gopts.Quiet, gopts.JSON, uint64(len(snapshots)))
defer statsProgress.Done()
for _, sn := range snapshots {
err = statsWalkSnapshot(ctx, sn, repo, opts, stats, statsProgress)
@@ -162,20 +161,20 @@ func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args
if opts.countMode == countModeRawData {
// the blob handles have been collected, but not yet counted
for blobHandle := range stats.blobs.Keys() {
pbs := repo.LookupBlob(blobHandle.Type, blobHandle.ID)
pbs := repo.LookupBlob(blobHandle)
if len(pbs) == 0 {
return fmt.Errorf("blob %v not found", blobHandle)
}
stats.TotalSize += uint64(pbs[0].Length)
stats.TotalSize += uint64(pbs[0].CiphertextLength())
if repo.Config().Version >= 2 {
stats.TotalUncompressedSize += uint64(crypto.CiphertextLength(int(pbs[0].DataLength())))
stats.TotalUncompressedSize += uint64(pbs[0].UncompressedCiphertextLength())
if pbs[0].IsCompressed() {
stats.TotalCompressedBlobsSize += uint64(pbs[0].Length)
stats.TotalCompressedBlobsUncompressedSize += uint64(crypto.CiphertextLength(int(pbs[0].DataLength())))
stats.TotalCompressedBlobsSize += uint64(pbs[0].CiphertextLength())
stats.TotalCompressedBlobsUncompressedSize += uint64(pbs[0].UncompressedCiphertextLength())
}
}
stats.TotalBlobCount++
statsProgress.update(0, 1, uint64(pbs[0].Length))
statsProgress.Update(0, 1, uint64(pbs[0].CiphertextLength()))
}
if stats.TotalCompressedBlobsSize > 0 {
stats.CompressionRatio = float64(stats.TotalCompressedBlobsUncompressedSize) / float64(stats.TotalCompressedBlobsSize)
@@ -186,7 +185,7 @@ func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args
}
}
// stop progress bar to prevent mangled output
updater.Done()
statsProgress.Done()
if gopts.JSON {
err = json.NewEncoder(gopts.Term.OutputWriter()).Encode(stats)
@@ -221,8 +220,8 @@ func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args
return nil
}
func statsWalkSnapshot(ctx context.Context, snapshot *data.Snapshot, repo restic.Loader, opts StatsOptions, stats *statsContainer, progress *statsProgress) error {
progress.processSnapshot()
func statsWalkSnapshot(ctx context.Context, snapshot *data.Snapshot, repo restic.Loader, opts StatsOptions, stats *statsContainer, sp *statsui.Progress) error {
sp.ProcessSnapshot()
if snapshot.Tree == nil {
return fmt.Errorf("snapshot %s has nil tree", snapshot.ID().Str())
}
@@ -232,12 +231,12 @@ func statsWalkSnapshot(ctx context.Context, snapshot *data.Snapshot, repo restic
if opts.countMode == countModeRawData {
// count just the sizes of unique blobs; we don't need to walk the tree
// ourselves in this case, since a nifty function does it for us
return data.FindUsedBlobs(ctx, repo, restic.IDs{*snapshot.Tree}, stats.blobs, nil)
return data.FindUsedBlobs(ctx, repo, restic.IDs{*snapshot.Tree}, stats.blobs, restic.NoopCounter)
}
hardLinkIndex := restorer.NewHardlinkIndex[struct{}]()
hardLinkIndex := data.NewHardlinkIndex[struct{}]()
err := walker.Walk(ctx, repo, *snapshot.Tree, walker.WalkVisitor{
ProcessNode: statsWalkTree(repo, opts, stats, hardLinkIndex, progress),
ProcessNode: statsWalkTree(repo, opts, stats, hardLinkIndex, sp),
})
if err != nil {
return fmt.Errorf("walking tree %s: %v", *snapshot.Tree, err)
@@ -246,7 +245,7 @@ func statsWalkSnapshot(ctx context.Context, snapshot *data.Snapshot, repo restic
return nil
}
func statsWalkTree(repo restic.Loader, opts StatsOptions, stats *statsContainer, hardLinkIndex *restorer.HardlinkIndex[struct{}], progress *statsProgress) walker.WalkFunc {
func statsWalkTree(repo restic.Loader, opts StatsOptions, stats *statsContainer, hardLinkIndex *data.HardlinkIndex[struct{}], progress *statsui.Progress) walker.WalkFunc {
return func(parentTreeID restic.ID, npath string, node *data.Node, nodeErr error) error {
if nodeErr != nil {
return nodeErr
@@ -254,7 +253,7 @@ func statsWalkTree(repo restic.Loader, opts StatsOptions, stats *statsContainer,
if node == nil {
return nil
}
progress.update(1, 0, uint64(node.Size))
progress.Update(1, 0, uint64(node.Size))
if opts.countMode == countModeUniqueFilesByContents || opts.countMode == countModeBlobsPerFile {
// only count this file if we haven't visited it before
fid := makeFileIDByContents(node)
@@ -274,14 +273,14 @@ func statsWalkTree(repo restic.Loader, opts StatsOptions, stats *statsContainer,
// ensure we have this file (by path) in our map; in this
// mode, a file is unique by both contents and path
nodePath := filepath.Join(npath, node.Name)
progress.update(0, 1, 0)
progress.Update(0, 1, 0)
if _, ok := stats.fileBlobs[nodePath]; !ok {
stats.fileBlobs[nodePath] = restic.NewIDSet()
stats.TotalFileCount++
}
if _, ok := stats.fileBlobs[nodePath][blobID]; !ok {
// is always a data blob since we're accessing it via a file's Content array
blobSize, found := repo.LookupBlobSize(restic.DataBlob, blobID)
blobSize, found := repo.LookupBlobSize(restic.BlobHandle{Type: restic.DataBlob, ID: blobID})
if !found {
return fmt.Errorf("blob %s not found for tree %s", blobID, parentTreeID)
}
@@ -371,76 +370,6 @@ type statsContainer struct {
// independent of references to files
blobs restic.AssociatedBlobSet
}
type statsProgress struct {
term ui.Terminal
m sync.Mutex
snapshotCount uint64
show bool
processedSnapshotCount uint64
processedFileCount uint64
processedBlobCount uint64
processedSize uint64
}
func newStatsProgress(term ui.Terminal, show bool, snapshotCount uint64) *statsProgress {
return &statsProgress{
term: term,
show: show,
snapshotCount: snapshotCount,
}
}
func (s *statsProgress) printProgress(runtime time.Duration, final bool) {
if !s.show {
return
}
s.m.Lock()
progressBase := s.processedSnapshotCount
if progressBase > 0 && !final {
progressBase--
}
status := fmt.Sprintf("[%s] %s %d / %d snapshots", ui.FormatDuration(runtime), ui.FormatPercent(progressBase, s.snapshotCount), s.processedSnapshotCount, s.snapshotCount)
if s.processedFileCount > 0 {
status += fmt.Sprintf(", %v files", s.processedFileCount)
}
if s.processedBlobCount > 0 {
status += fmt.Sprintf(", %d blobs", s.processedBlobCount)
}
status += fmt.Sprintf(", %s", ui.FormatBytes(s.processedSize))
s.m.Unlock()
if final {
s.term.SetStatus(nil)
s.term.Print(status)
} else {
s.term.SetStatus([]string{status})
}
}
func (s *statsProgress) update(fileCount uint64, blobCount uint64, size uint64) {
s.m.Lock()
defer s.m.Unlock()
s.processedFileCount += fileCount
s.processedBlobCount += blobCount
s.processedSize += size
}
func (s *statsProgress) processSnapshot() {
s.m.Lock()
defer s.m.Unlock()
s.processedSnapshotCount++
s.processedFileCount = 0
s.processedBlobCount = 0
s.processedSize = 0
}
// fileID is a 256-bit hash that distinguishes unique files.
type fileID [32]byte
@@ -453,7 +382,7 @@ const (
countModeDebug = "debug"
)
func statsDebug(ctx context.Context, repo restic.Repository, printer progress.Printer) error {
func statsDebug(ctx context.Context, repo restic.Repository, printer restic.Printer) error {
printer.E("Collecting size statistics\n\n")
for _, t := range []restic.FileType{restic.KeyFile, restic.LockFile, restic.IndexFile, restic.SnapshotFile, restic.PackFile} {
hist, err := statsDebugFileType(ctx, repo, t)
@@ -486,15 +415,18 @@ func statsDebugFileType(ctx context.Context, repo restic.Lister, tpe restic.File
func statsDebugBlobs(ctx context.Context, repo restic.Repository) ([restic.NumBlobTypes]*sizeHistogram, error) {
var hist [restic.NumBlobTypes]*sizeHistogram
for i := 0; i < len(hist); i++ {
for i := range len(hist) {
hist[i] = newSizeHistogram(2 * chunker.MaxSize)
}
err := repo.ListBlobs(ctx, func(pb restic.PackedBlob) {
hist[pb.Type].Add(uint64(pb.Length))
})
for pb := range repo.ListBlobs() {
if err := ctx.Err(); err != nil {
return hist, err
}
hist[pb.Handle().Type].Add(uint64(pb.CiphertextLength()))
}
return hist, err
return hist, nil
}
type sizeClass struct {
@@ -517,10 +449,7 @@ func newSizeHistogram(sizeLimit uint64) *sizeHistogram {
growthFactor := uint64(10)
for lowerBound < sizeLimit {
upperBound := lowerBound*growthFactor - 1
if upperBound > sizeLimit {
upperBound = sizeLimit
}
upperBound := min(lowerBound*growthFactor-1, sizeLimit)
h.buckets = append(h.buckets, sizeClass{lowerBound, upperBound, 0})
lowerBound *= growthFactor
}
+1 -38
View File
@@ -2,10 +2,8 @@ package main
import (
"testing"
"time"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
)
func TestSizeHistogramNew(t *testing.T) {
@@ -26,7 +24,7 @@ func TestSizeHistogramNew(t *testing.T) {
func TestSizeHistogramAdd(t *testing.T) {
h := newSizeHistogram(42)
for i := uint64(0); i < 45; i++ {
for i := range uint64(45) {
h.Add(i)
}
@@ -62,38 +60,3 @@ func TestSizeHistogramString(t *testing.T) {
rtest.Equals(t, "Count: 3\nTotal Size: 11 B\nSize Count\n-------------------\n 0 - 0 Byte 1\n 1 - 9 Byte 1\n10 - 42 Byte 1\n-------------------\n", h.String())
})
}
func TestStatsProgress(t *testing.T) {
term := &ui.MockTerminal{}
progress := newStatsProgress(term, true, 2)
progress.printProgress(0*time.Second, false)
rtest.Equals(t, []string{"[0:00] 0.00% 0 / 2 snapshots, 0 B"}, term.Output)
progress.processSnapshot()
progress.update(1, 2, 3)
progress.printProgress(5*time.Second, false)
// Output differs from the previous one because the progress is based on the number of processed snapshots,
// 1/2 snapshots means processing the snapshot 1 currently
rtest.Equals(t, []string{"[0:05] 0.00% 1 / 2 snapshots, 1 files, 2 blobs, 3 B"}, term.Output)
progress.processSnapshot()
progress.printProgress(10*time.Second, false)
rtest.Equals(t, []string{"[0:10] 50.00% 2 / 2 snapshots, 0 B"}, term.Output)
progress.update(4, 5, 6)
progress.printProgress(15*time.Second, false)
rtest.Equals(t, []string{"[0:15] 50.00% 2 / 2 snapshots, 4 files, 5 blobs, 6 B"}, term.Output)
progress.printProgress(20*time.Second, true)
rtest.Equals(t, []string{"[0:20] 100.00% 2 / 2 snapshots, 4 files, 5 blobs, 6 B"}, term.Output)
}
func TestStatsProgressJSON(t *testing.T) {
term := &ui.MockTerminal{}
progress := newStatsProgress(term, false, 2)
progress.printProgress(0*time.Second, false)
// JSON output is not available yet, so just make sure to not break normal json output
rtest.Equals(t, nil, term.Output)
}
Loaded 100 of 439 files, more files were not shown because too many files have changed in this diff. Show more