mirror of
https://github.com/restic/restic.git
synced 2026-12-04 15:44:46 +00:00
Compare commits
294
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c88ff768f | ||
|
|
9d1ea09e86 | ||
|
|
6a63ee1d11 | ||
|
|
7bed534cd1 | ||
|
|
bae91697d3 | ||
|
|
74f00280e2 | ||
|
|
55abaa6de8 | ||
|
|
0a7e093006 | ||
|
|
10aab6465e | ||
|
|
00f12ea705 | ||
|
|
d991764a22 | ||
|
|
5cda063cbb | ||
|
|
2126756613 | ||
|
|
d7aa4145e0 | ||
|
|
335d7e38aa | ||
|
|
edd3654c0a | ||
|
|
2c9b353cbf | ||
|
|
c904b78998 | ||
|
|
4dfa381b9f | ||
|
|
c4f9e50609 | ||
|
|
516c8d32e0 | ||
|
|
6619ac9620 | ||
|
|
354f6aeed6 | ||
|
|
c734245fd3 | ||
|
|
0a2b084306 | ||
|
|
e9a07fd773 | ||
|
|
c2c046c7b1 | ||
|
|
0039a14381 | ||
|
|
7f6d8acb85 | ||
|
|
068a324dcd | ||
|
|
f515b862de | ||
|
|
4619a31716 | ||
|
|
9a0b9e0eb5 | ||
|
|
b5d0152014 | ||
|
|
83a2726a30 | ||
|
|
b5463d900d | ||
|
|
4416b9fa09 | ||
|
|
29fecdbd40 | ||
|
|
84c2d0223f | ||
|
|
bba1b68082 | ||
|
|
dd09b6bd01 | ||
|
|
adc0284113 | ||
|
|
25aa69dbc7 | ||
|
|
b4be15a7d9 | ||
|
|
b1d146035a | ||
|
|
885e6b6e71 | ||
|
|
cb1d66a398 | ||
|
|
5d745e2ead | ||
|
|
2497d99f9f | ||
|
|
35f15c398a | ||
|
|
a9d74f178e | ||
|
|
e40a4a165e | ||
|
|
d714e22605 | ||
|
|
9da3b87b07 | ||
|
|
519a979107 | ||
|
|
ca1c625227 | ||
|
|
5127c4abf9 | ||
|
|
8e917cf0bd | ||
|
|
818dd21a4f | ||
|
|
6adedec6b4 | ||
|
|
9d17700830 | ||
|
|
1cce3790f4 | ||
|
|
1765e36f95 | ||
|
|
9c86adb783 | ||
|
|
ab17711e31 | ||
|
|
444c1cb221 | ||
|
|
c0acea6d75 | ||
|
|
7710556df1 | ||
|
|
a428df74c9 | ||
|
|
96188e33a3 | ||
|
|
f35acc2421 | ||
|
|
ca33201335 | ||
|
|
ba802d42b7 | ||
|
|
46ea365629 | ||
|
|
fb5e9df357 | ||
|
|
b593ba305b | ||
|
|
28d802df8c | ||
|
|
0946f45de6 | ||
|
|
5895e6d059 | ||
|
|
e982b6e7b5 | ||
|
|
479cf1fb3d | ||
|
|
dbaa8cf124 | ||
|
|
a80be1478a | ||
|
|
7bfa32a90a | ||
|
|
63b583c4ea | ||
|
|
85bf4430b8 | ||
|
|
e2b43a5f1f | ||
|
|
607aba3809 | ||
|
|
c6074f82fb | ||
|
|
8baffc4027 | ||
|
|
f215365af9 | ||
|
|
14e523a1d9 | ||
|
|
58f92708c2 | ||
|
|
31e96f4ec9 | ||
|
|
a2cb015591 | ||
|
|
e2495b72bb | ||
|
|
2c169edad4 | ||
|
|
fb36a7f59b | ||
|
|
8ed263c6dd | ||
|
|
0e4f288e83 | ||
|
|
da4d8f5851 | ||
|
|
32e9869cc8 | ||
|
|
d4088aa09b | ||
|
|
35dcda418c | ||
|
|
af4f50223e | ||
|
|
9e007fa3cc | ||
|
|
a4d85ce299 | ||
|
|
9b0ee37697 | ||
|
|
905ca56ee8 | ||
|
|
987caba408 | ||
|
|
bfca18c1b0 | ||
|
|
dba493cb6c | ||
|
|
512d0577d6 | ||
|
|
e428de5f84 | ||
|
|
d8ef26afa4 | ||
|
|
cc93a94e15 | ||
|
|
62991338ea | ||
|
|
75de8b54e6 | ||
|
|
e4056e70a8 | ||
|
|
8cc69782b5 | ||
|
|
ccb828e87b | ||
|
|
70a45791b2 | ||
|
|
9e1a526611 | ||
|
|
aa94be2dbd | ||
|
|
804ff4bc95 | ||
|
|
9670cd7459 | ||
|
|
634e9b2411 | ||
|
|
db03aed816 | ||
|
|
4e8eea7ab4 | ||
|
|
981adc47ac | ||
|
|
7134577c56 | ||
|
|
55e335ec6c | ||
|
|
d30d6b6281 | ||
|
|
8d7679c831 | ||
|
|
d9dd1b7534 | ||
|
|
1151d70655 | ||
|
|
369da8a770 | ||
|
|
9f84c80056 | ||
|
|
6070462465 | ||
|
|
1029fe6dd0 | ||
|
|
8f00b335b4 | ||
|
|
c6a064b68b | ||
|
|
8d191c19a5 | ||
|
|
d5267f03e0 | ||
|
|
5683224a3c | ||
|
|
71064fac10 | ||
|
|
52cde35aea | ||
|
|
f394723aa2 | ||
|
|
072305c5b3 | ||
|
|
a1420ea6c7 | ||
|
|
a3be3bd9e1 | ||
|
|
b24d05bcb4 | ||
|
|
c021b8cde0 | ||
|
|
18e5c446e0 | ||
|
|
f91afb2fa8 | ||
|
|
2148508050 | ||
|
|
37e8f50aeb | ||
|
|
7e5eaf1ead | ||
|
|
aae0985673 | ||
|
|
f9d953d4cd | ||
|
|
69a3ba5b33 | ||
|
|
c183fe2035 | ||
|
|
1174e97b30 | ||
|
|
440d925467 | ||
|
|
28521d27c1 | ||
|
|
af64caf5d9 | ||
|
|
9ab5fc59c2 | ||
|
|
6c509f7ac1 | ||
|
|
ea699bb0ba | ||
|
|
532f36a5a8 | ||
|
|
57ac5d107c | ||
|
|
2f31cde517 | ||
|
|
5cd39d01c1 | ||
|
|
61708772a2 | ||
|
|
d9d54a505e | ||
|
|
0f4236cb39 | ||
|
|
4d1b9cef63 | ||
|
|
284daaf0b4 | ||
|
|
980f194360 | ||
|
|
d795988fa8 | ||
|
|
203e595ccb | ||
|
|
6c67a095dc | ||
|
|
1a9decf03e | ||
|
|
718f09e02d | ||
|
|
82708ff7f7 | ||
|
|
18c47c5bf9 | ||
|
|
faea0d677a | ||
|
|
ae8fdb08fa | ||
|
|
5c8c048c1a | ||
|
|
6b88b072e0 | ||
|
|
7d36449ea8 | ||
|
|
71f38d266c | ||
|
|
0536e15bbf | ||
|
|
650f658244 | ||
|
|
ae96b2a0f8 | ||
|
|
ce9b6ceea1 | ||
|
|
406dec29a7 | ||
|
|
6fe10a72eb | ||
|
|
1a6d43286a | ||
|
|
151903d4d4 | ||
|
|
b86568b790 | ||
|
|
a5f3256626 | ||
|
|
5989671f87 | ||
|
|
b7f3a1367a | ||
|
|
4838b0ae3e | ||
|
|
c87da70af9 | ||
|
|
81b6414c55 | ||
|
|
637c1cfb66 | ||
|
|
b892b1a150 | ||
|
|
7015da44ad | ||
|
|
3ee465d363 | ||
|
|
8e11f5747d | ||
|
|
22a304af7e | ||
|
|
c8a0bc2c5e | ||
|
|
35e60dc2c7 | ||
|
|
8e93172bf8 | ||
|
|
b94ef4831d | ||
|
|
952b310d62 | ||
|
|
3eb5f83db3 | ||
|
|
d3ef21f870 | ||
|
|
31df7508c4 | ||
|
|
87c9ed4573 | ||
|
|
eedba12968 | ||
|
|
264cfbcff2 | ||
|
|
7f3c9eb749 | ||
|
|
347cac780d | ||
|
|
23d6946fc9 | ||
|
|
2db654533b | ||
|
|
f5843a7d97 | ||
|
|
e1e7fc8fb2 | ||
|
|
1acc19dac5 | ||
|
|
79e92b3bc6 | ||
|
|
766d9f9f1e | ||
|
|
131abbb4f0 | ||
|
|
d62e42e620 | ||
|
|
35caceace4 | ||
|
|
f2ff05f840 | ||
|
|
c062a78dcd | ||
|
|
35af104749 | ||
|
|
ccb5ae1592 | ||
|
|
97f1e99ed9 | ||
|
|
c060c317d3 | ||
|
|
a9e0b46358 | ||
|
|
8169814b38 | ||
|
|
f186e1e458 | ||
|
|
0938f52f38 | ||
|
|
9f9a3472aa | ||
|
|
14f86a462a | ||
|
|
825d67ba4b | ||
|
|
3b8b77e54d | ||
|
|
0bbfb072af | ||
|
|
e8ed2434cd | ||
|
|
c04f3e9d6c | ||
|
|
37fdbe5779 | ||
|
|
47328afb2e | ||
|
|
e6d054d896 | ||
|
|
fc81a0b6ad | ||
|
|
dee28f5b0e | ||
|
|
2d02a1ad39 | ||
|
|
bae49d00ee | ||
|
|
e5dba15367 | ||
|
|
bf56d71b09 | ||
|
|
e94ec65efb | ||
|
|
49f9e67520 | ||
|
|
3a4b0e3b8c | ||
|
|
abfc9bbdff | ||
|
|
784812361e | ||
|
|
c745f810b3 | ||
|
|
721411e04c | ||
|
|
b07ff6cd34 | ||
|
|
8b3bbb527c | ||
|
|
4a2d8e04aa | ||
|
|
a36488b706 | ||
|
|
cfb506a77a | ||
|
|
a15b1579ff | ||
|
|
ff95080f36 | ||
|
|
119bb9d9a8 | ||
|
|
8c6ee42d17 | ||
|
|
ccddc1914d | ||
|
|
4bc5eca7ea | ||
|
|
17ff3aa5f9 | ||
|
|
5683180a3b | ||
|
|
0fc7444e32 | ||
|
|
81571775d5 | ||
|
|
16b8b8cda0 | ||
|
|
7d25ca9d67 | ||
|
|
cc546b71e3 | ||
|
|
3cb49556f5 | ||
|
|
f625190393 | ||
|
|
620f5986f8 | ||
|
|
49c7364e79 | ||
|
|
e1e36ed848 | ||
|
|
a37010a825 | ||
|
|
a0d7745e8b |
No files matched your search
@@ -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.
|
||||
-->
|
||||
|
||||
|
||||
|
||||
@@ -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.
|
||||
-->
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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@81c6f93d4bc991e510b342a00b419b3bb4efc5c6
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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), Zachariah Mithani (AploSec), Manuel Riel
|
||||
(@m3nu) and calif.io 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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
```
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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), Zachariah Mithani (AploSec),
|
||||
Manuel Riel (@m3nu) and calif.io for reporting this.
|
||||
|
||||
https://github.com/restic/restic/issues/22180
|
||||
https://github.com/restic/restic/pull/22190
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+37
-30
@@ -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,7 +182,7 @@ 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 {
|
||||
@@ -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
|
||||
}
|
||||
@@ -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...)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
+8
-12
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -13,6 +14,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 +50,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 +63,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
|
||||
@@ -141,7 +137,7 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te
|
||||
printer.S(string(buf))
|
||||
return nil
|
||||
case "lock":
|
||||
lock, err := restic.LoadLock(ctx, repo, id)
|
||||
lock, err := repository.LoadLock(ctx, repo, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -176,11 +172,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 +203,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
|
||||
}
|
||||
|
||||
+33
-26
@@ -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) {}
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -157,7 +158,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 +167,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 +359,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 {
|
||||
|
||||
@@ -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"
|
||||
@@ -136,7 +137,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":
|
||||
|
||||
+54
-51
@@ -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"
|
||||
)
|
||||
|
||||
@@ -135,9 +136,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
|
||||
}
|
||||
@@ -213,7 +214,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,
|
||||
@@ -280,9 +281,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 +378,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 +413,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 +445,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 +479,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 +520,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,22 +530,23 @@ 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()
|
||||
err := f.repo.ListBlobs(wctx, func(pb restic.PackBlob) {
|
||||
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{}{}
|
||||
}
|
||||
})
|
||||
@@ -552,13 +558,6 @@ func (f *Finder) indexPacksToBlobs(ctx context.Context, packIDs map[string]struc
|
||||
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 +568,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 +598,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}
|
||||
@@ -676,11 +675,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 +694,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 +706,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()
|
||||
}
|
||||
|
||||
|
||||
@@ -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,9 +180,10 @@ 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
|
||||
err = repo.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
h := pb.Handle()
|
||||
if !done && h.Type == restic.TreeBlob {
|
||||
packID = pb.PackID()
|
||||
done = true
|
||||
}
|
||||
})
|
||||
@@ -228,20 +230,20 @@ 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 {
|
||||
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
switch blob.Handle().Type {
|
||||
case restic.DataBlob:
|
||||
dataPackID = blob.PackID
|
||||
dataPackID = blob.PackID()
|
||||
case restic.TreeBlob:
|
||||
treePackID = blob.PackID
|
||||
treePackID = blob.PackID()
|
||||
}
|
||||
}))
|
||||
return nil
|
||||
@@ -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()
|
||||
|
||||
@@ -6,12 +6,14 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"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 +191,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 +201,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
|
||||
@@ -312,10 +318,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,7 +357,7 @@ 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
|
||||
|
||||
@@ -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 != "" {
|
||||
|
||||
@@ -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 {
|
||||
@@ -108,7 +108,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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
@@ -61,18 +61,18 @@ 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)
|
||||
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
blobSetFromIndex.Insert(blob.Handle().ID)
|
||||
}))
|
||||
return nil
|
||||
})
|
||||
@@ -102,3 +102,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))
|
||||
}
|
||||
+78
-69
@@ -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,8 +290,8 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,9 +299,9 @@ func (p *textLsPrinter) Snapshot(sn *data.Snapshot) error {
|
||||
p.termPrinter.P("%v filtered by %v:", sn, 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
@@ -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":"/"},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+8
-20
@@ -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")
|
||||
@@ -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,7 +198,7 @@ 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)
|
||||
@@ -270,9 +272,9 @@ func checkMountpointOverlap(repoPath, mountpoint string) error {
|
||||
switch {
|
||||
case rp == mp:
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is the local repository directory%s", mp, tail))
|
||||
case isInside(rp, mp):
|
||||
case fs.HasPathPrefix(rp, mp):
|
||||
return errors.Fatal(fmt.Sprintf("mountpoint %s is inside the local repository directory %s%s", mp, rp, tail))
|
||||
case isInside(mp, rp):
|
||||
case fs.HasPathPrefix(mp, rp):
|
||||
return errors.Fatal(fmt.Sprintf("local repository directory %s is inside the mountpoint %s%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))
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+19
-20
@@ -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
|
||||
@@ -190,11 +190,11 @@ func runPrune(ctx context.Context, opts PruneOptions, gopts global.Options, term
|
||||
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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,9 +75,10 @@ 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
|
||||
err = repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
h := blob.Handle()
|
||||
if h.Type == restic.TreeBlob {
|
||||
trees[h.ID] = false
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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,75 @@
|
||||
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
|
||||
err = repo.ListBlobs(ctx, func(blob restic.PackBlob) {
|
||||
if blob.Handle().Type == restic.DataBlob {
|
||||
packfileID = blob.PackID()
|
||||
return
|
||||
}
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -9,6 +9,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 +78,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 +128,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 +148,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)
|
||||
@@ -145,7 +179,15 @@ func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOp
|
||||
})
|
||||
|
||||
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 +200,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)
|
||||
}
|
||||
@@ -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,
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
@@ -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) {
|
||||
|
||||
@@ -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(), "error in time option: parsing 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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
@@ -81,7 +82,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 +90,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
|
||||
|
||||
+35
-109
@@ -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,12 +415,12 @@ 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))
|
||||
err := repo.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
hist[pb.Handle().Type].Add(uint64(pb.CiphertextLength()))
|
||||
})
|
||||
|
||||
return hist, err
|
||||
@@ -517,10 +446,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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+11
-7
@@ -13,6 +13,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"
|
||||
)
|
||||
|
||||
func newTagCommand(globalOptions *global.Options) *cobra.Command {
|
||||
@@ -120,7 +121,7 @@ func changeTags(ctx context.Context, repo *repository.Repository, sn *data.Snaps
|
||||
}
|
||||
|
||||
func runTag(ctx context.Context, opts TagOptions, gopts global.Options, term ui.Terminal, args []string) error {
|
||||
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
|
||||
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
|
||||
|
||||
if len(opts.SetTags) == 0 && len(opts.AddTags) == 0 && len(opts.RemoveTags) == 0 {
|
||||
return errors.Fatal("nothing to do!")
|
||||
@@ -158,19 +159,22 @@ func runTag(ctx context.Context, opts TagOptions, gopts global.Options, term ui.
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
changed, err := changeTags(ctx, repo, sn, opts.SetTags.Flatten(), opts.AddTags.Flatten(), opts.RemoveTags.Flatten(), printFunc)
|
||||
if err != nil {
|
||||
printer.E("unable to modify the tags for snapshot ID %q, ignoring: %v", sn.ID(), err)
|
||||
continue
|
||||
return nil
|
||||
}
|
||||
if changed {
|
||||
summary.ChangedSnapshots++
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
printSummary(summary)
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -47,7 +48,7 @@ func (opts *UnlockOptions) AddFlags(f *pflag.FlagSet) {
|
||||
}
|
||||
|
||||
func runUnlock(ctx context.Context, opts UnlockOptions, gopts global.Options, term ui.Terminal) error {
|
||||
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
|
||||
printer := progress.NewTerminalPrinter(gopts.JSON, gopts.Verbosity, term)
|
||||
repo, err := global.OpenRepository(ctx, gopts, printer)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"runtime"
|
||||
|
||||
"github.com/restic/restic/internal/global"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ Exit status is 1 if there was any error.
|
||||
`,
|
||||
DisableAutoGenTag: true,
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
printer := ui.NewProgressPrinter(globalOptions.JSON, globalOptions.Verbosity, globalOptions.Term)
|
||||
printer := progress.NewTerminalPrinter(globalOptions.JSON, globalOptions.Verbosity, globalOptions.Term)
|
||||
|
||||
if globalOptions.JSON {
|
||||
type jsonVersion struct {
|
||||
|
||||
+1
-34
@@ -1,17 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// initMultiSnapshotFilter is used for commands that work on multiple snapshots
|
||||
// MUST be combined with FindFilteredSnapshots
|
||||
// MUST be combined with (*data,SnapshotFilter).FindAll
|
||||
// MUST be followed by finalizeSnapshotFilter after flag parsing
|
||||
func initMultiSnapshotFilter(flags *pflag.FlagSet, filt *data.SnapshotFilter, addHostShorthand bool) {
|
||||
hostShorthand := "H"
|
||||
@@ -47,33 +44,3 @@ func finalizeSnapshotFilter(filt *data.SnapshotFilter) {
|
||||
filt.Hosts = nil
|
||||
}
|
||||
}
|
||||
|
||||
// FindFilteredSnapshots yields Snapshots, either given explicitly by `snapshotIDs` or filtered from the list of all snapshots.
|
||||
func FindFilteredSnapshots(ctx context.Context, be restic.Lister, loader restic.LoaderUnpacked, f *data.SnapshotFilter, snapshotIDs []string, printer progress.Printer) <-chan *data.Snapshot {
|
||||
out := make(chan *data.Snapshot)
|
||||
go func() {
|
||||
defer close(out)
|
||||
be, err := restic.MemorizeList(ctx, be, restic.SnapshotFile)
|
||||
if err != nil {
|
||||
printer.E("could not load snapshots: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = f.FindAll(ctx, be, loader, snapshotIDs, func(id string, sn *data.Snapshot, err error) error {
|
||||
if err != nil {
|
||||
printer.E("Ignoring %q: %v", id, err)
|
||||
} else {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case out <- sn:
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
printer.E("could not load snapshots: %v", err)
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"github.com/restic/restic/internal/ui"
|
||||
)
|
||||
|
||||
func formatNode(path string, n *data.Node, long bool, human bool) string {
|
||||
func formatNodeOutput(n lsNodeOutput, long bool, human bool) string {
|
||||
if !long {
|
||||
return path
|
||||
return n.Path
|
||||
}
|
||||
|
||||
var mode os.FileMode
|
||||
@@ -19,9 +19,9 @@ func formatNode(path string, n *data.Node, long bool, human bool) string {
|
||||
|
||||
var size string
|
||||
if human {
|
||||
size = ui.FormatBytes(n.Size)
|
||||
size = ui.FormatBytes(n.fileSize())
|
||||
} else {
|
||||
size = fmt.Sprintf("%6d", n.Size)
|
||||
size = fmt.Sprintf("%6d", n.fileSize())
|
||||
}
|
||||
|
||||
switch n.Type {
|
||||
@@ -44,6 +44,10 @@ func formatNode(path string, n *data.Node, long bool, human bool) string {
|
||||
|
||||
return fmt.Sprintf("%s %5d %5d %s %s %s%s",
|
||||
mode|n.Mode, n.UID, n.GID, size,
|
||||
n.ModTime.Local().Format(global.TimeFormat), path,
|
||||
n.ModTime.Local().Format(global.TimeFormat), n.Path,
|
||||
target)
|
||||
}
|
||||
|
||||
func formatNode(path string, n *data.Node, long bool, human bool) string {
|
||||
return formatNodeOutput(lsNodeOutputFrom(path, n), long, human)
|
||||
}
|
||||
@@ -9,12 +9,13 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/backend"
|
||||
"github.com/restic/restic/internal/backend/all"
|
||||
"github.com/restic/restic/internal/backend/layout"
|
||||
"github.com/restic/restic/internal/backend/retry"
|
||||
"github.com/restic/restic/internal/data"
|
||||
"github.com/restic/restic/internal/errors"
|
||||
@@ -23,7 +24,7 @@ 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"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
"github.com/restic/restic/internal/ui/termstatus"
|
||||
)
|
||||
|
||||
@@ -193,6 +194,7 @@ func withTestEnvironment(t testing.TB) (env *testEnvironment, cleanup func()) {
|
||||
repository.TestUseLowSecurityKDFParameters(t)
|
||||
restic.TestDisableCheckPolynomial(t)
|
||||
retry.TestFastRetries(t)
|
||||
layout.TestDisablePackSubdirs(t)
|
||||
|
||||
tempdir, err := os.MkdirTemp(rtest.TestTempDir, "restic-test-")
|
||||
rtest.OK(t, err)
|
||||
@@ -211,11 +213,12 @@ func withTestEnvironment(t testing.TB) (env *testEnvironment, cleanup func()) {
|
||||
rtest.OK(t, os.MkdirAll(env.repo, 0700))
|
||||
|
||||
env.gopts = global.Options{
|
||||
Repo: env.repo,
|
||||
Quiet: true,
|
||||
CacheDir: env.cache,
|
||||
Password: rtest.TestPassword,
|
||||
Extended: make(options.Options),
|
||||
Repo: env.repo,
|
||||
Quiet: true,
|
||||
CacheDir: env.cache,
|
||||
Password: rtest.TestPassword,
|
||||
Extended: make(options.Options),
|
||||
Compression: repository.CompressionFastest,
|
||||
|
||||
// replace this hook with "nil" if listing a filetype more than once is necessary
|
||||
BackendTestHook: func(r backend.Backend) (backend.Backend, error) { return newOrderedListOnceBackend(r), nil },
|
||||
@@ -244,7 +247,7 @@ func testSetupBackupData(t testing.TB, env *testEnvironment) string {
|
||||
func listPacks(gopts global.Options, t *testing.T) restic.IDSet {
|
||||
var packs 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)
|
||||
ctx, r, unlock, err := openWithReadLock(ctx, gopts, false, printer)
|
||||
rtest.OK(t, err)
|
||||
defer unlock()
|
||||
@@ -263,16 +266,16 @@ func listPacks(gopts global.Options, t *testing.T) restic.IDSet {
|
||||
func listTreePacks(gopts global.Options, t *testing.T) restic.IDSet {
|
||||
var treePacks 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)
|
||||
ctx, r, unlock, err := openWithReadLock(ctx, gopts, false, printer)
|
||||
rtest.OK(t, err)
|
||||
defer unlock()
|
||||
|
||||
rtest.OK(t, r.LoadIndex(ctx, nil))
|
||||
rtest.OK(t, r.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
|
||||
treePacks = restic.NewIDSet()
|
||||
return r.ListBlobs(ctx, func(pb restic.PackedBlob) {
|
||||
if pb.Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID)
|
||||
return r.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
if pb.Handle().Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID())
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -294,13 +297,13 @@ func captureBackend(gopts *global.Options) func() backend.Backend {
|
||||
func removePacks(gopts global.Options, t testing.TB, remove restic.IDSet) {
|
||||
be := captureBackend(&gopts)
|
||||
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)
|
||||
ctx, _, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
|
||||
rtest.OK(t, err)
|
||||
defer unlock()
|
||||
|
||||
for id := range remove {
|
||||
rtest.OK(t, be().Remove(ctx, backend.Handle{Type: restic.PackFile, Name: id.String()}))
|
||||
rtest.OK(t, be().Remove(ctx, backend.Handle{Type: backend.PackFile, Name: id.String()}))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
@@ -310,18 +313,18 @@ func removePacks(gopts global.Options, t testing.TB, remove restic.IDSet) {
|
||||
func removePacksExcept(gopts global.Options, t testing.TB, keep restic.IDSet, removeTreePacks bool) {
|
||||
be := captureBackend(&gopts)
|
||||
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)
|
||||
ctx, r, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
|
||||
rtest.OK(t, err)
|
||||
defer unlock()
|
||||
|
||||
// Get all tree packs
|
||||
rtest.OK(t, r.LoadIndex(ctx, nil))
|
||||
rtest.OK(t, r.LoadIndex(ctx, restic.NoopTerminalCounterFactory))
|
||||
|
||||
treePacks := restic.NewIDSet()
|
||||
rtest.OK(t, r.ListBlobs(ctx, func(pb restic.PackedBlob) {
|
||||
if pb.Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID)
|
||||
rtest.OK(t, r.ListBlobs(ctx, func(pb restic.PackBlob) {
|
||||
if pb.Handle().Type == restic.TreeBlob {
|
||||
treePacks.Insert(pb.PackID())
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -330,20 +333,14 @@ func removePacksExcept(gopts global.Options, t testing.TB, keep restic.IDSet, re
|
||||
if treePacks.Has(id) != removeTreePacks || keep.Has(id) {
|
||||
return nil
|
||||
}
|
||||
return be().Remove(ctx, backend.Handle{Type: restic.PackFile, Name: id.String()})
|
||||
return be().Remove(ctx, backend.Handle{Type: backend.PackFile, Name: id.String()})
|
||||
})
|
||||
})
|
||||
rtest.OK(t, err)
|
||||
}
|
||||
|
||||
func includes(haystack []string, needle string) bool {
|
||||
for _, s := range haystack {
|
||||
if s == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
return slices.Contains(haystack, needle)
|
||||
}
|
||||
|
||||
func loadSnapshotMap(t testing.TB, gopts global.Options) map[string]struct{} {
|
||||
@@ -371,7 +368,7 @@ func lastSnapshot(old, new map[string]struct{}) (map[string]struct{}, string) {
|
||||
func testLoadSnapshot(t testing.TB, gopts global.Options, id restic.ID) *data.Snapshot {
|
||||
var snapshot *data.Snapshot
|
||||
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()
|
||||
@@ -421,6 +418,13 @@ func withCaptureStdout(t testing.TB, gopts global.Options, callback func(ctx con
|
||||
return buf, err
|
||||
}
|
||||
|
||||
func withCaptureStdoutStderr(t testing.TB, gopts global.Options, callback func(ctx context.Context, gopts global.Options) error) (*bytes.Buffer, *bytes.Buffer, error) {
|
||||
bufStdout := bytes.NewBuffer(nil)
|
||||
bufStderr := bytes.NewBuffer(nil)
|
||||
err := withTermStatusRaw(os.Stdin, bufStdout, bufStderr, gopts, callback)
|
||||
return bufStdout, bufStderr, err
|
||||
}
|
||||
|
||||
func withTermStatus(t testing.TB, gopts global.Options, callback func(ctx context.Context, gopts global.Options) error) error {
|
||||
// stdout and stderr are written to by printer functions etc. That is the written data
|
||||
// usually consists of one or multiple lines and therefore can be handled well
|
||||
@@ -429,18 +433,10 @@ func withTermStatus(t testing.TB, gopts global.Options, callback func(ctx contex
|
||||
}
|
||||
|
||||
func withTermStatusRaw(stdin io.ReadCloser, stdout, stderr io.Writer, gopts global.Options, callback func(ctx context.Context, gopts global.Options) error) error {
|
||||
ctx, cancel := context.WithCancel(context.TODO())
|
||||
var wg sync.WaitGroup
|
||||
|
||||
term := termstatus.New(stdin, stdout, stderr, gopts.Quiet)
|
||||
term, cancel := termstatus.Setup(stdin, stdout, stderr, gopts.Quiet)
|
||||
gopts.Term = term
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
term.Run(ctx)
|
||||
}()
|
||||
|
||||
defer wg.Wait()
|
||||
defer cancel()
|
||||
ctx, cancel := context.WithCancel(context.TODO())
|
||||
defer cancel()
|
||||
|
||||
return callback(ctx, gopts)
|
||||
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
"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/restic"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
"github.com/restic/restic/internal/ui"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
)
|
||||
|
||||
func TestCheckRestoreNoLock(t *testing.T) {
|
||||
repository.TestInjectKey(t, restic.TestParseID("a19acdab068765b022ffb81cb5aac83c5de4bf4fbce0d26e9ade8e636c6ae49f"), `{"mac":{"k":"TbkpCBdNYAvAwb+64r8VGw==","r":"Q5V1CnAvBQREgJAOQD40Bw=="},"encrypt":"SjCkTpms+XOUJR5LSsy2G+uO9ngG7H0L+IVwPV4u70A="}`)
|
||||
env, cleanup := withTestEnvironment(t)
|
||||
defer cleanup()
|
||||
|
||||
@@ -46,14 +48,14 @@ func TestCheckRestoreNoLock(t *testing.T) {
|
||||
// is expected by the first listing + some operations.
|
||||
type listOnceBackend struct {
|
||||
backend.Backend
|
||||
listedFileType map[restic.FileType]bool
|
||||
listedFileType map[backend.FileType]bool
|
||||
strictOrder bool
|
||||
}
|
||||
|
||||
func newListOnceBackend(be backend.Backend) *listOnceBackend {
|
||||
return &listOnceBackend{
|
||||
Backend: be,
|
||||
listedFileType: make(map[restic.FileType]bool),
|
||||
listedFileType: make(map[backend.FileType]bool),
|
||||
strictOrder: false,
|
||||
}
|
||||
}
|
||||
@@ -61,16 +63,16 @@ func newListOnceBackend(be backend.Backend) *listOnceBackend {
|
||||
func newOrderedListOnceBackend(be backend.Backend) *listOnceBackend {
|
||||
return &listOnceBackend{
|
||||
Backend: be,
|
||||
listedFileType: make(map[restic.FileType]bool),
|
||||
listedFileType: make(map[backend.FileType]bool),
|
||||
strictOrder: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (be *listOnceBackend) List(ctx context.Context, t restic.FileType, fn func(backend.FileInfo) error) error {
|
||||
if t != restic.LockFile && be.listedFileType[t] {
|
||||
func (be *listOnceBackend) List(ctx context.Context, t backend.FileType, fn func(backend.FileInfo) error) error {
|
||||
if t != backend.LockFile && be.listedFileType[t] {
|
||||
return errors.Errorf("tried listing type %v the second time", t)
|
||||
}
|
||||
if be.strictOrder && t == restic.SnapshotFile && be.listedFileType[restic.IndexFile] {
|
||||
if be.strictOrder && t == backend.SnapshotFile && be.listedFileType[backend.IndexFile] {
|
||||
return errors.Errorf("tried listing type snapshots after index")
|
||||
}
|
||||
be.listedFileType[t] = true
|
||||
@@ -165,20 +167,32 @@ func TestFindListOnce(t *testing.T) {
|
||||
|
||||
var snapshotIDs restic.IDSet
|
||||
rtest.OK(t, 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()
|
||||
|
||||
snapshotIDs = restic.NewIDSet()
|
||||
// specify the two oldest snapshots explicitly and use "latest" to reference the newest one
|
||||
for sn := range FindFilteredSnapshots(ctx, repo, repo, &data.SnapshotFilter{}, []string{
|
||||
secondSnapshot[0].String(),
|
||||
secondSnapshot[1].String()[:8],
|
||||
"latest",
|
||||
}, printer) {
|
||||
snapshotIDs.Insert(*sn.ID())
|
||||
err = (&data.SnapshotFilter{}).FindAll(ctx, repo, repo,
|
||||
[]string{
|
||||
secondSnapshot[0].String(),
|
||||
secondSnapshot[1].String()[:8],
|
||||
"latest",
|
||||
},
|
||||
|
||||
func(id string, sn *data.Snapshot, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
snapshotIDs.Insert(*sn.ID())
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}))
|
||||
|
||||
@@ -194,7 +208,7 @@ type failConfigOnceBackend struct {
|
||||
func (be *failConfigOnceBackend) Load(ctx context.Context, h backend.Handle,
|
||||
length int, offset int64, fn func(rd io.Reader) error) error {
|
||||
|
||||
if !be.failedOnce && h.Type == restic.ConfigFile {
|
||||
if !be.failedOnce && h.Type == backend.ConfigFile {
|
||||
be.failedOnce = true
|
||||
return fmt.Errorf("oops")
|
||||
}
|
||||
@@ -202,7 +216,7 @@ func (be *failConfigOnceBackend) Load(ctx context.Context, h backend.Handle,
|
||||
}
|
||||
|
||||
func (be *failConfigOnceBackend) Stat(ctx context.Context, h backend.Handle) (backend.FileInfo, error) {
|
||||
if !be.failedOnce && h.Type == restic.ConfigFile {
|
||||
if !be.failedOnce && h.Type == backend.ConfigFile {
|
||||
be.failedOnce = true
|
||||
return backend.FileInfo{}, fmt.Errorf("oops")
|
||||
}
|
||||
|
||||
+6
-10
@@ -5,10 +5,10 @@ import (
|
||||
|
||||
"github.com/restic/restic/internal/global"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/ui/progress"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
)
|
||||
|
||||
func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bool, exclusive bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bool, exclusive bool, printer restic.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
repo, err := global.OpenRepository(ctx, gopts, printer)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
@@ -16,9 +16,7 @@ func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bo
|
||||
|
||||
unlock := func() {}
|
||||
if !dryRun {
|
||||
var lock *repository.Unlocker
|
||||
|
||||
lock, ctx, err = repository.Lock(ctx, repo, exclusive, gopts.RetryLock, func(msg string) {
|
||||
unlock, ctx, err = repository.LockRepo(ctx, repo, exclusive, gopts.RetryLock, func(msg string) {
|
||||
if !gopts.JSON {
|
||||
printer.P("%s", msg)
|
||||
}
|
||||
@@ -26,8 +24,6 @@ func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bo
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
unlock = lock.Unlock
|
||||
} else {
|
||||
repo.SetDryRun()
|
||||
}
|
||||
@@ -35,18 +31,18 @@ func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bo
|
||||
return ctx, repo, unlock, nil
|
||||
}
|
||||
|
||||
func openWithReadLock(ctx context.Context, gopts global.Options, noLock bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
func openWithReadLock(ctx context.Context, gopts global.Options, noLock bool, printer restic.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
// TODO enforce read-only operations once the locking code has moved to the repository
|
||||
// As in-depth hardening, put the repository into read-only mode if noLock is true
|
||||
// Not possible if the repository has to be locked.
|
||||
return internalOpenWithLocked(ctx, gopts, noLock, false, printer)
|
||||
}
|
||||
|
||||
func openWithAppendLock(ctx context.Context, gopts global.Options, dryRun bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
func openWithAppendLock(ctx context.Context, gopts global.Options, dryRun bool, printer restic.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
// TODO enforce non-exclusive operations once the locking code has moved to the repository
|
||||
return internalOpenWithLocked(ctx, gopts, dryRun, false, printer)
|
||||
}
|
||||
|
||||
func openWithExclusiveLock(ctx context.Context, gopts global.Options, dryRun bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
func openWithExclusiveLock(ctx context.Context, gopts global.Options, dryRun bool, printer restic.Printer) (context.Context, *repository.Repository, func(), error) {
|
||||
return internalOpenWithLocked(ctx, gopts, dryRun, true, printer)
|
||||
}
|
||||
+4
-5
@@ -20,7 +20,6 @@ import (
|
||||
"github.com/restic/restic/internal/feature"
|
||||
"github.com/restic/restic/internal/global"
|
||||
"github.com/restic/restic/internal/repository"
|
||||
"github.com/restic/restic/internal/restic"
|
||||
"github.com/restic/restic/internal/ui/termstatus"
|
||||
)
|
||||
|
||||
@@ -50,7 +49,7 @@ The full documentation can be found at https://restic.readthedocs.io/ .
|
||||
|
||||
PersistentPreRunE: func(c *cobra.Command, _ []string) error {
|
||||
switch c.Name() {
|
||||
case "__complete", "__completeNoDesc":
|
||||
case cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:
|
||||
return nil
|
||||
}
|
||||
return globalOptions.PreRun(needsPassword(c.Name()))
|
||||
@@ -118,7 +117,7 @@ The full documentation can be found at https://restic.readthedocs.io/ .
|
||||
// user for authentication).
|
||||
func needsPassword(cmd string) bool {
|
||||
switch cmd {
|
||||
case "cache", "generate", "help", "options", "self-update", "version", "__complete", "__completeNoDesc":
|
||||
case "cache", "generate", "help", "options", "self-update", "version", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
@@ -198,7 +197,7 @@ func main() {
|
||||
|
||||
var exitMessage string
|
||||
switch {
|
||||
case restic.IsAlreadyLocked(err):
|
||||
case repository.IsAlreadyLocked(err):
|
||||
exitMessage = fmt.Sprintf("%v\nthe `unlock` command can be used to remove stale locks", err)
|
||||
case err == ErrInvalidSourceData:
|
||||
exitMessage = fmt.Sprintf("Warning: %v", err)
|
||||
@@ -228,7 +227,7 @@ func main() {
|
||||
exitCode = 3
|
||||
case errors.Is(err, global.ErrNoRepository):
|
||||
exitCode = 10
|
||||
case restic.IsAlreadyLocked(err):
|
||||
case repository.IsAlreadyLocked(err):
|
||||
exitCode = 11
|
||||
case errors.Is(err, repository.ErrNoKeyFound):
|
||||
exitCode = 12
|
||||
|
||||
@@ -305,7 +305,7 @@ From source
|
||||
***********
|
||||
|
||||
restic is written in the Go programming language and you need at least
|
||||
Go version 1.25. Building restic may also work with older versions of Go,
|
||||
Go version 1.26.10. Building restic may also work with older versions of Go,
|
||||
but that's not supported. See the `Getting
|
||||
started <https://go.dev/doc/install>`__ guide of the Go project for
|
||||
instructions how to install Go.
|
||||
|
||||
@@ -30,7 +30,8 @@ section here.
|
||||
For automated backups, restic supports specifying the repository location in the
|
||||
environment variable ``RESTIC_REPOSITORY``. Restic can also read the repository
|
||||
location from a file specified via the ``--repository-file`` option or the
|
||||
environment variable ``RESTIC_REPOSITORY_FILE``.
|
||||
environment variable ``RESTIC_REPOSITORY_FILE``. The file must contain a
|
||||
repository location; empty or whitespace-only files are rejected.
|
||||
|
||||
For automating the supply of the repository password to restic, several options
|
||||
exist:
|
||||
@@ -249,6 +250,14 @@ while creating the bucket.
|
||||
$ export AWS_ACCESS_KEY_ID=<MY_ACCESS_KEY>
|
||||
$ export AWS_SECRET_ACCESS_KEY=<MY_SECRET_ACCESS_KEY>
|
||||
|
||||
Restic can also read credentials from an AWS shared credentials file. Set
|
||||
``AWS_SHARED_CREDENTIALS_FILE`` to its path, or use the default location at
|
||||
``~/.aws/credentials``. When running restic in a container, mount the file
|
||||
read-only and set ``AWS_SHARED_CREDENTIALS_FILE`` to the path inside the
|
||||
container. Avoid passing secret values in ``docker run -e NAME=value``
|
||||
arguments, where they can be exposed in process listings. Docker's
|
||||
``--env-file`` option also keeps the values out of command-line arguments.
|
||||
|
||||
When using temporary credentials make sure to include the session token via
|
||||
the environment variable ``AWS_SESSION_TOKEN``.
|
||||
|
||||
@@ -281,36 +290,6 @@ after the bucket name like this:
|
||||
be converted to path-style URLs instead, for example ``s3.us-west-2.amazonaws.com/bucket_name``.
|
||||
See below for configuration options for S3-compatible storage from other providers.
|
||||
|
||||
Minio Server
|
||||
************
|
||||
|
||||
`Minio <https://min.io/>`__ is an Open Source Object Storage,
|
||||
written in Go and compatible with Amazon S3 API.
|
||||
|
||||
- Download and Install `Minio Download <https://min.io/download#/linux>`__.
|
||||
- You can also refer to `Minio Docs <https://min.io/docs/minio/linux/>`__ for step by step guidance
|
||||
on installation and getting started on Minio Client and Minio Server.
|
||||
|
||||
You must first setup the following environment variables with the
|
||||
credentials of your Minio Server.
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ export AWS_ACCESS_KEY_ID=<YOUR-MINIO-ACCESS-KEY-ID>
|
||||
$ export AWS_SECRET_ACCESS_KEY=<YOUR-MINIO-SECRET-ACCESS-KEY>
|
||||
|
||||
Now you can easily initialize restic to use Minio server as a backend with
|
||||
this command.
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ restic -r s3:http://localhost:9000/restic init
|
||||
enter password for new repository:
|
||||
enter password again:
|
||||
created restic repository 6ad29560f5 at s3:http://localhost:9000/restic
|
||||
Please note that knowledge of your password is required to access
|
||||
the repository. Losing your password means that your data is irrecoverably lost.
|
||||
|
||||
S3-compatible storage
|
||||
*********************
|
||||
|
||||
@@ -338,6 +317,11 @@ To select between path-style and virtual-hosted access, the extended option
|
||||
- ``dns``: Use virtual-hosted-style bucket access
|
||||
- ``path``: Use path-style bucket access
|
||||
|
||||
Amazon's dual-stack endpoints are used by default for AWS regions that have
|
||||
them. VPC interface and gateway endpoints do not support dual-stack, so if
|
||||
restic cannot reach your bucket from inside a VPC, pass
|
||||
``-o s3.disable-dualstack=true``.
|
||||
|
||||
Certain S3-compatible servers do not properly implement the ``ListObjectsV2`` API,
|
||||
most notably Ceph versions before v14.2.5. On these backends, as a temporary
|
||||
workaround, you can provide the ``-o s3.list-objects-v1=true`` option to use the
|
||||
|
||||
@@ -399,6 +399,9 @@ sign, write ``$$`` to the file - this has to be done even when there's no
|
||||
matching environment variable for the word following a single ``$``. Note
|
||||
that tilde (``~``) is not expanded, instead use the ``$HOME`` or equivalent
|
||||
environment variable (depending on your operating system).
|
||||
For environment variable names with non-alphanumeric characters,
|
||||
enclose the name in curly braces (e.g., ``${ProgramFiles(x86)}``).
|
||||
Without braces, the parser stops at the first non-alphanumeric character.
|
||||
|
||||
Patterns need to match on complete path components. For example, the pattern ``foo``:
|
||||
|
||||
@@ -494,6 +497,8 @@ By specifying the option ``--one-file-system`` you can instruct restic
|
||||
to only backup files from the file systems the initially specified files
|
||||
or directories reside on. In other words, it will prevent restic from crossing
|
||||
filesystem boundaries and subvolumes when performing a backup.
|
||||
Internally, restic identifies a file's filesystem by the "device ID"
|
||||
that is returned by calling lstat() on the file.
|
||||
|
||||
For example, if you backup ``/`` with this option and you have external
|
||||
media mounted under ``/media/usb`` then restic will not back up ``/media/usb``
|
||||
@@ -657,6 +662,12 @@ If there is a **bind-mount** below a directory that is to be saved, restic desce
|
||||
archived as a block device file and restored as such. This also means that the content of the
|
||||
corresponding disk is not read, at least not from the device file.
|
||||
|
||||
**Socket files** are not backed up because they represent active connections by running processes
|
||||
and are only meaningful if created by those processes.
|
||||
|
||||
**FIFO files** are backed up, but because their contents are volatile and never stored on disk,
|
||||
only the file system entry and metadata will be backed up.
|
||||
|
||||
By default, restic does not save the access time (atime) for any files or other
|
||||
items, since it is not possible to reliably disable updating the access time by
|
||||
restic itself. This means that for each new backup a lot of metadata is
|
||||
|
||||
@@ -648,3 +648,28 @@ data, you can run ``prune --repack-uncompressed``. When you plan to create
|
||||
your backups with maximum compression, you should also add the
|
||||
``--compression max`` flag to the prune command. For already backed up data,
|
||||
the compression level cannot be changed later on.
|
||||
|
||||
|
||||
Managing local cache directories
|
||||
================================
|
||||
|
||||
The ``cache`` command lists the local cache directories and can remove stale
|
||||
ones:
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
$ restic cache
|
||||
Repo ID Last Used Old Size
|
||||
------------------------------------
|
||||
604bdfd4 2 days ago no 1.5 GiB
|
||||
------------------------------------
|
||||
1 cache dirs in /home/user/.cache/restic
|
||||
|
||||
Cache directories that have not been used for 30 days are considered old; the
|
||||
threshold can be changed with ``--max-age`` (in days). Old cache directories
|
||||
can be removed using ``restic cache --cleanup``, which honors ``--max-age``
|
||||
too. Pass ``--no-size`` to skip computing the size of each cache directory.
|
||||
|
||||
restic also prints a warning at startup when it finds old cache directories,
|
||||
suggesting ``restic cache --cleanup``. To remove old cache directories
|
||||
automatically on every restic run, set the global flag ``--cleanup-cache``.
|
||||
+6
-3
@@ -92,9 +92,12 @@ By default, restic does not restore files as sparse. Use ``restore --sparse`` to
|
||||
enable the creation of sparse files if supported by the filesystem. Then restic
|
||||
will restore long runs of zero bytes as holes in the corresponding files.
|
||||
Reading from a hole returns the original zero bytes, but it does not consume
|
||||
disk space. Note that the exact location of the holes can differ from those in
|
||||
the original file, as their location is determined while restoring and is not
|
||||
stored explicitly.
|
||||
disk space. Note that restic does not keep track of which files were originally
|
||||
sparse or at what locations sparse holes were. When restoring, restic will create
|
||||
a sparse hole (by seeking forward instead of writing data) for any range of zeros
|
||||
at the start of a blob. This range can span the entire blob. Because large files
|
||||
result in blobs much larger than file system blocks, restoring a large sparse file
|
||||
with many holes may make it significantly larger than the original sparse file.
|
||||
|
||||
Restoring extended file attributes
|
||||
----------------------------------
|
||||
|
||||
+3
-1
@@ -323,7 +323,7 @@ five days that had a snapshot and remove the other snapshots:
|
||||
keep 5 snapshots:
|
||||
ID Time Host Tags Reasons Paths
|
||||
-------------------------------------------------------------------------------
|
||||
8a603ddf 2025-04-25 23:00:00 mopped daily snapshot /home/user/work
|
||||
ae33bf10 2025-04-25 23:00:00 mopped daily snapshot /home/user/work
|
||||
fb8b1418 2025-04-28 11:00:00 mopped daily snapshot /home/user/work
|
||||
1db188b4 2025-04-29 11:00:00 mopped daily snapshot /home/user/work
|
||||
7baa4f28 2025-05-01 11:00:00 mopped daily snapshot /home/user/work
|
||||
@@ -507,6 +507,8 @@ The ``prune`` command accepts the following options:
|
||||
|
||||
- ``--verbose`` increased verbosity shows additional statistics for ``prune``.
|
||||
|
||||
- ``--json`` gives the statistics in JSON format.
|
||||
|
||||
|
||||
Recovering from "no free space" errors
|
||||
**************************************
|
||||
|
||||
Loaded 100 of 391 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user