repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_backup_integration_test.go | cmd/restic/cmd_backup_integration_test.go | package main
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunBackupAssumeFailure(t testing.TB, dir string, target []string, opts BackupOptions, gopts global.Options) error {
return withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
t.Logf("backing up %v in %v", target, dir)
if dir != "" {
cleanup := rtest.Chdir(t, dir)
defer cleanup()
}
opts.GroupBy = data.SnapshotGroupByOptions{Host: true, Path: true}
return runBackup(ctx, opts, gopts, gopts.Term, target)
})
}
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)
}
func TestBackup(t *testing.T) {
testBackup(t, false)
}
func TestBackupWithFilesystemSnapshots(t *testing.T) {
if runtime.GOOS == "windows" && fs.HasSufficientPrivilegesForVSS() == nil {
testBackup(t, true)
}
}
func testBackup(t *testing.T, useFsSnapshot bool) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{UseFsSnapshot: useFsSnapshot}
// first backup
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
stat1 := dirStats(t, env.repo)
// second backup, implicit incremental
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 2)
stat2 := dirStats(t, env.repo)
if stat2.size > stat1.size+stat1.size/10 {
t.Error("repository size has grown by more than 10 percent")
}
t.Logf("repository grown by %d bytes", stat2.size-stat1.size)
testRunCheck(t, env.gopts)
// third backup, explicit incremental
opts.Parent = snapshotIDs[0].String()
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
snapshotIDs = testListSnapshots(t, env.gopts, 3)
stat3 := dirStats(t, env.repo)
if stat3.size > stat1.size+stat1.size/10 {
t.Error("repository size has grown by more than 10 percent")
}
t.Logf("repository grown by %d bytes", stat3.size-stat2.size)
// restore all backups and compare
for i, snapshotID := range snapshotIDs {
restoredir := filepath.Join(env.base, fmt.Sprintf("restore%d", i))
t.Logf("restoring snapshot %v to %v", snapshotID.Str(), restoredir)
testRunRestore(t, env.gopts, restoredir, snapshotID.String()+":"+toPathInSnapshot(filepath.Dir(env.testdata)))
diff := directoriesContentsDiff(t, env.testdata, filepath.Join(restoredir, "testdata"))
rtest.Assert(t, diff == "", "directories are not equal: %v", diff)
}
testRunCheck(t, env.gopts)
}
func toPathInSnapshot(path string) string {
// use path as is on most platforms, but convert it on windows
if runtime.GOOS == "windows" {
// the path generated by the test is always local so take the shortcut
vol := filepath.VolumeName(path)
if vol[len(vol)-1] != ':' {
panic(fmt.Sprintf("unexpected path: %q", path))
}
path = vol[:len(vol)-1] + string(filepath.Separator) + path[len(vol)+1:]
path = filepath.ToSlash(path)
}
return path
}
func TestBackupWithRelativePath(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
// first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
firstSnapshotID := testListSnapshots(t, env.gopts, 1)[0]
// second backup, implicit incremental
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
// that the correct parent snapshot was used
latestSn, _ := testRunSnapshots(t, env.gopts)
rtest.Assert(t, latestSn != nil, "missing latest snapshot")
rtest.Assert(t, latestSn.Parent != nil && latestSn.Parent.Equal(firstSnapshotID), "second snapshot selected unexpected parent %v instead of %v", latestSn.Parent, firstSnapshotID)
}
type vssDeleteOriginalFS struct {
fs.FS
testdata string
hasRemoved bool
}
func (f *vssDeleteOriginalFS) Lstat(name string) (*fs.ExtendedFileInfo, error) {
if !f.hasRemoved {
// call Lstat to trigger snapshot creation
_, _ = f.FS.Lstat(name)
// nuke testdata
var err error
for i := 0; i < 3; i++ {
// 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)
if err == nil {
break
}
time.Sleep(10 * time.Millisecond)
}
if err != nil {
return nil, err
}
f.hasRemoved = true
}
return f.FS.Lstat(name)
}
func TestBackupVSS(t *testing.T) {
if runtime.GOOS != "windows" || fs.HasSufficientPrivilegesForVSS() != nil {
t.Skip("vss fs test can only be run on windows with admin privileges")
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{UseFsSnapshot: true}
var testFS *vssDeleteOriginalFS
backupFSTestHook = func(fs fs.FS) fs.FS {
testFS = &vssDeleteOriginalFS{
FS: fs,
testdata: env.testdata,
}
return testFS
}
defer func() {
backupFSTestHook = nil
}()
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
rtest.Equals(t, true, testFS.hasRemoved, "testdata was not removed")
}
func TestBackupParentSelection(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
// first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata/0/0"}, opts, env.gopts)
firstSnapshotID := testListSnapshots(t, env.gopts, 1)[0]
// second backup, sibling path
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata/0/tests"}, opts, env.gopts)
testListSnapshots(t, env.gopts, 2)
// third backup, incremental for the first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata/0/0"}, opts, env.gopts)
// test that the correct parent snapshot was used
latestSn, _ := testRunSnapshots(t, env.gopts)
rtest.Assert(t, latestSn != nil, "missing latest snapshot")
rtest.Assert(t, latestSn.Parent != nil && latestSn.Parent.Equal(firstSnapshotID), "third snapshot selected unexpected parent %v instead of %v", latestSn.Parent, firstSnapshotID)
}
func TestDryRunBackup(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
dryOpts := BackupOptions{DryRun: true}
// dry run before first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, dryOpts, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 0)
packIDs := testRunList(t, env.gopts, "packs")
rtest.Assert(t, len(packIDs) == 0,
"expected no data, got %v", snapshotIDs)
indexIDs := testRunList(t, env.gopts, "index")
rtest.Assert(t, len(indexIDs) == 0,
"expected no index, got %v", snapshotIDs)
// first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
snapshotIDs = testListSnapshots(t, env.gopts, 1)
packIDs = testRunList(t, env.gopts, "packs")
indexIDs = testRunList(t, env.gopts, "index")
// dry run between backups
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, dryOpts, env.gopts)
snapshotIDsAfter := testListSnapshots(t, env.gopts, 1)
rtest.Equals(t, snapshotIDs, snapshotIDsAfter)
dataIDsAfter := testRunList(t, env.gopts, "packs")
rtest.Equals(t, packIDs, dataIDsAfter)
indexIDsAfter := testRunList(t, env.gopts, "index")
rtest.Equals(t, indexIDs, indexIDsAfter)
// second backup, implicit incremental
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
snapshotIDs = testListSnapshots(t, env.gopts, 2)
packIDs = testRunList(t, env.gopts, "packs")
indexIDs = testRunList(t, env.gopts, "index")
// another dry run
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, dryOpts, env.gopts)
snapshotIDsAfter = testListSnapshots(t, env.gopts, 2)
rtest.Equals(t, snapshotIDs, snapshotIDsAfter)
dataIDsAfter = testRunList(t, env.gopts, "packs")
rtest.Equals(t, packIDs, dataIDsAfter)
indexIDsAfter = testRunList(t, env.gopts, "index")
rtest.Equals(t, indexIDs, indexIDsAfter)
}
func TestBackupNonExistingFile(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
p := filepath.Join(env.testdata, "0", "0", "9")
dirs := []string{
filepath.Join(p, "0"),
filepath.Join(p, "1"),
filepath.Join(p, "nonexisting"),
filepath.Join(p, "5"),
}
opts := BackupOptions{}
// mix of existing and non-existing files
err := testRunBackupAssumeFailure(t, "", dirs, opts, env.gopts)
rtest.Assert(t, err != nil, "expected error for non-existing file")
rtest.Assert(t, errors.Is(err, ErrInvalidSourceData), "expected ErrInvalidSourceData; got %v", err)
// only non-existing file
dirs = []string{
filepath.Join(p, "nonexisting"),
}
err = testRunBackupAssumeFailure(t, "", dirs, opts, env.gopts)
rtest.Assert(t, err != nil, "expected error for non-existing file")
rtest.Assert(t, errors.Is(err, ErrNoSourceData), "expected ErrNoSourceData; got %v", err)
}
func TestBackupSelfHealing(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
p := filepath.Join(env.testdata, "test/test")
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, 5))
opts := BackupOptions{}
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
// remove all data packs
removePacksExcept(env.gopts, t, restic.NewIDSet(), false)
testRunRebuildIndex(t, env.gopts)
// now the repo is also missing the data blob in the index; check should report this
testRunCheckMustFail(t, env.gopts)
// second backup should report an error but "heal" this situation
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
rtest.Assert(t, err != nil,
"backup should have reported an error")
testRunCheck(t, env.gopts)
}
func TestBackupTreeLoadError(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
p := filepath.Join(env.testdata, "test/test")
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, 5))
opts := BackupOptions{}
// Backup a subdirectory first, such that we can remove the tree pack for the subdirectory
testRunBackup(t, env.testdata, []string{"test"}, opts, env.gopts)
treePacks := listTreePacks(env.gopts, t)
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
// delete the subdirectory pack first
removePacks(env.gopts, t, treePacks)
testRunRebuildIndex(t, env.gopts)
// now the repo is missing the tree blob in the index; check should report this
testRunCheckMustFail(t, env.gopts)
// second backup should report an error but "heal" this situation
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
rtest.Assert(t, err != nil, "backup should have reported an error for the subdirectory")
testRunCheck(t, env.gopts)
// remove all tree packs
removePacksExcept(env.gopts, t, restic.NewIDSet(), true)
testRunRebuildIndex(t, env.gopts)
// now the repo is also missing the data blob in the index; check should report this
testRunCheckMustFail(t, env.gopts)
// second backup should report an error but "heal" this situation
err = testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
rtest.Assert(t, err != nil, "backup should have reported an error")
testRunCheck(t, env.gopts)
}
var backupExcludeFilenames = []string{
"testfile1",
"foo.tar.gz",
"private/secret/passwords.txt",
"work/source/test.c",
}
func TestBackupExclude(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
datadir := filepath.Join(env.base, "testdata")
for _, filename := range backupExcludeFilenames {
fp := filepath.Join(datadir, filename)
rtest.OK(t, os.MkdirAll(filepath.Dir(fp), 0755))
rtest.OK(t, os.WriteFile(fp, []byte(filename), 0o666))
}
snapshots := make(map[string]struct{})
opts := BackupOptions{}
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
snapshots, snapshotID := lastSnapshot(snapshots, loadSnapshotMap(t, env.gopts))
files := testRunLs(t, env.gopts, snapshotID)
rtest.Assert(t, includes(files, "/testdata/foo.tar.gz"),
"expected file %q in first snapshot, but it's not included", "foo.tar.gz")
opts.Excludes = []string{"*.tar.gz"}
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
snapshots, snapshotID = lastSnapshot(snapshots, loadSnapshotMap(t, env.gopts))
files = testRunLs(t, env.gopts, snapshotID)
rtest.Assert(t, !includes(files, "/testdata/foo.tar.gz"),
"expected file %q not in first snapshot, but it's included", "foo.tar.gz")
opts.Excludes = []string{"*.tar.gz", "private/secret"}
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
_, snapshotID = lastSnapshot(snapshots, loadSnapshotMap(t, env.gopts))
files = testRunLs(t, env.gopts, snapshotID)
rtest.Assert(t, !includes(files, "/testdata/foo.tar.gz"),
"expected file %q not in first snapshot, but it's included", "foo.tar.gz")
rtest.Assert(t, !includes(files, "/testdata/private/secret/passwords.txt"),
"expected file %q not in first snapshot, but it's included", "passwords.txt")
}
func TestBackupErrors(t *testing.T) {
if runtime.GOOS == "windows" {
return
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
// Assume failure
inaccessibleFile := filepath.Join(env.testdata, "0", "0", "9", "0")
rtest.OK(t, os.Chmod(inaccessibleFile, 0000))
defer func() {
rtest.OK(t, os.Chmod(inaccessibleFile, 0644))
}()
opts := BackupOptions{}
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
rtest.Assert(t, err != nil, "Assumed failure, but no error occurred.")
rtest.Assert(t, err == ErrInvalidSourceData, "Wrong error returned")
testListSnapshots(t, env.gopts, 1)
}
const (
incrementalFirstWrite = 10 * 1042 * 1024
incrementalSecondWrite = 1 * 1042 * 1024
incrementalThirdWrite = 1 * 1042 * 1024
)
func TestIncrementalBackup(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
datadir := filepath.Join(env.base, "testdata")
testfile := filepath.Join(datadir, "testfile")
rtest.OK(t, appendRandomData(testfile, incrementalFirstWrite))
opts := BackupOptions{}
testRunBackup(t, "", []string{datadir}, opts, env.gopts)
testRunCheck(t, env.gopts)
stat1 := dirStats(t, env.repo)
rtest.OK(t, appendRandomData(testfile, incrementalSecondWrite))
testRunBackup(t, "", []string{datadir}, opts, env.gopts)
testRunCheck(t, env.gopts)
stat2 := dirStats(t, env.repo)
if stat2.size-stat1.size > incrementalFirstWrite {
t.Errorf("repository size has grown by more than %d bytes", incrementalFirstWrite)
}
t.Logf("repository grown by %d bytes", stat2.size-stat1.size)
rtest.OK(t, appendRandomData(testfile, incrementalThirdWrite))
testRunBackup(t, "", []string{datadir}, opts, env.gopts)
testRunCheck(t, env.gopts)
stat3 := dirStats(t, env.repo)
if stat3.size-stat2.size > incrementalFirstWrite {
t.Errorf("repository size has grown by more than %d bytes", incrementalFirstWrite)
}
t.Logf("repository grown by %d bytes", stat3.size-stat2.size)
}
func TestBackupTags(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testRunCheck(t, env.gopts)
newest, _ := testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 0,
"expected no tags, got %v", newest.Tags)
parent := newest
opts.Tags = data.TagLists{[]string{"NL"}}
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 1 && newest.Tags[0] == "NL",
"expected one NL tag, got %v", newest.Tags)
// Tagged backup should have untagged backup as parent.
rtest.Assert(t, parent.ID.Equal(*newest.Parent),
"expected parent to be %v, got %v", parent.ID, newest.Parent)
}
func TestBackupProgramVersion(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
newest, _ := testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
resticVersion := "restic " + global.Version
rtest.Assert(t, newest.ProgramVersion == resticVersion,
"expected %v, got %v", resticVersion, newest.ProgramVersion)
}
func TestQuietBackup(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
env.gopts.Quiet = false
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
env.gopts.Quiet = true
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testListSnapshots(t, env.gopts, 2)
testRunCheck(t, env.gopts)
}
func TestHardLink(t *testing.T) {
// this test assumes a test set with a single directory containing hard linked files
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("testdata", "test.hl.tar.gz")
fd, err := os.Open(datafile)
if os.IsNotExist(err) {
t.Skipf("unable to find data file %q, skipping", datafile)
return
}
rtest.OK(t, err)
rtest.OK(t, fd.Close())
testRunInit(t, env.gopts)
rtest.SetupTarTestFixture(t, env.testdata, datafile)
linkTests := createFileSetPerHardlink(env.testdata)
opts := BackupOptions{}
// first backup
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
// restore all backups and compare
for i, snapshotID := range snapshotIDs {
restoredir := filepath.Join(env.base, fmt.Sprintf("restore%d", i))
t.Logf("restoring snapshot %v to %v", snapshotID.Str(), restoredir)
testRunRestore(t, env.gopts, restoredir, snapshotID.String())
diff := directoriesContentsDiff(t, env.testdata, filepath.Join(restoredir, "testdata"))
rtest.Assert(t, diff == "", "directories are not equal %v", diff)
linkResults := createFileSetPerHardlink(filepath.Join(restoredir, "testdata"))
rtest.Assert(t, linksEqual(linkTests, linkResults),
"links are not equal")
}
testRunCheck(t, env.gopts)
}
func linksEqual(source, dest map[uint64][]string) bool {
for _, vs := range source {
found := false
for kd, vd := range dest {
if linkEqual(vs, vd) {
delete(dest, kd)
found = true
break
}
}
if !found {
return false
}
}
return len(dest) == 0
}
func linkEqual(source, dest []string) bool {
// equal if sliced are equal without considering order
if source == nil && dest == nil {
return true
}
if source == nil || dest == nil {
return false
}
if len(source) != len(dest) {
return false
}
for i := range source {
found := false
for j := range dest {
if source[i] == dest[j] {
found = true
break
}
}
if !found {
return false
}
}
return true
}
func TestStdinFromCommand(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{
StdinCommand: true,
// test that subdirectories are handled correctly
StdinFilename: "stdin/subdir/file",
}
testRunBackup(t, filepath.Dir(env.testdata), []string{"python", "-c", "import sys; print('something'); sys.exit(0)"}, opts, env.gopts)
snapshots := testListSnapshots(t, env.gopts, 1)
files := testRunLs(t, env.gopts, snapshots[0].String())
rtest.Assert(t, includes(files, "/stdin/subdir/file"), "file %q missing from snapshot, got %v", "stdin/subdir/file", files)
testRunCheck(t, env.gopts)
}
func TestStdinFromCommandNoOutput(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{
StdinCommand: true,
StdinFilename: "stdin",
}
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"python", "-c", "import sys; sys.exit(0)"}, opts, env.gopts)
rtest.Assert(t, err != nil && err.Error() == "at least one source file could not be read", "No data error expected")
testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
}
func TestStdinFromCommandFailExitCode(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{
StdinCommand: true,
StdinFilename: "stdin",
}
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"python", "-c", "import sys; print('test'); sys.exit(1)"}, opts, env.gopts)
rtest.Assert(t, err != nil, "Expected error while backing up")
testListSnapshots(t, env.gopts, 0)
testRunCheck(t, env.gopts)
}
func TestStdinFromCommandFailNoOutputAndExitCode(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{
StdinCommand: true,
StdinFilename: "stdin",
}
err := testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"python", "-c", "import sys; sys.exit(1)"}, opts, env.gopts)
rtest.Assert(t, err != nil, "Expected error while backing up")
testListSnapshots(t, env.gopts, 0)
testRunCheck(t, env.gopts)
}
func TestBackupEmptyPassword(t *testing.T) {
// basic sanity test that empty passwords work
env, cleanup := withTestEnvironment(t)
defer cleanup()
env.gopts.Password = ""
env.gopts.InsecureNoPassword = true
testSetupBackupData(t, env)
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{}, env.gopts)
testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
}
func TestBackupSkipIfUnchanged(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{SkipIfUnchanged: true}
for i := 0; i < 3; i++ {
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
}
testRunCheck(t, env.gopts)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_cat.go | cmd/restic/cmd_cat.go | package main
import (
"context"
"encoding/json"
"strings"
"github.com/spf13/cobra"
"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"
"github.com/restic/restic/internal/ui"
)
var catAllowedCmds = []string{"config", "index", "snapshot", "key", "masterkey", "lock", "pack", "blob", "tree"}
func newCatCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "cat [flags] [masterkey|config|pack ID|blob ID|snapshot ID|index ID|key ID|lock ID|tree snapshot:subfolder]",
Short: "Print internal objects to stdout",
Long: `
The "cat" command is used to print internal objects to stdout.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runCat(cmd.Context(), *globalOptions, args, globalOptions.Term)
},
ValidArgs: catAllowedCmds,
}
return cmd
}
func validateCatArgs(args []string) error {
if len(args) < 1 {
return errors.Fatal("type not specified")
}
validType := false
for _, v := range catAllowedCmds {
if v == args[0] {
validType = true
break
}
}
if !validType {
return errors.Fatalf("invalid type %q, must be one of [%s]", args[0], strings.Join(catAllowedCmds, "|"))
}
if args[0] != "masterkey" && args[0] != "config" && len(args) != 2 {
return errors.Fatal("ID not specified")
}
return nil
}
func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
if err := validateCatArgs(args); err != nil {
return err
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
tpe := args[0]
var id restic.ID
if tpe != "masterkey" && tpe != "config" && tpe != "snapshot" && tpe != "tree" {
id, err = restic.ParseID(args[1])
if err != nil {
return errors.Fatalf("unable to parse ID: %v", err)
}
}
switch tpe {
case "config":
buf, err := json.MarshalIndent(repo.Config(), "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "index":
buf, err := repo.LoadUnpacked(ctx, restic.IndexFile, id)
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "snapshot":
sn, _, err := data.FindSnapshot(ctx, repo, repo, args[1])
if err != nil {
return errors.Fatalf("could not find snapshot: %v", err)
}
buf, err := json.MarshalIndent(sn, "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "key":
key, err := repository.LoadKey(ctx, repo, id)
if err != nil {
return err
}
buf, err := json.MarshalIndent(&key, "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "masterkey":
buf, err := json.MarshalIndent(repo.Key(), "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "lock":
lock, err := restic.LoadLock(ctx, repo, id)
if err != nil {
return err
}
buf, err := json.MarshalIndent(&lock, "", " ")
if err != nil {
return err
}
printer.S(string(buf))
return nil
case "pack":
buf, err := repo.LoadRaw(ctx, restic.PackFile, id)
// allow returning broken pack files
if buf == nil {
return err
}
hash := restic.Hash(buf)
if !hash.Equal(id) {
printer.E("Warning: hash of data does not match ID, want\n %v\ngot:\n %v", id.String(), hash.String())
}
_, err = term.OutputRaw().Write(buf)
return err
case "blob":
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
for _, t := range []restic.BlobType{restic.DataBlob, restic.TreeBlob} {
if _, ok := repo.LookupBlobSize(t, id); !ok {
continue
}
buf, err := repo.LoadBlob(ctx, t, id, nil)
if err != nil {
return err
}
_, err = term.OutputRaw().Write(buf)
return err
}
return errors.Fatal("blob not found")
case "tree":
sn, subfolder, err := data.FindSnapshot(ctx, repo, repo, args[1])
if err != nil {
return errors.Fatalf("could not find snapshot: %v", err)
}
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
sn.Tree, err = data.FindTreeDirectory(ctx, repo, sn.Tree, subfolder)
if err != nil {
return err
}
buf, err := repo.LoadBlob(ctx, restic.TreeBlob, *sn.Tree, nil)
if err != nil {
return err
}
_, err = term.OutputRaw().Write(buf)
return err
default:
return errors.Fatal("invalid type")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_mount.go | cmd/restic/cmd_mount.go | //go:build darwin || freebsd || linux
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/fuse"
systemFuse "github.com/anacrolix/fuse"
"github.com/anacrolix/fuse/fs"
)
func registerMountCommand(cmdRoot *cobra.Command, globalOptions *global.Options) {
cmdRoot.AddCommand(newMountCommand(globalOptions))
}
func newMountCommand(globalOptions *global.Options) *cobra.Command {
var opts MountOptions
cmd := &cobra.Command{
Use: "mount [flags] mountpoint",
Short: "Mount the repository",
Long: `
The "mount" command mounts the repository via fuse to a directory. This is a
read-only mount.
Snapshot Directories
====================
If you need a different template for directories that contain snapshots,
you can pass a time template via --time-template and path templates via
--path-template.
Example time template without colons:
--time-template "2006-01-02_15-04-05"
You need to specify a sample format for exactly the following timestamp:
Mon Jan 2 15:04:05 -0700 MST 2006
For details please see the documentation for time.Format() at:
https://godoc.org/time#Time.Format
For path templates, you can use the following patterns which will be replaced:
%i by short snapshot ID
%I by long snapshot ID
%u by username
%h by hostname
%t by tags
%T by timestamp as specified by --time-template
The default path templates are:
"ids/%i"
"snapshots/%T"
"hosts/%h/%T"
"tags/%t/%T"
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
GroupID: cmdGroupDefault,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runMount(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// MountOptions collects all options for the mount command.
type MountOptions struct {
OwnerRoot bool
AllowOther bool
NoDefaultPermissions bool
data.SnapshotFilter
TimeTemplate string
PathTemplates []string
}
func (opts *MountOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.OwnerRoot, "owner-root", false, "use 'root' as the owner of files and dirs")
f.BoolVar(&opts.AllowOther, "allow-other", false, "allow other users to access the data in the mounted directory")
f.BoolVar(&opts.NoDefaultPermissions, "no-default-permissions", false, "for 'allow-other', ignore Unix permissions and allow users to read all snapshot files")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
f.StringArrayVar(&opts.PathTemplates, "path-template", nil, "set `template` for path names (can be specified multiple times)")
f.StringVar(&opts.TimeTemplate, "snapshot-template", time.RFC3339, "set `template` to use for snapshot dirs")
f.StringVar(&opts.TimeTemplate, "time-template", time.RFC3339, "set `template` to use for times")
_ = f.MarkDeprecated("snapshot-template", "use --time-template")
}
func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
if opts.TimeTemplate == "" {
return errors.Fatal("time template string cannot be empty")
}
if strings.HasPrefix(opts.TimeTemplate, "/") || strings.HasSuffix(opts.TimeTemplate, "/") {
return errors.Fatal("time template string cannot start or end with '/'")
}
if len(args) == 0 {
return errors.Fatal("wrong number of parameters")
}
mountpoint := args[0]
// Check the existence of the mount point at the earliest stage to
// prevent unnecessary computations while opening the repository.
if _, err := os.Stat(mountpoint); errors.Is(err, os.ErrNotExist) {
printer.P("Mountpoint %s doesn't exist", mountpoint)
return err
}
debug.Log("start mount")
defer debug.Log("finish mount")
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
fuseMountName := fmt.Sprintf("restic:%s", repo.Config().ID[:10])
mountOptions := []systemFuse.MountOption{
systemFuse.ReadOnly(),
systemFuse.FSName(fuseMountName),
systemFuse.MaxReadahead(128 * 1024),
}
if opts.AllowOther {
mountOptions = append(mountOptions, systemFuse.AllowOther())
// let the kernel check permissions unless it is explicitly disabled
if !opts.NoDefaultPermissions {
mountOptions = append(mountOptions, systemFuse.DefaultPermissions())
}
}
systemFuse.Debug = func(msg interface{}) {
debug.Log("fuse: %v", msg)
}
c, err := systemFuse.Mount(mountpoint, mountOptions...)
if err != nil {
return err
}
cfg := fuse.Config{
OwnerIsRoot: opts.OwnerRoot,
Filter: opts.SnapshotFilter,
TimeTemplate: opts.TimeTemplate,
PathTemplates: opts.PathTemplates,
}
root := fuse.NewRoot(repo, cfg)
printer.S("Now serving the repository at %s", mountpoint)
printer.S("Use another terminal or tool to browse the contents of this folder.")
printer.S("When finished, quit with Ctrl-c here or umount the mountpoint.")
debug.Log("serving mount at %v", mountpoint)
done := make(chan struct{})
go func() {
defer close(done)
err = fs.Serve(c, root)
}()
select {
case <-ctx.Done():
debug.Log("running umount cleanup handler for mount at %v", mountpoint)
err := systemFuse.Unmount(mountpoint)
if err != nil {
printer.E("unable to umount (maybe already umounted or still in use?): %v", err)
}
return ErrOK
case <-done:
// clean shutdown, nothing to do
}
return err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_version.go | cmd/restic/cmd_version.go | package main
import (
"encoding/json"
"runtime"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
"github.com/spf13/cobra"
)
func newVersionCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Print version information",
Long: `
The "version" command prints detailed information about the build environment
and the version of this software.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
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)
if globalOptions.JSON {
type jsonVersion struct {
MessageType string `json:"message_type"` // version
Version string `json:"version"`
GoVersion string `json:"go_version"`
GoOS string `json:"go_os"`
GoArch string `json:"go_arch"`
}
jsonS := jsonVersion{
MessageType: "version",
Version: global.Version,
GoVersion: runtime.Version(),
GoOS: runtime.GOOS,
GoArch: runtime.GOARCH,
}
err := json.NewEncoder(globalOptions.Term.OutputWriter()).Encode(jsonS)
if err != nil {
printer.E("JSON encode failed: %v\n", err)
return
}
} else {
printer.S("restic %s compiled with %v on %v/%v\n",
global.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
},
}
return cmd
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_check_test.go | cmd/restic/cmd_check_test.go | package main
import (
"io/fs"
"math"
"os"
"reflect"
"strings"
"testing"
"github.com/restic/restic/internal/errors"
"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) {
testCases := []struct {
input string
output float64
expectError bool
}{
{"0%", 0.0, false},
{"1%", 1.0, false},
{"100%", 100.0, false},
{"123%", 123.0, false},
{"123.456%", 123.456, false},
{"0.742%", 0.742, false},
{"-100%", -100.0, false},
{" 1%", 0.0, true},
{"1 %", 0.0, true},
{"1% ", 0.0, true},
}
for _, testCase := range testCases {
output, err := parsePercentage(testCase.input)
if testCase.expectError {
rtest.Assert(t, err != nil, "Expected error for case %s", testCase.input)
rtest.Assert(t, output == 0.0, "Expected output to be 0.0, got %s", output)
} else {
rtest.Assert(t, err == nil, "Expected no error for case %s", testCase.input)
rtest.Assert(t, math.Abs(testCase.output-output) < 0.00001, "Expected %f, got %f",
testCase.output, output)
}
}
}
func TestStringToIntSlice(t *testing.T) {
testCases := []struct {
input string
output []uint
expectError bool
}{
{"3/5", []uint{3, 5}, false},
{"1/100", []uint{1, 100}, false},
{"abc", nil, true},
{"1/a", nil, true},
{"/", nil, true},
}
for _, testCase := range testCases {
output, err := stringToIntSlice(testCase.input)
if testCase.expectError {
rtest.Assert(t, err != nil, "Expected error for case %s", testCase.input)
rtest.Assert(t, output == nil, "Expected output to be nil, got %s", output)
} else {
rtest.Assert(t, err == nil, "Expected no error for case %s", testCase.input)
rtest.Assert(t, len(output) == 2, "Invalid output length for case %s", testCase.input)
rtest.Assert(t, reflect.DeepEqual(output, testCase.output), "Expected %f, got %f",
testCase.output, output)
}
}
}
func TestSelectPacksByBucket(t *testing.T) {
var testPacks = make(map[restic.ID]int64)
for i := 1; i <= 10; i++ {
id := restic.NewRandomID()
// ensure relevant part of generated id is reproducible
id[0] = byte(i)
testPacks[id] = 0
}
selectedPacks := selectPacksByBucket(testPacks, 0, 10)
rtest.Assert(t, len(selectedPacks) == 0, "Expected 0 selected packs")
for i := uint(1); i <= 5; i++ {
selectedPacks = selectPacksByBucket(testPacks, i, 5)
rtest.Assert(t, len(selectedPacks) == 2, "Expected 2 selected packs")
}
selectedPacks = selectPacksByBucket(testPacks, 1, 1)
rtest.Assert(t, len(selectedPacks) == 10, "Expected 10 selected packs")
for testPack := range testPacks {
_, ok := selectedPacks[testPack]
rtest.Assert(t, ok, "Expected input and output to be equal")
}
}
func TestSelectRandomPacksByPercentage(t *testing.T) {
var testPacks = make(map[restic.ID]int64)
for i := 1; i <= 10; i++ {
testPacks[restic.NewRandomID()] = 0
}
selectedPacks := selectRandomPacksByPercentage(testPacks, 0.0)
rtest.Assert(t, len(selectedPacks) == 1, "Expected 1 selected packs")
selectedPacks = selectRandomPacksByPercentage(testPacks, 10.0)
rtest.Assert(t, len(selectedPacks) == 1, "Expected 1 selected pack")
for pack := range selectedPacks {
_, ok := testPacks[pack]
rtest.Assert(t, ok, "Unexpected selection")
}
selectedPacks = selectRandomPacksByPercentage(testPacks, 50.0)
rtest.Assert(t, len(selectedPacks) == 5, "Expected 5 selected packs")
for pack := range selectedPacks {
_, ok := testPacks[pack]
rtest.Assert(t, ok, "Unexpected item in selection")
}
selectedPacks = selectRandomPacksByPercentage(testPacks, 100.0)
rtest.Assert(t, len(selectedPacks) == 10, "Expected 10 selected packs")
for testPack := range testPacks {
_, ok := selectedPacks[testPack]
rtest.Assert(t, ok, "Expected input and output to be equal")
}
}
func TestSelectNoRandomPacksByPercentage(t *testing.T) {
// that the repository without pack files works
var testPacks = make(map[restic.ID]int64)
selectedPacks := selectRandomPacksByPercentage(testPacks, 10.0)
rtest.Assert(t, len(selectedPacks) == 0, "Expected 0 selected packs")
}
func TestSelectRandomPacksByFileSize(t *testing.T) {
var testPacks = make(map[restic.ID]int64)
for i := 1; i <= 10; i++ {
id := restic.NewRandomID()
// ensure unique ids
id[0] = byte(i)
testPacks[id] = 0
}
selectedPacks := selectRandomPacksByFileSize(testPacks, 10, 500)
rtest.Assert(t, len(selectedPacks) == 1, "Expected 1 selected packs")
selectedPacks = selectRandomPacksByFileSize(testPacks, 10240, 51200)
rtest.Assert(t, len(selectedPacks) == 2, "Expected 2 selected packs")
for pack := range selectedPacks {
_, ok := testPacks[pack]
rtest.Assert(t, ok, "Unexpected selection")
}
selectedPacks = selectRandomPacksByFileSize(testPacks, 500, 500)
rtest.Assert(t, len(selectedPacks) == 10, "Expected 10 selected packs")
for pack := range selectedPacks {
_, ok := testPacks[pack]
rtest.Assert(t, ok, "Unexpected item in selection")
}
}
func TestSelectNoRandomPacksByFileSize(t *testing.T) {
// that the repository without pack files works
var testPacks = make(map[restic.ID]int64)
selectedPacks := selectRandomPacksByFileSize(testPacks, 10, 500)
rtest.Assert(t, len(selectedPacks) == 0, "Expected 0 selected packs")
}
func checkIfFileWithSimilarNameExists(files []fs.DirEntry, fileName string) bool {
found := false
for _, file := range files {
if file.IsDir() {
dirName := file.Name()
if strings.Contains(dirName, fileName) {
found = true
}
}
}
return found
}
func TestPrepareCheckCache(t *testing.T) {
// Create a temporary directory for the cache
tmpDirBase := t.TempDir()
testCases := []struct {
opts CheckOptions
withValidCache bool
}{
{CheckOptions{WithCache: true}, true}, // Shouldn't create temp directory
{CheckOptions{WithCache: false}, true}, // Should create temp directory
{CheckOptions{WithCache: false}, false}, // Should create cache directory first, then temp directory
}
for _, testCase := range testCases {
t.Run("", func(t *testing.T) {
if !testCase.withValidCache {
// remove tmpDirBase to simulate non-existing cache directory
err := os.Remove(tmpDirBase)
rtest.OK(t, err)
}
gopts := global.Options{CacheDir: tmpDirBase}
cleanup := prepareCheckCache(testCase.opts, &gopts, &progress.NoopPrinter{})
files, err := os.ReadDir(tmpDirBase)
rtest.OK(t, err)
if !testCase.opts.WithCache {
// If using a temporary cache directory, the cache directory should exist
// listing all directories inside tmpDirBase (cacheDir)
// one directory should be tmpDir created by prepareCheckCache with 'restic-check-cache-' in path
found := checkIfFileWithSimilarNameExists(files, "restic-check-cache-")
if !found {
t.Errorf("Expected temporary directory to exist, but it does not")
}
} else {
// If not using the cache, the temp directory should not exist
rtest.Assert(t, len(files) == 0, "expected cache directory not to exist, but it does: %v", files)
}
// Call the cleanup function to remove the temporary cache directory
cleanup()
// Verify that the cache directory has been removed
files, err = os.ReadDir(tmpDirBase)
rtest.OK(t, err)
rtest.Assert(t, len(files) == 0, "Expected cache directory to be removed, but it still exists: %v", files)
})
}
}
func TestPrepareDefaultCheckCache(t *testing.T) {
gopts := global.Options{CacheDir: ""}
cleanup := prepareCheckCache(CheckOptions{}, &gopts, &progress.NoopPrinter{})
_, err := os.ReadDir(gopts.CacheDir)
rtest.OK(t, err)
// Call the cleanup function to remove the temporary cache directory
cleanup()
// Verify that the cache directory has been removed
_, err = os.ReadDir(gopts.CacheDir)
rtest.Assert(t, errors.Is(err, os.ErrNotExist), "Expected cache directory to be removed, but it still exists")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/exclude.go | cmd/restic/exclude.go | package main
import (
"github.com/restic/restic/internal/archiver"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/repository"
)
// rejectResticCache returns a RejectByNameFunc that rejects the restic cache
// directory (if set).
func rejectResticCache(repo *repository.Repository) (archiver.RejectByNameFunc, error) {
if repo.Cache() == nil {
return func(string) bool {
return false
}, nil
}
cacheBase := repo.Cache().BaseDir()
if cacheBase == "" {
return nil, errors.New("cacheBase is empty string")
}
return func(item string) bool {
if fs.HasPathPrefix(cacheBase, item) {
debug.Log("rejecting restic cache directory %v", item)
return true
}
return false
}, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair_index.go | cmd/restic/cmd_repair_index.go | package main
import (
"context"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newRepairIndexCommand(globalOptions *global.Options) *cobra.Command {
var opts RepairIndexOptions
cmd := &cobra.Command{
Use: "index [flags]",
Short: "Build a new index",
Long: `
The "repair index" command creates a new index based on the pack files in the
repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
return runRebuildIndex(cmd.Context(), opts, *globalOptions, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// RepairIndexOptions collects all options for the repair index command.
type RepairIndexOptions struct {
ReadAllPacks bool
}
func (opts *RepairIndexOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.ReadAllPacks, "read-all-packs", false, "read all pack files to generate new index from scratch")
}
func newRebuildIndexCommand(globalOptions *global.Options) *cobra.Command {
var opts RepairIndexOptions
replacement := newRepairIndexCommand(globalOptions)
cmd := &cobra.Command{
Use: "rebuild-index [flags]",
Short: replacement.Short,
Long: replacement.Long,
Deprecated: `Use "repair index" instead`,
DisableAutoGenTag: true,
// must create a new instance of the run function as it captures opts
// by reference
RunE: func(cmd *cobra.Command, _ []string) error {
return runRebuildIndex(cmd.Context(), opts, *globalOptions, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
func runRebuildIndex(ctx context.Context, opts RepairIndexOptions, gopts global.Options, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
err = repository.RepairIndex(ctx, repo, repository.RepairIndexOptions{
ReadAllPacks: opts.ReadAllPacks,
}, printer)
if err != nil {
return err
}
printer.P("done\n")
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_rewrite_integration_test.go | cmd/restic/cmd_rewrite_integration_test.go | package main
import (
"context"
"path/filepath"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/filter"
"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"
)
func testRunRewriteExclude(t testing.TB, gopts global.Options, excludes []string, forget bool, metadata snapshotMetadataArgs) {
opts := RewriteOptions{
ExcludePatternOptions: filter.ExcludePatternOptions{
Excludes: excludes,
},
Forget: forget,
Metadata: metadata,
}
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRewrite(context.TODO(), opts, gopts, nil, gopts.Term)
}))
}
func createBasicRewriteRepo(t testing.TB, env *testEnvironment) restic.ID {
testSetupBackupData(t, env)
// create backup
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{}, env.gopts)
snapshotIDs := testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == 1, "expected one snapshot, got %v", snapshotIDs)
testRunCheck(t, env.gopts)
return snapshotIDs[0]
}
func getSnapshot(t testing.TB, snapshotID restic.ID, env *testEnvironment) *data.Snapshot {
t.Helper()
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)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
snapshots, err = data.TestLoadAllSnapshots(ctx, repo, nil)
return err
})
rtest.OK(t, err)
for _, s := range snapshots {
if *s.ID() == snapshotID {
return s
}
}
return nil
}
func TestRewrite(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createBasicRewriteRepo(t, env)
// exclude some data
testRunRewriteExclude(t, env.gopts, []string{"3"}, false, snapshotMetadataArgs{Hostname: "", Time: ""})
snapshotIDs := testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == 2, "expected two snapshots, got %v", snapshotIDs)
testRunCheck(t, env.gopts)
}
func TestRewriteUnchanged(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
snapshotID := createBasicRewriteRepo(t, env)
// use an exclude that will not exclude anything
testRunRewriteExclude(t, env.gopts, []string{"3dflkhjgdflhkjetrlkhjgfdlhkj"}, false, snapshotMetadataArgs{Hostname: "", Time: ""})
newSnapshotIDs := testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(newSnapshotIDs) == 1, "expected one snapshot, got %v", newSnapshotIDs)
rtest.Assert(t, snapshotID == newSnapshotIDs[0], "snapshot id changed unexpectedly")
testRunCheck(t, env.gopts)
}
func TestRewriteReplace(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
snapshotID := createBasicRewriteRepo(t, env)
snapshot := getSnapshot(t, snapshotID, env)
// exclude some data
testRunRewriteExclude(t, env.gopts, []string{"3"}, true, snapshotMetadataArgs{Hostname: "", Time: ""})
bytesExcluded, err := ui.ParseBytes("16K")
rtest.OK(t, err)
newSnapshotIDs := testListSnapshots(t, env.gopts, 1)
rtest.Assert(t, snapshotID != newSnapshotIDs[0], "snapshot id should have changed")
newSnapshot := getSnapshot(t, newSnapshotIDs[0], env)
rtest.Equals(t, snapshot.Summary.TotalFilesProcessed-1, newSnapshot.Summary.TotalFilesProcessed, "snapshot file count should have changed")
rtest.Equals(t, snapshot.Summary.TotalBytesProcessed-uint64(bytesExcluded), newSnapshot.Summary.TotalBytesProcessed, "snapshot size should have changed")
// check forbids unused blobs, thus remove them first
testRunPrune(t, env.gopts, PruneOptions{MaxUnused: "0"})
testRunCheck(t, env.gopts)
}
func testRewriteMetadata(t *testing.T, metadata snapshotMetadataArgs) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createBasicRewriteRepo(t, env)
testRunRewriteExclude(t, env.gopts, []string{}, true, metadata)
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)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
snapshots, err = data.TestLoadAllSnapshots(ctx, repo, nil)
return err
})
rtest.OK(t, err)
rtest.Assert(t, len(snapshots) == 1, "expected one snapshot, got %v", len(snapshots))
newSnapshot := snapshots[0]
if metadata.Time != "" {
rtest.Assert(t, newSnapshot.Time.Format(global.TimeFormat) == metadata.Time, "New snapshot should have time %s", metadata.Time)
}
if metadata.Hostname != "" {
rtest.Assert(t, newSnapshot.Hostname == metadata.Hostname, "New snapshot should have host %s", metadata.Hostname)
}
}
func TestRewriteMetadata(t *testing.T) {
newHost := "new host"
newTime := "1999-01-01 11:11:11"
for _, metadata := range []snapshotMetadataArgs{
{Hostname: "", Time: newTime},
{Hostname: newHost, Time: ""},
{Hostname: newHost, Time: newTime},
} {
testRewriteMetadata(t, metadata)
}
}
func TestRewriteSnaphotSummary(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createBasicRewriteRepo(t, env)
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runRewrite(context.TODO(), RewriteOptions{SnapshotSummary: true}, gopts, []string{}, gopts.Term)
}))
// no new snapshot should be created as the snapshot already has a summary
snapshots := testListSnapshots(t, env.gopts, 1)
// 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)
_, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
sn, err := data.LoadSnapshot(ctx, repo, snapshots[0])
rtest.OK(t, err)
oldSummary = sn.Summary
sn.Summary = nil
rtest.OK(t, repo.RemoveUnpacked(ctx, restic.WriteableSnapshotFile, snapshots[0]))
snapshots[0], err = data.SaveSnapshot(ctx, repo, sn)
return err
})
rtest.OK(t, err)
// rewrite snapshot and lookup ID of new snapshot
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runRewrite(context.TODO(), RewriteOptions{SnapshotSummary: true}, gopts, []string{}, gopts.Term)
}))
newSnapshots := testListSnapshots(t, env.gopts, 2)
newSnapshot := restic.NewIDSet(newSnapshots...).Sub(restic.NewIDSet(snapshots...)).List()[0]
newSn := testLoadSnapshot(t, env.gopts, newSnapshot)
rtest.Assert(t, newSn.Summary != nil, "snapshot should have summary attached")
rtest.Equals(t, oldSummary.TotalBytesProcessed, newSn.Summary.TotalBytesProcessed, "unexpected TotalBytesProcessed value")
rtest.Equals(t, oldSummary.TotalFilesProcessed, newSn.Summary.TotalFilesProcessed, "unexpected TotalFilesProcessed value")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_forget_integration_test.go | cmd/restic/cmd_forget_integration_test.go | package main
import (
"context"
"path/filepath"
"strings"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunForgetMayFail(t testing.TB, gopts global.Options, opts ForgetOptions, args ...string) error {
pruneOpts := PruneOptions{
MaxUnused: "5%",
}
return withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runForget(context.TODO(), opts, pruneOpts, gopts, gopts.Term, args)
})
}
func testRunForget(t testing.TB, gopts global.Options, opts ForgetOptions, args ...string) {
rtest.OK(t, testRunForgetMayFail(t, gopts, opts, args...))
}
func TestRunForgetSafetyNet(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{
Host: "example",
}
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testListSnapshots(t, env.gopts, 2)
// --keep-tags invalid
err := testRunForgetMayFail(t, env.gopts, ForgetOptions{
KeepTags: data.TagLists{data.TagList{"invalid"}},
GroupBy: data.SnapshotGroupByOptions{Host: true, Path: true},
})
rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group "host example, path`), "wrong error message got %v", err)
// disallow `forget --unsafe-allow-remove-all`
err = testRunForgetMayFail(t, env.gopts, ForgetOptions{
UnsafeAllowRemoveAll: true,
})
rtest.Assert(t, strings.Contains(err.Error(), `--unsafe-allow-remove-all is not allowed unless a snapshot filter option is specified`), "wrong error message got %v", err)
// disallow `forget` without options
err = testRunForgetMayFail(t, env.gopts, ForgetOptions{})
rtest.Assert(t, strings.Contains(err.Error(), `no policy was specified, no snapshots will be removed`), "wrong error message got %v", err)
// `forget --host example --unsafe-allow-remove-all` should work
testRunForget(t, env.gopts, ForgetOptions{
UnsafeAllowRemoveAll: true,
GroupBy: data.SnapshotGroupByOptions{Host: true, Path: true},
SnapshotFilter: data.SnapshotFilter{
Hosts: []string{opts.Host},
},
})
testListSnapshots(t, env.gopts, 0)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_debug.go | cmd/restic/cmd_debug.go | //go:build debug
package main
import (
"context"
"crypto/aes"
"crypto/cipher"
"encoding/json"
"fmt"
"io"
"os"
"runtime"
"sort"
"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"
)
func registerDebugCommand(cmd *cobra.Command, globalOptions *global.Options) {
cmd.AddCommand(
newDebugCommand(globalOptions),
)
}
func newDebugCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "debug",
Short: "Debug commands",
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
}
cmd.AddCommand(newDebugDumpCommand(globalOptions))
cmd.AddCommand(newDebugExamineCommand(globalOptions))
return cmd
}
func newDebugDumpCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "dump [indexes|snapshots|all|packs]",
Short: "Dump data structures",
Long: `
The "dump" command dumps data structures from the repository as JSON objects. It
is used for debugging purposes only.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runDebugDump(cmd.Context(), *globalOptions, args, globalOptions.Term)
},
}
return cmd
}
func newDebugExamineCommand(globalOptions *global.Options) *cobra.Command {
var opts DebugExamineOptions
cmd := &cobra.Command{
Use: "examine pack-ID...",
Short: "Examine a pack file",
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runDebugExamine(cmd.Context(), *globalOptions, opts, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
type DebugExamineOptions struct {
TryRepair bool
RepairByte bool
ExtractPack bool
ReuploadBlobs bool
}
func (opts *DebugExamineOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.ExtractPack, "extract-pack", false, "write blobs to the current directory")
f.BoolVar(&opts.ReuploadBlobs, "reupload-blobs", false, "reupload blobs to the repository")
f.BoolVar(&opts.TryRepair, "try-repair", false, "try to repair broken blobs with single bit flips")
f.BoolVar(&opts.RepairByte, "repair-byte", false, "try to repair broken blobs by trying bytes")
}
func prettyPrintJSON(wr io.Writer, item interface{}) error {
buf, err := json.MarshalIndent(item, "", " ")
if err != nil {
return err
}
_, err = wr.Write(append(buf, '\n'))
return err
}
func debugPrintSnapshots(ctx context.Context, repo *repository.Repository, wr io.Writer) error {
return data.ForAllSnapshots(ctx, repo, repo, nil, func(id restic.ID, snapshot *data.Snapshot, err error) error {
if err != nil {
return err
}
if _, err := fmt.Fprintf(wr, "snapshot_id: %v\n", id); err != nil {
return err
}
return prettyPrintJSON(wr, snapshot)
})
}
// 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)
if len(args) != 1 {
return errors.Fatal("type not specified")
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
tpe := args[0]
switch tpe {
case "indexes":
return 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)
case "all":
printer.S("snapshots:")
err := debugPrintSnapshots(ctx, repo, gopts.Term.OutputWriter())
if err != nil {
return err
}
printer.S("indexes:")
err = dumpIndexes(ctx, repo, gopts.Term.OutputWriter(), printer)
if err != nil {
return err
}
return nil
default:
return errors.Fatalf("no such type %q", tpe)
}
}
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.Blob, 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)
if opts.ExtractPack && gopts.NoLock {
return fmt.Errorf("--extract-pack and --no-lock are mutually exclusive")
}
ctx, repo, unlock, err := openWithAppendLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
ids := make([]restic.ID, 0)
for _, name := range args {
id, err := restic.ParseID(name)
if err != nil {
id, err = restic.Find(ctx, repo, restic.PackFile, name)
if err != nil {
printer.E("error: %v", err)
continue
}
}
ids = append(ids, id)
}
if len(ids) == 0 {
return errors.Fatal("no pack files to examine")
}
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
for _, id := range ids {
err := examinePack(ctx, opts, repo, id, printer)
if err != nil {
printer.E("error: %v", err)
}
if err == context.Canceled {
break
}
}
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.Blob, fileSize int, printer progress.Printer) {
// track current size and offset
var size, offset uint64
sort.Slice(blobs, func(i, j int) bool {
return blobs[i].Offset < blobs[j].Offset
})
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")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_debug_disabled.go | cmd/restic/cmd_debug_disabled.go | //go:build !debug
package main
import (
"github.com/restic/restic/internal/global"
"github.com/spf13/cobra"
)
func registerDebugCommand(_ *cobra.Command, _ *global.Options) {
// No commands to register in non-debug mode
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key_remove.go | cmd/restic/cmd_key_remove.go | package main
import (
"context"
"fmt"
"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"
)
func newKeyRemoveCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "remove [ID]",
Short: "Remove key ID (password) from the repository.",
Long: `
The "remove" sub-command removes the selected key ID. The "remove" command does not allow
removing the current key being used to access the repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runKeyRemove(cmd.Context(), *globalOptions, args, globalOptions.Term)
},
}
return cmd
}
func runKeyRemove(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) != 1 {
return fmt.Errorf("key remove expects one argument as the key id")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
return deleteKey(ctx, repo, args[0], printer)
}
func deleteKey(ctx context.Context, repo *repository.Repository, idPrefix string, printer progress.Printer) error {
id, err := restic.Find(ctx, repo, restic.KeyFile, idPrefix)
if err != nil {
return err
}
if id == repo.KeyID() {
return errors.Fatal("refusing to remove key currently used to access repository")
}
err = repository.RemoveKey(ctx, repo, id)
if err != nil {
return err
}
printer.P("removed key %v", id)
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair.go | cmd/restic/cmd_repair.go | package main
import (
"github.com/restic/restic/internal/global"
"github.com/spf13/cobra"
)
func newRepairCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "repair",
Short: "Repair the repository",
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
}
cmd.AddCommand(
newRepairIndexCommand(globalOptions),
newRepairPacksCommand(globalOptions),
newRepairSnapshotsCommand(globalOptions),
)
return cmd
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_mount_disabled.go | cmd/restic/cmd_mount_disabled.go | //go:build !darwin && !freebsd && !linux
package main
import (
"github.com/restic/restic/internal/global"
"github.com/spf13/cobra"
)
func registerMountCommand(_ *cobra.Command, _ *global.Options) {
// Mount command not supported on these platforms
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_backup_test.go | cmd/restic/cmd_backup_test.go | package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestCollectTargets(t *testing.T) {
dir := rtest.TempDir(t)
fooSpace := "foo "
barStar := "bar*" // Must sort before the others, below.
if runtime.GOOS == "windows" { // Doesn't allow "*" or trailing space.
fooSpace = "foo"
barStar = "bar"
}
var expect []string
for _, filename := range []string{
barStar, "baz", "cmdline arg", fooSpace,
"fromfile", "fromfile-raw", "fromfile-verbatim", "quux",
} {
// All mentioned files must exist for collectTargets.
f, err := os.Create(filepath.Join(dir, filename))
rtest.OK(t, err)
rtest.OK(t, f.Close())
expect = append(expect, f.Name())
}
f1, err := os.Create(filepath.Join(dir, "fromfile"))
rtest.OK(t, err)
// Empty lines should be ignored. A line starting with '#' is a comment.
_, err = fmt.Fprintf(f1, "\n%s*\n # here's a comment\n", f1.Name())
rtest.OK(t, err)
rtest.OK(t, f1.Close())
f2, err := os.Create(filepath.Join(dir, "fromfile-verbatim"))
rtest.OK(t, err)
for _, filename := range []string{fooSpace, barStar} {
// Empty lines should be ignored. CR+LF is allowed.
_, err = fmt.Fprintf(f2, "%s\r\n\n", filepath.Join(dir, filename))
rtest.OK(t, err)
}
rtest.OK(t, f2.Close())
f3, err := os.Create(filepath.Join(dir, "fromfile-raw"))
rtest.OK(t, err)
for _, filename := range []string{"baz", "quux"} {
_, err = fmt.Fprintf(f3, "%s\x00", filepath.Join(dir, filename))
rtest.OK(t, err)
}
rtest.OK(t, err)
rtest.OK(t, f3.Close())
opts := BackupOptions{
FilesFrom: []string{f1.Name()},
FilesFromVerbatim: []string{f2.Name()},
FilesFromRaw: []string{f3.Name()},
}
targets, err := collectTargets(opts, []string{filepath.Join(dir, "cmdline arg")}, t.Logf, nil)
rtest.OK(t, err)
sort.Strings(targets)
rtest.Equals(t, expect, targets)
_, err = collectTargets(opts, []string{filepath.Join(dir, "cmdline arg"), filepath.Join(dir, "non-existing-file")}, t.Logf, nil)
rtest.Assert(t, err == ErrInvalidSourceData, "expected error when not all targets exist")
}
func TestReadFilenamesRaw(t *testing.T) {
// These should all be returned exactly as-is.
expected := []string{
"\xef\xbb\xbf/utf-8-bom",
"/absolute",
"../.././relative",
"\t\t leading and trailing space \t\t",
"newline\nin filename",
"not UTF-8: \x80\xff/simple",
` / *[]* \ `,
}
var buf bytes.Buffer
for _, name := range expected {
buf.WriteString(name)
buf.WriteByte(0)
}
got, err := readFilenamesRaw(&buf)
rtest.OK(t, err)
rtest.Equals(t, expected, got)
// Empty input is ok.
got, err = readFilenamesRaw(strings.NewReader(""))
rtest.OK(t, err)
rtest.Equals(t, 0, len(got))
// An empty filename is an error.
_, err = readFilenamesRaw(strings.NewReader("foo\x00\x00"))
rtest.Assert(t, err != nil, "no error for zero byte")
rtest.Assert(t, strings.Contains(err.Error(), "empty filename"),
"wrong error message: %v", err.Error())
// No trailing NUL byte is an error, because it likely means we're
// reading a line-oriented text file (someone forgot -print0).
_, err = readFilenamesRaw(strings.NewReader("simple.txt"))
rtest.Assert(t, err != nil, "no error for zero byte")
rtest.Assert(t, strings.Contains(err.Error(), "zero byte"),
"wrong error message: %v", err.Error())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_rewrite.go | cmd/restic/cmd_rewrite.go | package main
import (
"context"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/filter"
"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/restic/restic/internal/walker"
)
func newRewriteCommand(globalOptions *global.Options) *cobra.Command {
var opts RewriteOptions
cmd := &cobra.Command{
Use: "rewrite [flags] [snapshotID ...]",
Short: "Rewrite snapshots to exclude unwanted files",
Long: `
The "rewrite" command excludes files from existing snapshots. It creates new
snapshots containing the same data as the original ones, but without the files
you specify to exclude. All metadata (time, host, tags) will be preserved.
The snapshots to rewrite are specified using the --host, --tag and --path options,
or by providing a list of snapshot IDs. Please note that specifying neither any of
these options nor a snapshot ID will cause the command to rewrite all snapshots.
The special tag 'rewrite' will be added to the new snapshots to distinguish
them from the original ones, unless --forget is used. If the --forget option is
used, the original snapshots will instead be directly removed from the repository.
Please note that the --forget option only removes the snapshots and not the actual
data stored in the repository. In order to delete the no longer referenced data,
use the "prune" command.
When rewrite is used with the --snapshot-summary option, a new snapshot is
created containing statistics summary data. Only two fields in the summary will
be non-zero: TotalFilesProcessed and TotalBytesProcessed.
When rewrite is called with one of the --exclude options, TotalFilesProcessed
and TotalBytesProcessed will be updated in the snapshot summary.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runRewrite(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
type snapshotMetadata struct {
Hostname string
Time *time.Time
}
type snapshotMetadataArgs struct {
Hostname string
Time string
}
func (sma snapshotMetadataArgs) empty() bool {
return sma.Hostname == "" && sma.Time == ""
}
func (sma snapshotMetadataArgs) convert() (*snapshotMetadata, error) {
if sma.empty() {
return nil, nil
}
var timeStamp *time.Time
if sma.Time != "" {
t, err := time.ParseInLocation(global.TimeFormat, sma.Time, time.Local)
if err != nil {
return nil, errors.Fatalf("error in time option: %v", err)
}
timeStamp = &t
}
return &snapshotMetadata{Hostname: sma.Hostname, Time: timeStamp}, nil
}
// RewriteOptions collects all options for the rewrite command.
type RewriteOptions struct {
Forget bool
DryRun bool
SnapshotSummary bool
Metadata snapshotMetadataArgs
data.SnapshotFilter
filter.ExcludePatternOptions
}
func (opts *RewriteOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVarP(&opts.Forget, "forget", "", false, "remove original snapshots after creating new ones")
f.BoolVarP(&opts.DryRun, "dry-run", "n", false, "do not do anything, just print what would be done")
f.StringVar(&opts.Metadata.Hostname, "new-host", "", "replace hostname")
f.StringVar(&opts.Metadata.Time, "new-time", "", "replace time of the backup")
f.BoolVarP(&opts.SnapshotSummary, "snapshot-summary", "s", false, "create snapshot summary record if it does not exist")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
opts.ExcludePatternOptions.Add(f)
}
// rewriteFilterFunc returns the filtered tree ID or an error. If a snapshot summary is returned, the snapshot will
// 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) {
if sn.Tree == nil {
return false, errors.Errorf("snapshot %v has nil tree", sn.ID().Str())
}
rejectByNameFuncs, err := opts.ExcludePatternOptions.CollectPatterns(printer.E)
if err != nil {
return false, err
}
metadata, err := opts.Metadata.convert()
if err != nil {
return false, err
}
var filter rewriteFilterFunc
if len(rejectByNameFuncs) > 0 || opts.SnapshotSummary {
selectByName := func(nodepath string) bool {
for _, reject := range rejectByNameFuncs {
if reject(nodepath) {
return false
}
}
return true
}
rewriteNode := func(node *data.Node, path string) *data.Node {
if selectByName(path) {
return node
}
printer.P("excluding %s", path)
return nil
}
rewriter, querySize := walker.NewSnapshotSizeRewriter(rewriteNode)
filter = func(ctx context.Context, sn *data.Snapshot, uploader restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error) {
id, err := rewriter.RewriteTree(ctx, repo, uploader, "/", *sn.Tree)
if err != nil {
return restic.ID{}, nil, err
}
ss := querySize()
summary := &data.SnapshotSummary{}
if sn.Summary != nil {
*summary = *sn.Summary
}
summary.TotalFilesProcessed = ss.FileCount
summary.TotalBytesProcessed = ss.FileSize
return id, summary, err
}
} else {
filter = func(_ context.Context, sn *data.Snapshot, _ restic.BlobSaver) (restic.ID, *data.SnapshotSummary, error) {
return *sn.Tree, nil, nil
}
}
return filterAndReplaceSnapshot(ctx, repo, sn,
filter, opts.DryRun, opts.Forget, metadata, "rewrite", printer)
}
func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *data.Snapshot,
filter rewriteFilterFunc, dryRun bool, forget bool, newMetadata *snapshotMetadata, addTag string, printer progress.Printer) (bool, error) {
var filteredTree restic.ID
var summary *data.SnapshotSummary
err := repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
var err error
filteredTree, summary, err = filter(ctx, sn, uploader)
return err
})
if err != nil {
return false, err
}
if filteredTree.IsNull() {
if dryRun {
printer.P("would delete empty snapshot")
} else {
if err = repo.RemoveUnpacked(ctx, restic.WriteableSnapshotFile, *sn.ID()); err != nil {
return false, err
}
debug.Log("removed empty snapshot %v", sn.ID())
printer.P("removed empty snapshot %v", sn.ID().Str())
}
return true, nil
}
matchingSummary := true
if summary != nil {
matchingSummary = sn.Summary != nil && *summary == *sn.Summary
}
if filteredTree == *sn.Tree && newMetadata == nil && matchingSummary {
debug.Log("Snapshot %v not modified", sn)
return false, nil
}
debug.Log("Snapshot %v modified", sn)
if dryRun {
printer.P("would save new snapshot")
if forget {
printer.P("would remove old snapshot")
}
if newMetadata != nil && newMetadata.Time != nil {
printer.P("would set time to %s", newMetadata.Time)
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("would set hostname to %s", newMetadata.Hostname)
}
return true, nil
}
// Always set the original snapshot id as this essentially a new snapshot.
sn.Original = sn.ID()
sn.Tree = &filteredTree
if summary != nil {
sn.Summary = summary
}
if !forget {
sn.AddTags([]string{addTag})
}
if newMetadata != nil && newMetadata.Time != nil {
printer.P("setting time to %s", *newMetadata.Time)
sn.Time = *newMetadata.Time
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("setting host to %s", newMetadata.Hostname)
sn.Hostname = newMetadata.Hostname
}
// Save the new snapshot.
id, err := data.SaveSnapshot(ctx, repo, sn)
if err != nil {
return false, err
}
printer.P("saved new snapshot %v", id.Str())
if forget {
if err = repo.RemoveUnpacked(ctx, restic.WriteableSnapshotFile, *sn.ID()); err != nil {
return false, err
}
debug.Log("removed old snapshot %v", sn.ID())
printer.P("removed old snapshot %v", sn.ID().Str())
}
return true, nil
}
func runRewrite(ctx context.Context, opts RewriteOptions, gopts global.Options, args []string, term ui.Terminal) error {
if !opts.SnapshotSummary && opts.ExcludePatternOptions.Empty() && opts.Metadata.empty() {
return errors.Fatal("Nothing to do: no excludes provided and no new metadata provided")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
var (
repo *repository.Repository
unlock func()
err error
)
if opts.Forget {
printer.P("create exclusive lock for repository")
ctx, repo, unlock, err = openWithExclusiveLock(ctx, gopts, opts.DryRun, printer)
} else {
ctx, repo, unlock, err = openWithAppendLock(ctx, gopts, opts.DryRun, printer)
}
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
changedCount := 0
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
printer.P("\n%v", sn)
changed, err := rewriteSnapshot(ctx, repo, sn, opts, printer)
if err != nil {
return errors.Fatalf("unable to rewrite snapshot ID %q: %v", sn.ID().Str(), err)
}
if changed {
changedCount++
}
}
if ctx.Err() != nil {
return ctx.Err()
}
printer.P("")
if changedCount == 0 {
if !opts.DryRun {
printer.P("no snapshots were modified")
} else {
printer.P("no snapshots would be modified")
}
} else {
if !opts.DryRun {
printer.P("modified %v snapshots", changedCount)
} else {
printer.P("would modify %v snapshots", changedCount)
}
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_generate.go | cmd/restic/cmd_generate.go | package main
import (
"io"
"os"
"time"
"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/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/spf13/pflag"
)
func newGenerateCommand(globalOptions *global.Options) *cobra.Command {
var opts generateOptions
cmd := &cobra.Command{
Use: "generate [flags]",
Short: "Generate manual pages and auto-completion files (bash, fish, zsh, powershell)",
Long: `
The "generate" command writes automatically generated files (like the man pages
and the auto-completion files for bash, fish and zsh).
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
return runGenerate(opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
type generateOptions struct {
ManDir string
BashCompletionFile string
FishCompletionFile string
ZSHCompletionFile string
PowerShellCompletionFile string
}
func (opts *generateOptions) AddFlags(f *pflag.FlagSet) {
f.StringVar(&opts.ManDir, "man", "", "write man pages to `directory`")
f.StringVar(&opts.BashCompletionFile, "bash-completion", "", "write bash completion `file` (`-` for stdout)")
f.StringVar(&opts.FishCompletionFile, "fish-completion", "", "write fish completion `file` (`-` for stdout)")
f.StringVar(&opts.ZSHCompletionFile, "zsh-completion", "", "write zsh completion `file` (`-` for stdout)")
f.StringVar(&opts.PowerShellCompletionFile, "powershell-completion", "", "write powershell completion `file` (`-` for stdout)")
}
func writeManpages(root *cobra.Command, dir string, printer progress.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 {
return err
}
header := &doc.GenManHeader{
Title: "restic backup",
Section: "1",
Source: "generated by `restic generate`",
Date: &date,
}
printer.P("writing man pages to directory %v", dir)
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) {
printer.PT("writing %s completion file to %v", shell, filename)
var outWriter io.Writer
if filename != "-" {
var outFile *os.File
outFile, err = os.Create(filename)
if err != nil {
return
}
defer func() { err = outFile.Close() }()
outWriter = outFile
} else {
outWriter = gopts.Term.OutputWriter()
}
err = generate(outWriter)
return
}
func checkStdoutForSingleShell(opts generateOptions) error {
completionFileOpts := []string{
opts.BashCompletionFile,
opts.FishCompletionFile,
opts.ZSHCompletionFile,
opts.PowerShellCompletionFile,
}
seenIsStdout := false
for _, completionFileOpt := range completionFileOpts {
if completionFileOpt == "-" {
if seenIsStdout {
return errors.Fatal("the generate command can generate shell completions to stdout for single shell only")
}
seenIsStdout = true
}
}
return nil
}
func runGenerate(opts generateOptions, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) > 0 {
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)
cmdRoot := newRootCommand(&global.Options{})
if opts.ManDir != "" {
err := writeManpages(cmdRoot, opts.ManDir, printer)
if err != nil {
return err
}
}
err := checkStdoutForSingleShell(opts)
if err != nil {
return err
}
if opts.BashCompletionFile != "" {
err := writeCompletion(opts.BashCompletionFile, "bash", cmdRoot.GenBashCompletion, printer, gopts)
if err != nil {
return err
}
}
if opts.FishCompletionFile != "" {
err := writeCompletion(opts.FishCompletionFile, "fish", func(w io.Writer) error { return cmdRoot.GenFishCompletion(w, true) }, printer, gopts)
if err != nil {
return err
}
}
if opts.ZSHCompletionFile != "" {
err := writeCompletion(opts.ZSHCompletionFile, "zsh", cmdRoot.GenZshCompletion, printer, gopts)
if err != nil {
return err
}
}
if opts.PowerShellCompletionFile != "" {
err := writeCompletion(opts.PowerShellCompletionFile, "powershell", cmdRoot.GenPowerShellCompletion, printer, gopts)
if err != nil {
return err
}
}
var empty generateOptions
if opts == empty {
return errors.Fatal("nothing to do, please specify at least one output file/dir")
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/integration_helpers_test.go | cmd/restic/integration_helpers_test.go | package main
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/backend/all"
"github.com/restic/restic/internal/backend/retry"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/options"
"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/termstatus"
)
type dirEntry struct {
path string
fi os.FileInfo
link uint64
}
func walkDir(t testing.TB, dir string) <-chan *dirEntry {
ch := make(chan *dirEntry, 100)
go func() {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
t.Logf("error: %v\n", err)
return nil
}
name, err := filepath.Rel(dir, path)
if err != nil {
t.Logf("error: %v\n", err)
return nil
}
ch <- &dirEntry{
path: name,
fi: info,
link: nlink(info),
}
return nil
})
if err != nil {
t.Logf("Walk() error: %v\n", err)
}
close(ch)
}()
// first element is root
<-ch
return ch
}
func isSymlink(fi os.FileInfo) bool {
mode := fi.Mode() & (os.ModeType | os.ModeCharDevice)
return mode == os.ModeSymlink
}
func sameModTime(fi1, fi2 os.FileInfo) bool {
switch runtime.GOOS {
case "darwin", "freebsd", "openbsd", "netbsd", "solaris":
if isSymlink(fi1) && isSymlink(fi2) {
return true
}
}
return fi1.ModTime().Equal(fi2.ModTime())
}
// directoriesContentsDiff returns a diff between both directories. If these
// contain exactly the same contents, then the diff is an empty string.
func directoriesContentsDiff(t testing.TB, dir1, dir2 string) string {
var out bytes.Buffer
ch1 := walkDir(t, dir1)
ch2 := walkDir(t, dir2)
var a, b *dirEntry
for {
var ok bool
if ch1 != nil && a == nil {
a, ok = <-ch1
if !ok {
ch1 = nil
}
}
if ch2 != nil && b == nil {
b, ok = <-ch2
if !ok {
ch2 = nil
}
}
if ch1 == nil && ch2 == nil {
break
}
if ch1 == nil {
fmt.Fprintf(&out, "+%v\n", b.path)
} else if ch2 == nil {
fmt.Fprintf(&out, "-%v\n", a.path)
} else if !a.equals(&out, b) {
if a.path < b.path {
fmt.Fprintf(&out, "-%v\n", a.path)
a = nil
continue
} else if a.path > b.path {
fmt.Fprintf(&out, "+%v\n", b.path)
b = nil
continue
}
fmt.Fprintf(&out, "%%%v\n", a.path)
}
a, b = nil, nil
}
return out.String()
}
type dirStat struct {
files, dirs, other uint
size uint64
}
func isFile(fi os.FileInfo) bool {
return fi.Mode()&(os.ModeType|os.ModeCharDevice) == 0
}
// dirStats walks dir and collects stats.
func dirStats(t testing.TB, dir string) (stat dirStat) {
for entry := range walkDir(t, dir) {
if isFile(entry.fi) {
stat.files++
stat.size += uint64(entry.fi.Size())
continue
}
if entry.fi.IsDir() {
stat.dirs++
continue
}
stat.other++
}
return stat
}
type testEnvironment struct {
base, cache, repo, mountpoint, testdata string
gopts global.Options
}
type logOutputter struct {
t testing.TB
}
func (l *logOutputter) Write(p []byte) (n int, err error) {
l.t.Helper()
l.t.Log(strings.TrimSuffix(string(p), "\n"))
return len(p), nil
}
// withTestEnvironment creates a test environment and returns a cleanup
// function which removes it.
func withTestEnvironment(t testing.TB) (env *testEnvironment, cleanup func()) {
if !rtest.RunIntegrationTest {
t.Skip("integration tests disabled")
}
repository.TestUseLowSecurityKDFParameters(t)
restic.TestDisableCheckPolynomial(t)
retry.TestFastRetries(t)
tempdir, err := os.MkdirTemp(rtest.TestTempDir, "restic-test-")
rtest.OK(t, err)
env = &testEnvironment{
base: tempdir,
cache: filepath.Join(tempdir, "cache"),
repo: filepath.Join(tempdir, "repo"),
testdata: filepath.Join(tempdir, "testdata"),
mountpoint: filepath.Join(tempdir, "mount"),
}
rtest.OK(t, os.MkdirAll(env.mountpoint, 0700))
rtest.OK(t, os.MkdirAll(env.testdata, 0700))
rtest.OK(t, os.MkdirAll(env.cache, 0700))
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),
// 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 },
// start with default set of backends
Backends: all.Backends(),
}
cleanup = func() {
if !rtest.TestCleanupTempDirs {
t.Logf("leaving temporary directory %v used for test", tempdir)
return
}
rtest.RemoveAll(t, tempdir)
}
return env, cleanup
}
func testSetupBackupData(t testing.TB, env *testEnvironment) string {
datafile := filepath.Join("testdata", "backup-data.tar.gz")
testRunInit(t, env.gopts)
rtest.SetupTarTestFixture(t, env.testdata, datafile)
return datafile
}
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)
ctx, r, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
packs = restic.NewIDSet()
return r.List(ctx, restic.PackFile, func(id restic.ID, size int64) error {
packs.Insert(id)
return nil
})
})
rtest.OK(t, err)
return packs
}
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)
ctx, r, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
rtest.OK(t, r.LoadIndex(ctx, nil))
treePacks = restic.NewIDSet()
return r.ListBlobs(ctx, func(pb restic.PackedBlob) {
if pb.Type == restic.TreeBlob {
treePacks.Insert(pb.PackID)
}
})
})
rtest.OK(t, err)
return treePacks
}
func captureBackend(gopts *global.Options) func() backend.Backend {
var be backend.Backend
gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
be = r
return r, nil
}
return func() backend.Backend {
return be
}
}
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)
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()}))
}
return nil
})
rtest.OK(t, err)
}
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)
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))
treePacks := restic.NewIDSet()
rtest.OK(t, r.ListBlobs(ctx, func(pb restic.PackedBlob) {
if pb.Type == restic.TreeBlob {
treePacks.Insert(pb.PackID)
}
}))
// remove all packs containing data blobs
return r.List(ctx, restic.PackFile, func(id restic.ID, size int64) error {
if treePacks.Has(id) != removeTreePacks || keep.Has(id) {
return nil
}
return be().Remove(ctx, backend.Handle{Type: restic.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
}
func loadSnapshotMap(t testing.TB, gopts global.Options) map[string]struct{} {
snapshotIDs := testRunList(t, gopts, "snapshots")
m := make(map[string]struct{})
for _, id := range snapshotIDs {
m[id.String()] = struct{}{}
}
return m
}
func lastSnapshot(old, new map[string]struct{}) (map[string]struct{}, string) {
for k := range new {
if _, ok := old[k]; !ok {
old[k] = struct{}{}
return old, k
}
}
return old, ""
}
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)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
rtest.OK(t, err)
defer unlock()
snapshot, err = data.LoadSnapshot(ctx, repo, id)
return err
})
rtest.OK(t, err)
return snapshot
}
func appendRandomData(filename string, bytes uint) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = f.Seek(0, 2)
if err != nil {
return err
}
_, err = io.Copy(f, io.LimitReader(rand.Reader, int64(bytes)))
if err != nil {
return err
}
return f.Close()
}
func testFileSize(filename string, size int64) error {
fi, err := os.Stat(filename)
if err != nil {
return err
}
if fi.Size() != size {
return errors.Fatalf("wrong file size for %v: expected %v, got %v", filename, size, fi.Size())
}
return nil
}
func withCaptureStdout(t testing.TB, gopts global.Options, callback func(ctx context.Context, gopts global.Options) error) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
err := withTermStatusRaw(os.Stdin, buf, &logOutputter{t: t}, gopts, callback)
return buf, 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
// by t.Log.
return withTermStatusRaw(os.Stdin, &logOutputter{t: t}, &logOutputter{t: t}, gopts, callback)
}
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)
gopts.Term = term
wg.Add(1)
go func() {
defer wg.Done()
term.Run(ctx)
}()
defer wg.Wait()
defer cancel()
return callback(ctx, gopts)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair_index_integration_test.go | cmd/restic/cmd_repair_index_integration_test.go | package main
import (
"context"
"io"
"path/filepath"
"strings"
"sync"
"testing"
"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/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunRebuildIndex(t testing.TB, gopts global.Options) {
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.Quiet = true
return runRebuildIndex(context.TODO(), RepairIndexOptions{}, gopts, gopts.Term)
}))
}
func testRebuildIndex(t *testing.T, backendTestHook global.BackendWrapper) {
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)
if !strings.Contains(out, "contained in several indexes") {
t.Fatalf("did not find checker hint for packs in several indexes")
}
if err != nil {
t.Fatalf("expected no error from checker for test repository, got %v", err)
}
if !strings.Contains(out, "restic repair index") {
t.Fatalf("did not find hint for repair index command")
}
env.gopts.BackendTestHook = backendTestHook
testRunRebuildIndex(t, env.gopts)
env.gopts.BackendTestHook = nil
out, err = testRunCheckOutput(t, env.gopts, false)
if len(out) != 0 {
t.Fatalf("expected no output from the checker, got: %v", out)
}
if err != nil {
t.Fatalf("expected no error from checker after repair index, got: %v", err)
}
}
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
lock sync.Mutex
hasErred bool
}
func (b *indexErrorBackend) Load(ctx context.Context, h backend.Handle, length int, offset int64, consumer func(rd io.Reader) error) error {
return b.Backend.Load(ctx, h, length, offset, func(rd io.Reader) error {
// protect hasErred
b.lock.Lock()
defer b.lock.Unlock()
if !b.hasErred && h.Type == restic.IndexFile {
b.hasErred = true
return consumer(errorReadCloser{rd})
}
return consumer(rd)
})
}
type errorReadCloser struct {
io.Reader
}
func (erd errorReadCloser) Read(p []byte) (int, error) {
n, err := erd.Reader.Read(p)
if n > 0 {
p[0] ^= 1
}
return n, err
}
func TestRebuildIndexDamage(t *testing.T) {
testRebuildIndex(t, func(r backend.Backend) (backend.Backend, error) {
return &indexErrorBackend{
Backend: r,
}, nil
})
}
type appendOnlyBackend struct {
backend.Backend
}
// called via repo.Backend().Remove()
func (b *appendOnlyBackend) Remove(_ context.Context, h backend.Handle) error {
return errors.Errorf("Failed to remove %v", h)
}
func TestRebuildIndexFailsOnAppendOnly(t *testing.T) {
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)
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
return &appendOnlyBackend{r}, nil
}
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
gopts.Quiet = true
return runRebuildIndex(context.TODO(), RepairIndexOptions{}, gopts, gopts.Term)
})
if err == nil {
t.Error("expected rebuildIndex to fail")
}
t.Log(err)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair_snapshots_integration_test.go | cmd/restic/cmd_repair_snapshots_integration_test.go | package main
import (
"context"
"hash/fnv"
"io"
"math/rand"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunRepairSnapshot(t testing.TB, gopts global.Options, forget bool) {
opts := RepairOptions{
Forget: forget,
}
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRepairSnapshots(context.TODO(), gopts, opts, nil, gopts.Term)
}))
}
func createRandomFile(t testing.TB, env *testEnvironment, path string, size int) {
fn := filepath.Join(env.testdata, path)
rtest.OK(t, os.MkdirAll(filepath.Dir(fn), 0o755))
h := fnv.New64()
_, err := h.Write([]byte(path))
rtest.OK(t, err)
r := rand.New(rand.NewSource(int64(h.Sum64())))
f, err := os.OpenFile(fn, os.O_CREATE|os.O_RDWR, 0o644)
rtest.OK(t, err)
_, err = io.Copy(f, io.LimitReader(r, int64(size)))
rtest.OK(t, err)
rtest.OK(t, f.Close())
}
func TestRepairSnapshotsWithLostData(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
createRandomFile(t, env, "foo/bar/file", 512*1024)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
testListSnapshots(t, env.gopts, 1)
// damage repository
removePacksExcept(env.gopts, t, restic.NewIDSet(), false)
createRandomFile(t, env, "foo/bar/file2", 256*1024)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 2)
testRunCheckMustFail(t, env.gopts)
// repair but keep broken snapshots
testRunRebuildIndex(t, env.gopts)
testRunRepairSnapshot(t, env.gopts, false)
testListSnapshots(t, env.gopts, 4)
testRunCheckMustFail(t, env.gopts)
// 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)
rtest.OK(t, err)
}
func TestRepairSnapshotsWithLostTree(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
createRandomFile(t, env, "foo/bar/file", 12345)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
oldSnapshot := testListSnapshots(t, env.gopts, 1)
oldPacks := testRunList(t, env.gopts, "packs")
// keep foo/bar unchanged
createRandomFile(t, env, "foo/bar2", 1024)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
testListSnapshots(t, env.gopts, 2)
// remove tree for foo/bar and the now completely broken first snapshot
removePacks(env.gopts, t, restic.NewIDSet(oldPacks...))
testRunForget(t, env.gopts, ForgetOptions{}, oldSnapshot[0].String())
testRunCheckMustFail(t, env.gopts)
// repair
testRunRebuildIndex(t, env.gopts)
testRunRepairSnapshot(t, env.gopts, true)
testListSnapshots(t, env.gopts, 1)
_, err := testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
func TestRepairSnapshotsWithLostRootTree(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
createRandomFile(t, env, "foo/bar/file", 12345)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
testListSnapshots(t, env.gopts, 1)
oldPacks := testRunList(t, env.gopts, "packs")
// remove all trees
removePacks(env.gopts, t, restic.NewIDSet(oldPacks...))
testRunCheckMustFail(t, env.gopts)
// repair
testRunRebuildIndex(t, env.gopts)
testRunRepairSnapshot(t, env.gopts, true)
testListSnapshots(t, env.gopts, 0)
_, err := testRunCheckOutput(t, env.gopts, false)
rtest.OK(t, err)
}
func TestRepairSnapshotsIntact(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{}, env.gopts)
oldSnapshotIDs := testListSnapshots(t, env.gopts, 1)
// use an exclude that will not exclude anything
testRunRepairSnapshot(t, env.gopts, false)
snapshotIDs := testListSnapshots(t, env.gopts, 1)
rtest.Assert(t, reflect.DeepEqual(oldSnapshotIDs, snapshotIDs), "unexpected snapshot id mismatch %v vs. %v", oldSnapshotIDs, snapshotIDs)
testRunCheck(t, env.gopts)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_find_integration_test.go | cmd/restic/cmd_find_integration_test.go | package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunFind(t testing.TB, wantJSON bool, opts FindOptions, gopts global.Options, pattern string) []byte {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = wantJSON
return runFind(ctx, opts, gopts, []string{pattern}, gopts.Term)
})
rtest.OK(t, err)
return buf.Bytes()
}
func TestFind(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
results := testRunFind(t, false, FindOptions{}, env.gopts, "unexistingfile")
rtest.Assert(t, len(results) == 0, "unexisting file found in repo (%v)", datafile)
results = testRunFind(t, false, FindOptions{}, env.gopts, "testfile")
lines := strings.Split(string(results), "\n")
rtest.Assert(t, len(lines) == 2, "expected one file found in repo (%v)", datafile)
results = testRunFind(t, false, FindOptions{}, env.gopts, "testfile*")
lines = strings.Split(string(results), "\n")
rtest.Assert(t, len(lines) == 4, "expected three files found in repo (%v)", datafile)
}
type testMatch struct {
Path string `json:"path,omitempty"`
Permissions string `json:"permissions,omitempty"`
Size uint64 `json:"size,omitempty"`
Date time.Time `json:"date,omitempty"`
UID uint32 `json:"uid,omitempty"`
GID uint32 `json:"gid,omitempty"`
}
type testMatches struct {
Hits int `json:"hits,omitempty"`
SnapshotID string `json:"snapshot,omitempty"`
Matches []testMatch `json:"matches,omitempty"`
}
func TestFindJSON(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
testRunCheck(t, env.gopts)
snapshot, _ := testRunSnapshots(t, env.gopts)
results := testRunFind(t, true, FindOptions{}, env.gopts, "unexistingfile")
matches := []testMatches{}
rtest.OK(t, json.Unmarshal(results, &matches))
rtest.Assert(t, len(matches) == 0, "expected no match in repo (%v)", datafile)
results = testRunFind(t, true, FindOptions{}, env.gopts, "testfile")
rtest.OK(t, json.Unmarshal(results, &matches))
rtest.Assert(t, len(matches) == 1, "expected a single snapshot in repo (%v)", datafile)
rtest.Assert(t, len(matches[0].Matches) == 1, "expected a single file to match (%v)", datafile)
rtest.Assert(t, matches[0].Hits == 1, "expected hits to show 1 match (%v)", datafile)
results = testRunFind(t, true, FindOptions{}, env.gopts, "testfile*")
rtest.OK(t, json.Unmarshal(results, &matches))
rtest.Assert(t, len(matches) == 1, "expected a single snapshot in repo (%v)", datafile)
rtest.Assert(t, len(matches[0].Matches) == 3, "expected 3 files to match (%v)", datafile)
rtest.Assert(t, matches[0].Hits == 3, "expected hits to show 3 matches (%v)", datafile)
results = testRunFind(t, true, FindOptions{TreeID: true}, env.gopts, snapshot.Tree.String())
rtest.OK(t, json.Unmarshal(results, &matches))
rtest.Assert(t, len(matches) == 1, "expected a single snapshot in repo (%v)", matches)
rtest.Assert(t, len(matches[0].Matches) == 3, "expected 3 files to match (%v)", matches[0].Matches)
rtest.Assert(t, matches[0].Hits == 3, "expected hits to show 3 matches (%v)", datafile)
}
func TestFindSorting(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
// first backup
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
sn1 := testListSnapshots(t, env.gopts, 1)[0]
// second backup
testRunBackup(t, "", []string{env.testdata}, opts, env.gopts)
snapshots := testListSnapshots(t, env.gopts, 2)
// get id of new snapshot without depending on file order returned by filesystem
sn2 := snapshots[0]
if sn1.Equal(sn2) {
sn2 = snapshots[1]
}
// first restic find - with default FindOptions{}
results := testRunFind(t, true, FindOptions{}, env.gopts, "testfile")
lines := strings.Split(string(results), "\n")
rtest.Assert(t, len(lines) == 2, "expected two lines of output, found %d", len(lines))
matches := []testMatches{}
rtest.OK(t, json.Unmarshal(results, &matches))
// run second restic find with --reverse, sort oldest to newest
resultsReverse := testRunFind(t, true, FindOptions{Reverse: true}, env.gopts, "testfile")
lines = strings.Split(string(resultsReverse), "\n")
rtest.Assert(t, len(lines) == 2, "expected two lines of output, found %d", len(lines))
matchesReverse := []testMatches{}
rtest.OK(t, json.Unmarshal(resultsReverse, &matchesReverse))
// compare result sets
rtest.Assert(t, sn1.String() == matchesReverse[0].SnapshotID, "snapshot[0] must match old snapshot")
rtest.Assert(t, sn2.String() == matchesReverse[1].SnapshotID, "snapshot[1] must match new snapshot")
rtest.Assert(t, matches[0].SnapshotID == matchesReverse[1].SnapshotID, "matches should be sorted 1")
rtest.Assert(t, matches[1].SnapshotID == matchesReverse[0].SnapshotID, "matches should be sorted 2")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair_snapshots.go | cmd/restic/cmd_repair_snapshots.go | package main
import (
"context"
"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/walker"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newRepairSnapshotsCommand(globalOptions *global.Options) *cobra.Command {
var opts RepairOptions
cmd := &cobra.Command{
Use: "snapshots [flags] [snapshot ID] [...]",
Short: "Repair snapshots",
Long: `
The "repair snapshots" command repairs broken snapshots. It scans the given
snapshots and generates new ones with damaged directories and file contents
removed. If the broken snapshots are deleted, a prune run will be able to
clean up the repository.
The command depends on a correct index, thus make sure to run "repair index"
first!
WARNING
=======
Repairing and deleting broken snapshots causes data loss! It will remove broken
directories and modify broken files in the modified snapshots.
If the contents of directories and files are still available, the better option
is to run "backup" which in that case is able to heal existing snapshots. Only
use the "repair snapshots" command if you need to recover an old and broken
snapshot!
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runRepairSnapshots(cmd.Context(), *globalOptions, opts, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// RepairOptions collects all options for the repair command.
type RepairOptions struct {
DryRun bool
Forget bool
data.SnapshotFilter
}
func (opts *RepairOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVarP(&opts.DryRun, "dry-run", "n", false, "do not do anything, just print what would be done")
f.BoolVarP(&opts.Forget, "forget", "", false, "remove original snapshots after creating new ones")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
func runRepairSnapshots(ctx context.Context, gopts global.Options, opts RepairOptions, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun, printer)
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
if err := repo.LoadIndex(ctx, printer); err != nil {
return err
}
// Three 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)
rewriter := walker.NewTreeRewriter(walker.RewriteOpts{
RewriteNode: func(node *data.Node, path string) *data.Node {
if node.Type == data.NodeTypeIrregular || node.Type == data.NodeTypeInvalid {
printer.P(" file %q: removed node with invalid type %q", path, node.Type)
return nil
}
if node.Type != data.NodeTypeFile {
return node
}
ok := true
var newContent = restic.IDs{}
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 {
ok = false
} else {
newContent = append(newContent, id)
newSize += uint64(size)
}
}
if !ok {
printer.P(" file %q: removed missing content", path)
} else if newSize != node.Size {
printer.P(" file %q: fixed incorrect size", path)
}
// no-ops if already correct
node.Content = newContent
node.Size = newSize
return node
},
RewriteFailedTree: func(_ restic.ID, path string, _ error) (*data.Tree, error) {
if path == "/" {
printer.P(" dir %q: not readable", path)
// remove snapshots with invalid root node
return nil, nil
}
// If a subtree fails to load, remove it
printer.P(" dir %q: replaced with empty directory", path)
return &data.Tree{}, nil
},
AllowUnstableSerialization: true,
})
changedCount := 0
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
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) {
id, err := rewriter.RewriteTree(ctx, repo, uploader, "/", *sn.Tree)
return id, nil, err
}, opts.DryRun, opts.Forget, nil, "repaired", printer)
if err != nil {
return errors.Fatalf("unable to rewrite snapshot ID %q: %v", sn.ID().Str(), err)
}
if changed {
changedCount++
}
}
if ctx.Err() != nil {
return ctx.Err()
}
printer.P("")
if changedCount == 0 {
if !opts.DryRun {
printer.P("no snapshots were modified")
} else {
printer.P("no snapshots would be modified")
}
} else {
if !opts.DryRun {
printer.P("modified %v snapshots", changedCount)
} else {
printer.P("would modify %v snapshots", changedCount)
}
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_tag_integration_test.go | cmd/restic/cmd_tag_integration_test.go | package main
import (
"context"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunTag(t testing.TB, opts TagOptions, gopts global.Options) {
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runTag(context.TODO(), opts, gopts, gopts.Term, []string{})
}))
}
func TestTag(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ := testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a new backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 0,
"expected no tags, got %v", newest.Tags)
rtest.Assert(t, newest.Original == nil,
"expected original ID to be nil, got %v", newest.Original)
originalID := *newest.ID
testRunTag(t, TagOptions{SetTags: data.TagLists{[]string{"NL"}}}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 1 && newest.Tags[0] == "NL",
"set failed, expected one NL tag, got %v", newest.Tags)
rtest.Assert(t, newest.Original != nil, "expected original snapshot id, got nil")
rtest.Assert(t, *newest.Original == originalID,
"expected original ID to be set to the first snapshot id")
testRunTag(t, TagOptions{AddTags: data.TagLists{[]string{"CH"}}}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 2 && newest.Tags[0] == "NL" && newest.Tags[1] == "CH",
"add failed, expected CH,NL tags, got %v", newest.Tags)
rtest.Assert(t, newest.Original != nil, "expected original snapshot id, got nil")
rtest.Assert(t, *newest.Original == originalID,
"expected original ID to be set to the first snapshot id")
testRunTag(t, TagOptions{RemoveTags: data.TagLists{[]string{"NL"}}}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 1 && newest.Tags[0] == "CH",
"remove failed, expected one CH tag, got %v", newest.Tags)
rtest.Assert(t, newest.Original != nil, "expected original snapshot id, got nil")
rtest.Assert(t, *newest.Original == originalID,
"expected original ID to be set to the first snapshot id")
testRunTag(t, TagOptions{AddTags: data.TagLists{[]string{"US", "RU"}}}, env.gopts)
testRunTag(t, TagOptions{RemoveTags: data.TagLists{[]string{"CH", "US", "RU"}}}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 0,
"expected no tags, got %v", newest.Tags)
rtest.Assert(t, newest.Original != nil, "expected original snapshot id, got nil")
rtest.Assert(t, *newest.Original == originalID,
"expected original ID to be set to the first snapshot id")
// Check special case of removing all tags.
testRunTag(t, TagOptions{SetTags: data.TagLists{[]string{""}}}, env.gopts)
testRunCheck(t, env.gopts)
newest, _ = testRunSnapshots(t, env.gopts)
if newest == nil {
t.Fatal("expected a backup, got nil")
}
rtest.Assert(t, len(newest.Tags) == 0,
"expected no tags, got %v", newest.Tags)
rtest.Assert(t, newest.Original != nil, "expected original snapshot id, got nil")
rtest.Assert(t, *newest.Original == originalID,
"expected original ID to be set to the first snapshot id")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/integration_filter_pattern_test.go | cmd/restic/integration_filter_pattern_test.go | package main
import (
"os"
"path/filepath"
"testing"
"github.com/restic/restic/internal/filter"
rtest "github.com/restic/restic/internal/test"
)
func TestBackupFailsWhenUsingInvalidPatterns(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
var err error
// Test --exclude
err = testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{ExcludePatternOptions: filter.ExcludePatternOptions{Excludes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --exclude: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
// Test --iexclude
err = testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{ExcludePatternOptions: filter.ExcludePatternOptions{InsensitiveExcludes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --iexclude: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
}
func TestBackupFailsWhenUsingInvalidPatternsFromFile(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
// Create an exclude file with some invalid patterns
excludeFile := env.base + "/excludefile"
fileErr := os.WriteFile(excludeFile, []byte("*.go\n*[._]log[.-][0-9]\n!*[._]log[.-][0-9]"), 0644)
if fileErr != nil {
t.Fatalf("Could not write exclude file: %v", fileErr)
}
var err error
// Test --exclude-file:
err = testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{ExcludePatternOptions: filter.ExcludePatternOptions{ExcludeFiles: []string{excludeFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --exclude-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
// Test --iexclude-file
err = testRunBackupAssumeFailure(t, filepath.Dir(env.testdata), []string{"testdata"}, BackupOptions{ExcludePatternOptions: filter.ExcludePatternOptions{InsensitiveExcludeFiles: []string{excludeFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --iexclude-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
}
func TestRestoreFailsWhenUsingInvalidPatterns(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
var err error
// Test --exclude
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{ExcludePatternOptions: filter.ExcludePatternOptions{Excludes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --exclude: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
// Test --iexclude
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{ExcludePatternOptions: filter.ExcludePatternOptions{InsensitiveExcludes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --iexclude: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
// Test --include
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{IncludePatternOptions: filter.IncludePatternOptions{Includes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --include: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
// Test --iinclude
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{IncludePatternOptions: filter.IncludePatternOptions{InsensitiveIncludes: []string{"*[._]log[.-][0-9]", "!*[._]log[.-][0-9]"}}}, env.gopts)
rtest.Equals(t, `Fatal: --iinclude: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
}
func TestRestoreFailsWhenUsingInvalidPatternsFromFile(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
// Create an include file with some invalid patterns
patternsFile := env.base + "/patternsFile"
fileErr := os.WriteFile(patternsFile, []byte("*.go\n*[._]log[.-][0-9]\n!*[._]log[.-][0-9]"), 0644)
if fileErr != nil {
t.Fatalf("Could not write include file: %v", fileErr)
}
err := testRunRestoreAssumeFailure(t, "latest", RestoreOptions{IncludePatternOptions: filter.IncludePatternOptions{IncludeFiles: []string{patternsFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --include-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{ExcludePatternOptions: filter.ExcludePatternOptions{ExcludeFiles: []string{patternsFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --exclude-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{IncludePatternOptions: filter.IncludePatternOptions{InsensitiveIncludeFiles: []string{patternsFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --iinclude-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
err = testRunRestoreAssumeFailure(t, "latest", RestoreOptions{ExcludePatternOptions: filter.ExcludePatternOptions{InsensitiveExcludeFiles: []string{patternsFile}}}, env.gopts)
rtest.Equals(t, `Fatal: --iexclude-file: invalid pattern(s) provided:
*[._]log[.-][0-9]
!*[._]log[.-][0-9]`, err.Error())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key_add.go | cmd/restic/cmd_key_add.go | package main
import (
"context"
"fmt"
"github.com/restic/restic/internal/errors"
"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"
)
func newKeyAddCommand(globalOptions *global.Options) *cobra.Command {
var opts KeyAddOptions
cmd := &cobra.Command{
Use: "add",
Short: "Add a new key (password) to the repository; returns the new key ID",
Long: `
The "add" sub-command creates a new key and validates the key. Returns the new key ID.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runKeyAdd(cmd.Context(), *globalOptions, opts, args, globalOptions.Term)
},
}
opts.Add(cmd.Flags())
return cmd
}
type KeyAddOptions struct {
NewPasswordFile string
InsecureNoPassword bool
Username string
Hostname string
}
func (opts *KeyAddOptions) Add(flags *pflag.FlagSet) {
flags.StringVarP(&opts.NewPasswordFile, "new-password-file", "", "", "`file` from which to read the new password")
flags.BoolVar(&opts.InsecureNoPassword, "new-insecure-no-password", false, "add an empty password for the repository (insecure)")
flags.StringVarP(&opts.Username, "user", "", "", "the username for new key")
flags.StringVarP(&opts.Hostname, "host", "", "", "the hostname for new key")
}
func runKeyAdd(ctx context.Context, gopts global.Options, opts KeyAddOptions, args []string, term ui.Terminal) error {
if len(args) > 0 {
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)
ctx, repo, unlock, err := openWithAppendLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
return addKey(ctx, repo, gopts, opts, printer)
}
func addKey(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyAddOptions, printer progress.Printer) error {
pw, err := getNewPassword(ctx, gopts, opts.NewPasswordFile, opts.InsecureNoPassword)
if err != nil {
return err
}
id, err := repository.AddKey(ctx, repo, pw, opts.Username, opts.Hostname, repo.Key())
if err != nil {
return errors.Fatalf("creating new key failed: %v", err)
}
err = switchToNewKeyAndRemoveIfBroken(ctx, repo, id, pw)
if err != nil {
return err
}
printer.P("saved new key with ID %s", id.ID())
return nil
}
// testKeyNewPassword is used to set a new password during integration testing.
var testKeyNewPassword string
func getNewPassword(ctx context.Context, gopts global.Options, newPasswordFile string, insecureNoPassword bool) (string, error) {
if testKeyNewPassword != "" {
return testKeyNewPassword, nil
}
if insecureNoPassword {
if newPasswordFile != "" {
return "", fmt.Errorf("only either --new-password-file or --new-insecure-no-password may be specified")
}
return "", nil
}
if newPasswordFile != "" {
password, err := global.LoadPasswordFromFile(newPasswordFile)
if err != nil {
return "", err
}
if password == "" {
return "", fmt.Errorf("an empty password is not allowed by default. Pass the flag `--new-insecure-no-password` to restic to disable this check")
}
return password, nil
}
// Since we already have an open repository, temporary remove the password
// to prompt the user for the passwd.
newopts := gopts
newopts.Password = ""
// empty passwords are already handled above
newopts.InsecureNoPassword = false
return global.ReadPasswordTwice(ctx, newopts,
"enter new password: ",
"enter password again: ")
}
func switchToNewKeyAndRemoveIfBroken(ctx context.Context, repo *repository.Repository, key *repository.Key, pw string) error {
// Verify new key to make sure it really works. A broken key can render the
// whole repository inaccessible
err := repo.SearchKey(ctx, pw, 0, key.ID().String())
if err != nil {
// the key is invalid, try to remove it
_ = repository.RemoveKey(ctx, repo, key.ID())
return errors.Fatalf("failed to access repository with new key: %v", err)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_check_integration_test.go | cmd/restic/cmd_check_integration_test.go | package main
import (
"context"
"strings"
"testing"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunCheck(t testing.TB, gopts global.Options) {
t.Helper()
output, err := testRunCheckOutput(t, gopts, true)
if err != nil {
t.Error(output)
t.Fatalf("unexpected error: %+v", err)
}
}
func testRunCheckMustFail(t testing.TB, gopts global.Options) {
t.Helper()
_, 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 {
opts := CheckOptions{
ReadData: true,
CheckUnused: checkUnused,
}
_, err := runCheck(context.TODO(), opts, gopts, nil, gopts.Term)
return err
})
return buf.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)
return err
})
return buf.String(), err
}
func TestCheckWithSnaphotFilter(t *testing.T) {
testCases := []struct {
opts CheckOptions
args []string
expectedOutput string
}{
{ // full --read-data, all snapshots
CheckOptions{ReadData: true},
nil,
"4 / 4 packs",
},
{ // full --read-data, all snapshots
CheckOptions{ReadData: true},
nil,
"2 / 2 snapshots",
},
{ // full --read-data, latest snapshot
CheckOptions{ReadData: true},
[]string{"latest"},
"2 / 2 packs",
},
{ // full --read-data, latest snapshot
CheckOptions{ReadData: true},
[]string{"latest"},
"1 / 1 snapshots",
},
{ // --read-data-subset, latest snapshot
CheckOptions{ReadDataSubset: "1%"},
[]string{"latest"},
"1 / 1 packs",
},
{ // --read-data-subset, latest snapshot
CheckOptions{ReadDataSubset: "1%"},
[]string{"latest"},
"filtered",
},
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, env.testdata+"/0", []string{"for_cmd_ls"}, opts, env.gopts)
testRunBackup(t, env.testdata+"/0", []string{"0/9"}, opts, env.gopts)
for _, testCase := range testCases {
output, err := testRunCheckOutputWithOpts(t, env.gopts, testCase.opts, testCase.args)
rtest.OK(t, err)
hasOutput := strings.Contains(output, testCase.expectedOutput)
rtest.Assert(t, hasOutput, `expected to find substring %q, but did not find it`, testCase.expectedOutput)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_dump_test.go | cmd/restic/cmd_dump_test.go | package main
import (
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestDumpSplitPath(t *testing.T) {
testPaths := []struct {
path string
result []string
}{
{"", []string{""}},
{"test", []string{"test"}},
{"test/dir", []string{"test", "dir"}},
{"test/dir/sub", []string{"test", "dir", "sub"}},
{"/", []string{""}},
{"/test", []string{"test"}},
{"/test/dir", []string{"test", "dir"}},
{"/test/dir/sub", []string{"test", "dir", "sub"}},
}
for _, path := range testPaths {
parts := splitPath(path.path)
rtest.Equals(t, path.result, parts)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_diff.go | cmd/restic/cmd_diff.go | package main
import (
"context"
"encoding/json"
"path"
"reflect"
"sort"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"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/spf13/cobra"
"github.com/spf13/pflag"
)
func newDiffCommand(globalOptions *global.Options) *cobra.Command {
var opts DiffOptions
cmd := &cobra.Command{
Use: "diff [flags] snapshotID snapshotID",
Short: "Show differences between two snapshots",
Long: `
The "diff" command shows differences from the first to the second snapshot. The
first characters in each line display what has happened to a particular file or
directory:
* + The item was added
* - The item was removed
* U The metadata (access mode, timestamps, ...) for the item was updated
* M The file's content was modified
* T The type was changed, e.g. a file was made a symlink
* ? Bitrot detected: The file's content has changed but all metadata is the same
Metadata comparison will likely not work if a backup was created using the
'--ignore-inode' or '--ignore-ctime' option.
To only compare files in specific subfolders, you can use the
"snapshotID:subfolder" syntax, where "subfolder" is a path within the
snapshot.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runDiff(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// DiffOptions collects all options for the diff command.
type DiffOptions struct {
ShowMetadata bool
}
func (opts *DiffOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.ShowMetadata, "metadata", false, "print changes in metadata")
}
func loadSnapshot(ctx context.Context, be restic.Lister, repo restic.LoaderUnpacked, desc string) (*data.Snapshot, string, error) {
sn, subfolder, err := data.FindSnapshot(ctx, be, repo, desc)
if err != nil {
return nil, "", errors.Fatalf("%s", err)
}
return sn, subfolder, err
}
// Comparer collects all things needed to compare two snapshots.
type Comparer struct {
repo restic.BlobLoader
opts DiffOptions
printChange func(change *Change)
printError func(string, ...interface{})
}
type Change struct {
MessageType string `json:"message_type"` // "change"
Path string `json:"path"`
Modifier string `json:"modifier"`
}
func NewChange(path string, mode string) *Change {
return &Change{MessageType: "change", Path: path, Modifier: mode}
}
// DiffStat collects stats for all types of items.
type DiffStat struct {
Files int `json:"files"`
Dirs int `json:"dirs"`
Others int `json:"others"`
DataBlobs int `json:"data_blobs"`
TreeBlobs int `json:"tree_blobs"`
Bytes uint64 `json:"bytes"`
}
// Add adds stats information for node to s.
func (s *DiffStat) Add(node *data.Node) {
if node == nil {
return
}
switch node.Type {
case data.NodeTypeFile:
s.Files++
case data.NodeTypeDir:
s.Dirs++
default:
s.Others++
}
}
// addBlobs adds the blobs of node to s.
func addBlobs(bs restic.AssociatedBlobSet, node *data.Node) {
if node == nil {
return
}
switch node.Type {
case data.NodeTypeFile:
for _, blob := range node.Content {
h := restic.BlobHandle{
ID: blob,
Type: restic.DataBlob,
}
bs.Insert(h)
}
case data.NodeTypeDir:
h := restic.BlobHandle{
ID: *node.Subtree,
Type: restic.TreeBlob,
}
bs.Insert(h)
}
}
type DiffStatsContainer struct {
MessageType string `json:"message_type"` // "statistics"
SourceSnapshot string `json:"source_snapshot"`
TargetSnapshot string `json:"target_snapshot"`
ChangedFiles int `json:"changed_files"`
Added DiffStat `json:"added"`
Removed DiffStat `json:"removed"`
BlobsBefore, BlobsAfter, BlobsCommon restic.AssociatedBlobSet `json:"-"`
}
// updateBlobs updates the blob counters in the stats struct.
func updateBlobs(repo restic.Loader, blobs restic.AssociatedBlobSet, stats *DiffStat, printError func(string, ...interface{})) {
for h := range blobs.Keys() {
switch h.Type {
case restic.DataBlob:
stats.DataBlobs++
case restic.TreeBlob:
stats.TreeBlobs++
}
size, found := repo.LookupBlobSize(h.Type, h.ID)
if !found {
printError("unable to find blob size for %v", h)
continue
}
stats.Bytes += uint64(size)
}
}
func (c *Comparer) printDir(ctx context.Context, mode string, stats *DiffStat, blobs restic.AssociatedBlobSet, prefix string, id restic.ID) error {
debug.Log("print %v tree %v", mode, id)
tree, err := data.LoadTree(ctx, c.repo, id)
if err != nil {
return err
}
for _, node := range tree.Nodes {
if ctx.Err() != nil {
return ctx.Err()
}
name := path.Join(prefix, node.Name)
if node.Type == data.NodeTypeDir {
name += "/"
}
c.printChange(NewChange(name, mode))
stats.Add(node)
addBlobs(blobs, node)
if node.Type == data.NodeTypeDir {
err := c.printDir(ctx, mode, stats, blobs, name, *node.Subtree)
if err != nil && err != context.Canceled {
c.printError("error: %v", err)
}
}
}
return ctx.Err()
}
func (c *Comparer) collectDir(ctx context.Context, blobs restic.AssociatedBlobSet, id restic.ID) error {
debug.Log("print tree %v", id)
tree, err := data.LoadTree(ctx, c.repo, id)
if err != nil {
return err
}
for _, node := range tree.Nodes {
if ctx.Err() != nil {
return ctx.Err()
}
addBlobs(blobs, node)
if node.Type == data.NodeTypeDir {
err := c.collectDir(ctx, blobs, *node.Subtree)
if err != nil && err != context.Canceled {
c.printError("error: %v", err)
}
}
}
return ctx.Err()
}
func uniqueNodeNames(tree1, tree2 *data.Tree) (tree1Nodes, tree2Nodes map[string]*data.Node, uniqueNames []string) {
names := make(map[string]struct{})
tree1Nodes = make(map[string]*data.Node)
for _, node := range tree1.Nodes {
tree1Nodes[node.Name] = node
names[node.Name] = struct{}{}
}
tree2Nodes = make(map[string]*data.Node)
for _, node := range tree2.Nodes {
tree2Nodes[node.Name] = node
names[node.Name] = struct{}{}
}
uniqueNames = make([]string, 0, len(names))
for name := range names {
uniqueNames = append(uniqueNames, name)
}
sort.Strings(uniqueNames)
return tree1Nodes, tree2Nodes, uniqueNames
}
func (c *Comparer) diffTree(ctx context.Context, stats *DiffStatsContainer, prefix string, id1, id2 restic.ID) error {
debug.Log("diffing %v to %v", id1, id2)
tree1, err := data.LoadTree(ctx, c.repo, id1)
if err != nil {
return err
}
tree2, err := data.LoadTree(ctx, c.repo, id2)
if err != nil {
return err
}
tree1Nodes, tree2Nodes, names := uniqueNodeNames(tree1, tree2)
for _, name := range names {
if ctx.Err() != nil {
return ctx.Err()
}
node1, t1 := tree1Nodes[name]
node2, t2 := tree2Nodes[name]
addBlobs(stats.BlobsBefore, node1)
addBlobs(stats.BlobsAfter, node2)
switch {
case t1 && t2:
name := path.Join(prefix, name)
mod := ""
if node1.Type != node2.Type {
mod += "T"
}
if node2.Type == data.NodeTypeDir {
name += "/"
}
if node1.Type == data.NodeTypeFile &&
node2.Type == data.NodeTypeFile &&
!reflect.DeepEqual(node1.Content, node2.Content) {
mod += "M"
stats.ChangedFiles++
node1NilContent := *node1
node2NilContent := *node2
node1NilContent.Content = nil
node2NilContent.Content = nil
// the bitrot detection may not work if `backup --ignore-inode` or `--ignore-ctime` were used
if node1NilContent.Equals(node2NilContent) {
// probable bitrot detected
mod += "?"
}
} else if c.opts.ShowMetadata && !node1.Equals(*node2) {
mod += "U"
}
if mod != "" {
c.printChange(NewChange(name, mod))
}
if node1.Type == data.NodeTypeDir && node2.Type == data.NodeTypeDir {
var err error
if (*node1.Subtree).Equal(*node2.Subtree) {
err = c.collectDir(ctx, stats.BlobsCommon, *node1.Subtree)
} else {
err = c.diffTree(ctx, stats, name, *node1.Subtree, *node2.Subtree)
}
if err != nil && err != context.Canceled {
c.printError("error: %v", err)
}
}
case t1 && !t2:
prefix := path.Join(prefix, name)
if node1.Type == data.NodeTypeDir {
prefix += "/"
}
c.printChange(NewChange(prefix, "-"))
stats.Removed.Add(node1)
if node1.Type == data.NodeTypeDir {
err := c.printDir(ctx, "-", &stats.Removed, stats.BlobsBefore, prefix, *node1.Subtree)
if err != nil && err != context.Canceled {
c.printError("error: %v", err)
}
}
case !t1 && t2:
prefix := path.Join(prefix, name)
if node2.Type == data.NodeTypeDir {
prefix += "/"
}
c.printChange(NewChange(prefix, "+"))
stats.Added.Add(node2)
if node2.Type == data.NodeTypeDir {
err := c.printDir(ctx, "+", &stats.Added, stats.BlobsAfter, prefix, *node2.Subtree)
if err != nil && err != context.Canceled {
c.printError("error: %v", err)
}
}
}
}
return ctx.Err()
}
func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) != 2 {
return errors.Fatalf("specify two snapshot IDs")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
// cache snapshots listing
be, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
sn1, subfolder1, err := loadSnapshot(ctx, be, repo, args[0])
if err != nil {
return err
}
sn2, subfolder2, err := loadSnapshot(ctx, be, repo, args[1])
if err != nil {
return err
}
if !gopts.JSON {
printer.P("comparing snapshot %v to %v:\n\n", sn1.ID().Str(), sn2.ID().Str())
}
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
if sn1.Tree == nil {
return errors.Errorf("snapshot %v has nil tree", sn1.ID().Str())
}
if sn2.Tree == nil {
return errors.Errorf("snapshot %v has nil tree", sn2.ID().Str())
}
sn1.Tree, err = data.FindTreeDirectory(ctx, repo, sn1.Tree, subfolder1)
if err != nil {
return err
}
sn2.Tree, err = data.FindTreeDirectory(ctx, repo, sn2.Tree, subfolder2)
if err != nil {
return err
}
c := &Comparer{
repo: repo,
opts: opts,
printError: printer.E,
printChange: func(change *Change) {
printer.S("%-5s%v", change.Modifier, change.Path)
},
}
if gopts.JSON {
enc := json.NewEncoder(gopts.Term.OutputWriter())
c.printChange = func(change *Change) {
err := enc.Encode(change)
if err != nil {
printer.E("JSON encode failed: %v", err)
}
}
}
if gopts.Quiet {
c.printChange = func(_ *Change) {}
}
stats := &DiffStatsContainer{
MessageType: "statistics",
SourceSnapshot: args[0],
TargetSnapshot: args[1],
BlobsBefore: repo.NewAssociatedBlobSet(),
BlobsAfter: repo.NewAssociatedBlobSet(),
BlobsCommon: repo.NewAssociatedBlobSet(),
}
stats.BlobsBefore.Insert(restic.BlobHandle{Type: restic.TreeBlob, ID: *sn1.Tree})
stats.BlobsAfter.Insert(restic.BlobHandle{Type: restic.TreeBlob, ID: *sn2.Tree})
err = c.diffTree(ctx, stats, "/", *sn1.Tree, *sn2.Tree)
if err != nil {
return err
}
both := stats.BlobsBefore.Intersect(stats.BlobsAfter)
updateBlobs(repo, stats.BlobsBefore.Sub(both).Sub(stats.BlobsCommon), &stats.Removed, printer.E)
updateBlobs(repo, stats.BlobsAfter.Sub(both).Sub(stats.BlobsCommon), &stats.Added, printer.E)
if gopts.JSON {
err := json.NewEncoder(gopts.Term.OutputWriter()).Encode(stats)
if err != nil {
printer.E("JSON encode failed: %v", err)
}
} else {
printer.S("")
printer.S("Files: %5d new, %5d removed, %5d changed", stats.Added.Files, stats.Removed.Files, stats.ChangedFiles)
printer.S("Dirs: %5d new, %5d removed", stats.Added.Dirs, stats.Removed.Dirs)
printer.S("Others: %5d new, %5d removed", stats.Added.Others, stats.Removed.Others)
printer.S("Data Blobs: %5d new, %5d removed", stats.Added.DataBlobs, stats.Removed.DataBlobs)
printer.S("Tree Blobs: %5d new, %5d removed", stats.Added.TreeBlobs, stats.Removed.TreeBlobs)
printer.S(" Added: %-5s", ui.FormatBytes(stats.Added.Bytes))
printer.S(" Removed: %-5s", ui.FormatBytes(stats.Removed.Bytes))
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/lock.go | cmd/restic/lock.go | package main
import (
"context"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui/progress"
)
func internalOpenWithLocked(ctx context.Context, gopts global.Options, dryRun bool, exclusive bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
repo, err := global.OpenRepository(ctx, gopts, printer)
if err != nil {
return nil, nil, nil, err
}
unlock := func() {}
if !dryRun {
var lock *repository.Unlocker
lock, ctx, err = repository.Lock(ctx, repo, exclusive, gopts.RetryLock, func(msg string) {
if !gopts.JSON {
printer.P("%s", msg)
}
}, printer.E)
if err != nil {
return nil, nil, nil, err
}
unlock = lock.Unlock
} else {
repo.SetDryRun()
}
return ctx, repo, unlock, nil
}
func openWithReadLock(ctx context.Context, gopts global.Options, noLock bool, printer progress.Printer) (context.Context, *repository.Repository, func(), error) {
// TODO enforce read-only operations once the locking code has moved to the repository
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) {
// 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) {
return internalOpenWithLocked(ctx, gopts, dryRun, true, printer)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_check.go | cmd/restic/cmd_check.go | package main
import (
"context"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/backend/cache"
"github.com/restic/restic/internal/checker"
"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"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func newCheckCommand(globalOptions *global.Options) *cobra.Command {
var opts CheckOptions
cmd := &cobra.Command{
Use: "check [flags]",
Short: "Check the repository for errors",
Long: `
The "check" command tests the repository for errors and reports any errors it
finds. It can also be used to read all data and therefore simulate a restore.
By default, the "check" command will always load all data directly from the
repository and not use a local cache.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
summary, err := runCheck(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
if globalOptions.JSON {
if err != nil && summary.NumErrors == 0 {
summary.NumErrors = 1
}
globalOptions.Term.Print(ui.ToJSONString(summary))
}
return err
},
PreRunE: func(_ *cobra.Command, _ []string) error {
return checkFlags(opts)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// CheckOptions bundles all options for the 'check' command.
type CheckOptions struct {
ReadData bool
ReadDataSubset string
CheckUnused bool
WithCache bool
data.SnapshotFilter
}
func (opts *CheckOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.ReadData, "read-data", false, "read all data blobs")
f.StringVar(&opts.ReadDataSubset, "read-data-subset", "", "read a `subset` of data packs, specified as 'n/t' for specific part, or either 'x%' or 'x.y%' or a size in bytes with suffixes k/K, m/M, g/G, t/T for a random subset")
var ignored bool
f.BoolVar(&ignored, "check-unused", false, "find unused blobs")
err := f.MarkDeprecated("check-unused", "`--check-unused` is deprecated and will be ignored")
if err != nil {
// MarkDeprecated only returns an error when the flag is not found
panic(err)
}
f.BoolVar(&opts.WithCache, "with-cache", false, "use existing cache, only read uncached data from repository")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
func checkFlags(opts CheckOptions) error {
if opts.ReadData && opts.ReadDataSubset != "" {
return errors.Fatal("check flags --read-data and --read-data-subset cannot be used together")
}
if opts.ReadDataSubset != "" {
dataSubset, err := stringToIntSlice(opts.ReadDataSubset)
argumentError := errors.Fatal("check flag --read-data-subset has invalid value, please see documentation")
if err == nil {
if len(dataSubset) != 2 {
return argumentError
}
if dataSubset[0] == 0 || dataSubset[1] == 0 || dataSubset[0] > dataSubset[1] {
return errors.Fatal("check flag --read-data-subset=n/t values must be positive integers, and n <= t, e.g. --read-data-subset=1/2")
}
if dataSubset[1] > totalBucketsMax {
return errors.Fatalf("check flag --read-data-subset=n/t t must be at most %d", totalBucketsMax)
}
} else if strings.HasSuffix(opts.ReadDataSubset, "%") {
percentage, err := parsePercentage(opts.ReadDataSubset)
if err != nil {
return argumentError
}
if percentage <= 0.0 || percentage > 100.0 {
return errors.Fatal(
"check flag --read-data-subset=x% x must be above 0.0% and at most 100.0%")
}
} else {
fileSize, err := ui.ParseBytes(opts.ReadDataSubset)
if err != nil {
return argumentError
}
if fileSize <= 0.0 {
return errors.Fatal(
"check flag --read-data-subset=n n must be above 0")
}
}
}
return nil
}
// See doReadData in runCheck below for why this is 256.
const totalBucketsMax = 256
// stringToIntSlice converts string to []uint, using '/' as element separator
func stringToIntSlice(param string) (split []uint, err error) {
if param == "" {
return nil, nil
}
parts := strings.Split(param, "/")
result := make([]uint, len(parts))
for idx, part := range parts {
uintval, err := strconv.ParseUint(part, 10, 0)
if err != nil {
return nil, err
}
result[idx] = uint(uintval)
}
return result, nil
}
// ParsePercentage parses a percentage string of the form "X%" where X is a float constant,
// and returns the value of that constant. It does not check the range of the value.
func parsePercentage(s string) (float64, error) {
if !strings.HasSuffix(s, "%") {
return 0, errors.Errorf(`parsePercentage: %q does not end in "%%"`, s)
}
s = s[:len(s)-1]
p, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, errors.Errorf("parsePercentage: %v", err)
}
return p, nil
}
// prepareCheckCache configures a special cache directory for check.
//
// - if --with-cache is specified, the default cache is used
// - 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()) {
cleanup = func() {}
if opts.WithCache {
// use the default cache, no setup needed
return cleanup
}
if gopts.NoCache {
// don't use any cache, no setup needed
return cleanup
}
cachedir := gopts.CacheDir
if cachedir == "" {
cachedir = cache.EnvDir()
}
if cachedir != "" {
// use a cache in a temporary directory
err := os.MkdirAll(cachedir, 0755)
if err != nil {
printer.E("unable to create cache directory %s, disabling cache: %v", cachedir, err)
gopts.NoCache = true
return cleanup
}
}
tempdir, err := os.MkdirTemp(cachedir, "restic-check-cache-")
if err != nil {
// if an error occurs, don't use any cache
printer.E("unable to create temporary directory for cache during check, disabling cache: %v\n", err)
gopts.NoCache = true
return cleanup
}
gopts.CacheDir = tempdir
printer.P("using temporary cache in %v\n", tempdir)
cleanup = func() {
err := os.RemoveAll(tempdir)
if err != nil {
printer.E("error removing temporary cache directory: %v\n", err)
}
}
return cleanup
}
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
if !gopts.JSON {
printer = ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
} else {
printer = newJSONErrorPrinter(term)
}
cleanup := prepareCheckCache(opts, &gopts, printer)
defer cleanup()
if !gopts.NoLock {
printer.P("create exclusive lock for repository\n")
}
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return summary, err
}
defer unlock()
chkr := checker.New(repo, opts.CheckUnused)
err = chkr.LoadSnapshots(ctx, &opts.SnapshotFilter, args)
if err != nil {
return summary, err
}
printer.P("load indexes\n")
hints, errs := chkr.LoadIndex(ctx, printer)
if ctx.Err() != nil {
return summary, ctx.Err()
}
errorsFound := false
for _, hint := range hints {
switch hint.(type) {
case *repository.ErrDuplicatePacks:
printer.S("%s", hint.Error())
summary.HintRepairIndex = true
case *repository.ErrMixedPack:
printer.S("%s", hint.Error())
summary.HintPrune = true
default:
printer.E("error: %v\n", hint)
errorsFound = true
}
}
if summary.HintRepairIndex {
printer.S("Duplicate packs are non-critical, you can run `restic repair index' to correct this.\n")
}
if summary.HintPrune {
printer.S("Mixed packs with tree and data blobs are non-critical, you can run `restic prune` to correct this.\n")
}
if len(errs) > 0 {
for _, err := range errs {
printer.E("error: %v\n", err)
}
summary.NumErrors += len(errs)
summary.HintRepairIndex = true
printer.E("\nThe repository index is damaged and must be repaired. You must run `restic repair index' to correct this.\n\n")
return summary, errors.Fatal("repository contains errors")
}
orphanedPacks := 0
errChan := make(chan error)
salvagePacks := restic.NewIDSet()
printer.P("check all packs\n")
go chkr.Packs(ctx, errChan)
for err := range errChan {
var packErr *repository.PackError
if errors.As(err, &packErr) {
if packErr.Orphaned {
orphanedPacks++
printer.V("%v\n", err)
} else {
if packErr.Truncated {
salvagePacks.Insert(packErr.ID)
}
errorsFound = true
summary.NumErrors++
printer.E("%v\n", err)
}
} else {
errorsFound = true
printer.E("%v\n", err)
}
}
if orphanedPacks > 0 {
summary.HintPrune = true
if !errorsFound {
// hide notice if repository is damaged
printer.P("%d additional files were found in the repo, which likely contain duplicate data.\nThis is non-critical, you can run `restic prune` to correct this.\n", orphanedPacks)
}
}
if ctx.Err() != nil {
return summary, ctx.Err()
}
printer.P("check snapshots, trees and blobs\n")
errChan = make(chan error)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
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 {
printer.E("error for tree %v:\n", e.ID.Str())
for _, treeErr := range e.Errors {
summary.NumErrors++
printer.E(" %v\n", treeErr)
}
} else {
summary.NumErrors++
printer.E("error: %v\n", err)
}
}
// Wait for the progress bar to be complete before printing more below.
// Must happen after `errChan` is read from in the above loop to avoid
// deadlocking in the case of errors.
wg.Wait()
if ctx.Err() != nil {
return summary, ctx.Err()
}
// the following block only used for tests
if opts.CheckUnused {
unused, err := chkr.UnusedBlobs(ctx)
if err != nil {
return summary, err
}
for _, id := range unused {
printer.P("unused blob %v\n", id)
errorsFound = true
}
}
readDataFilter, err := buildPacksFilter(opts, printer, chkr.IsFiltered())
if err != nil {
return summary, err
}
if readDataFilter != nil {
p := printer.NewCounter("packs")
errChan := make(chan error)
go chkr.ReadPacks(ctx, readDataFilter, p, errChan)
for err := range errChan {
errorsFound = true
summary.NumErrors++
printer.E("%v\n", err)
if err, ok := err.(*repository.ErrPackData); ok {
salvagePacks.Insert(err.PackID)
}
}
p.Done()
}
if len(salvagePacks) > 0 {
printer.E("\nThe repository contains damaged pack 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")
for id := range salvagePacks {
summary.BrokenPacks = append(summary.BrokenPacks, id.String())
}
printer.E("restic repair packs %v\nrestic repair snapshots --forget\n\n", strings.Join(summary.BrokenPacks, " "))
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 ctx.Err() != nil {
return summary, ctx.Err()
}
if errorsFound {
if len(salvagePacks) == 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")
}
printer.P("no errors were found\n")
return summary, nil
}
func buildPacksFilter(opts CheckOptions, printer progress.Printer,
filteredStatus bool) (func(packs map[restic.ID]int64) map[restic.ID]int64, error) {
typeData := ""
if filteredStatus {
typeData = "filtered "
}
switch {
case opts.ReadData:
return func(packs map[restic.ID]int64) map[restic.ID]int64 {
printer.P("read all %sdata", typeData)
return packs
}, nil
case opts.ReadDataSubset != "":
dataSubset, err := stringToIntSlice(opts.ReadDataSubset)
if err == nil {
bucket := dataSubset[0]
totalBuckets := dataSubset[1]
return func(packs map[restic.ID]int64) map[restic.ID]int64 {
packCount := uint64(len(packs))
packs = selectPacksByBucket(packs, bucket, totalBuckets)
printer.P("read group #%d of %d %sdata packs (out of total %d packs in %d groups", bucket, len(packs), typeData, packCount, totalBuckets)
return packs
}, nil
} else if strings.HasSuffix(opts.ReadDataSubset, "%") {
percentage, err := parsePercentage(opts.ReadDataSubset)
if err != nil {
return nil, err
}
return func(packs map[restic.ID]int64) map[restic.ID]int64 {
printer.P("read %.1f%% of %spackfiles", percentage, typeData)
return selectRandomPacksByPercentage(packs, percentage)
}, nil
}
repoSize := int64(0)
return func(packs map[restic.ID]int64) map[restic.ID]int64 {
for _, size := range packs {
repoSize += size
}
subsetSize, _ := ui.ParseBytes(opts.ReadDataSubset)
if subsetSize > repoSize {
subsetSize = repoSize
}
if repoSize > 0 {
packs = selectRandomPacksByFileSize(packs, subsetSize, repoSize)
}
percentage := float64(subsetSize) / float64(repoSize) * 100.0
if repoSize == 0 {
percentage = 100
}
printer.P("read %d bytes (%.1f%%) of %sdata packs\n", subsetSize, percentage, typeData)
return packs
}, nil
}
return nil, nil
}
// selectPacksByBucket selects subsets of packs by ranges of buckets.
func selectPacksByBucket(allPacks map[restic.ID]int64, bucket, totalBuckets uint) map[restic.ID]int64 {
packs := make(map[restic.ID]int64)
for pack, size := range allPacks {
// If we ever check more than the first byte
// of pack, update totalBucketsMax.
if (uint(pack[0]) % totalBuckets) == (bucket - 1) {
packs[pack] = size
}
}
return packs
}
// selectRandomPacksByPercentage selects the given percentage of packs which are randomly chosen.
func selectRandomPacksByPercentage(allPacks map[restic.ID]int64, percentage float64) map[restic.ID]int64 {
packCount := len(allPacks)
packsToCheck := int(float64(packCount) * (percentage / 100.0))
if packCount > 0 && packsToCheck < 1 {
packsToCheck = 1
}
timeNs := time.Now().UnixNano()
r := rand.New(rand.NewSource(timeNs))
idx := r.Perm(packCount)
var keys []restic.ID
for k := range allPacks {
keys = append(keys, k)
}
packs := make(map[restic.ID]int64)
for i := 0; i < packsToCheck; i++ {
id := keys[idx[i]]
packs[id] = allPacks[id]
}
return packs
}
func selectRandomPacksByFileSize(allPacks map[restic.ID]int64, subsetSize int64, repoSize int64) map[restic.ID]int64 {
subsetPercentage := (float64(subsetSize) / float64(repoSize)) * 100.0
packs := selectRandomPacksByPercentage(allPacks, subsetPercentage)
return packs
}
type checkSummary struct {
MessageType string `json:"message_type"` // "summary"
NumErrors int `json:"num_errors"`
BrokenPacks []string `json:"broken_packs"` // run "restic repair packs ID..." and "restic repair snapshots --forget" to remove damaged files
HintRepairIndex bool `json:"suggest_repair_index"` // run "restic repair index"
HintPrune bool `json:"suggest_prune"` // run "restic prune"
}
type checkError struct {
MessageType string `json:"message_type"` // "error"
Message string `json:"message"`
}
type jsonErrorPrinter struct {
term ui.Terminal
}
func newJSONErrorPrinter(term ui.Terminal) *jsonErrorPrinter {
return &jsonErrorPrinter{
term: term,
}
}
func (*jsonErrorPrinter) NewCounter(_ string) *progress.Counter {
return nil
}
func (*jsonErrorPrinter) NewCounterTerminalOnly(_ string) *progress.Counter {
return nil
}
func (p *jsonErrorPrinter) E(msg string, args ...interface{}) {
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{}) {}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_ls_test.go | cmd/restic/cmd_ls_test.go | package main
import (
"bytes"
"encoding/json"
"os"
"testing"
"time"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
)
type lsTestNode struct {
path string
data.Node
}
var lsTestNodes = []lsTestNode{
// Mode is omitted when zero.
// Permissions, by convention is "-" per mode bit
{
path: "/bar/baz",
Node: data.Node{
Name: "baz",
Type: data.NodeTypeFile,
Size: 12345,
UID: 10000000,
GID: 20000000,
User: "nobody",
Group: "nobodies",
Links: 1,
},
},
// Even empty files get an explicit size.
{
path: "/foo/empty",
Node: data.Node{
Name: "empty",
Type: data.NodeTypeFile,
Size: 0,
UID: 1001,
GID: 1001,
User: "not printed",
Group: "not printed",
Links: 0xF00,
},
},
// Non-regular files do not get a size.
// Mode is printed in decimal, including the type bits.
{
path: "/foo/link",
Node: data.Node{
Name: "link",
Type: data.NodeTypeSymlink,
Mode: os.ModeSymlink | 0777,
LinkTarget: "not printed",
},
},
{
path: "/some/directory",
Node: data.Node{
Name: "directory",
Type: data.NodeTypeDir,
Mode: os.ModeDir | 0755,
ModTime: time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC),
AccessTime: time.Date(2021, 2, 3, 4, 5, 6, 7, time.UTC),
ChangeTime: time.Date(2022, 3, 4, 5, 6, 7, 8, time.UTC),
},
},
// Test encoding of setuid/setgid/sticky bit
{
path: "/some/sticky",
Node: data.Node{
Name: "sticky",
Type: data.NodeTypeDir,
Mode: os.ModeDir | 0755 | os.ModeSetuid | os.ModeSetgid | os.ModeSticky,
},
},
}
func TestLsNodeJSON(t *testing.T) {
for i, expect := range []string{
`{"name":"baz","type":"file","path":"/bar/baz","uid":10000000,"gid":20000000,"size":12345,"permissions":"----------","mtime":"0001-01-01T00:00:00Z","atime":"0001-01-01T00:00:00Z","ctime":"0001-01-01T00:00:00Z","message_type":"node","struct_type":"node"}`,
`{"name":"empty","type":"file","path":"/foo/empty","uid":1001,"gid":1001,"size":0,"permissions":"----------","mtime":"0001-01-01T00:00:00Z","atime":"0001-01-01T00:00:00Z","ctime":"0001-01-01T00:00:00Z","message_type":"node","struct_type":"node"}`,
`{"name":"link","type":"symlink","path":"/foo/link","uid":0,"gid":0,"mode":134218239,"permissions":"Lrwxrwxrwx","mtime":"0001-01-01T00:00:00Z","atime":"0001-01-01T00:00:00Z","ctime":"0001-01-01T00:00:00Z","message_type":"node","struct_type":"node"}`,
`{"name":"directory","type":"dir","path":"/some/directory","uid":0,"gid":0,"mode":2147484141,"permissions":"drwxr-xr-x","mtime":"2020-01-02T03:04:05Z","atime":"2021-02-03T04:05:06.000000007Z","ctime":"2022-03-04T05:06:07.000000008Z","message_type":"node","struct_type":"node"}`,
`{"name":"sticky","type":"dir","path":"/some/sticky","uid":0,"gid":0,"mode":2161115629,"permissions":"dugtrwxr-xr-x","mtime":"0001-01-01T00:00:00Z","atime":"0001-01-01T00:00:00Z","ctime":"0001-01-01T00:00:00Z","message_type":"node","struct_type":"node"}`,
} {
c := lsTestNodes[i]
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
err := lsNodeJSON(enc, 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{}
err = json.NewDecoder(buf).Decode(&v)
rtest.OK(t, err)
}
}
func TestLsNcduNode(t *testing.T) {
for i, expect := range []string{
`{"name":"baz","asize":12345,"dsize":12800,"dev":0,"ino":0,"nlink":1,"notreg":false,"uid":10000000,"gid":20000000,"mode":0,"mtime":0}`,
`{"name":"empty","asize":0,"dsize":0,"dev":0,"ino":0,"nlink":3840,"notreg":false,"uid":1001,"gid":1001,"mode":0,"mtime":0}`,
`{"name":"link","asize":0,"dsize":0,"dev":0,"ino":0,"nlink":0,"notreg":true,"uid":0,"gid":0,"mode":511,"mtime":0}`,
`{"name":"directory","asize":0,"dsize":0,"dev":0,"ino":0,"nlink":0,"notreg":false,"uid":0,"gid":0,"mode":493,"mtime":1577934245}`,
`{"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)
rtest.OK(t, err)
rtest.Equals(t, expect, string(out))
// Sanity check: output must be valid JSON.
var v interface{}
err = json.Unmarshal(out, &v)
rtest.OK(t, err)
}
}
func TestLsNcdu(t *testing.T) {
var buf bytes.Buffer
printer := &ncduLsPrinter{
out: &buf,
}
modTime := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
rtest.OK(t, printer.Snapshot(&data.Snapshot{
Hostname: "host",
Paths: []string{"/example"},
}))
rtest.OK(t, printer.Node("/directory", &data.Node{
Type: data.NodeTypeDir,
Name: "directory",
ModTime: modTime,
}, false))
rtest.OK(t, printer.Node("/directory/data", &data.Node{
Type: data.NodeTypeFile,
Name: "data",
Size: 42,
ModTime: modTime,
}, false))
rtest.OK(t, printer.LeaveDir("/directory"))
rtest.OK(t, printer.Node("/file", &data.Node{
Type: data.NodeTypeFile,
Name: "file",
Size: 12345,
ModTime: modTime,
}, false))
rtest.OK(t, printer.Close())
rtest.Equals(t, `[1, 2, {"time":"0001-01-01T00:00:00Z","tree":null,"paths":["/example"],"hostname":"host"}, [{"name":"/"},
[
{"name":"directory","asize":0,"dsize":0,"dev":0,"ino":0,"nlink":0,"notreg":false,"uid":0,"gid":0,"mode":0,"mtime":1577934245},
{"name":"data","asize":42,"dsize":512,"dev":0,"ino":0,"nlink":0,"notreg":false,"uid":0,"gid":0,"mode":0,"mtime":1577934245}
],
{"name":"file","asize":12345,"dsize":12800,"dev":0,"ino":0,"nlink":0,"notreg":false,"uid":0,"gid":0,"mode":0,"mtime":1577934245}
]
]
`, buf.String())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_cat_test.go | cmd/restic/cmd_cat_test.go | package main
import (
"strings"
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestCatArgsValidation(t *testing.T) {
for _, test := range []struct {
args []string
err string
}{
{[]string{}, "Fatal: type not specified"},
{[]string{"masterkey"}, ""},
{[]string{"invalid"}, `Fatal: invalid type "invalid"`},
{[]string{"snapshot"}, "Fatal: ID not specified"},
{[]string{"snapshot", "12345678"}, ""},
} {
t.Run("", func(t *testing.T) {
err := validateCatArgs(test.args)
if test.err == "" {
rtest.Assert(t, err == nil, "unexpected error %q", err)
} else {
rtest.Assert(t, strings.Contains(err.Error(), test.err), "unexpected error expected %q to contain %q", err, test.err)
}
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_list_integration_test.go | cmd/restic/cmd_list_integration_test.go | package main
import (
"bufio"
"context"
"io"
"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"
)
func testRunList(t testing.TB, gopts global.Options, tpe string) restic.IDs {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runList(ctx, gopts, []string{tpe}, gopts.Term)
})
rtest.OK(t, err)
return parseIDsFromReader(t, buf)
}
func parseIDsFromReader(t testing.TB, rd io.Reader) restic.IDs {
t.Helper()
IDs := restic.IDs{}
sc := bufio.NewScanner(rd)
for sc.Scan() {
if len(sc.Text()) == 64 {
id, err := restic.ParseID(sc.Text())
if err != nil {
t.Logf("parse id %v: %v", sc.Text(), err)
continue
}
IDs = append(IDs, id)
} else {
// 'list blobs' is different because it lists the blobs together with the blob type
// e.g. "tree ac08ce34ba4f8123618661bef2425f7028ffb9ac740578a3ee88684d2523fee8"
parts := strings.Split(sc.Text(), " ")
id, err := restic.ParseID(parts[len(parts)-1])
if err != nil {
t.Logf("parse id %v: %v", sc.Text(), err)
continue
}
IDs = append(IDs, id)
}
}
return IDs
}
func testListSnapshots(t testing.TB, gopts global.Options, expected int) restic.IDs {
t.Helper()
snapshotIDs := testRunList(t, gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == expected, "expected %v snapshot, got %v", expected, snapshotIDs)
return snapshotIDs
}
// 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)
_, 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))
// get blobs from index
blobSetFromIndex = restic.NewIDSet()
rtest.OK(t, repo.ListBlobs(ctx, func(blob restic.PackedBlob) {
blobSetFromIndex.Insert(blob.ID)
}))
return nil
})
rtest.OK(t, err)
return blobSetFromIndex
}
func TestListBlobs(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
// first backup
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
// run the `list blobs` command
resticIDs := testRunList(t, env.gopts, "blobs")
// convert to set
testIDSet := restic.NewIDSet(resticIDs...)
blobSetFromIndex := testListBlobs(t, env.gopts)
rtest.Assert(t, blobSetFromIndex.Equals(testIDSet), "the set of restic.ID s should be equal")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_generate_integration_test.go | cmd/restic/cmd_generate_integration_test.go | package main
import (
"context"
"strings"
"testing"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunGenerate(t testing.TB, gopts global.Options, opts generateOptions) ([]byte, error) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runGenerate(opts, gopts, []string{}, gopts.Term)
})
return buf.Bytes(), err
}
func TestGenerateStdout(t *testing.T) {
testCases := []struct {
name string
opts generateOptions
}{
{"bash", generateOptions{BashCompletionFile: "-"}},
{"fish", generateOptions{FishCompletionFile: "-"}},
{"zsh", generateOptions{ZSHCompletionFile: "-"}},
{"powershell", generateOptions{PowerShellCompletionFile: "-"}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
output, err := testRunGenerate(t, global.Options{}, tc.opts)
rtest.OK(t, err)
rtest.Assert(t, strings.Contains(string(output), "# "+tc.name+" completion for restic"), "has no expected completion header")
})
}
t.Run("Generate shell completions to stdout for two shells", func(t *testing.T) {
_, err := testRunGenerate(t, global.Options{}, generateOptions{BashCompletionFile: "-", FishCompletionFile: "-"})
rtest.Assert(t, err != nil, "generate shell completions to stdout for two shells fails")
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_recover.go | cmd/restic/cmd_recover.go | package main
import (
"context"
"os"
"time"
"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"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
"github.com/spf13/cobra"
)
func newRecoverCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "recover [flags]",
Short: "Recover data from the repository not referenced by snapshots",
Long: `
The "recover" command builds a new snapshot from all directories it can find in
the raw data of the repository which are not referenced in an existing snapshot.
It can be used if, for example, a snapshot has been removed by accident with "forget".
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
return runRecover(cmd.Context(), *globalOptions, globalOptions.Term)
},
}
return cmd
}
func runRecover(ctx context.Context, gopts global.Options, term ui.Terminal) error {
hostname, err := os.Hostname()
if err != nil {
return err
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
printer.P("ensuring index is complete\n")
err = repository.RepairIndex(ctx, repo, repository.RepairIndexOptions{}, printer)
if err != nil {
return err
}
printer.P("load index files\n")
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
// trees maps a tree ID to whether or not it is referenced by a different
// 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
}
})
if err != nil {
return err
}
printer.P("load %d trees\n", len(trees))
bar := printer.NewCounter("trees loaded")
bar.SetMax(uint64(len(trees)))
for id := range trees {
tree, err := data.LoadTree(ctx, repo, id)
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
printer.E("unable to load tree %v: %v\n", id.Str(), err)
continue
}
for _, node := range tree.Nodes {
if node.Type == data.NodeTypeDir && node.Subtree != nil {
trees[*node.Subtree] = true
}
}
bar.Add(1)
}
bar.Done()
printer.P("load snapshots\n")
err = data.ForAllSnapshots(ctx, snapshotLister, repo, nil, func(_ restic.ID, sn *data.Snapshot, _ error) error {
trees[*sn.Tree] = true
return nil
})
if err != nil {
return err
}
printer.P("done\n")
roots := restic.NewIDSet()
for id, seen := range trees {
if !seen {
printer.V("found root tree %v\n", id.Str())
roots.Insert(id)
}
}
printer.S("\nfound %d unreferenced roots\n", len(roots))
if len(roots) == 0 {
printer.P("no snapshot to write.\n")
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
tree := data.NewTree(len(roots))
for id := range roots {
var subtreeID = id
node := data.Node{
Type: data.NodeTypeDir,
Name: id.Str(),
Mode: 0755,
Subtree: &subtreeID,
AccessTime: time.Now(),
ModTime: time.Now(),
ChangeTime: time.Now(),
}
err := tree.Insert(&node)
if err != nil {
return err
}
}
var treeID restic.ID
err = repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
var err error
treeID, err = data.SaveTree(ctx, uploader, tree)
if err != nil {
return errors.Fatalf("unable to save new tree to the repository: %v", err)
}
return nil
})
if err != nil {
return err
}
return createSnapshot(ctx, printer, "/recover", hostname, []string{"recovered"}, repo, &treeID)
}
func createSnapshot(ctx context.Context, printer progress.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)
}
sn.Tree = tree
id, err := data.SaveSnapshot(ctx, repo, sn)
if err != nil {
return errors.Fatalf("unable to save snapshot: %v", err)
}
printer.S("saved new snapshot %v\n", id.Str())
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_stats_test.go | cmd/restic/cmd_stats_test.go | package main
import (
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestSizeHistogramNew(t *testing.T) {
h := newSizeHistogram(42)
exp := &sizeHistogram{
count: 0,
totalSize: 0,
buckets: []sizeClass{
{0, 0, 0},
{1, 9, 0},
{10, 42, 0},
},
}
rtest.Equals(t, exp, h)
}
func TestSizeHistogramAdd(t *testing.T) {
h := newSizeHistogram(42)
for i := uint64(0); i < 45; i++ {
h.Add(i)
}
exp := &sizeHistogram{
count: 45,
totalSize: 990,
buckets: []sizeClass{
{0, 0, 1},
{1, 9, 9},
{10, 42, 33},
},
oversized: []uint64{43, 44},
}
rtest.Equals(t, exp, h)
}
func TestSizeHistogramString(t *testing.T) {
t.Run("overflow", func(t *testing.T) {
h := newSizeHistogram(42)
h.Add(8)
h.Add(50)
rtest.Equals(t, "Count: 2\nTotal Size: 58 B\nSize Count\n-----------------\n1 - 9 Byte 1\n-----------------\nOversized: [50]\n", h.String())
})
t.Run("withZero", func(t *testing.T) {
h := newSizeHistogram(42)
h.Add(0)
h.Add(1)
h.Add(10)
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())
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_list.go | cmd/restic/cmd_list.go | package main
import (
"context"
"strings"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository/index"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/spf13/cobra"
)
func newListCommand(globalOptions *global.Options) *cobra.Command {
var listAllowedArgs = []string{"blobs", "packs", "index", "snapshots", "keys", "locks"}
var listAllowedArgsUseString = strings.Join(listAllowedArgs, "|")
cmd := &cobra.Command{
Use: "list [flags] [" + listAllowedArgsUseString + "]",
Short: "List objects in the repository",
Long: `
The "list" command allows listing objects in the repository based on type.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
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)
},
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)
if len(args) != 1 {
return errors.Fatal("type not specified")
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock || args[0] == "locks", printer)
if err != nil {
return err
}
defer unlock()
var t restic.FileType
switch args[0] {
case "packs":
t = restic.PackFile
case "index":
t = restic.IndexFile
case "snapshots":
t = restic.SnapshotFile
case "keys":
t = restic.KeyFile
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 blobs := range idx.Values() {
if ctx.Err() != nil {
return ctx.Err()
}
printer.S("%v %v", blobs.Type, blobs.ID)
}
return nil
})
default:
return errors.Fatal("invalid type")
}
return repo.List(ctx, t, func(id restic.ID, _ int64) error {
printer.S("%s", id)
return nil
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key_integration_test.go | cmd/restic/cmd_key_integration_test.go | package main
import (
"bufio"
"context"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/restic/restic/internal/backend"
"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 {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyList(ctx, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
scanner := bufio.NewScanner(buf)
exp := regexp.MustCompile(`^ ([a-f0-9]+) `)
IDs := []string{}
for scanner.Scan() {
if id := exp.FindStringSubmatch(scanner.Text()); id != nil {
IDs = append(IDs, id[1])
}
}
return IDs
}
func testRunKeyAddNewKey(t testing.TB, newPassword string, gopts global.Options) {
testKeyNewPassword = newPassword
defer func() {
testKeyNewPassword = ""
}()
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{}, []string{}, gopts.Term)
})
rtest.OK(t, err)
}
func testRunKeyAddNewKeyUserHost(t testing.TB, gopts global.Options) {
testKeyNewPassword = "john's geheimnis"
defer func() {
testKeyNewPassword = ""
}()
t.Log("adding key for john@example.com")
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{
Username: "john",
Hostname: "example.com",
}, []string{}, gopts.Term)
})
rtest.OK(t, err)
_ = withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
repo, err := global.OpenRepository(ctx, gopts, &progress.NoopPrinter{})
rtest.OK(t, err)
key, err := repository.SearchKey(ctx, repo, testKeyNewPassword, 2, "")
rtest.OK(t, err)
rtest.Equals(t, "john", key.Username)
rtest.Equals(t, "example.com", key.Hostname)
return nil
})
}
func testRunKeyPasswd(t testing.TB, newPassword string, gopts global.Options) {
testKeyNewPassword = newPassword
defer func() {
testKeyNewPassword = ""
}()
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyPasswd(ctx, gopts, KeyPasswdOptions{}, []string{}, gopts.Term)
})
rtest.OK(t, err)
}
func testRunKeyRemove(t testing.TB, gopts global.Options, IDs []string) {
t.Logf("remove %d keys: %q\n", len(IDs), IDs)
for _, id := range IDs {
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyRemove(ctx, gopts, []string{id}, gopts.Term)
})
rtest.OK(t, err)
}
}
func TestKeyAddRemove(t *testing.T) {
passwordList := []string{
"OnnyiasyatvodsEvVodyawit",
"raicneirvOjEfEigonOmLasOd",
}
env, cleanup := withTestEnvironment(t)
// must list keys more than once
env.gopts.BackendTestHook = nil
defer cleanup()
testRunInit(t, env.gopts)
testRunKeyPasswd(t, "geheim2", env.gopts)
env.gopts.Password = "geheim2"
t.Logf("changed password to %q", env.gopts.Password)
for _, newPassword := range passwordList {
testRunKeyAddNewKey(t, newPassword, env.gopts)
t.Logf("added new password %q", newPassword)
env.gopts.Password = newPassword
testRunKeyRemove(t, env.gopts, testRunKeyListOtherIDs(t, env.gopts))
}
env.gopts.Password = passwordList[len(passwordList)-1]
t.Logf("testing access with last password %q\n", env.gopts.Password)
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyList(ctx, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
testRunCheck(t, env.gopts)
testRunKeyAddNewKeyUserHost(t, env.gopts)
}
func TestKeyAddInvalid(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{
NewPasswordFile: "some-file",
InsecureNoPassword: true,
}, []string{}, gopts.Term)
})
rtest.Assert(t, strings.Contains(err.Error(), "only either"), "unexpected error message, got %q", err)
pwfile := filepath.Join(t.TempDir(), "pwfile")
rtest.OK(t, os.WriteFile(pwfile, []byte{}, 0o666))
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{
NewPasswordFile: pwfile,
}, []string{}, gopts.Term)
})
rtest.Assert(t, strings.Contains(err.Error(), "an empty password is not allowed by default"), "unexpected error message, got %q", err)
}
func TestKeyAddEmpty(t *testing.T) {
env, cleanup := withTestEnvironment(t)
// must list keys more than once
env.gopts.BackendTestHook = nil
defer cleanup()
testRunInit(t, env.gopts)
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{
InsecureNoPassword: true,
}, []string{}, gopts.Term)
})
rtest.OK(t, err)
env.gopts.Password = ""
env.gopts.InsecureNoPassword = true
testRunCheck(t, env.gopts)
}
type emptySaveBackend struct {
backend.Backend
}
func (b *emptySaveBackend) Save(ctx context.Context, h backend.Handle, _ backend.RewindReader) error {
return b.Backend.Save(ctx, h, backend.NewByteReader([]byte{}, nil))
}
func TestKeyProblems(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
return &emptySaveBackend{r}, nil
}
testKeyNewPassword = "geheim2"
defer func() {
testKeyNewPassword = ""
}()
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyPasswd(ctx, gopts, KeyPasswdOptions{}, []string{}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil, "expected passwd change to fail")
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{}, []string{}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil, "expected key adding to fail")
t.Logf("testing access with initial password %q\n", env.gopts.Password)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyList(ctx, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
testRunCheck(t, env.gopts)
}
func TestKeyCommandInvalidArguments(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
return &emptySaveBackend{r}, nil
}
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyAdd(ctx, gopts, KeyAddOptions{}, []string{"johndoe"}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "no arguments"), "unexpected error for key add: %v", err)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyPasswd(ctx, gopts, KeyPasswdOptions{}, []string{"johndoe"}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "no arguments"), "unexpected error for key passwd: %v", err)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyList(ctx, gopts, []string{"johndoe"}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "no arguments"), "unexpected error for key list: %v", err)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyRemove(ctx, gopts, []string{}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "one argument"), "unexpected error for key remove: %v", err)
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runKeyRemove(ctx, gopts, []string{"john", "doe"}, gopts.Term)
})
t.Log(err)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "one argument"), "unexpected error for key remove: %v", err)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/find_test.go | cmd/restic/find_test.go | package main
import (
"testing"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
"github.com/spf13/pflag"
)
func TestSnapshotFilter(t *testing.T) {
for _, test := range []struct {
name string
args []string
expected []string
env string
}{
{
"no value",
[]string{},
nil,
"",
},
{
"args only",
[]string{"--host", "abc"},
[]string{"abc"},
"",
},
{
"env default",
[]string{},
[]string{"def"},
"def",
},
{
"both",
[]string{"--host", "abc"},
[]string{"abc"},
"def",
},
{
"env set, empty flag overrides",
[]string{"--host", ""},
nil, // empty host filter means all hosts
"envhost",
},
{
"env set, multiple flags override",
[]string{"--host", "host1", "--host", "host2"},
[]string{"host1", "host2"},
"envhost",
},
{
"env set, multiple hosts including empty",
[]string{"--host", "host1", "--host", ""},
[]string{"host1", ""},
"envhost",
},
} {
t.Run(test.name, func(t *testing.T) {
t.Setenv("RESTIC_HOST", test.env)
for _, mode := range []bool{false, true} {
set := pflag.NewFlagSet("test", pflag.PanicOnError)
flt := &data.SnapshotFilter{}
if mode {
initMultiSnapshotFilter(set, flt, false)
} else {
initSingleSnapshotFilter(set, flt)
}
err := set.Parse(test.args)
rtest.OK(t, err)
// Apply the finalization logic to handle env defaults
finalizeSnapshotFilter(flt)
rtest.Equals(t, test.expected, flt.Hosts, "unexpected hosts")
}
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/format.go | cmd/restic/format.go | package main
import (
"fmt"
"os"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
)
func formatNode(path string, n *data.Node, long bool, human bool) string {
if !long {
return path
}
var mode os.FileMode
var target string
var size string
if human {
size = ui.FormatBytes(n.Size)
} else {
size = fmt.Sprintf("%6d", n.Size)
}
switch n.Type {
case data.NodeTypeFile:
mode = 0
case data.NodeTypeDir:
mode = os.ModeDir
case data.NodeTypeSymlink:
mode = os.ModeSymlink
target = fmt.Sprintf(" -> %v", n.LinkTarget)
case data.NodeTypeDev:
mode = os.ModeDevice
case data.NodeTypeCharDev:
mode = os.ModeDevice | os.ModeCharDevice
case data.NodeTypeFifo:
mode = os.ModeNamedPipe
case data.NodeTypeSocket:
mode = os.ModeSocket
}
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,
target)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/find.go | cmd/restic/find.go | 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 restic.FindFilteredSnapshots or FindFilteredSnapshots
// MUST be followed by finalizeSnapshotFilter after flag parsing
func initMultiSnapshotFilter(flags *pflag.FlagSet, filt *data.SnapshotFilter, addHostShorthand bool) {
hostShorthand := "H"
if !addHostShorthand {
hostShorthand = ""
}
flags.StringArrayVarP(&filt.Hosts, "host", hostShorthand, nil, "only consider snapshots for this `host` (can be specified multiple times, use empty string to unset default value) (default: $RESTIC_HOST)")
flags.Var(&filt.Tags, "tag", "only consider snapshots including `tag[,tag,...]` (can be specified multiple times)")
flags.StringArrayVar(&filt.Paths, "path", nil, "only consider snapshots including this (absolute) `path` (can be specified multiple times, snapshots must include all specified paths)")
}
// initSingleSnapshotFilter is used for commands that work on a single snapshot
// MUST be combined with restic.FindFilteredSnapshot
// MUST be followed by finalizeSnapshotFilter after flag parsing
func initSingleSnapshotFilter(flags *pflag.FlagSet, filt *data.SnapshotFilter) {
flags.StringArrayVarP(&filt.Hosts, "host", "H", nil, "only consider snapshots for this `host`, when snapshot ID \"latest\" is given (can be specified multiple times, use empty string to unset default value) (default: $RESTIC_HOST)")
flags.Var(&filt.Tags, "tag", "only consider snapshots including `tag[,tag,...]`, when snapshot ID \"latest\" is given (can be specified multiple times)")
flags.StringArrayVar(&filt.Paths, "path", nil, "only consider snapshots including this (absolute) `path`, when snapshot ID \"latest\" is given (can be specified multiple times, snapshots must include all specified paths)")
}
// finalizeSnapshotFilter applies RESTIC_HOST default only if --host flag wasn't explicitly set.
// This allows users to override RESTIC_HOST by providing --host="" or --host with explicit values.
func finalizeSnapshotFilter(filt *data.SnapshotFilter) {
// Only apply RESTIC_HOST default if the --host flag wasn't changed by the user
if filt.Hosts == nil {
if host := os.Getenv("RESTIC_HOST"); host != "" {
filt.Hosts = []string{host}
}
}
// If flag was set to empty string explicitly (e.g., --host=""),
// filt.Hosts will be []string{""} which should be cleaned up to allow all hosts
if len(filt.Hosts) == 1 && filt.Hosts[0] == "" {
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
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_diff_integration_test.go | cmd/restic/cmd_diff_integration_test.go | package main
import (
"bufio"
"context"
"encoding/json"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunDiffOutput(t testing.TB, gopts global.Options, firstSnapshotID string, secondSnapshotID string) (string, error) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
opts := DiffOptions{
ShowMetadata: false,
}
return runDiff(ctx, opts, gopts, []string{firstSnapshotID, secondSnapshotID}, gopts.Term)
})
return buf.String(), err
}
func copyFile(dst string, src string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
dstFile, err := os.Create(dst)
if err != nil {
// ignore subsequent errors
_ = srcFile.Close()
return err
}
_, err = io.Copy(dstFile, srcFile)
if err != nil {
// ignore subsequent errors
_ = srcFile.Close()
_ = dstFile.Close()
return err
}
err = srcFile.Close()
if err != nil {
// ignore subsequent errors
_ = dstFile.Close()
return err
}
err = dstFile.Close()
if err != nil {
return err
}
return nil
}
var diffOutputRegexPatterns = []string{
"-.+modfile",
"M.+modfile1",
"\\+.+modfile2",
"\\+.+modfile3",
"\\+.+modfile4",
"-.+submoddir",
"-.+submoddir.subsubmoddir",
"\\+.+submoddir2",
"\\+.+submoddir2.subsubmoddir",
"Files: +2 new, +1 removed, +1 changed",
"Dirs: +3 new, +2 removed",
"Data Blobs: +2 new, +1 removed",
"Added: +7[0-9]{2}\\.[0-9]{3} KiB",
"Removed: +2[0-9]{2}\\.[0-9]{3} KiB",
}
func setupDiffRepo(t *testing.T) (*testEnvironment, func(), string, string) {
env, cleanup := withTestEnvironment(t)
testRunInit(t, env.gopts)
datadir := filepath.Join(env.base, "testdata")
testdir := filepath.Join(datadir, "testdir")
subtestdir := filepath.Join(testdir, "subtestdir")
testfile := filepath.Join(testdir, "testfile")
rtest.OK(t, os.Mkdir(testdir, 0755))
rtest.OK(t, os.Mkdir(subtestdir, 0755))
rtest.OK(t, appendRandomData(testfile, 256*1024))
moddir := filepath.Join(datadir, "moddir")
submoddir := filepath.Join(moddir, "submoddir")
subsubmoddir := filepath.Join(submoddir, "subsubmoddir")
modfile := filepath.Join(moddir, "modfile")
rtest.OK(t, os.Mkdir(moddir, 0755))
rtest.OK(t, os.Mkdir(submoddir, 0755))
rtest.OK(t, os.Mkdir(subsubmoddir, 0755))
rtest.OK(t, copyFile(modfile, testfile))
rtest.OK(t, appendRandomData(modfile+"1", 256*1024))
snapshots := make(map[string]struct{})
opts := BackupOptions{}
testRunBackup(t, "", []string{datadir}, opts, env.gopts)
snapshots, firstSnapshotID := lastSnapshot(snapshots, loadSnapshotMap(t, env.gopts))
rtest.OK(t, os.Rename(modfile, modfile+"3"))
rtest.OK(t, os.Rename(submoddir, submoddir+"2"))
rtest.OK(t, appendRandomData(modfile+"1", 256*1024))
rtest.OK(t, appendRandomData(modfile+"2", 256*1024))
rtest.OK(t, os.Mkdir(modfile+"4", 0755))
testRunBackup(t, "", []string{datadir}, opts, env.gopts)
_, secondSnapshotID := lastSnapshot(snapshots, loadSnapshotMap(t, env.gopts))
return env, cleanup, firstSnapshotID, secondSnapshotID
}
func TestDiff(t *testing.T) {
env, cleanup, firstSnapshotID, secondSnapshotID := setupDiffRepo(t)
defer cleanup()
// quiet suppresses the diff output except for the summary
env.gopts.Quiet = false
_, err := testRunDiffOutput(t, env.gopts, "", secondSnapshotID)
rtest.Assert(t, err != nil, "expected error on invalid snapshot id")
out, err := testRunDiffOutput(t, env.gopts, firstSnapshotID, secondSnapshotID)
rtest.OK(t, err)
for _, pattern := range diffOutputRegexPatterns {
r, err := regexp.Compile(pattern)
rtest.Assert(t, err == nil, "failed to compile regexp %v", pattern)
rtest.Assert(t, r.MatchString(out), "expected pattern %v in output, got\n%v", pattern, out)
}
// check quiet output
env.gopts.Quiet = true
outQuiet, err := testRunDiffOutput(t, env.gopts, firstSnapshotID, secondSnapshotID)
rtest.OK(t, err)
rtest.Assert(t, len(outQuiet) < len(out), "expected shorter output on quiet mode %v vs. %v", len(outQuiet), len(out))
}
type typeSniffer struct {
MessageType string `json:"message_type"`
}
func TestDiffJSON(t *testing.T) {
env, cleanup, firstSnapshotID, secondSnapshotID := setupDiffRepo(t)
defer cleanup()
// quiet suppresses the diff output except for the summary
env.gopts.Quiet = false
env.gopts.JSON = true
out, err := testRunDiffOutput(t, env.gopts, firstSnapshotID, secondSnapshotID)
rtest.OK(t, err)
var stat DiffStatsContainer
var changes int
scanner := bufio.NewScanner(strings.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
var sniffer typeSniffer
rtest.OK(t, json.Unmarshal([]byte(line), &sniffer))
switch sniffer.MessageType {
case "change":
changes++
case "statistics":
rtest.OK(t, json.Unmarshal([]byte(line), &stat))
default:
t.Fatalf("unexpected message type %v", sniffer.MessageType)
}
}
rtest.Equals(t, 9, changes)
rtest.Assert(t, stat.Added.Files == 2 && stat.Added.Dirs == 3 && stat.Added.DataBlobs == 2 &&
stat.Removed.Files == 1 && stat.Removed.Dirs == 2 && stat.Removed.DataBlobs == 1 &&
stat.ChangedFiles == 1, "unexpected statistics")
// check quiet output
env.gopts.Quiet = true
outQuiet, err := testRunDiffOutput(t, env.gopts, firstSnapshotID, secondSnapshotID)
rtest.OK(t, err)
stat = DiffStatsContainer{}
rtest.OK(t, json.Unmarshal([]byte(outQuiet), &stat))
rtest.Assert(t, stat.Added.Files == 2 && stat.Added.Dirs == 3 && stat.Added.DataBlobs == 2 &&
stat.Removed.Files == 1 && stat.Removed.Dirs == 2 && stat.Removed.DataBlobs == 1 &&
stat.ChangedFiles == 1, "unexpected statistics")
rtest.Assert(t, stat.SourceSnapshot == firstSnapshotID && stat.TargetSnapshot == secondSnapshotID, "unexpected snapshot ids")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_snapshots_test.go | cmd/restic/cmd_snapshots_test.go | package main
import (
"strings"
"testing"
rtest "github.com/restic/restic/internal/test"
)
// Regression test for #2979: no snapshots should print as [], not null.
func TestEmptySnapshotGroupJSON(t *testing.T) {
for _, grouped := range []bool{false, true} {
var w strings.Builder
err := printSnapshotGroupJSON(&w, nil, grouped)
rtest.OK(t, err)
rtest.Equals(t, "[]", strings.TrimSpace(w.String()))
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_options.go | cmd/restic/cmd_options.go | package main
import (
"fmt"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/options"
"github.com/spf13/cobra"
)
func newOptionsCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "options",
Short: "Print list of extended options",
Long: `
The "options" command prints a list of extended options.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
GroupID: cmdGroupAdvanced,
DisableAutoGenTag: true,
Run: func(_ *cobra.Command, _ []string) {
globalOptions.Term.Print("All Extended Options:")
var maxLen int
for _, opt := range options.List() {
if l := len(opt.Namespace + "." + opt.Name); l > maxLen {
maxLen = l
}
}
for _, opt := range options.List() {
globalOptions.Term.Print(fmt.Sprintf(" %*s %s", -maxLen, opt.Namespace+"."+opt.Name, opt.Text))
}
},
}
return cmd
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/integration_helpers_windows_test.go | cmd/restic/integration_helpers_windows_test.go | //go:build windows
package main
import (
"fmt"
"io"
"os"
)
func (e *dirEntry) equals(out io.Writer, other *dirEntry) bool {
if e.path != other.path {
fmt.Fprintf(out, "%v: path does not match (%v != %v)\n", e.path, e.path, other.path)
return false
}
if e.fi.Mode() != other.fi.Mode() {
fmt.Fprintf(out, "%v: mode does not match (%v != %v)\n", e.path, e.fi.Mode(), other.fi.Mode())
return false
}
if !sameModTime(e.fi, other.fi) {
fmt.Fprintf(out, "%v: ModTime does not match (%v != %v)\n", e.path, e.fi.ModTime(), other.fi.ModTime())
return false
}
return true
}
func nlink(_ os.FileInfo) uint64 {
return 1
}
func inode(_ os.FileInfo) uint64 {
return uint64(0)
}
func createFileSetPerHardlink(dir string) map[uint64][]string {
linkTests := make(map[uint64][]string)
files, err := os.ReadDir(dir)
if err != nil {
return nil
}
for i, f := range files {
linkTests[uint64(i)] = append(linkTests[uint64(i)], f.Name())
}
return linkTests
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_recover_integration_test.go | cmd/restic/cmd_recover_integration_test.go | package main
import (
"context"
"testing"
"github.com/restic/restic/internal/global"
rtest "github.com/restic/restic/internal/test"
)
func testRunRecover(t testing.TB, gopts global.Options) {
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRecover(context.TODO(), gopts, gopts.Term)
}))
}
func TestRecover(t *testing.T) {
env, cleanup := withTestEnvironment(t)
// must list index more than once
env.gopts.BackendTestHook = nil
defer cleanup()
testSetupBackupData(t, env)
// create backup and forget it afterwards
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
ids := testListSnapshots(t, env.gopts, 1)
sn := testLoadSnapshot(t, env.gopts, ids[0])
testRunForget(t, env.gopts, ForgetOptions{}, ids[0].String())
testListSnapshots(t, env.gopts, 0)
testRunRecover(t, env.gopts)
ids = testListSnapshots(t, env.gopts, 1)
testRunCheck(t, env.gopts)
// check that the root tree is included in the snapshot
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runCat(context.TODO(), gopts, []string{"tree", ids[0].String() + ":" + sn.Tree.Str()}, gopts.Term)
}))
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_self_update_disabled.go | cmd/restic/cmd_self_update_disabled.go | //go:build !selfupdate
package main
import (
"github.com/restic/restic/internal/global"
"github.com/spf13/cobra"
)
func registerSelfUpdateCommand(_ *cobra.Command, _ *global.Options) {
// No commands to register in non-selfupdate mode
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_restore_integration_test.go | cmd/restic/cmd_restore_integration_test.go | package main
import (
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunRestore(t testing.TB, gopts global.Options, dir string, snapshotID string) {
testRunRestoreExcludes(t, gopts, dir, snapshotID, nil)
}
func testRunRestoreExcludes(t testing.TB, gopts global.Options, dir string, snapshotID string, excludes []string) {
opts := RestoreOptions{
Target: dir,
}
opts.Excludes = excludes
rtest.OK(t, testRunRestoreAssumeFailure(t, snapshotID, opts, gopts))
}
func testRunRestoreAssumeFailure(t testing.TB, snapshotID string, opts RestoreOptions, gopts global.Options) error {
return withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runRestore(ctx, opts, gopts, gopts.Term, []string{snapshotID})
})
}
func testRunRestoreLatest(t testing.TB, gopts global.Options, dir string, paths []string, hosts []string) {
opts := RestoreOptions{
Target: dir,
SnapshotFilter: data.SnapshotFilter{
Hosts: hosts,
Paths: paths,
},
}
rtest.OK(t, testRunRestoreAssumeFailure(t, "latest", opts, gopts))
}
func testRunRestoreIncludes(t testing.TB, gopts global.Options, dir string, snapshotID restic.ID, includes []string) {
opts := RestoreOptions{
Target: dir,
}
opts.Includes = includes
rtest.OK(t, testRunRestoreAssumeFailure(t, snapshotID.String(), opts, gopts))
}
func testRunRestoreIncludesFromFile(t testing.TB, gopts global.Options, dir string, snapshotID restic.ID, includesFile string) {
opts := RestoreOptions{
Target: dir,
}
opts.IncludeFiles = []string{includesFile}
rtest.OK(t, testRunRestoreAssumeFailure(t, snapshotID.String(), opts, gopts))
}
func testRunRestoreExcludesFromFile(t testing.TB, gopts global.Options, dir string, snapshotID restic.ID, excludesFile string) {
opts := RestoreOptions{
Target: dir,
}
opts.ExcludeFiles = []string{excludesFile}
rtest.OK(t, testRunRestoreAssumeFailure(t, snapshotID.String(), opts, gopts))
}
func TestRestoreMustFailWhenUsingBothIncludesAndExcludes(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
// Add both include and exclude patterns
includePatterns := []string{"dir1/*include_me.txt", "dir2/**", "dir4/**/*_me.txt"}
excludePatterns := []string{"dir1/*include_me.txt", "dir2/**", "dir4/**/*_me.txt"}
restoredir := filepath.Join(env.base, "restore")
restoreOpts := RestoreOptions{
Target: restoredir,
}
restoreOpts.Includes = includePatterns
restoreOpts.Excludes = excludePatterns
err := testRunRestoreAssumeFailure(t, "latest", restoreOpts, env.gopts)
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "exclude and include patterns are mutually exclusive"),
"expected: %s error, got %v", "exclude and include patterns are mutually exclusive", err)
}
func TestRestoreIncludes(t *testing.T) {
testfiles := []struct {
path string
size uint
include bool // Whether this file should be included in the restore
}{
{"dir1/include_me.txt", 100, true},
{"dir1/something_else.txt", 200, false},
{"dir2/also_include_me.txt", 150, true},
{"dir2/important_file.txt", 150, true},
{"dir3/not_included.txt", 180, false},
{"dir4/subdir/should_include_me.txt", 120, true},
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
// Create test files and directories
for _, testFile := range testfiles {
fullPath := filepath.Join(env.testdata, testFile.path)
rtest.OK(t, os.MkdirAll(filepath.Dir(fullPath), 0755))
rtest.OK(t, appendRandomData(fullPath, testFile.size))
}
opts := BackupOptions{}
// Perform backup
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
snapshotID := testListSnapshots(t, env.gopts, 1)[0]
// Restore using includes
includePatterns := []string{"dir1/*include_me.txt", "dir2/**", "dir4/**/*_me.txt"}
restoredir := filepath.Join(env.base, "restore")
testRunRestoreIncludes(t, env.gopts, restoredir, snapshotID, includePatterns)
testRestoreFileInclusions := func(t *testing.T) {
// Check that only the included files are restored
for _, testFile := range testfiles {
restoredFilePath := filepath.Join(restoredir, "testdata", testFile.path)
_, err := os.Stat(restoredFilePath)
if testFile.include {
rtest.OK(t, err)
} else {
rtest.Assert(t, os.IsNotExist(err), "File %s should not have been restored", testFile.path)
}
}
}
testRestoreFileInclusions(t)
// Create an include file with some patterns
patternsFile := env.base + "/patternsFile"
fileErr := os.WriteFile(patternsFile, []byte(strings.Join(includePatterns, "\n")), 0644)
if fileErr != nil {
t.Fatalf("Could not write include file: %v", fileErr)
}
restoredir = filepath.Join(env.base, "restore-include-from-file")
testRunRestoreIncludesFromFile(t, env.gopts, restoredir, snapshotID, patternsFile)
testRestoreFileInclusions(t)
}
func TestRestoreFilter(t *testing.T) {
testfiles := []struct {
name string
size uint
exclude bool
}{
{"testfile1.c", 100, true},
{"testfile2.exe", 101, true},
{"subdir1/subdir2/testfile3.docx", 102, true},
{"subdir1/subdir2/testfile4.c", 102, false},
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
for _, testFile := range testfiles {
p := filepath.Join(env.testdata, testFile.name)
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, testFile.size))
}
opts := BackupOptions{}
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
snapshotID := testListSnapshots(t, env.gopts, 1)[0]
// no restore filter should restore all files
testRunRestore(t, env.gopts, filepath.Join(env.base, "restore0"), snapshotID.String())
for _, testFile := range testfiles {
rtest.OK(t, testFileSize(filepath.Join(env.base, "restore0", "testdata", testFile.name), int64(testFile.size)))
}
excludePatterns := []string{"testfile1.c", "*.exe", "*file3*"}
// checks if the files are excluded correctly
testRestoredFileExclusions := func(t *testing.T, restoredir string) {
for _, testFile := range testfiles {
restoredFilePath := filepath.Join(restoredir, "testdata", testFile.name)
_, err := os.Stat(restoredFilePath)
if testFile.exclude {
rtest.Assert(t, os.IsNotExist(err), "File %s should not have been restored", testFile.name)
} else {
rtest.OK(t, testFileSize(restoredFilePath, int64(testFile.size)))
}
}
}
// restore with excludes
restoredir := filepath.Join(env.base, "restore-with-excludes")
testRunRestoreExcludes(t, env.gopts, restoredir, snapshotID.String(), excludePatterns)
testRestoredFileExclusions(t, restoredir)
// Create an exclude file with some patterns
patternsFile := env.base + "/patternsFile"
fileErr := os.WriteFile(patternsFile, []byte(strings.Join(excludePatterns, "\n")), 0644)
if fileErr != nil {
t.Fatalf("Could not write include file: %v", fileErr)
}
// restore with excludes from file
restoredir = filepath.Join(env.base, "restore-with-exclude-from-file")
testRunRestoreExcludesFromFile(t, env.gopts, restoredir, snapshotID, patternsFile)
testRestoredFileExclusions(t, restoredir)
}
func TestRestore(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
for i := 0; i < 10; i++ {
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))))
}
opts := BackupOptions{}
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
// Restore latest without any filters
restoredir := filepath.Join(env.base, "restore")
testRunRestoreLatest(t, env.gopts, restoredir, nil, nil)
diff := directoriesContentsDiff(t, env.testdata, filepath.Join(restoredir, filepath.Base(env.testdata)))
rtest.Assert(t, diff == "", "directories are not equal %v", diff)
}
func TestRestoreLatest(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
p := filepath.Join(env.testdata, "testfile.c")
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, 100))
opts := BackupOptions{}
// chdir manually here so we can get the current directory. This is not the
// same as the temp dir returned by os.MkdirTemp() on darwin.
back := rtest.Chdir(t, filepath.Dir(env.testdata))
defer back()
curdir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
testRunBackup(t, "", []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
rtest.OK(t, os.Remove(p))
rtest.OK(t, appendRandomData(p, 101))
testRunBackup(t, "", []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
// Restore latest without any filters
testRunRestoreLatest(t, env.gopts, filepath.Join(env.base, "restore0"), nil, nil)
rtest.OK(t, testFileSize(filepath.Join(env.base, "restore0", "testdata", "testfile.c"), int64(101)))
// Setup test files in different directories backed up in different snapshots
p1 := filepath.Join(curdir, filepath.FromSlash("p1/testfile.c"))
rtest.OK(t, os.MkdirAll(filepath.Dir(p1), 0755))
rtest.OK(t, appendRandomData(p1, 102))
testRunBackup(t, "", []string{"p1"}, opts, env.gopts)
testRunCheck(t, env.gopts)
p2 := filepath.Join(curdir, filepath.FromSlash("p2/testfile.c"))
rtest.OK(t, os.MkdirAll(filepath.Dir(p2), 0755))
rtest.OK(t, appendRandomData(p2, 103))
testRunBackup(t, "", []string{"p2"}, opts, env.gopts)
testRunCheck(t, env.gopts)
p1rAbs := filepath.Join(env.base, "restore1", "p1/testfile.c")
p2rAbs := filepath.Join(env.base, "restore2", "p2/testfile.c")
testRunRestoreLatest(t, env.gopts, filepath.Join(env.base, "restore1"), []string{filepath.Dir(p1)}, nil)
rtest.OK(t, testFileSize(p1rAbs, int64(102)))
if _, err := os.Stat(p2rAbs); os.IsNotExist(err) {
rtest.Assert(t, os.IsNotExist(err),
"expected %v to not exist in restore, but it exists, err %v", p2rAbs, err)
}
testRunRestoreLatest(t, env.gopts, filepath.Join(env.base, "restore2"), []string{filepath.Dir(p2)}, nil)
rtest.OK(t, testFileSize(p2rAbs, int64(103)))
if _, err := os.Stat(p1rAbs); os.IsNotExist(err) {
rtest.Assert(t, os.IsNotExist(err),
"expected %v to not exist in restore, but it exists, err %v", p1rAbs, err)
}
}
func TestRestoreWithPermissionFailure(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("testdata", "repo-restore-permissions-test.tar.gz")
rtest.SetupTarTestFixture(t, env.base, datafile)
snapshots := testListSnapshots(t, env.gopts, 1)
testRunRestore(t, env.gopts, filepath.Join(env.base, "restore"), snapshots[0].String())
// make sure that all files have been restored, regardless of any
// permission errors
files := testRunLs(t, env.gopts, snapshots[0].String())
for _, filename := range files {
fi, err := os.Lstat(filepath.Join(env.base, "restore", filename))
rtest.OK(t, err)
rtest.Assert(t, !isFile(fi) || fi.Size() > 0,
"file %v restored, but filesize is 0", filename)
}
}
func setZeroModTime(filename string) error {
var utimes = []syscall.Timespec{
syscall.NsecToTimespec(0),
syscall.NsecToTimespec(0),
}
return syscall.UtimesNano(filename, utimes)
}
func TestRestoreNoMetadataOnIgnoredIntermediateDirs(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testRunInit(t, env.gopts)
p := filepath.Join(env.testdata, "subdir1", "subdir2", "subdir3", "file.ext")
rtest.OK(t, os.MkdirAll(filepath.Dir(p), 0755))
rtest.OK(t, appendRandomData(p, 200))
rtest.OK(t, setZeroModTime(filepath.Join(env.testdata, "subdir1", "subdir2")))
opts := BackupOptions{}
testRunBackup(t, filepath.Dir(env.testdata), []string{filepath.Base(env.testdata)}, opts, env.gopts)
testRunCheck(t, env.gopts)
snapshotID := testListSnapshots(t, env.gopts, 1)[0]
// restore with filter "*.ext", this should restore "file.ext", but
// since the directories are ignored and only created because of
// "file.ext", no meta data should be restored for them.
testRunRestoreIncludes(t, env.gopts, filepath.Join(env.base, "restore0"), snapshotID, []string{"*.ext"})
f1 := filepath.Join(env.base, "restore0", "testdata", "subdir1", "subdir2")
_, err := os.Stat(f1)
rtest.OK(t, err)
// restore with filter "*", this should restore meta data on everything.
testRunRestoreIncludes(t, env.gopts, filepath.Join(env.base, "restore1"), snapshotID, []string{"*"})
f2 := filepath.Join(env.base, "restore1", "testdata", "subdir1", "subdir2")
fi, err := os.Stat(f2)
rtest.OK(t, err)
rtest.Assert(t, fi.ModTime().Equal(time.Unix(0, 0)),
"meta data of intermediate directory hasn't been restore")
}
func TestRestoreDefaultLayout(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("..", "..", "internal", "backend", "testdata", "repo-layout-default.tar.gz")
rtest.SetupTarTestFixture(t, env.base, datafile)
// check the repo
testRunCheck(t, env.gopts)
// restore latest snapshot
target := filepath.Join(env.base, "restore")
testRunRestoreLatest(t, env.gopts, target, nil, nil)
rtest.RemoveAll(t, filepath.Join(env.base, "repo"))
rtest.RemoveAll(t, target)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_init_integration_test.go | cmd/restic/cmd_init_integration_test.go | package main
import (
"context"
"os"
"path/filepath"
"testing"
"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/progress"
)
func testRunInit(t testing.TB, gopts global.Options) {
repository.TestUseLowSecurityKDFParameters(t)
restic.TestDisableCheckPolynomial(t)
restic.TestSetLockTimeout(t, 0)
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runInit(ctx, InitOptions{}, gopts, nil, gopts.Term)
})
rtest.OK(t, err)
t.Logf("repository initialized at %v", gopts.Repo)
// 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.WriteFile(filepath.Join(gopts.Repo, path, "tmp12345"), []byte("junk file"), 0o600))
}
}
func TestInitCopyChunkerParams(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env2, cleanup2 := withTestEnvironment(t)
defer cleanup2()
testRunInit(t, env2.gopts)
initOpts := InitOptions{
SecondaryRepoOptions: global.SecondaryRepoOptions{
Repo: env2.gopts.Repo,
Password: env2.gopts.Password,
},
}
err := withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runInit(ctx, initOpts, gopts, nil, gopts.Term)
})
rtest.Assert(t, err != nil, "expected invalid init options to fail")
initOpts.CopyChunkerParameters = true
err = withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runInit(ctx, initOpts, gopts, nil, gopts.Term)
})
rtest.OK(t, err)
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{})
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{})
return err
})
rtest.OK(t, err)
rtest.Assert(t, repo.Config().ChunkerPolynomial == otherRepo.Config().ChunkerPolynomial,
"expected equal chunker polynomials, got %v expected %v", repo.Config().ChunkerPolynomial,
otherRepo.Config().ChunkerPolynomial)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_self_update.go | cmd/restic/cmd_self_update.go | //go:build selfupdate
package main
import (
"context"
"os"
"path/filepath"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/selfupdate"
"github.com/restic/restic/internal/ui"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func registerSelfUpdateCommand(cmd *cobra.Command, globalOptions *global.Options) {
cmd.AddCommand(
newSelfUpdateCommand(globalOptions),
)
}
func newSelfUpdateCommand(globalOptions *global.Options) *cobra.Command {
var opts SelfUpdateOptions
cmd := &cobra.Command{
Use: "self-update [flags]",
Short: "Update the restic binary",
Long: `
The command "self-update" downloads the latest stable release of restic from
GitHub and replaces the currently running binary. After download, the
authenticity of the binary is verified using the GPG signature on the release
files.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runSelfUpdate(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// SelfUpdateOptions collects all options for the update-restic command.
type SelfUpdateOptions struct {
Output string
}
func (opts *SelfUpdateOptions) AddFlags(f *pflag.FlagSet) {
f.StringVar(&opts.Output, "output", "", "Save the downloaded file as `filename` (default: running binary itself)")
}
func runSelfUpdate(ctx context.Context, opts SelfUpdateOptions, gopts global.Options, args []string, term ui.Terminal) error {
if opts.Output == "" {
file, err := os.Executable()
if err != nil {
return errors.Wrap(err, "unable to find executable")
}
opts.Output = file
}
fi, err := os.Lstat(opts.Output)
if err != nil {
dirname := filepath.Dir(opts.Output)
di, err := os.Lstat(dirname)
if err != nil {
return err
}
if !di.Mode().IsDir() {
return errors.Fatalf("output parent path %v is not a directory, use --output to specify a different file path", dirname)
}
} else {
if !fi.Mode().IsRegular() {
return errors.Fatalf("output path %v is not a normal file, use --output to specify a different file path", opts.Output)
}
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
printer.P("writing restic to %v", opts.Output)
v, err := selfupdate.DownloadLatestStableRelease(ctx, opts.Output, global.Version, printer.P)
if err != nil {
return errors.Fatalf("unable to update restic: %v", err)
}
if v != global.Version {
printer.S("successfully updated restic to version %v", v)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_snapshots_integration_test.go | cmd/restic/cmd_snapshots_integration_test.go | package main
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunSnapshots(t testing.TB, gopts global.Options) (newest *Snapshot, snapmap map[restic.ID]Snapshot) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = true
opts := SnapshotOptions{}
return runSnapshots(ctx, opts, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
snapshots := []Snapshot{}
rtest.OK(t, json.Unmarshal(buf.Bytes(), &snapshots))
snapmap = make(map[restic.ID]Snapshot, len(snapshots))
for _, sn := range snapshots {
snapmap[*sn.ID] = sn
if newest == nil || sn.Time.After(newest.Time) {
newest = &sn
}
}
return
}
func TestSnapshotsGroupByAndLatest(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
// two backups on the same host but with different paths
opts := BackupOptions{Host: "testhost", TimeStamp: time.Now().Format(time.DateTime)}
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata"}, opts, env.gopts)
// Use later timestamp for second backup
opts.TimeStamp = time.Now().Add(time.Second).Format(time.DateTime)
snapshotsIDs := loadSnapshotMap(t, env.gopts)
testRunBackup(t, filepath.Dir(env.testdata), []string{"testdata/0"}, opts, env.gopts)
_, secondSnapshotID := lastSnapshot(snapshotsIDs, loadSnapshotMap(t, env.gopts))
buf, err := withCaptureStdout(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = true
// only group by host but not path
opts := SnapshotOptions{GroupBy: data.SnapshotGroupByOptions{Host: true}, Latest: 1}
return runSnapshots(ctx, opts, gopts, []string{}, gopts.Term)
})
rtest.OK(t, err)
snapshots := []SnapshotGroup{}
rtest.OK(t, json.Unmarshal(buf.Bytes(), &snapshots))
rtest.Assert(t, len(snapshots) == 1, "expected only one snapshot group, got %d", len(snapshots))
rtest.Assert(t, snapshots[0].GroupKey.Hostname == "testhost", "expected group_key.hostname to be set to testhost, got %s", snapshots[0].GroupKey.Hostname)
rtest.Assert(t, snapshots[0].GroupKey.Paths == nil, "expected group_key.paths to be set to nil, got %s", snapshots[0].GroupKey.Paths)
rtest.Assert(t, snapshots[0].GroupKey.Tags == nil, "expected group_key.tags to be set to nil, got %s", snapshots[0].GroupKey.Tags)
rtest.Assert(t, len(snapshots[0].Snapshots) == 1, "expected only one latest snapshot, got %d", len(snapshots[0].Snapshots))
rtest.Equals(t, snapshots[0].Snapshots[0].ID.String(), secondSnapshotID, "unexpected snapshot ID")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_repair_packs.go | cmd/restic/cmd_repair_packs.go | package main
import (
"bytes"
"context"
"io"
"os"
"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/spf13/cobra"
)
func newRepairPacksCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "packs [packIDs...]",
Short: "Salvage damaged pack files",
Long: `
The "repair packs" command extracts intact blobs from the specified pack files, rebuilds
the index to remove the damaged pack files and removes the pack files from the repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runRepairPacks(cmd.Context(), *globalOptions, globalOptions.Term, args)
},
}
return cmd
}
func runRepairPacks(ctx context.Context, gopts global.Options, term ui.Terminal, args []string) error {
ids := restic.NewIDSet()
for _, arg := range args {
id, err := restic.ParseID(arg)
if err != nil {
return err
}
ids.Insert(id)
}
if len(ids) == 0 {
return errors.Fatal("no ids specified")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
err = repo.LoadIndex(ctx, printer)
if err != nil {
return errors.Fatalf("%s", err)
}
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
}
f, err := os.OpenFile("pack-"+id.String(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666)
if err != nil {
return err
}
if _, err := io.Copy(f, bytes.NewReader(buf)); err != nil {
_ = f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
}
err = repository.RepairPacks(ctx, repo, ids, printer)
if err != nil {
return errors.Fatalf("%s", err)
}
printer.E("\nUse `restic repair snapshots --forget` to remove the corrupted data blobs from all snapshots")
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_prune.go | cmd/restic/cmd_prune.go | package main
import (
"context"
"math"
"runtime"
"strconv"
"strings"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"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"
"github.com/spf13/pflag"
)
func newPruneCommand(globalOptions *global.Options) *cobra.Command {
var opts PruneOptions
cmd := &cobra.Command{
Use: "prune [flags]",
Short: "Remove unneeded data from the repository",
Long: `
The "prune" command checks the repository and removes data that is not
referenced and therefore not needed any more.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
return runPrune(cmd.Context(), opts, *globalOptions, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// PruneOptions collects all options for the cleanup command.
type PruneOptions struct {
DryRun bool
UnsafeNoSpaceRecovery string
unsafeRecovery bool
MaxUnused string
maxUnusedBytes func(used uint64) (unused uint64) // calculates the number of unused bytes after repacking, according to MaxUnused
MaxRepackSize string
MaxRepackBytes uint64
RepackCacheableOnly bool
RepackSmall bool
RepackUncompressed bool
SmallPackSize string
SmallPackBytes uint64
}
func (opts *PruneOptions) AddFlags(f *pflag.FlagSet) {
opts.AddLimitedFlags(f)
f.BoolVarP(&opts.DryRun, "dry-run", "n", false, "do not modify the repository, just print what would be done")
f.StringVarP(&opts.UnsafeNoSpaceRecovery, "unsafe-recover-no-free-space", "", "", "UNSAFE, READ THE DOCUMENTATION BEFORE USING! Try to recover a repository stuck with no free space. Do not use without trying out 'prune --max-repack-size 0' first.")
}
func (opts *PruneOptions) AddLimitedFlags(f *pflag.FlagSet) {
f.StringVar(&opts.MaxUnused, "max-unused", "5%", "tolerate given `limit` of unused data (absolute value in bytes with suffixes k/K, m/M, g/G, t/T, a value in % or the word 'unlimited')")
f.StringVar(&opts.MaxRepackSize, "max-repack-size", "", "stop after repacking this much data in total (allowed suffixes for `size`: k/K, m/M, g/G, t/T)")
f.BoolVar(&opts.RepackCacheableOnly, "repack-cacheable-only", false, "only repack packs which are cacheable")
f.BoolVar(&opts.RepackSmall, "repack-small", false, "repack pack files below 80% of target pack 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: k/K, m/M)")
}
func verifyPruneOptions(opts *PruneOptions) error {
opts.MaxRepackBytes = math.MaxUint64
if len(opts.MaxRepackSize) > 0 {
size, err := ui.ParseBytes(opts.MaxRepackSize)
if err != nil {
return err
}
opts.MaxRepackBytes = uint64(size)
}
if opts.UnsafeNoSpaceRecovery != "" {
// prevent repacking data to make sure users cannot get stuck.
opts.MaxRepackBytes = 0
}
maxUnused := strings.TrimSpace(opts.MaxUnused)
if maxUnused == "" {
return errors.Fatalf("invalid value for --max-unused: %q", opts.MaxUnused)
}
// parse MaxUnused either as unlimited, a percentage, or an absolute number of bytes
switch {
case maxUnused == "unlimited":
opts.maxUnusedBytes = func(_ uint64) uint64 {
return math.MaxUint64
}
case strings.HasSuffix(maxUnused, "%"):
maxUnused = strings.TrimSuffix(maxUnused, "%")
p, err := strconv.ParseFloat(maxUnused, 64)
if err != nil {
return errors.Fatalf("invalid percentage %q passed for --max-unused: %v", opts.MaxUnused, err)
}
if p < 0 {
return errors.Fatal("percentage for --max-unused must be positive")
}
if p >= 100 {
return errors.Fatal("percentage for --max-unused must be below 100%")
}
opts.maxUnusedBytes = func(used uint64) uint64 {
return uint64(p / (100 - p) * float64(used))
}
default:
size, err := ui.ParseBytes(maxUnused)
if err != nil {
return errors.Fatalf("invalid number of bytes %q for --max-unused: %v", opts.MaxUnused, err)
}
opts.maxUnusedBytes = func(_ uint64) uint64 {
return uint64(size)
}
}
if opts.SmallPackSize != "" {
size, err := ui.ParseBytes(opts.SmallPackSize)
if err != nil {
return errors.Fatalf("invalid number of bytes %q for --repack-smaller-than: %v", opts.SmallPackSize, err)
}
opts.SmallPackBytes = uint64(size)
opts.RepackSmall = true
}
return nil
}
func runPrune(ctx context.Context, opts PruneOptions, gopts global.Options, term ui.Terminal) error {
err := verifyPruneOptions(&opts)
if err != nil {
return err
}
if opts.RepackUncompressed && gopts.Compression == repository.CompressionOff {
return errors.Fatal("disabled compression and `--repack-uncompressed` are mutually exclusive")
}
if gopts.NoLock && !opts.DryRun {
return errors.Fatal("--no-lock is only applicable in combination with --dry-run for prune command")
}
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun && gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
if opts.UnsafeNoSpaceRecovery != "" {
repoID := repo.Config().ID
if opts.UnsafeNoSpaceRecovery != repoID {
return errors.Fatalf("must pass id '%s' to --unsafe-recover-no-free-space", repoID)
}
opts.unsafeRecovery = true
}
return runPruneWithRepo(ctx, opts, repo, restic.NewIDSet(), printer)
}
func runPruneWithRepo(ctx context.Context, opts PruneOptions, repo *repository.Repository, ignoreSnapshots restic.IDSet, printer progress.Printer) error {
if repo.Cache() == nil {
printer.S("warning: running prune without a cache, this may be very slow!")
}
// loading the index before the snapshots is ok, as we use an exclusive lock here
err := repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
popts := repository.PruneOptions{
DryRun: opts.DryRun,
UnsafeRecovery: opts.unsafeRecovery,
MaxUnusedBytes: opts.maxUnusedBytes,
MaxRepackBytes: opts.MaxRepackBytes,
SmallPackBytes: opts.SmallPackBytes,
RepackCacheableOnly: opts.RepackCacheableOnly,
RepackSmall: opts.RepackSmall,
RepackUncompressed: opts.RepackUncompressed,
}
plan, err := repository.PlanPrune(ctx, popts, repo, func(ctx context.Context, repo restic.Repository, usedBlobs restic.FindBlobSet) error {
return getUsedBlobs(ctx, repo, usedBlobs, ignoreSnapshots, printer)
}, printer)
if err != nil {
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
if popts.DryRun {
printer.P("\nWould have made the following changes:")
}
err = printPruneStats(printer, plan.Stats())
if err != nil {
return err
}
// Trigger GC to reset garbage collection threshold
runtime.GC()
return plan.Execute(ctx, printer)
}
// printPruneStats prints out the statistics
func printPruneStats(printer progress.Printer, stats repository.PruneStats) error {
printer.V("\nused: %10d blobs / %s\n", stats.Blobs.Used, ui.FormatBytes(stats.Size.Used))
if stats.Blobs.Duplicate > 0 {
printer.V("duplicates: %10d blobs / %s\n", stats.Blobs.Duplicate, ui.FormatBytes(stats.Size.Duplicate))
}
printer.V("unused: %10d blobs / %s\n", stats.Blobs.Unused, ui.FormatBytes(stats.Size.Unused))
if stats.Size.Unref > 0 {
printer.V("unreferenced: %s\n", 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\n", totalBlobs, ui.FormatBytes(totalSize))
printer.V("unused size: %s of total size\n", ui.FormatPercent(unusedSize, totalSize))
printer.P("\nto repack: %10d blobs / %s\n", stats.Blobs.Repack, ui.FormatBytes(stats.Size.Repack))
printer.P("this removes: %10d blobs / %s\n", stats.Blobs.Repackrm, ui.FormatBytes(stats.Size.Repackrm))
printer.P("to delete: %10d blobs / %s\n", 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\n", stats.Blobs.Remove+stats.Blobs.Repackrm, ui.FormatBytes(totalPruneSize))
if stats.Size.Uncompressed > 0 {
printer.P("not yet compressed: %s\n", ui.FormatBytes(stats.Size.Uncompressed))
}
printer.P("remaining: %10d blobs / %s\n", totalBlobs-(stats.Blobs.Remove+stats.Blobs.Repackrm), ui.FormatBytes(totalSize-totalPruneSize))
unusedAfter := unusedSize - stats.Size.Remove - stats.Size.Repackrm
printer.P("unused size after prune: %s (%s of remaining size)\n",
ui.FormatBytes(unusedAfter), ui.FormatPercent(unusedAfter, totalSize-totalPruneSize))
printer.P("\n")
printer.V("totally used packs: %10d\n", stats.Packs.Used)
printer.V("partly used packs: %10d\n", stats.Packs.PartlyUsed)
printer.V("unused packs: %10d\n\n", stats.Packs.Unused)
printer.V("to keep: %10d packs\n", stats.Packs.Keep)
printer.V("to repack: %10d packs\n", stats.Packs.Repack)
printer.V("to delete: %10d packs\n", stats.Packs.Remove)
if stats.Packs.Unref > 0 {
printer.V("to delete: %10d unreferenced packs\n\n", stats.Packs.Unref)
}
return nil
}
func getUsedBlobs(ctx context.Context, repo restic.Repository, usedBlobs restic.FindBlobSet, ignoreSnapshots restic.IDSet, printer progress.Printer) error {
var snapshotTrees restic.IDs
printer.P("loading all snapshots...\n")
err := data.ForAllSnapshots(ctx, repo, repo, ignoreSnapshots,
func(id restic.ID, sn *data.Snapshot, err error) error {
if err != nil {
debug.Log("failed to load snapshot %v (error %v)", id, err)
return err
}
debug.Log("add snapshot %v (tree %v)", id, *sn.Tree)
snapshotTrees = append(snapshotTrees, *sn.Tree)
return nil
})
if err != nil {
return errors.Fatalf("failed loading snapshot: %v", err)
}
printer.P("finding data that is still in use for %d snapshots\n", len(snapshotTrees))
bar := printer.NewCounter("snapshots")
bar.SetMax(uint64(len(snapshotTrees)))
defer bar.Done()
err = data.FindUsedBlobs(ctx, repo, snapshotTrees, usedBlobs, bar)
if err != nil {
return errors.Fatalf("failed finding blobs: %v", err)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_copy_integration_test.go | cmd/restic/cmd_copy_integration_test.go | package main
import (
"context"
"fmt"
"path/filepath"
"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"
)
func testRunCopy(t testing.TB, srcGopts global.Options, dstGopts global.Options) {
gopts := srcGopts
gopts.Repo = dstGopts.Repo
gopts.Password = dstGopts.Password
gopts.InsecureNoPassword = dstGopts.InsecureNoPassword
copyOpts := CopyOptions{
SecondaryRepoOptions: global.SecondaryRepoOptions{
Repo: srcGopts.Repo,
Password: srcGopts.Password,
InsecureNoPassword: srcGopts.InsecureNoPassword,
},
}
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runCopy(context.TODO(), copyOpts, gopts, nil, gopts.Term)
}))
}
func TestCopy(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env2, cleanup2 := withTestEnvironment(t)
defer cleanup2()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "2")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "3")}, opts, env.gopts)
testRunCheck(t, env.gopts)
testRunInit(t, env2.gopts)
testRunCopy(t, env.gopts, env2.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 3)
copiedSnapshotIDs := testListSnapshots(t, env2.gopts, 3)
// Check that the copies size seems reasonable
stat := dirStats(t, env.repo)
stat2 := dirStats(t, env2.repo)
sizeDiff := int64(stat.size) - int64(stat2.size)
if sizeDiff < 0 {
sizeDiff = -sizeDiff
}
rtest.Assert(t, sizeDiff < int64(stat.size)/50, "expected less than 2%% size difference: %v vs. %v",
stat.size, stat2.size)
// Check integrity of the copy
testRunCheck(t, env2.gopts)
// Check that the copied snapshots have the same tree contents as the old ones (= identical tree hash)
origRestores := make(map[string]struct{})
for i, snapshotID := range snapshotIDs {
restoredir := filepath.Join(env.base, fmt.Sprintf("restore%d", i))
origRestores[restoredir] = struct{}{}
testRunRestore(t, env.gopts, restoredir, snapshotID.String())
}
for i, snapshotID := range copiedSnapshotIDs {
restoredir := filepath.Join(env2.base, fmt.Sprintf("restore%d", i))
testRunRestore(t, env2.gopts, restoredir, snapshotID.String())
foundMatch := false
for cmpdir := range origRestores {
diff := directoriesContentsDiff(t, restoredir, cmpdir)
if diff == "" {
delete(origRestores, cmpdir)
foundMatch = true
}
}
rtest.Assert(t, foundMatch, "found no counterpart for snapshot %v", snapshotID)
}
rtest.Assert(t, len(origRestores) == 0, "found not copied snapshots")
// check that snapshots were properly batched while copying
_, _, countBlobs := testPackAndBlobCounts(t, env.gopts)
countTreePacksDst, countDataPacksDst, countBlobsDst := testPackAndBlobCounts(t, env2.gopts)
rtest.Equals(t, countBlobs, countBlobsDst, "expected blob count in boths repos to be equal")
rtest.Equals(t, countTreePacksDst, 1, "expected 1 tree packfile")
rtest.Equals(t, countDataPacksDst, 1, "expected 1 data packfile")
}
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)
_, 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)
rtest.OK(t, err)
rtest.Assert(t, len(blobs) > 0, "a packfile should contain at least one blob")
switch blobs[0].Type {
case restic.TreeBlob:
countTreePacks++
case restic.DataBlob:
countDataPacks++
}
countBlobs += len(blobs)
return nil
}))
return nil
}))
return countTreePacks, countDataPacks, countBlobs
}
func TestCopyIncremental(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env2, cleanup2 := withTestEnvironment(t)
defer cleanup2()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "2")}, opts, env.gopts)
testRunCheck(t, env.gopts)
testRunInit(t, env2.gopts)
testRunCopy(t, env.gopts, env2.gopts)
testListSnapshots(t, env.gopts, 2)
testListSnapshots(t, env2.gopts, 2)
// Check that the copies size seems reasonable
testRunCheck(t, env2.gopts)
// check that no snapshots are copied, as there are no new ones
testRunCopy(t, env.gopts, env2.gopts)
testRunCheck(t, env2.gopts)
testListSnapshots(t, env2.gopts, 2)
// check that only new snapshots are copied
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "3")}, opts, env.gopts)
testRunCopy(t, env.gopts, env2.gopts)
testRunCheck(t, env2.gopts)
testListSnapshots(t, env.gopts, 3)
testListSnapshots(t, env2.gopts, 3)
// also test the reverse direction
testRunCopy(t, env2.gopts, env.gopts)
testRunCheck(t, env.gopts)
testListSnapshots(t, env.gopts, 3)
}
func TestCopyUnstableJSON(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env2, cleanup2 := withTestEnvironment(t)
defer cleanup2()
// contains a symlink created using `ln -s '../i/'$'\355\246\361''d/samba' broken-symlink`
datafile := filepath.Join("testdata", "copy-unstable-json.tar.gz")
rtest.SetupTarTestFixture(t, env.base, datafile)
testRunInit(t, env2.gopts)
testRunCopy(t, env.gopts, env2.gopts)
testRunCheck(t, env2.gopts)
testListSnapshots(t, env2.gopts, 1)
}
func TestCopyToEmptyPassword(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env2, cleanup2 := withTestEnvironment(t)
defer cleanup2()
env2.gopts.Password = ""
env2.gopts.InsecureNoPassword = true
testSetupBackupData(t, env)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, BackupOptions{}, env.gopts)
testRunInit(t, env2.gopts)
testRunCopy(t, env.gopts, env2.gopts)
testListSnapshots(t, env.gopts, 1)
testListSnapshots(t, env2.gopts, 1)
testRunCheck(t, env2.gopts)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_ls_integration_test.go | cmd/restic/cmd_ls_integration_test.go | package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func testRunLsWithOpts(t testing.TB, gopts global.Options, opts LsOptions, args []string) []byte {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.Quiet = true
return runLs(context.TODO(), opts, gopts, args, gopts.Term)
})
rtest.OK(t, err)
return buf.Bytes()
}
func testRunLs(t testing.TB, gopts global.Options, snapshotID string) []string {
out := testRunLsWithOpts(t, gopts, LsOptions{}, []string{snapshotID})
return strings.Split(string(out), "\n")
}
func assertIsValidJSON(t *testing.T, data []byte) {
// Sanity check: output must be valid JSON.
var v []any
err := json.Unmarshal(data, &v)
rtest.OK(t, err)
rtest.Assert(t, len(v) == 4, "invalid ncdu output, expected 4 array elements, got %v", len(v))
}
func TestRunLsNcdu(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
// backup such that there are multiple toplevel elements
testRunBackup(t, env.testdata+"/0", []string{"."}, opts, env.gopts)
for _, paths := range [][]string{
{"latest"},
{"latest", "/0"},
{"latest", "/0", "/0/9"},
} {
ncdu := testRunLsWithOpts(t, env.gopts, LsOptions{Ncdu: true}, paths)
assertIsValidJSON(t, ncdu)
}
}
func TestRunLsSort(t *testing.T) {
rtest.Equals(t, SortMode(0), SortModeName, "unexpected default sort mode")
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, env.testdata+"/0", []string{"for_cmd_ls"}, opts, env.gopts)
for _, test := range []struct {
mode SortMode
expected []string
}{
{
SortModeSize,
[]string{
"/for_cmd_ls",
"/for_cmd_ls/file2.txt",
"/for_cmd_ls/file1.txt",
"/for_cmd_ls/python.py",
"",
},
},
{
SortModeExt,
[]string{
"/for_cmd_ls",
"/for_cmd_ls/python.py",
"/for_cmd_ls/file1.txt",
"/for_cmd_ls/file2.txt",
"",
},
},
{
SortModeName,
[]string{
"/for_cmd_ls",
"/for_cmd_ls/file1.txt",
"/for_cmd_ls/file2.txt",
"/for_cmd_ls/python.py",
"", // last empty line
},
},
} {
out := testRunLsWithOpts(t, env.gopts, LsOptions{Sort: test.mode}, []string{"latest"})
fileList := strings.Split(string(out), "\n")
rtest.Equals(t, test.expected, fileList, fmt.Sprintf("mismatch for mode %v", test.mode))
}
}
// JSON lines test
func TestRunLsJson(t *testing.T) {
pathList := []string{
"/0",
"/0/for_cmd_ls",
"/0/for_cmd_ls/file1.txt",
"/0/for_cmd_ls/file2.txt",
"/0/for_cmd_ls/python.py",
}
env, cleanup := withTestEnvironment(t)
defer cleanup()
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, env.testdata, []string{"0/for_cmd_ls"}, opts, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 1)
env.gopts.Quiet = true
env.gopts.JSON = true
buf := testRunLsWithOpts(t, env.gopts, LsOptions{}, []string{"latest"})
byteLines := bytes.Split(buf, []byte{'\n'})
// partial copy of snapshot structure from cmd_ls
type lsSnapshot struct {
*data.Snapshot
ID *restic.ID `json:"id"`
ShortID string `json:"short_id"` // deprecated
MessageType string `json:"message_type"` // "snapshot"
StructType string `json:"struct_type"` // "snapshot", deprecated
}
var snappy lsSnapshot
rtest.OK(t, json.Unmarshal(byteLines[0], &snappy))
rtest.Equals(t, snappy.ShortID, snapshotIDs[0].Str(), "expected snap IDs to be identical")
// partial copy of node structure from cmd_ls
type lsNode struct {
Name string `json:"name"`
Type string `json:"type"`
Path string `json:"path"`
Permissions string `json:"permissions,omitempty"`
Inode uint64 `json:"inode,omitempty"`
MessageType string `json:"message_type"` // "node"
StructType string `json:"struct_type"` // "node", deprecated
}
var testNode lsNode
for i, nodeLine := range byteLines[1:] {
if len(nodeLine) == 0 {
break
}
rtest.OK(t, json.Unmarshal(nodeLine, &testNode))
rtest.Equals(t, pathList[i], testNode.Path)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_features.go | cmd/restic/cmd_features.go | package main
import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/feature"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
)
func newFeaturesCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "features",
Short: "Print list of feature flags",
Long: `
The "features" command prints a list of supported feature flags.
To pass feature flags to restic, set the RESTIC_FEATURES environment variable
to "featureA=true,featureB=false". Specifying an unknown feature flag is an error.
A feature can either be in alpha, beta, stable or deprecated state.
An _alpha_ feature is disabled by default and may change in arbitrary ways between restic versions or be removed.
A _beta_ feature is enabled by default, but still can change in minor ways or be removed.
A _stable_ feature is always enabled and cannot be disabled. The flag will be removed in a future restic version.
A _deprecated_ feature is always disabled and cannot be enabled. The flag will be removed in a future restic version.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
GroupID: cmdGroupAdvanced,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
if len(args) != 0 {
return errors.Fatal("the feature command expects no arguments")
}
globalOptions.Term.Print("All Feature Flags:\n")
flags := feature.Flag.List()
tab := table.New()
tab.AddColumn("Name", "{{ .Name }}")
tab.AddColumn("Type", "{{ .Type }}")
tab.AddColumn("Default", "{{ .Default }}")
tab.AddColumn("Description", "{{ .Description }}")
for _, flag := range flags {
tab.AddRow(flag)
}
return tab.Write(globalOptions.Term.OutputWriter())
},
}
return cmd
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_copy.go | cmd/restic/cmd_copy.go | package main
import (
"context"
"fmt"
"iter"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"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"
"golang.org/x/sync/errgroup"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newCopyCommand(globalOptions *global.Options) *cobra.Command {
var opts CopyOptions
cmd := &cobra.Command{
Use: "copy [flags] [snapshotID ...]",
Short: "Copy snapshots from one repository to another",
Long: `
The "copy" command copies one or more snapshots from one repository to another.
NOTE: This process will have to both download (read) and upload (write) the
entire snapshot(s) due to the different encryption keys used in the source and
destination repositories. This /may incur higher bandwidth usage and costs/ than
expected during normal backup runs.
NOTE: The copying process does not re-chunk files, which may break deduplication
between the files copied and files already stored in the destination repository.
This means that copied files, which existed in both the source and destination
repository, /may occupy up to twice their space/ in the destination repository.
This can be mitigated by the "--copy-chunker-params" option when initializing a
new destination repository using the "init" command.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runCopy(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// CopyOptions bundles all options for the copy command.
type CopyOptions struct {
global.SecondaryRepoOptions
data.SnapshotFilter
}
func (opts *CopyOptions) AddFlags(f *pflag.FlagSet) {
opts.SecondaryRepoOptions.AddFlags(f, "destination", "to copy snapshots from")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
// 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) {
// check whether the destination has a snapshot with the same persistent ID which has similar snapshot fields
srcOriginal := *sn.ID()
if sn.Original != nil {
srcOriginal = *sn.Original
}
if originalSns, ok := dstSnapshotByOriginal[srcOriginal]; ok {
isCopy := false
for _, originalSn := range originalSns {
if similarSnapshots(originalSn, sn) {
printer.V("\n%v", sn)
printer.V("skipping source snapshot %s, was already copied to snapshot %s", sn.ID().Str(), originalSn.ID().Str())
isCopy = true
break
}
}
if isCopy {
continue
}
}
if !yield(sn) {
return
}
}
}
}
func runCopy(ctx context.Context, opts CopyOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
secondaryGopts, isFromRepo, err := opts.SecondaryRepoOptions.FillGlobalOpts(ctx, gopts, "destination")
if err != nil {
return err
}
if isFromRepo {
// swap global options, if the secondary repo was set via from-repo
gopts, secondaryGopts = secondaryGopts, gopts
}
ctx, srcRepo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
ctx, dstRepo, unlock, err := openWithAppendLock(ctx, secondaryGopts, false, printer)
if err != nil {
return err
}
defer unlock()
srcSnapshotLister, err := restic.MemorizeList(ctx, srcRepo, restic.SnapshotFile)
if err != nil {
return err
}
dstSnapshotLister, err := restic.MemorizeList(ctx, dstRepo, restic.SnapshotFile)
if err != nil {
return err
}
debug.Log("Loading source index")
if err := srcRepo.LoadIndex(ctx, printer); err != nil {
return err
}
debug.Log("Loading destination index")
if err := dstRepo.LoadIndex(ctx, printer); err != nil {
return err
}
dstSnapshotByOriginal := make(map[restic.ID][]*data.Snapshot)
for sn := range FindFilteredSnapshots(ctx, dstSnapshotLister, dstRepo, &opts.SnapshotFilter, nil, printer) {
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()
}
selectedSnapshots := collectAllSnapshots(ctx, opts, srcSnapshotLister, srcRepo, dstSnapshotByOriginal, args, printer)
if err := copyTreeBatched(ctx, srcRepo, dstRepo, selectedSnapshots, printer); err != nil {
return err
}
return ctx.Err()
}
func similarSnapshots(sna *data.Snapshot, snb *data.Snapshot) bool {
// everything except Parent and Original must match
if !sna.Time.Equal(snb.Time) || !sna.Tree.Equal(*snb.Tree) || sna.Hostname != snb.Hostname ||
sna.Username != snb.Username || sna.UID != snb.UID || sna.GID != snb.GID ||
len(sna.Paths) != len(snb.Paths) || len(sna.Excludes) != len(snb.Excludes) ||
len(sna.Tags) != len(snb.Tags) {
return false
}
if !sna.HasPaths(snb.Paths) || !sna.HasTags(snb.Tags) {
return false
}
for i, a := range sna.Excludes {
if a != snb.Excludes[i] {
return false
}
}
return true
}
// 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 {
// remember already processed trees across all snapshots
visitedTrees := srcRepo.NewAssociatedBlobSet()
targetSize := uint64(dstRepo.PackSize()) * 100
minDuration := 1 * time.Minute
// use pull-based iterator to allow iteration in multiple steps
next, stop := iter.Pull(selectedSnapshots)
defer stop()
for {
var batch []*data.Snapshot
batchSize := uint64(0)
startTime := time.Now()
// 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()
if !ok {
break
}
batch = append(batch, sn)
printer.P("\n%v", sn)
printer.P(" copy started, this may take a while...")
sizeBlobs, err := copyTree(ctx, srcRepo, dstRepo, visitedTrees, *sn.Tree, printer, uploader)
if err != nil {
return err
}
debug.Log("tree copied")
batchSize += sizeBlobs
}
return nil
})
if err != nil {
return err
}
// if no snapshots were processed in this batch, we're done
if len(batch) == 0 {
break
}
// add a newline to separate saved snapshot messages from the other messages
if len(batch) > 1 {
printer.P("")
}
// save all the snapshots
for _, sn := range batch {
err := copySaveSnapshot(ctx, sn, dstRepo, printer)
if err != nil {
return err
}
}
}
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) {
wg, wgCtx := errgroup.WithContext(ctx)
treeStream := data.StreamTrees(wgCtx, wg, srcRepo, restic.IDs{rootTreeID}, func(treeID restic.ID) bool {
handle := restic.BlobHandle{ID: treeID, Type: restic.TreeBlob}
visited := visitedTrees.Has(handle)
visitedTrees.Insert(handle)
return visited
}, nil)
copyBlobs := srcRepo.NewAssociatedBlobSet()
packList := restic.NewIDSet()
enqueue := func(h restic.BlobHandle) {
if _, ok := dstRepo.LookupBlobSize(h.Type, h.ID); !ok {
pb := srcRepo.LookupBlob(h.Type, h.ID)
copyBlobs.Insert(h)
for _, p := range pb {
packList.Insert(p.PackID)
}
}
}
wg.Go(func() error {
for tree := range treeStream {
if tree.Error != nil {
return fmt.Errorf("LoadTree(%v) returned error %v", tree.ID.Str(), tree.Error)
}
// copy raw tree bytes to avoid problems if the serialization changes
enqueue(restic.BlobHandle{ID: tree.ID, Type: restic.TreeBlob})
for _, entry := range tree.Nodes {
// Recursion into directories is handled by StreamTrees
// Copy the blobs for this file.
for _, blobID := range entry.Content {
enqueue(restic.BlobHandle{Type: restic.DataBlob, ID: blobID})
}
}
}
return nil
})
err := wg.Wait()
if err != nil {
return 0, err
}
sizeBlobs := copyStats(srcRepo, copyBlobs, packList, printer)
bar := printer.NewCounter("packs copied")
err = repository.CopyBlobs(ctx, srcRepo, dstRepo, uploader, packList, copyBlobs, bar, printer.P)
if err != nil {
return 0, errors.Fatalf("%s", err)
}
return sizeBlobs, nil
}
// copyStats: print statistics for the blobs to be copied
func copyStats(srcRepo restic.Repository, copyBlobs restic.AssociatedBlobSet, packList restic.IDSet, printer progress.Printer) uint64 {
// count and size
countBlobs := 0
sizeBlobs := uint64(0)
for blob := range copyBlobs.Keys() {
for _, blob := range srcRepo.LookupBlob(blob.Type, blob.ID) {
countBlobs++
sizeBlobs += uint64(blob.Length)
break
}
}
printer.V(" copy %d blobs with disk size %s in %d packfiles\n",
countBlobs, ui.FormatBytes(uint64(sizeBlobs)), len(packList))
return sizeBlobs
}
func copySaveSnapshot(ctx context.Context, sn *data.Snapshot, dstRepo restic.Repository, printer progress.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 {
sn.Original = sn.ID()
}
newID, err := data.SaveSnapshot(ctx, dstRepo, sn)
if err != nil {
return err
}
printer.P("snapshot %s saved, copied from source snapshot %s", newID.Str(), sn.ID().Str())
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/integration_test.go | cmd/restic/integration_test.go | package main
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"testing"
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"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"
)
func TestCheckRestoreNoLock(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("testdata", "small-repo.tar.gz")
rtest.SetupTarTestFixture(t, env.base, datafile)
err := filepath.Walk(env.repo, func(p string, fi os.FileInfo, e error) error {
if e != nil {
return e
}
return os.Chmod(p, fi.Mode() & ^(os.FileMode(0222)))
})
rtest.OK(t, err)
env.gopts.NoLock = true
testRunCheck(t, env.gopts)
snapshotIDs := testListSnapshots(t, env.gopts, 4)
testRunRestore(t, env.gopts, filepath.Join(env.base, "restore"), snapshotIDs[0].String())
}
// a listOnceBackend only allows listing once per filetype
// listing filetypes more than once may cause problems with eventually consistent
// backends (like e.g. Amazon S3) as the second listing may be inconsistent to what
// is expected by the first listing + some operations.
type listOnceBackend struct {
backend.Backend
listedFileType map[restic.FileType]bool
strictOrder bool
}
func newListOnceBackend(be backend.Backend) *listOnceBackend {
return &listOnceBackend{
Backend: be,
listedFileType: make(map[restic.FileType]bool),
strictOrder: false,
}
}
func newOrderedListOnceBackend(be backend.Backend) *listOnceBackend {
return &listOnceBackend{
Backend: be,
listedFileType: make(map[restic.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] {
return errors.Errorf("tried listing type %v the second time", t)
}
if be.strictOrder && t == restic.SnapshotFile && be.listedFileType[restic.IndexFile] {
return errors.Errorf("tried listing type snapshots after index")
}
be.listedFileType[t] = true
return be.Backend.List(ctx, t, fn)
}
func TestListOnce(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
return newOrderedListOnceBackend(r), nil
}
pruneOpts := PruneOptions{MaxUnused: "0"}
checkOpts := CheckOptions{ReadData: true, CheckUnused: true}
createPrunableRepo(t, env)
testRunPrune(t, env.gopts, pruneOpts)
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
_, err := runCheck(context.TODO(), checkOpts, gopts, nil, gopts.Term)
return err
}))
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runRebuildIndex(context.TODO(), RepairIndexOptions{}, gopts, gopts.Term)
}))
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runRebuildIndex(context.TODO(), RepairIndexOptions{ReadAllPacks: true}, gopts, gopts.Term)
}))
}
type writeToOnly struct {
rd io.Reader
}
func (r *writeToOnly) Read(_ []byte) (n int, err error) {
return 0, fmt.Errorf("should have called WriteTo instead")
}
func (r *writeToOnly) WriteTo(w io.Writer) (int64, error) {
return io.Copy(w, r.rd)
}
type onlyLoadWithWriteToBackend struct {
backend.Backend
}
func (be *onlyLoadWithWriteToBackend) Load(ctx context.Context, h backend.Handle,
length int, offset int64, fn func(rd io.Reader) error) error {
return be.Backend.Load(ctx, h, length, offset, func(rd io.Reader) error {
return fn(&writeToOnly{rd: rd})
})
}
func TestBackendLoadWriteTo(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
// setup backend which only works if it's WriteTo method is correctly propagated upwards
env.gopts.BackendInnerTestHook = func(r backend.Backend) (backend.Backend, error) {
return &onlyLoadWithWriteToBackend{Backend: r}, nil
}
testSetupBackupData(t, env)
// add some data, but make sure that it isn't cached during upload
opts := BackupOptions{}
env.gopts.NoCache = true
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
// loading snapshots must still work
env.gopts.NoCache = false
testListSnapshots(t, env.gopts, 1)
}
func TestFindListOnce(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) {
return newOrderedListOnceBackend(r), nil
}
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "2")}, opts, env.gopts)
secondSnapshot := testListSnapshots(t, env.gopts, 2)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "3")}, opts, env.gopts)
thirdSnapshot := restic.NewIDSet(testListSnapshots(t, env.gopts, 3)...)
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)
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())
}
return nil
}))
// the snapshots can only be listed once, if both lists match then the there has been only a single List() call
rtest.Equals(t, thirdSnapshot, snapshotIDs)
}
type failConfigOnceBackend struct {
backend.Backend
failedOnce bool
}
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 {
be.failedOnce = true
return fmt.Errorf("oops")
}
return be.Backend.Load(ctx, h, length, offset, fn)
}
func (be *failConfigOnceBackend) Stat(ctx context.Context, h backend.Handle) (backend.FileInfo, error) {
if !be.failedOnce && h.Type == restic.ConfigFile {
be.failedOnce = true
return backend.FileInfo{}, fmt.Errorf("oops")
}
return be.Backend.Stat(ctx, h)
}
func TestBackendRetryConfig(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
var wrappedBackend *failConfigOnceBackend
// cause config loading to fail once
env.gopts.BackendInnerTestHook = func(r backend.Backend) (backend.Backend, error) {
wrappedBackend = &failConfigOnceBackend{Backend: r}
return wrappedBackend, nil
}
testSetupBackupData(t, env)
rtest.Assert(t, wrappedBackend != nil, "backend not wrapped on init")
rtest.Assert(t, wrappedBackend != nil && wrappedBackend.failedOnce, "config loading was not retried on init")
wrappedBackend = nil
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, BackupOptions{}, env.gopts)
rtest.Assert(t, wrappedBackend != nil, "backend not wrapped on backup")
rtest.Assert(t, wrappedBackend != nil && wrappedBackend.failedOnce, "config loading was not retried on init")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_backup.go | cmd/restic/cmd_backup.go | package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
"github.com/restic/restic/internal/archiver"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/filter"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/textfile"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/backup"
)
func newBackupCommand(globalOptions *global.Options) *cobra.Command {
var opts BackupOptions
cmd := &cobra.Command{
Use: "backup [flags] [FILE/DIR] ...",
Short: "Create a new backup of files and/or directories",
Long: `
The "backup" command creates a new snapshot and saves the files and directories
given as the arguments.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was a fatal error (no snapshot created).
Exit status is 3 if some source data could not be read (incomplete snapshot created).
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
PreRun: func(_ *cobra.Command, _ []string) {
if opts.Host == "" {
hostname, err := os.Hostname()
if err != nil {
debug.Log("os.Hostname() returned err: %v", err)
return
}
opts.Host = hostname
}
},
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runBackup(cmd.Context(), opts, *globalOptions, globalOptions.Term, args)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// BackupOptions bundles all options for the backup command.
type BackupOptions struct {
filter.ExcludePatternOptions
Parent string
GroupBy data.SnapshotGroupByOptions
Force bool
ExcludeOtherFS bool
ExcludeIfPresent []string
ExcludeCaches bool
ExcludeLargerThan string
ExcludeCloudFiles bool
Stdin bool
StdinFilename string
StdinCommand bool
Tags data.TagLists
Host string
FilesFrom []string
FilesFromVerbatim []string
FilesFromRaw []string
TimeStamp string
WithAtime bool
IgnoreInode bool
IgnoreCtime bool
UseFsSnapshot bool
DryRun bool
ReadConcurrency uint
NoScan bool
SkipIfUnchanged bool
}
func (opts *BackupOptions) AddFlags(f *pflag.FlagSet) {
f.StringVar(&opts.Parent, "parent", "", "use this parent `snapshot` (default: latest snapshot in the group determined by --group-by and not newer than the timestamp determined by --time)")
opts.GroupBy = data.SnapshotGroupByOptions{Host: true, Path: true}
f.VarP(&opts.GroupBy, "group-by", "g", "`group` snapshots by host, paths and/or tags, separated by comma (disable grouping with '')")
f.BoolVarP(&opts.Force, "force", "f", false, `force re-reading the source files/directories (overrides the "parent" flag)`)
opts.ExcludePatternOptions.Add(f)
f.BoolVarP(&opts.ExcludeOtherFS, "one-file-system", "x", false, "exclude other file systems, don't cross filesystem boundaries and subvolumes")
f.StringArrayVar(&opts.ExcludeIfPresent, "exclude-if-present", nil, "takes `filename[:header]`, exclude contents of directories containing filename (except filename itself) if header of that file is as provided (can be specified multiple times)")
f.BoolVar(&opts.ExcludeCaches, "exclude-caches", false, `excludes cache directories that are marked with a CACHEDIR.TAG file. See https://bford.info/cachedir/ for the Cache Directory Tagging Standard`)
f.StringVar(&opts.ExcludeLargerThan, "exclude-larger-than", "", "max `size` of the files to be backed up (allowed suffixes: k/K, m/M, g/G, t/T)")
f.BoolVar(&opts.Stdin, "stdin", false, "read backup from stdin")
f.StringVar(&opts.StdinFilename, "stdin-filename", "stdin", "`filename` to use when reading from stdin")
f.BoolVar(&opts.StdinCommand, "stdin-from-command", false, "interpret arguments as command to execute and store its stdout")
f.Var(&opts.Tags, "tag", "add `tags` for the new snapshot in the format `tag[,tag,...]` (can be specified multiple times)")
f.UintVar(&opts.ReadConcurrency, "read-concurrency", 0, "read `n` files concurrently (default: $RESTIC_READ_CONCURRENCY or 2)")
f.StringVarP(&opts.Host, "host", "H", "", "set the `hostname` for the snapshot manually (default: $RESTIC_HOST). To prevent an expensive rescan use the \"parent\" flag")
f.StringVar(&opts.Host, "hostname", "", "set the `hostname` for the snapshot manually")
err := f.MarkDeprecated("hostname", "use --host")
if err != nil {
// MarkDeprecated only returns an error when the flag could not be found
panic(err)
}
f.StringArrayVar(&opts.FilesFrom, "files-from", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)")
f.StringArrayVar(&opts.FilesFromVerbatim, "files-from-verbatim", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)")
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.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" {
f.BoolVar(&opts.UseFsSnapshot, "use-fs-snapshot", false, "use filesystem snapshot where possible (currently only Windows VSS)")
}
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
f.BoolVar(&opts.ExcludeCloudFiles, "exclude-cloud-files", false, "excludes online-only cloud files (such as OneDrive, iCloud drive, …)")
}
f.BoolVar(&opts.SkipIfUnchanged, "skip-if-unchanged", false, "skip snapshot creation if identical to parent snapshot")
// parse read concurrency from env, on error the default value will be used
readConcurrency, _ := strconv.ParseUint(os.Getenv("RESTIC_READ_CONCURRENCY"), 10, 32)
opts.ReadConcurrency = uint(readConcurrency)
// 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
}
}
var backupFSTestHook func(fs fs.FS) fs.FS
// ErrInvalidSourceData is used to report an incomplete backup
var ErrInvalidSourceData = errors.New("at least one source file could not be read")
// ErrNoSourceData is used to report that no source data was found
var ErrNoSourceData = errors.Fatal("all source directories/files do not exist")
// filterExisting returns a slice of all existing items, or an error if no
// items exist at all.
func filterExisting(items []string, warnf func(msg string, args ...interface{})) (result []string, err error) {
for _, item := range items {
_, err := fs.Lstat(item)
if errors.Is(err, os.ErrNotExist) {
warnf("%v does not exist, skipping\n", item)
continue
}
result = append(result, item)
}
if len(result) == 0 {
return nil, ErrNoSourceData
} else if len(result) < len(items) {
return result, ErrInvalidSourceData
}
return result, nil
}
// readLines reads all lines from the named file and returns them as a
// string slice.
//
// If filename is empty, readPatternsFromFile returns an empty slice.
// If filename is a dash (-), readPatternsFromFile will read the lines from the
// standard input.
func readLines(filename string, stdin io.ReadCloser) ([]string, error) {
if filename == "" {
return nil, nil
}
var (
data []byte
err error
)
if filename == "-" {
data, err = io.ReadAll(stdin)
} else {
data, err = textfile.Read(filename)
}
if err != nil {
return nil, err
}
var lines []string
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
// readFilenamesFromFileRaw reads a list of filenames from the given file,
// or stdin if filename is "-". Each filename is terminated by a zero byte,
// which is stripped off.
func readFilenamesFromFileRaw(filename string, stdin io.ReadCloser) (names []string, err error) {
f := stdin
if filename != "-" {
if f, err = os.Open(filename); err != nil {
return nil, err
}
}
names, err = readFilenamesRaw(f)
if err != nil {
// ignore subsequent errors
_ = f.Close()
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
return names, nil
}
func readFilenamesRaw(r io.Reader) (names []string, err error) {
br := bufio.NewReader(r)
for {
name, err := br.ReadString(0)
switch err {
case nil:
case io.EOF:
if name == "" {
return names, nil
}
return nil, errors.Fatal("--files-from-raw: trailing zero byte missing")
default:
return nil, err
}
name = name[:len(name)-1]
if name == "" {
// The empty filename is never valid. Handle this now to
// prevent downstream code from erroneously backing up
// filepath.Clean("") == ".".
return nil, errors.Fatal("--files-from-raw: empty filename in listing")
}
names = append(names, name)
}
}
// Check returns an error when an invalid combination of options was set.
func (opts BackupOptions) Check(gopts global.Options, args []string) error {
if gopts.Password == "" && !gopts.InsecureNoPassword {
if opts.Stdin {
return errors.Fatal("cannot read both password and data from stdin")
}
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 opts.Stdin || opts.StdinCommand {
if len(opts.FilesFrom) > 0 {
return errors.Fatal("--stdin and --files-from cannot be used together")
}
if len(opts.FilesFromVerbatim) > 0 {
return errors.Fatal("--stdin and --files-from-verbatim cannot be used together")
}
if len(opts.FilesFromRaw) > 0 {
return errors.Fatal("--stdin and --files-from-raw cannot be used together")
}
if len(args) > 0 && !opts.StdinCommand {
return errors.Fatal("--stdin was specified and files/dirs were listed as arguments")
}
}
return nil
}
// 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) {
// exclude restic cache
if repo.Cache() != nil {
f, err := rejectResticCache(repo)
if err != nil {
return nil, err
}
fs = append(fs, f)
}
fsPatterns, err := opts.ExcludePatternOptions.CollectPatterns(warnf)
if err != nil {
return nil, err
}
for _, pat := range fsPatterns {
fs = append(fs, archiver.RejectByNameFunc(pat))
}
return fs, nil
}
// 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) {
// allowed devices
if opts.ExcludeOtherFS && !opts.Stdin && !opts.StdinCommand {
f, err := archiver.RejectByDevice(targets, fs)
if err != nil {
return nil, err
}
funcs = append(funcs, f)
}
if len(opts.ExcludeLargerThan) != 0 && !opts.Stdin && !opts.StdinCommand {
maxSize, err := ui.ParseBytes(opts.ExcludeLargerThan)
if err != nil {
return nil, err
}
f, err := archiver.RejectBySize(maxSize)
if err != nil {
return nil, err
}
funcs = append(funcs, f)
}
if opts.ExcludeCloudFiles && !opts.Stdin && !opts.StdinCommand {
f, err := archiver.RejectCloudFiles(warnf)
if err != nil {
return nil, err
}
funcs = append(funcs, f)
}
if opts.ExcludeCaches {
opts.ExcludeIfPresent = append(opts.ExcludeIfPresent, "CACHEDIR.TAG:Signature: 8a477f597d28d172789f06886806bc55")
}
for _, spec := range opts.ExcludeIfPresent {
f, err := archiver.RejectIfPresent(spec, warnf)
if err != nil {
return nil, err
}
funcs = append(funcs, f)
}
return funcs, nil
}
// 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) {
if opts.Stdin || opts.StdinCommand {
return nil, nil
}
for _, file := range opts.FilesFrom {
fromfile, err := readLines(file, stdin)
if err != nil {
return nil, err
}
// expand wildcards
for _, line := range fromfile {
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' { // '#' marks a comment.
continue
}
var expanded []string
expanded, err := filepath.Glob(line)
if err != nil {
return nil, fmt.Errorf("pattern: %s: %w", line, err)
}
if len(expanded) == 0 {
warnf("pattern %q does not match any files, skipping\n", line)
}
targets = append(targets, expanded...)
}
}
for _, file := range opts.FilesFromVerbatim {
fromfile, err := readLines(file, stdin)
if err != nil {
return nil, err
}
for _, line := range fromfile {
if line == "" {
continue
}
targets = append(targets, line)
}
}
for _, file := range opts.FilesFromRaw {
fromfile, err := readFilenamesFromFileRaw(file, stdin)
if err != nil {
return nil, err
}
targets = append(targets, fromfile...)
}
// Merge args into files-from so we can reuse the normal args checks
// and have the ability to use both files-from and args at the same time.
targets = append(targets, args...)
if len(targets) == 0 && !opts.Stdin {
return nil, errors.Fatal("nothing to backup, please specify source files/dirs")
}
return filterExisting(targets, warnf)
}
// parent returns the ID of the parent snapshot. If there is none, nil is
// returned.
func findParentSnapshot(ctx context.Context, repo restic.ListerLoaderUnpacked, opts BackupOptions, targets []string, timeStampLimit time.Time) (*data.Snapshot, error) {
if opts.Force {
return nil, nil
}
snName := opts.Parent
if snName == "" {
snName = "latest"
}
f := data.SnapshotFilter{TimestampLimit: timeStampLimit}
if opts.GroupBy.Host {
f.Hosts = []string{opts.Host}
}
if opts.GroupBy.Path {
f.Paths = targets
}
if opts.GroupBy.Tag {
f.Tags = []data.TagList{opts.Tags.Flatten()}
}
sn, _, err := f.FindLatest(ctx, repo, repo, snName)
// Snapshot not found is ok if no explicit parent was set
if opts.Parent == "" && errors.Is(err, data.ErrNoSnapshotFound) {
err = nil
}
return sn, err
}
func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, term ui.Terminal, args []string) error {
var vsscfg fs.VSSConfig
var err error
var printer backup.ProgressPrinter
if gopts.JSON {
printer = backup.NewJSONProgress(term, gopts.Verbosity)
} else {
printer = backup.NewTextProgress(term, gopts.Verbosity)
}
if runtime.GOOS == "windows" {
if vsscfg, err = fs.ParseVSSConfig(gopts.Extended); err != nil {
return err
}
}
err = opts.Check(gopts, args)
if err != nil {
return err
}
success := true
targets, err := collectTargets(opts, args, printer.E, term.InputRaw())
if err != nil {
if errors.Is(err, ErrInvalidSourceData) {
success = false
} else {
return err
}
}
timeStamp := time.Now()
backupStart := timeStamp
if opts.TimeStamp != "" {
timeStamp, err = time.ParseInLocation(global.TimeFormat, opts.TimeStamp, time.Local)
if err != nil {
return errors.Fatalf("error in time option: %v", err)
}
}
if gopts.Verbosity >= 2 && !gopts.JSON {
printer.P("open repository")
}
ctx, repo, unlock, err := openWithAppendLock(ctx, gopts, opts.DryRun, printer)
if err != nil {
return err
}
defer unlock()
progressReporter := backup.NewProgress(printer,
ui.CalculateProgressInterval(!gopts.Quiet, gopts.JSON, term.CanUpdateStatus()))
defer progressReporter.Done()
// rejectByNameFuncs collect functions that can reject items from the backup based on path only
rejectByNameFuncs, err := collectRejectByNameFuncs(opts, repo, printer.E)
if err != nil {
return err
}
var parentSnapshot *data.Snapshot
if !opts.Stdin {
parentSnapshot, err = findParentSnapshot(ctx, repo, opts, targets, timeStamp)
if err != nil {
return err
}
if !gopts.JSON {
if parentSnapshot != nil {
printer.P("using parent snapshot %v\n", parentSnapshot.ID().Str())
} else {
printer.P("no parent snapshot found, will read all files\n")
}
}
}
if !gopts.JSON {
printer.V("load index files")
}
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
var targetFS fs.FS = fs.Local{}
if runtime.GOOS == "windows" && opts.UseFsSnapshot {
if err = fs.HasSufficientPrivilegesForVSS(); err != nil {
return err
}
errorHandler := func(item string, err error) {
_ = progressReporter.Error(item, err)
}
messageHandler := func(msg string, args ...interface{}) {
if !gopts.JSON {
printer.P(msg, args...)
}
}
localVss := fs.NewLocalVss(errorHandler, messageHandler, vsscfg)
defer localVss.DeleteSnapshots()
targetFS = localVss
}
if opts.Stdin || opts.StdinCommand {
if !gopts.JSON {
printer.V("read data from stdin")
}
filename := path.Join("/", opts.StdinFilename)
source := term.InputRaw()
if opts.StdinCommand {
source, err = fs.NewCommandReader(ctx, args, printer.E)
if err != nil {
return err
}
}
targetFS, err = fs.NewReader(filename, source, fs.ReaderOptions{
ModTime: timeStamp,
Mode: 0644,
})
if err != nil {
return fmt.Errorf("failed to backup from stdin: %w", err)
}
targets = []string{filename}
}
if backupFSTestHook != nil {
targetFS = backupFSTestHook(targetFS)
}
// rejectFuncs collect functions that can reject items from the backup based on path and file info
rejectFuncs, err := collectRejectFuncs(opts, targets, targetFS, printer.E)
if err != nil {
return err
}
selectByNameFilter := archiver.CombineRejectByNames(rejectByNameFuncs)
selectFilter := archiver.CombineRejects(rejectFuncs)
wg, wgCtx := errgroup.WithContext(ctx)
cancelCtx, cancel := context.WithCancel(wgCtx)
defer cancel()
if !opts.NoScan {
sc := archiver.NewScanner(targetFS)
sc.SelectByName = selectByNameFilter
sc.Select = selectFilter
sc.Error = printer.ScannerError
sc.Result = progressReporter.ReportTotal
if !gopts.JSON {
printer.V("start scan on %v", targets)
}
wg.Go(func() error { return sc.Scan(cancelCtx, targets) })
}
arch := archiver.New(repo, targetFS, archiver.Options{ReadConcurrency: opts.ReadConcurrency})
arch.SelectByName = selectByNameFilter
arch.Select = selectFilter
arch.WithAtime = opts.WithAtime
arch.Error = func(item string, err error) error {
success = false
reterr := progressReporter.Error(item, err)
// If we receive a fatal error during the execution of the snapshot,
// we abort the snapshot.
if reterr == nil && errors.IsFatal(err) {
reterr = err
}
return reterr
}
arch.CompleteItem = progressReporter.CompleteItem
arch.StartFile = progressReporter.StartFile
arch.CompleteBlob = progressReporter.CompleteBlob
if opts.IgnoreInode {
// --ignore-inode implies --ignore-ctime: on FUSE, the ctime is not
// reliable either.
arch.ChangeIgnoreFlags |= archiver.ChangeIgnoreCtime | archiver.ChangeIgnoreInode
}
if opts.IgnoreCtime {
arch.ChangeIgnoreFlags |= archiver.ChangeIgnoreCtime
}
snapshotOpts := archiver.SnapshotOptions{
Excludes: opts.Excludes,
Tags: opts.Tags.Flatten(),
BackupStart: backupStart,
Time: timeStamp,
Hostname: opts.Host,
ParentSnapshot: parentSnapshot,
ProgramVersion: "restic " + global.Version,
SkipIfUnchanged: opts.SkipIfUnchanged,
}
if !gopts.JSON {
printer.V("start backup on %v", targets)
}
_, id, summary, err := arch.Snapshot(ctx, targets, snapshotOpts)
// cleanly shutdown all running goroutines
cancel()
// let's see if one returned an error
werr := wg.Wait()
// return original error
if err != nil {
return errors.Fatalf("unable to save snapshot: %v", err)
}
// Report finished execution
progressReporter.Finish(id, summary, opts.DryRun)
if !success {
return ErrInvalidSourceData
}
// Return error if any
return werr
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key_passwd.go | cmd/restic/cmd_key_passwd.go | package main
import (
"context"
"fmt"
"github.com/restic/restic/internal/errors"
"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"
)
func newKeyPasswdCommand(globalOptions *global.Options) *cobra.Command {
var opts KeyPasswdOptions
cmd := &cobra.Command{
Use: "passwd",
Short: "Change key (password); creates a new key ID and removes the old key ID, returns new key ID",
Long: `
The "passwd" sub-command creates a new key, validates the key and remove the old key ID.
Returns the new key ID.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runKeyPasswd(cmd.Context(), *globalOptions, opts, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
type KeyPasswdOptions struct {
KeyAddOptions
}
func (opts *KeyPasswdOptions) AddFlags(flags *pflag.FlagSet) {
opts.KeyAddOptions.Add(flags)
}
func runKeyPasswd(ctx context.Context, gopts global.Options, opts KeyPasswdOptions, args []string, term ui.Terminal) error {
if len(args) > 0 {
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)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
return changePassword(ctx, repo, gopts, opts, printer)
}
func changePassword(ctx context.Context, repo *repository.Repository, gopts global.Options, opts KeyPasswdOptions, printer progress.Printer) error {
pw, err := getNewPassword(ctx, gopts, opts.NewPasswordFile, opts.InsecureNoPassword)
if err != nil {
return err
}
id, err := repository.AddKey(ctx, repo, pw, "", "", repo.Key())
if err != nil {
return errors.Fatalf("creating new key failed: %v", err)
}
oldID := repo.KeyID()
err = switchToNewKeyAndRemoveIfBroken(ctx, repo, id, pw)
if err != nil {
return err
}
err = repository.RemoveKey(ctx, repo, oldID)
if err != nil {
return err
}
printer.P("saved new key as %s", id)
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_forget_test.go | cmd/restic/cmd_forget_test.go | package main
import (
"testing"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
"github.com/spf13/pflag"
)
func TestForgetPolicyValues(t *testing.T) {
testCases := []struct {
input string
value ForgetPolicyCount
err string
}{
{"0", ForgetPolicyCount(0), ""},
{"1", ForgetPolicyCount(1), ""},
{"unlimited", ForgetPolicyCount(-1), ""},
{"", ForgetPolicyCount(0), "strconv.ParseInt: parsing \"\": invalid syntax"},
{"-1", ForgetPolicyCount(0), ErrNegativePolicyCount.Error()},
{"abc", ForgetPolicyCount(0), "strconv.ParseInt: parsing \"abc\": invalid syntax"},
}
for _, testCase := range testCases {
t.Run("", func(t *testing.T) {
var count ForgetPolicyCount
err := count.Set(testCase.input)
if testCase.err != "" {
rtest.Assert(t, err != nil, "should have returned error for input %+v", testCase.input)
rtest.Equals(t, testCase.err, err.Error())
} else {
rtest.Assert(t, err == nil, "expected no error for input %+v, got %v", testCase.input, err)
rtest.Equals(t, testCase.value, count)
rtest.Equals(t, testCase.input, count.String())
}
})
}
}
func TestForgetOptionValues(t *testing.T) {
const negValErrorMsg = "Fatal: negative values other than -1 are not allowed for --keep-*"
const negDurationValErrorMsg = "Fatal: durations containing negative values are not allowed for --keep-within*"
testCases := []struct {
input ForgetOptions
errorMsg string
}{
{ForgetOptions{Last: 1}, ""},
{ForgetOptions{Hourly: 1}, ""},
{ForgetOptions{Daily: 1}, ""},
{ForgetOptions{Weekly: 1}, ""},
{ForgetOptions{Monthly: 1}, ""},
{ForgetOptions{Yearly: 1}, ""},
{ForgetOptions{Last: 0}, ""},
{ForgetOptions{Hourly: 0}, ""},
{ForgetOptions{Daily: 0}, ""},
{ForgetOptions{Weekly: 0}, ""},
{ForgetOptions{Monthly: 0}, ""},
{ForgetOptions{Yearly: 0}, ""},
{ForgetOptions{Last: -1}, ""},
{ForgetOptions{Hourly: -1}, ""},
{ForgetOptions{Daily: -1}, ""},
{ForgetOptions{Weekly: -1}, ""},
{ForgetOptions{Monthly: -1}, ""},
{ForgetOptions{Yearly: -1}, ""},
{ForgetOptions{Last: -2}, negValErrorMsg},
{ForgetOptions{Hourly: -2}, negValErrorMsg},
{ForgetOptions{Daily: -2}, negValErrorMsg},
{ForgetOptions{Weekly: -2}, negValErrorMsg},
{ForgetOptions{Monthly: -2}, negValErrorMsg},
{ForgetOptions{Yearly: -2}, negValErrorMsg},
{ForgetOptions{Within: data.ParseDurationOrPanic("1y2m3d3h")}, ""},
{ForgetOptions{WithinHourly: data.ParseDurationOrPanic("1y2m3d3h")}, ""},
{ForgetOptions{WithinDaily: data.ParseDurationOrPanic("1y2m3d3h")}, ""},
{ForgetOptions{WithinWeekly: data.ParseDurationOrPanic("1y2m3d3h")}, ""},
{ForgetOptions{WithinMonthly: data.ParseDurationOrPanic("2y4m6d8h")}, ""},
{ForgetOptions{WithinYearly: data.ParseDurationOrPanic("2y4m6d8h")}, ""},
{ForgetOptions{Within: data.ParseDurationOrPanic("-1y2m3d3h")}, negDurationValErrorMsg},
{ForgetOptions{WithinHourly: data.ParseDurationOrPanic("1y-2m3d3h")}, negDurationValErrorMsg},
{ForgetOptions{WithinDaily: data.ParseDurationOrPanic("1y2m-3d3h")}, negDurationValErrorMsg},
{ForgetOptions{WithinWeekly: data.ParseDurationOrPanic("1y2m3d-3h")}, negDurationValErrorMsg},
{ForgetOptions{WithinMonthly: data.ParseDurationOrPanic("-2y4m6d8h")}, negDurationValErrorMsg},
{ForgetOptions{WithinYearly: data.ParseDurationOrPanic("2y-4m6d8h")}, negDurationValErrorMsg},
}
for _, testCase := range testCases {
err := verifyForgetOptions(&testCase.input)
if testCase.errorMsg != "" {
rtest.Assert(t, err != nil, "should have returned error for input %+v", testCase.input)
rtest.Equals(t, testCase.errorMsg, err.Error())
} else {
rtest.Assert(t, err == nil, "expected no error for input %+v", testCase.input)
}
}
}
func TestForgetHostnameDefaulting(t *testing.T) {
t.Setenv("RESTIC_HOST", "testhost")
tests := []struct {
name string
args []string
want []string
}{
{
name: "env default when flag not set",
args: nil,
want: []string{"testhost"},
},
{
name: "flag overrides env",
args: []string{"--host", "flaghost"},
want: []string{"flaghost"},
},
{
name: "empty flag clears env",
args: []string{"--host", ""},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
set := pflag.NewFlagSet(tt.name, pflag.ContinueOnError)
opts := ForgetOptions{}
opts.AddFlags(set)
err := set.Parse(tt.args)
rtest.Assert(t, err == nil, "expected no error for input")
finalizeSnapshotFilter(&opts.SnapshotFilter)
rtest.Equals(t, tt.want, opts.Hosts)
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/format_test.go | cmd/restic/format_test.go | package main
import (
"testing"
"time"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
)
func TestFormatNode(t *testing.T) {
// overwrite time zone to ensure the data is formatted reproducibly
tz := time.Local
time.Local = time.UTC
defer func() {
time.Local = tz
}()
testPath := "/test/path"
node := data.Node{
Name: "baz",
Type: data.NodeTypeFile,
Size: 14680064,
UID: 1000,
GID: 2000,
ModTime: time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC),
}
for _, c := range []struct {
path string
data.Node
long bool
human bool
expect string
}{
{
path: testPath,
Node: node,
long: false,
human: false,
expect: testPath,
},
{
path: testPath,
Node: node,
long: true,
human: false,
expect: "---------- 1000 2000 14680064 2020-01-02 03:04:05 " + testPath,
},
{
path: testPath,
Node: node,
long: true,
human: true,
expect: "---------- 1000 2000 14.000 MiB 2020-01-02 03:04:05 " + testPath,
},
} {
r := formatNode(c.path, &c.Node, c.long, c.human)
rtest.Equals(t, c.expect, r)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_restore.go | cmd/restic/cmd_restore.go | package main
import (
"context"
"path/filepath"
"runtime"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/filter"
"github.com/restic/restic/internal/global"
"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"
"github.com/spf13/pflag"
)
func newRestoreCommand(globalOptions *global.Options) *cobra.Command {
var opts RestoreOptions
cmd := &cobra.Command{
Use: "restore [flags] snapshotID",
Short: "Extract the data from a snapshot",
Long: `
The "restore" command extracts the data from a snapshot from the repository to
a directory.
The special snapshotID "latest" can be used to restore the latest snapshot in the
repository.
To only restore a specific subfolder, you can use the "snapshotID:subfolder"
syntax, where "subfolder" is a path within the snapshot.
POSIX ACLs are always restored by their numeric value, while file ownership can optionally be restored by name instead of numeric value.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runRestore(cmd.Context(), opts, *globalOptions, globalOptions.Term, args)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// RestoreOptions collects all options for the restore command.
type RestoreOptions struct {
filter.ExcludePatternOptions
filter.IncludePatternOptions
Target string
data.SnapshotFilter
DryRun bool
Sparse bool
Verify bool
Overwrite restorer.OverwriteBehavior
Delete bool
ExcludeXattrPattern []string
IncludeXattrPattern []string
OwnershipByName bool
}
func (opts *RestoreOptions) AddFlags(f *pflag.FlagSet) {
f.StringVarP(&opts.Target, "target", "t", "", "directory to extract data to")
opts.ExcludePatternOptions.Add(f)
opts.IncludePatternOptions.Add(f)
f.StringArrayVar(&opts.ExcludeXattrPattern, "exclude-xattr", nil, "exclude xattr by `pattern` (can be specified multiple times)")
f.StringArrayVar(&opts.IncludeXattrPattern, "include-xattr", nil, "include xattr by `pattern` (can be specified multiple times)")
initSingleSnapshotFilter(f, &opts.SnapshotFilter)
f.BoolVar(&opts.DryRun, "dry-run", false, "do not write any data, just show what would be done")
f.BoolVar(&opts.Sparse, "sparse", false, "restore files as sparse")
f.BoolVar(&opts.Verify, "verify", false, "verify restored files content")
f.Var(&opts.Overwrite, "overwrite", "overwrite behavior, one of (always|if-changed|if-newer|never)")
f.BoolVar(&opts.Delete, "delete", false, "delete files from target directory if they do not exist in snapshot. Use '--dry-run -vv' to check what would be deleted")
if runtime.GOOS != "windows" {
f.BoolVar(&opts.OwnershipByName, "ownership-by-name", false, "restore file ownership by user name and group name (except POSIX ACLs)")
}
}
func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
term ui.Terminal, args []string) error {
var printer restoreui.ProgressPrinter
if gopts.JSON {
printer = restoreui.NewJSONProgress(term, gopts.Verbosity)
} else {
printer = restoreui.NewTextProgress(term, gopts.Verbosity)
}
excludePatternFns, err := opts.ExcludePatternOptions.CollectPatterns(printer.E)
if err != nil {
return err
}
includePatternFns, err := opts.IncludePatternOptions.CollectPatterns(printer.E)
if err != nil {
return err
}
hasExcludes := len(excludePatternFns) > 0
hasIncludes := len(includePatternFns) > 0
switch {
case len(args) == 0:
return errors.Fatal("no snapshot ID specified")
case len(args) > 1:
return errors.Fatalf("more than one snapshot ID specified: %v", args)
}
if opts.Target == "" {
return errors.Fatal("please specify a directory to restore to (--target)")
}
if hasExcludes && hasIncludes {
return errors.Fatal("exclude and include patterns are mutually exclusive")
}
if opts.DryRun && opts.Verify {
return errors.Fatal("--dry-run and --verify are mutually exclusive")
}
if opts.Delete && filepath.Clean(opts.Target) == "/" && !hasExcludes && !hasIncludes {
return errors.Fatal("'--target / --delete' must be combined with an include or exclude filter")
}
snapshotIDString := args[0]
debug.Log("restore %v to %v", snapshotIDString, opts.Target)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
sn, subfolder, err := (&data.SnapshotFilter{
Hosts: opts.Hosts,
Paths: opts.Paths,
Tags: opts.Tags,
}).FindLatest(ctx, repo, repo, snapshotIDString)
if err != nil {
return errors.Fatalf("failed to find snapshot: %v", err)
}
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
sn.Tree, err = data.FindTreeDirectory(ctx, repo, sn.Tree, subfolder)
if err != nil {
return err
}
progress := restoreui.NewProgress(printer, ui.CalculateProgressInterval(!gopts.Quiet, gopts.JSON, term.CanUpdateStatus()))
res := restorer.NewRestorer(repo, sn, restorer.Options{
DryRun: opts.DryRun,
Sparse: opts.Sparse,
Progress: progress,
Overwrite: opts.Overwrite,
Delete: opts.Delete,
OwnershipByName: opts.OwnershipByName,
})
totalErrors := 0
res.Error = func(location string, err error) error {
totalErrors++
return progress.Error(location, err)
}
res.Warn = func(message string) {
printer.E("Warning: %s\n", message)
}
res.Info = func(message string) {
if gopts.JSON {
return
}
printer.P("Info: %s\n", message)
}
selectExcludeFilter := func(item string, isDir bool) (selectedForRestore bool, childMayBeSelected bool) {
matched := false
for _, rejectFn := range excludePatternFns {
matched = matched || rejectFn(item)
// implementing a short-circuit here to improve the performance
// to prevent additional pattern matching once the first pattern
// matches.
if matched {
break
}
}
// An exclude filter is basically a 'wildcard but foo',
// so even if a childMayMatch, other children of a dir may not,
// therefore childMayMatch does not matter, but we should not go down
// unless the dir is selected for restore
selectedForRestore = !matched
childMayBeSelected = selectedForRestore && isDir
return selectedForRestore, childMayBeSelected
}
selectIncludeFilter := func(item string, isDir bool) (selectedForRestore bool, childMayBeSelected bool) {
selectedForRestore = false
childMayBeSelected = false
for _, includeFn := range includePatternFns {
matched, childMayMatch := includeFn(item)
selectedForRestore = selectedForRestore || matched
childMayBeSelected = childMayBeSelected || childMayMatch
if selectedForRestore && childMayBeSelected {
break
}
}
childMayBeSelected = childMayBeSelected && isDir
return selectedForRestore, childMayBeSelected
}
if hasExcludes {
res.SelectFilter = selectExcludeFilter
} else if hasIncludes {
res.SelectFilter = selectIncludeFilter
}
res.XattrSelectFilter, err = getXattrSelectFilter(opts, printer)
if err != nil {
return err
}
if !gopts.JSON {
printer.P("restoring %s to %s\n", res.Snapshot(), opts.Target)
}
countRestoredFiles, err := res.RestoreTo(ctx, opts.Target)
if err != nil {
return err
}
progress.Finish()
if totalErrors > 0 {
return errors.Fatalf("There were %d errors", totalErrors)
}
if opts.Verify {
if !gopts.JSON {
printer.P("verifying files in %s\n", opts.Target)
}
var count int
t0 := time.Now()
bar := printer.NewCounterTerminalOnly("files verified")
count, err = res.VerifyFiles(ctx, opts.Target, countRestoredFiles, bar)
if err != nil {
return err
}
if totalErrors > 0 {
return errors.Fatalf("There were %d errors", totalErrors)
}
if !gopts.JSON {
printer.P("finished verifying %d files in %s (took %s)\n", count, opts.Target,
time.Since(t0).Round(time.Millisecond))
}
}
return nil
}
func getXattrSelectFilter(opts RestoreOptions, printer progress.Printer) (func(xattrName string) bool, error) {
hasXattrExcludes := len(opts.ExcludeXattrPattern) > 0
hasXattrIncludes := len(opts.IncludeXattrPattern) > 0
if hasXattrExcludes && hasXattrIncludes {
return nil, errors.Fatal("exclude and include xattr patterns are mutually exclusive")
}
if hasXattrExcludes {
if err := filter.ValidatePatterns(opts.ExcludeXattrPattern); err != nil {
return nil, errors.Fatalf("--exclude-xattr: %s", err)
}
return func(xattrName string) bool {
shouldReject := filter.RejectByPattern(opts.ExcludeXattrPattern, printer.E)(xattrName)
return !shouldReject
}, nil
}
if hasXattrIncludes {
// User has either input include xattr pattern(s) or we're using our default include pattern
if err := filter.ValidatePatterns(opts.IncludeXattrPattern); err != nil {
return nil, errors.Fatalf("--include-xattr: %s", err)
}
return func(xattrName string) bool {
shouldInclude, _ := filter.IncludeByPattern(opts.IncludeXattrPattern, printer.E)(xattrName)
return shouldInclude
}, nil
}
// default to including all xattrs
return func(_ string) bool { return true }, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_tag.go | cmd/restic/cmd_tag.go | package main
import (
"context"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"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"
)
func newTagCommand(globalOptions *global.Options) *cobra.Command {
var opts TagOptions
cmd := &cobra.Command{
Use: "tag [flags] [snapshotID ...]",
Short: "Modify tags on snapshots",
Long: `
The "tag" command allows you to modify tags on exiting snapshots.
You can either set/replace the entire set of tags on a snapshot, or
add tags to/remove tags from the existing set.
When no snapshotID is given, all snapshots matching the host, tag and path filter criteria are modified.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runTag(cmd.Context(), opts, *globalOptions, globalOptions.Term, args)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// TagOptions bundles all options for the 'tag' command.
type TagOptions struct {
data.SnapshotFilter
SetTags data.TagLists
AddTags data.TagLists
RemoveTags data.TagLists
}
func (opts *TagOptions) AddFlags(f *pflag.FlagSet) {
f.Var(&opts.SetTags, "set", "`tags` which will replace the existing tags in the format `tag[,tag,...]` (can be given multiple times)")
f.Var(&opts.AddTags, "add", "`tags` which will be added to the existing tags in the format `tag[,tag,...]` (can be given multiple times)")
f.Var(&opts.RemoveTags, "remove", "`tags` which will be removed from the existing tags in the format `tag[,tag,...]` (can be given multiple times)")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
type changedSnapshot struct {
MessageType string `json:"message_type"` // changed
OldSnapshotID restic.ID `json:"old_snapshot_id"`
NewSnapshotID restic.ID `json:"new_snapshot_id"`
}
type changedSnapshotsSummary struct {
MessageType string `json:"message_type"` // summary
ChangedSnapshots int `json:"changed_snapshots"`
}
func changeTags(ctx context.Context, repo *repository.Repository, sn *data.Snapshot, setTags, addTags, removeTags []string, printFunc func(changedSnapshot)) (bool, error) {
var changed bool
if len(setTags) != 0 {
// Setting the tag to an empty string really means no tags.
if len(setTags) == 1 && setTags[0] == "" {
setTags = nil
}
sn.Tags = setTags
changed = true
} else {
changed = sn.AddTags(addTags)
if sn.RemoveTags(removeTags) {
changed = true
}
}
if changed {
// Retain the original snapshot id over all tag changes.
if sn.Original == nil {
sn.Original = sn.ID()
}
// Save the new snapshot.
id, err := data.SaveSnapshot(ctx, repo, sn)
if err != nil {
return false, err
}
debug.Log("old snapshot %v saved as a new snapshot %v", sn.ID(), id)
// Remove the old snapshot.
if err = repo.RemoveUnpacked(ctx, restic.WriteableSnapshotFile, *sn.ID()); err != nil {
return false, err
}
debug.Log("old snapshot %v removed", sn.ID())
printFunc(changedSnapshot{MessageType: "changed", OldSnapshotID: *sn.ID(), NewSnapshotID: id})
}
return changed, nil
}
func runTag(ctx context.Context, opts TagOptions, gopts global.Options, term ui.Terminal, args []string) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
if len(opts.SetTags) == 0 && len(opts.AddTags) == 0 && len(opts.RemoveTags) == 0 {
return errors.Fatal("nothing to do!")
}
if len(opts.SetTags) != 0 && (len(opts.AddTags) != 0 || len(opts.RemoveTags) != 0) {
return errors.Fatal("--set and --add/--remove cannot be given at the same time")
}
printer.P("create exclusive lock for repository")
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
printFunc := func(c changedSnapshot) {
printer.V("old snapshot ID: %v -> new snapshot ID: %v", c.OldSnapshotID, c.NewSnapshotID)
}
summary := changedSnapshotsSummary{MessageType: "summary", ChangedSnapshots: 0}
printSummary := func(c changedSnapshotsSummary) {
if c.ChangedSnapshots == 0 {
printer.P("no snapshots were modified")
} else {
printer.P("modified %v snapshots", c.ChangedSnapshots)
}
}
if gopts.JSON {
printFunc = func(c changedSnapshot) {
term.Print(ui.ToJSONString(c))
}
printSummary = func(c changedSnapshotsSummary) {
term.Print(ui.ToJSONString(c))
}
}
for sn := range FindFilteredSnapshots(ctx, repo, repo, &opts.SnapshotFilter, args, printer) {
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
}
if changed {
summary.ChangedSnapshots++
}
}
if ctx.Err() != nil {
return ctx.Err()
}
printSummary(summary)
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_prune_integration_test.go | cmd/restic/cmd_prune_integration_test.go | package main
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
rtest "github.com/restic/restic/internal/test"
)
func testRunPrune(t testing.TB, gopts global.Options, opts PruneOptions) {
t.Helper()
rtest.OK(t, testRunPruneOutput(t, gopts, opts))
}
func testRunPruneMustFail(t testing.TB, gopts global.Options, opts PruneOptions) {
t.Helper()
err := testRunPruneOutput(t, gopts, opts)
rtest.Assert(t, err != nil, "expected non nil error")
}
func testRunPruneOutput(t testing.TB, gopts global.Options, opts PruneOptions) error {
oldHook := gopts.BackendTestHook
gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) { return newListOnceBackend(r), nil }
defer func() {
gopts.BackendTestHook = oldHook
}()
return withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runPrune(context.TODO(), opts, gopts, gopts.Term)
})
}
func TestPrune(t *testing.T) {
testPruneVariants(t, false)
testPruneVariants(t, true)
}
func testPruneVariants(t *testing.T, unsafeNoSpaceRecovery bool) {
suffix := ""
if unsafeNoSpaceRecovery {
suffix = "-recovery"
}
t.Run("0"+suffix, func(t *testing.T) {
opts := PruneOptions{MaxUnused: "0%", unsafeRecovery: unsafeNoSpaceRecovery}
checkOpts := CheckOptions{ReadData: true, CheckUnused: !unsafeNoSpaceRecovery}
testPrune(t, opts, checkOpts)
})
t.Run("50"+suffix, func(t *testing.T) {
opts := PruneOptions{MaxUnused: "50%", unsafeRecovery: unsafeNoSpaceRecovery}
checkOpts := CheckOptions{ReadData: true}
testPrune(t, opts, checkOpts)
})
t.Run("unlimited"+suffix, func(t *testing.T) {
opts := PruneOptions{MaxUnused: "unlimited", unsafeRecovery: unsafeNoSpaceRecovery}
checkOpts := CheckOptions{ReadData: true}
testPrune(t, opts, checkOpts)
})
t.Run("CacheableOnly"+suffix, func(t *testing.T) {
opts := PruneOptions{MaxUnused: "5%", RepackCacheableOnly: true, unsafeRecovery: unsafeNoSpaceRecovery}
checkOpts := CheckOptions{ReadData: true}
testPrune(t, opts, checkOpts)
})
t.Run("Small", func(t *testing.T) {
opts := PruneOptions{MaxUnused: "unlimited", RepackSmall: true}
checkOpts := CheckOptions{ReadData: true, CheckUnused: true}
testPrune(t, opts, checkOpts)
})
}
func createPrunableRepo(t *testing.T, env *testEnvironment) {
testSetupBackupData(t, env)
opts := BackupOptions{}
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9")}, opts, env.gopts)
firstSnapshot := testListSnapshots(t, env.gopts, 1)[0]
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "2")}, opts, env.gopts)
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "3")}, opts, env.gopts)
testListSnapshots(t, env.gopts, 3)
testRunForgetJSON(t, env.gopts)
testRunForget(t, env.gopts, ForgetOptions{}, firstSnapshot.String())
}
func testRunForgetJSON(t testing.TB, gopts global.Options, args ...string) {
buf, err := withCaptureStdout(t, gopts, func(ctx context.Context, gopts global.Options) error {
gopts.JSON = true
opts := ForgetOptions{
DryRun: true,
Last: 1,
}
pruneOpts := PruneOptions{
MaxUnused: "5%",
}
return runForget(context.TODO(), opts, pruneOpts, gopts, gopts.Term, args)
})
rtest.OK(t, err)
var forgets []*ForgetGroup
rtest.OK(t, json.Unmarshal(buf.Bytes(), &forgets))
rtest.Assert(t, len(forgets) == 1,
"Expected 1 snapshot group, got %v", len(forgets))
rtest.Assert(t, len(forgets[0].Keep) == 1,
"Expected 1 snapshot to be kept, got %v", len(forgets[0].Keep))
rtest.Assert(t, len(forgets[0].Remove) == 2,
"Expected 2 snapshots to be removed, got %v", len(forgets[0].Remove))
}
func testPrune(t *testing.T, pruneOpts PruneOptions, checkOpts CheckOptions) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
createPrunableRepo(t, env)
testRunPrune(t, env.gopts, pruneOpts)
rtest.OK(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
_, err := runCheck(context.TODO(), checkOpts, gopts, nil, gopts.Term)
return err
}))
}
var pruneDefaultOptions = PruneOptions{MaxUnused: "5%"}
func TestPruneWithDamagedRepository(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("testdata", "backup-data.tar.gz")
testRunInit(t, env.gopts)
rtest.SetupTarTestFixture(t, env.testdata, datafile)
opts := BackupOptions{}
// create and delete snapshot to create unused blobs
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "2")}, opts, env.gopts)
firstSnapshot := testListSnapshots(t, env.gopts, 1)[0]
testRunForget(t, env.gopts, ForgetOptions{}, firstSnapshot.String())
oldPacks := listPacks(env.gopts, t)
// create new snapshot, but lose all data
testRunBackup(t, "", []string{filepath.Join(env.testdata, "0", "0", "9", "3")}, opts, env.gopts)
testListSnapshots(t, env.gopts, 1)
removePacksExcept(env.gopts, t, oldPacks, false)
oldHook := env.gopts.BackendTestHook
env.gopts.BackendTestHook = func(r backend.Backend) (backend.Backend, error) { return newListOnceBackend(r), nil }
defer func() {
env.gopts.BackendTestHook = oldHook
}()
// prune should fail
rtest.Equals(t, repository.ErrPacksMissing, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runPrune(context.TODO(), pruneDefaultOptions, gopts, gopts.Term)
}), "prune should have reported index not complete error")
}
// Test repos for edge cases
func TestEdgeCaseRepos(t *testing.T) {
opts := CheckOptions{}
// repo where index is completely missing
// => check and prune should fail
t.Run("no-index", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-index-missing.tar.gz", opts, pruneDefaultOptions, false, false)
})
// repo where an existing and used blob is missing from the index
// => check and prune should fail
t.Run("index-missing-blob", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-index-missing-blob.tar.gz", opts, pruneDefaultOptions, false, false)
})
// repo where a blob is missing
// => check and prune should fail
t.Run("missing-data", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-data-missing.tar.gz", opts, pruneDefaultOptions, false, false)
})
// repo where blobs which are not needed are missing or in invalid pack files
// => check should fail and prune should repair this
t.Run("missing-unused-data", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-unused-data-missing.tar.gz", opts, pruneDefaultOptions, false, true)
})
// repo where data exists that is not referenced
// => check and prune should fully work
t.Run("unreferenced-data", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-unreferenced-data.tar.gz", opts, pruneDefaultOptions, true, true)
})
// repo where an obsolete index still exists
// => check and prune should fully work
t.Run("obsolete-index", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-obsolete-index.tar.gz", opts, pruneDefaultOptions, true, true)
})
// repo which contains mixed (data/tree) packs
// => check and prune should fully work
t.Run("mixed-packs", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-mixed.tar.gz", opts, pruneDefaultOptions, true, true)
})
// repo which contains duplicate blobs
// => checking for unused data should report an error and prune resolves the
// situation
opts = CheckOptions{
ReadData: true,
CheckUnused: true,
}
t.Run("duplicates", func(t *testing.T) {
testEdgeCaseRepo(t, "repo-duplicates.tar.gz", opts, pruneDefaultOptions, false, true)
})
}
func testEdgeCaseRepo(t *testing.T, tarfile string, optionsCheck CheckOptions, optionsPrune PruneOptions, checkOK, pruneOK bool) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
datafile := filepath.Join("testdata", tarfile)
rtest.SetupTarTestFixture(t, env.base, datafile)
if checkOK {
testRunCheck(t, env.gopts)
} else {
rtest.Assert(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
_, err := runCheck(context.TODO(), optionsCheck, gopts, nil, gopts.Term)
return err
}) != nil,
"check should have reported an error")
}
if pruneOK {
testRunPrune(t, env.gopts, optionsPrune)
testRunCheck(t, env.gopts)
} else {
rtest.Assert(t, withTermStatus(t, env.gopts, func(ctx context.Context, gopts global.Options) error {
return runPrune(context.TODO(), optionsPrune, gopts, gopts.Term)
}) != nil,
"prune should have reported an error")
}
}
func TestPruneRepackSmallerThanSmoke(t *testing.T) {
env, cleanup := withTestEnvironment(t)
defer cleanup()
// the implementation is already unit tested, so just check that
// the setting reaches its goal
createPrunableRepo(t, env)
testRunPrune(t, env.gopts, PruneOptions{
SmallPackSize: "4M",
MaxUnused: "5%",
})
testRunPruneMustFail(t, env.gopts, PruneOptions{
SmallPackSize: "500M",
MaxUnused: "5%",
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/integration_helpers_unix_test.go | cmd/restic/integration_helpers_unix_test.go | //go:build !windows
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"syscall"
)
func (e *dirEntry) equals(out io.Writer, other *dirEntry) bool {
if e.path != other.path {
_, _ = fmt.Fprintf(out, "%v: path does not match (%v != %v)\n", e.path, e.path, other.path)
return false
}
if e.fi.Mode() != other.fi.Mode() {
_, _ = fmt.Fprintf(out, "%v: mode does not match (%v != %v)\n", e.path, e.fi.Mode(), other.fi.Mode())
return false
}
if !sameModTime(e.fi, other.fi) {
_, _ = fmt.Fprintf(out, "%v: ModTime does not match (%v != %v)\n", e.path, e.fi.ModTime(), other.fi.ModTime())
return false
}
stat, _ := e.fi.Sys().(*syscall.Stat_t)
stat2, _ := other.fi.Sys().(*syscall.Stat_t)
if stat.Uid != stat2.Uid {
_, _ = fmt.Fprintf(out, "%v: UID does not match (%v != %v)\n", e.path, stat.Uid, stat2.Uid)
return false
}
if stat.Gid != stat2.Gid {
_, _ = fmt.Fprintf(out, "%v: GID does not match (%v != %v)\n", e.path, stat.Gid, stat2.Gid)
return false
}
if stat.Nlink != stat2.Nlink {
_, _ = fmt.Fprintf(out, "%v: Number of links do not match (%v != %v)\n", e.path, stat.Nlink, stat2.Nlink)
return false
}
return true
}
func nlink(info os.FileInfo) uint64 {
stat, _ := info.Sys().(*syscall.Stat_t)
return uint64(stat.Nlink)
}
func createFileSetPerHardlink(dir string) map[uint64][]string {
var stat syscall.Stat_t
linkTests := make(map[uint64][]string)
files, err := os.ReadDir(dir)
if err != nil {
return nil
}
for _, f := range files {
if err := syscall.Stat(filepath.Join(dir, f.Name()), &stat); err != nil {
return nil
}
linkTests[uint64(stat.Ino)] = append(linkTests[uint64(stat.Ino)], f.Name())
}
return linkTests
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_mount_integration_test.go | cmd/restic/cmd_mount_integration_test.go | //go:build darwin || freebsd || linux
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"time"
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"
)
const (
mountWait = 20
mountSleep = 100 * time.Millisecond
mountTestSubdir = "snapshots"
)
func snapshotsDirExists(t testing.TB, dir string) bool {
f, err := os.Open(filepath.Join(dir, mountTestSubdir))
if err != nil && os.IsNotExist(err) {
return false
}
if err != nil {
t.Error(err)
}
if err := f.Close(); err != nil {
t.Error(err)
}
return true
}
// 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++ {
if snapshotsDirExists(t, dir) {
t.Log("mounted directory is ready")
return
}
time.Sleep(mountSleep)
}
t.Errorf("subdir %q of dir %s never appeared", mountTestSubdir, dir)
}
func testRunMount(t testing.TB, gopts global.Options, dir string, wg *sync.WaitGroup) {
defer wg.Done()
opts := MountOptions{
TimeTemplate: time.RFC3339,
}
rtest.OK(t, withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
return runMount(context.TODO(), opts, gopts, []string{dir}, gopts.Term)
}))
}
func testRunUmount(t testing.TB, dir string) {
var err error
for i := 0; i < mountWait; i++ {
if err = systemFuse.Unmount(dir); err == nil {
t.Logf("directory %v umounted", dir)
return
}
time.Sleep(mountSleep)
}
t.Errorf("unable to umount dir %v, last error was: %v", dir, err)
}
func listSnapshots(t testing.TB, dir string) []string {
snapshotsDir, err := os.Open(filepath.Join(dir, "snapshots"))
rtest.OK(t, err)
names, err := snapshotsDir.Readdirnames(-1)
rtest.OK(t, err)
rtest.OK(t, snapshotsDir.Close())
return names
}
func checkSnapshots(t testing.TB, gopts global.Options, mountpoint string, snapshotIDs restic.IDs, expectedSnapshotsInFuseDir int) {
t.Logf("checking for %d snapshots: %v", len(snapshotIDs), snapshotIDs)
var wg sync.WaitGroup
wg.Add(1)
go testRunMount(t, gopts, mountpoint, &wg)
waitForMount(t, mountpoint)
defer wg.Wait()
defer testRunUmount(t, mountpoint)
if !snapshotsDirExists(t, mountpoint) {
t.Fatal(`virtual directory "snapshots" doesn't exist`)
}
ids := listSnapshots(t, gopts.Repo)
t.Logf("found %v snapshots in repo: %v", len(ids), ids)
namesInSnapshots := listSnapshots(t, mountpoint)
t.Logf("found %v snapshots in fuse mount: %v", len(namesInSnapshots), namesInSnapshots)
rtest.Assert(t,
expectedSnapshotsInFuseDir == len(namesInSnapshots),
"Invalid number of snapshots: expected %d, got %d", expectedSnapshotsInFuseDir, len(namesInSnapshots))
namesMap := make(map[string]bool)
for _, name := range namesInSnapshots {
namesMap[name] = false
}
// Is "latest" present?
if len(namesMap) != 0 {
_, ok := namesMap["latest"]
if !ok {
t.Errorf("Symlink latest isn't present in fuse dir")
} else {
namesMap["latest"] = true
}
}
err := withTermStatus(t, gopts, func(ctx context.Context, gopts global.Options) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, gopts.Term)
_, repo, unlock, err := openWithReadLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
for _, id := range snapshotIDs {
snapshot, err := data.LoadSnapshot(ctx, repo, id)
rtest.OK(t, err)
ts := snapshot.Time.Format(time.RFC3339)
present, ok := namesMap[ts]
if !ok {
t.Errorf("Snapshot %v (%q) isn't present in fuse dir", id.Str(), ts)
}
for i := 1; present; i++ {
ts = fmt.Sprintf("%s-%d", snapshot.Time.Format(time.RFC3339), i)
present, ok = namesMap[ts]
if !ok {
t.Errorf("Snapshot %v (%q) isn't present in fuse dir", id.Str(), ts)
}
if !present {
break
}
}
namesMap[ts] = true
}
return nil
})
rtest.OK(t, err)
for name, present := range namesMap {
rtest.Assert(t, present, "Directory %s is present in fuse dir but is not a snapshot", name)
}
}
func TestMount(t *testing.T) {
if !rtest.RunFuseTest {
t.Skip("Skipping fuse tests")
}
env, cleanup := withTestEnvironment(t)
// must list snapshots more than once
env.gopts.BackendTestHook = nil
defer cleanup()
testRunInit(t, env.gopts)
checkSnapshots(t, env.gopts, env.mountpoint, []restic.ID{}, 0)
rtest.SetupTarTestFixture(t, env.testdata, filepath.Join("testdata", "backup-data.tar.gz"))
// first backup
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
snapshotIDs := testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == 1,
"expected one snapshot, got %v", snapshotIDs)
checkSnapshots(t, env.gopts, env.mountpoint, snapshotIDs, 2)
// second backup, implicit incremental
testRunBackup(t, "", []string{env.testdata}, BackupOptions{}, env.gopts)
snapshotIDs = testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == 2,
"expected two snapshots, got %v", snapshotIDs)
checkSnapshots(t, env.gopts, env.mountpoint, snapshotIDs, 3)
// third backup, explicit incremental
bopts := BackupOptions{Parent: snapshotIDs[0].String()}
testRunBackup(t, "", []string{env.testdata}, bopts, env.gopts)
snapshotIDs = testRunList(t, env.gopts, "snapshots")
rtest.Assert(t, len(snapshotIDs) == 3,
"expected three snapshots, got %v", snapshotIDs)
checkSnapshots(t, env.gopts, env.mountpoint, snapshotIDs, 4)
}
func TestMountSameTimestamps(t *testing.T) {
if !rtest.RunFuseTest {
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
defer cleanup()
rtest.SetupTarTestFixture(t, env.base, filepath.Join("testdata", "repo-same-timestamps.tar.gz"))
ids := []restic.ID{
restic.TestParseID("280303689e5027328889a06d718b729e96a1ce6ae9ef8290bff550459ae611ee"),
restic.TestParseID("75ad6cdc0868e082f2596d5ab8705e9f7d87316f5bf5690385eeff8dbe49d9f5"),
restic.TestParseID("5fd0d8b2ef0fa5d23e58f1e460188abb0f525c0f0c4af8365a1280c807a80a1b"),
}
checkSnapshots(t, env.gopts, env.mountpoint, ids, 4)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_dump.go | cmd/restic/cmd_dump.go | package main
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/dump"
"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/spf13/cobra"
"github.com/spf13/pflag"
)
func newDumpCommand(globalOptions *global.Options) *cobra.Command {
var opts DumpOptions
cmd := &cobra.Command{
Use: "dump [flags] snapshotID file",
Short: "Print a backed-up file to stdout",
Long: `
The "dump" command extracts files from a snapshot from the repository. If a
single file is selected, it prints its contents to stdout. Folders are output
as a tar (default) or zip file containing the contents of the specified folder.
Pass "/" as file name to dump the whole snapshot as an archive file.
The special snapshotID "latest" can be used to use the latest snapshot in the
repository.
To include the folder content at the root of the archive, you can use the
"snapshotID:subfolder" syntax, where "subfolder" is a path within the
snapshot.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runDump(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// DumpOptions collects all options for the dump command.
type DumpOptions struct {
data.SnapshotFilter
Archive string
Target string
}
func (opts *DumpOptions) AddFlags(f *pflag.FlagSet) {
initSingleSnapshotFilter(f, &opts.SnapshotFilter)
f.StringVarP(&opts.Archive, "archive", "a", "tar", "set archive `format` as \"tar\" or \"zip\"")
f.StringVarP(&opts.Target, "target", "t", "", "write the output to target `path`")
}
func splitPath(p string) []string {
d, f := path.Split(p)
if d == "" || d == "/" {
return []string{f}
}
s := splitPath(path.Join("/", d))
return append(s, f)
}
func printFromTree(ctx context.Context, tree *data.Tree, repo restic.BlobLoader, prefix string, pathComponents []string, d *dump.Dumper, canWriteArchiveFunc func() error) error {
// If we print / we need to assume that there are multiple nodes at that
// level in the tree.
if pathComponents[0] == "" {
if err := canWriteArchiveFunc(); err != nil {
return err
}
return d.DumpTree(ctx, tree, "/")
}
item := filepath.Join(prefix, pathComponents[0])
l := len(pathComponents)
for _, node := range tree.Nodes {
if ctx.Err() != nil {
return ctx.Err()
}
// If dumping something in the highest level it will just take the
// first item it finds and dump that according to the switch case below.
if node.Name == pathComponents[0] {
switch {
case l == 1 && node.Type == data.NodeTypeFile:
return d.WriteNode(ctx, node)
case l > 1 && node.Type == data.NodeTypeDir:
subtree, err := data.LoadTree(ctx, repo, *node.Subtree)
if err != nil {
return errors.Wrapf(err, "cannot load subtree for %q", item)
}
return printFromTree(ctx, subtree, repo, item, pathComponents[1:], d, canWriteArchiveFunc)
case node.Type == data.NodeTypeDir:
if err := canWriteArchiveFunc(); err != nil {
return err
}
subtree, err := data.LoadTree(ctx, repo, *node.Subtree)
if err != nil {
return err
}
return d.DumpTree(ctx, subtree, item)
case l > 1:
return fmt.Errorf("%q should be a dir, but is a %q", item, node.Type)
case node.Type != data.NodeTypeFile:
return fmt.Errorf("%q should be a file, but is a %q", item, node.Type)
}
}
}
return fmt.Errorf("path %q not found in snapshot", item)
}
func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) != 2 {
return errors.Fatal("no file and no snapshot ID specified")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
switch opts.Archive {
case "tar", "zip":
default:
return fmt.Errorf("unknown archive format %q", opts.Archive)
}
snapshotIDString := args[0]
pathToPrint := args[1]
debug.Log("dump file %q from %q", pathToPrint, snapshotIDString)
splittedPath := splitPath(path.Clean(pathToPrint))
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
sn, subfolder, err := (&data.SnapshotFilter{
Hosts: opts.Hosts,
Paths: opts.Paths,
Tags: opts.Tags,
}).FindLatest(ctx, repo, repo, snapshotIDString)
if err != nil {
return errors.Fatalf("failed to find snapshot: %v", err)
}
err = repo.LoadIndex(ctx, printer)
if err != nil {
return err
}
sn.Tree, err = data.FindTreeDirectory(ctx, repo, sn.Tree, subfolder)
if err != nil {
return err
}
tree, err := data.LoadTree(ctx, repo, *sn.Tree)
if err != nil {
return errors.Fatalf("loading tree for snapshot %q failed: %v", snapshotIDString, err)
}
outputFileWriter := term.OutputRaw()
canWriteArchiveFunc := checkStdoutArchive(term)
if opts.Target != "" {
file, err := os.Create(opts.Target)
if err != nil {
return fmt.Errorf("cannot dump to file: %w", err)
}
defer func() {
_ = file.Close()
}()
outputFileWriter = file
canWriteArchiveFunc = func() error { return nil }
}
d := dump.New(opts.Archive, repo, outputFileWriter)
err = printFromTree(ctx, tree, repo, "/", splittedPath, d, canWriteArchiveFunc)
if err != nil {
return errors.Fatalf("cannot dump file: %v", err)
}
return nil
}
func checkStdoutArchive(term ui.Terminal) func() error {
if term.OutputIsTerminal() {
return func() error { return fmt.Errorf("stdout is the terminal, please redirect output") }
}
return func() error { return nil }
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_migrate.go | cmd/restic/cmd_migrate.go | package main
import (
"context"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/migrations"
"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"
)
func newMigrateCommand(globalOptions *global.Options) *cobra.Command {
var opts MigrateOptions
cmd := &cobra.Command{
Use: "migrate [flags] [migration name] [...]",
Short: "Apply migrations",
Long: `
The "migrate" command checks which migrations can be applied for a repository
and prints a list with available migration names. If one or more migration
names are specified, these migrations are applied.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
GroupID: cmdGroupDefault,
RunE: func(cmd *cobra.Command, args []string) error {
return runMigrate(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// MigrateOptions bundles all options for the 'check' command.
type MigrateOptions struct {
Force bool
}
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 {
printer.P("available migrations:\n")
found := false
for _, m := range migrations.All {
ok, _, err := m.Check(ctx, repo)
if err != nil {
return err
}
if ok {
printer.P(" %v\t%v\n", m.Name(), m.Desc())
found = true
}
}
if !found {
printer.P("no migrations found\n")
}
return nil
}
func applyMigrations(ctx context.Context, opts MigrateOptions, gopts global.Options, repo restic.Repository, args []string, term ui.Terminal, printer progress.Printer) error {
var firsterr error
for _, name := range args {
found := false
for _, m := range migrations.All {
if m.Name() == name {
found = true
ok, reason, err := m.Check(ctx, repo)
if err != nil {
return err
}
if !ok {
if !opts.Force {
if reason == "" {
reason = "check failed"
}
printer.E("migration %v cannot be applied: %v\nIf you want to apply this migration anyway, re-run with option --force\n", m.Name(), reason)
continue
}
printer.E("check for migration %v failed, continuing anyway\n", m.Name())
}
if m.RepoCheck() {
printer.P("checking repository integrity...\n")
checkOptions := CheckOptions{}
checkGopts := gopts
// the repository is already locked
checkGopts.NoLock = true
_, err = runCheck(ctx, checkOptions, checkGopts, []string{}, term)
if err != nil {
return err
}
}
printer.P("applying migration %v...\n", m.Name())
if err = m.Apply(ctx, repo); err != nil {
printer.E("migration %v failed: %v\n", m.Name(), err)
if firsterr == nil {
firsterr = err
}
continue
}
printer.P("migration %v: success\n", m.Name())
}
}
if !found {
printer.E("unknown migration %v", name)
}
}
return firsterr
}
func runMigrate(ctx context.Context, opts MigrateOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(false, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, false, printer)
if err != nil {
return err
}
defer unlock()
if len(args) == 0 {
return checkMigrations(ctx, repo, printer)
}
return applyMigrations(ctx, opts, gopts, repo, args, term, printer)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/doc.go | cmd/restic/doc.go | // This package contains the code for the restic executable.
package main
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_snapshots.go | cmd/restic/cmd_snapshots.go | package main
import (
"context"
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newSnapshotsCommand(globalOptions *global.Options) *cobra.Command {
var opts SnapshotOptions
cmd := &cobra.Command{
Use: "snapshots [flags] [snapshotID ...]",
Short: "List all snapshots",
Long: `
The "snapshots" command lists all snapshots stored in the repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runSnapshots(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// SnapshotOptions bundles all options for the snapshots command.
type SnapshotOptions struct {
data.SnapshotFilter
Compact bool
Last bool // This option should be removed in favour of Latest.
Latest int
GroupBy data.SnapshotGroupByOptions
}
func (opts *SnapshotOptions) AddFlags(f *pflag.FlagSet) {
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
f.BoolVarP(&opts.Compact, "compact", "c", false, "use compact output format")
f.BoolVar(&opts.Last, "last", false, "only show the last snapshot for each host and path")
err := f.MarkDeprecated("last", "use --latest 1")
if err != nil {
// MarkDeprecated only returns an error when the flag is not found
panic(err)
}
f.IntVar(&opts.Latest, "latest", 0, "only show the last `n` snapshots for each host and path")
f.VarP(&opts.GroupBy, "group-by", "g", "`group` snapshots by host, paths and/or tags, separated by comma")
}
func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
var snapshots data.Snapshots
for sn := range FindFilteredSnapshots(ctx, repo, repo, &opts.SnapshotFilter, args, printer) {
snapshots = append(snapshots, sn)
}
if ctx.Err() != nil {
return ctx.Err()
}
snapshotGroups, grouped, err := data.GroupSnapshots(snapshots, opts.GroupBy)
if err != nil {
return err
}
for k, list := range snapshotGroups {
if ctx.Err() != nil {
return ctx.Err()
}
if opts.Last {
// This branch should be removed in the same time
// that --last.
list = filterLatestSnapshotsInGroup(list, 1)
} else if opts.Latest > 0 {
list = filterLatestSnapshotsInGroup(list, opts.Latest)
}
sort.Sort(sort.Reverse(list))
snapshotGroups[k] = list
}
if gopts.JSON {
err := printSnapshotGroupJSON(gopts.Term.OutputWriter(), snapshotGroups, grouped)
if err != nil {
printer.E("error printing snapshots: %v", err)
}
return nil
}
for k, list := range snapshotGroups {
if ctx.Err() != nil {
return ctx.Err()
}
if grouped {
err := PrintSnapshotGroupHeader(gopts.Term.OutputWriter(), k)
if err != nil {
return err
}
}
err := PrintSnapshots(gopts.Term.OutputWriter(), list, nil, opts.Compact)
if err != nil {
return err
}
}
return nil
}
// filterLatestSnapshotsInGroup filters a list of snapshots to only return
// the `limit` last entries. It is assumed that the snapshot list only contains
// one group of snapshots.
func filterLatestSnapshotsInGroup(list data.Snapshots, limit int) data.Snapshots {
// Sort the snapshots so that the newer ones are listed first
sort.SliceStable(list, func(i, j int) bool {
return list[i].Time.After(list[j].Time)
})
return list[:min(limit, len(list))]
}
// PrintSnapshots prints a text table of the snapshots in list to stdout.
func PrintSnapshots(stdout io.Writer, list data.Snapshots, reasons []data.KeepReason, compact bool) error {
// keep the reasons a snasphot is being kept in a map, so that it doesn't
// get lost when the list of snapshots is sorted
keepReasons := make(map[restic.ID]data.KeepReason, len(reasons))
if len(reasons) > 0 {
for i, sn := range list {
id := sn.ID()
keepReasons[*id] = reasons[i]
}
}
// check if any snapshot contains a summary
hasSize := false
for _, sn := range list {
hasSize = hasSize || (sn.Summary != nil)
}
// always sort the snapshots so that the newer ones are listed last
sort.SliceStable(list, func(i, j int) bool {
return list[i].Time.Before(list[j].Time)
})
// Determine the max widths for host and tag.
maxHost, maxTag := 10, 6
for _, sn := range list {
if len(sn.Hostname) > maxHost {
maxHost = len(sn.Hostname)
}
for _, tag := range sn.Tags {
if len(tag) > maxTag {
maxTag = len(tag)
}
}
}
tab := table.New()
if compact {
tab.AddColumn("ID", "{{ .ID }}")
tab.AddColumn("Time", "{{ .Timestamp }}")
tab.AddColumn("Host", "{{ .Hostname }}")
tab.AddColumn("Tags ", `{{ join .Tags "\n" }}`)
if hasSize {
tab.AddColumn("Size", `{{ .Size }}`)
}
} else {
tab.AddColumn("ID", "{{ .ID }}")
tab.AddColumn("Time", "{{ .Timestamp }}")
tab.AddColumn("Host ", "{{ .Hostname }}")
tab.AddColumn("Tags ", `{{ join .Tags "," }}`)
if len(reasons) > 0 {
tab.AddColumn("Reasons", `{{ join .Reasons "\n" }}`)
}
tab.AddColumn("Paths", `{{ join .Paths "\n" }}`)
if hasSize {
tab.AddColumn("Size", `{{ .Size }}`)
}
}
type snapshot struct {
ID string
Timestamp string
Hostname string
Tags []string
Reasons []string
Paths []string
Size string
}
var multiline bool
for _, sn := range list {
data := snapshot{
ID: sn.ID().Str(),
Timestamp: sn.Time.Local().Format(global.TimeFormat),
Hostname: sn.Hostname,
Tags: sn.Tags,
Paths: sn.Paths,
}
if len(reasons) > 0 {
id := sn.ID()
data.Reasons = keepReasons[*id].Matches
}
if len(sn.Paths) > 1 && !compact {
multiline = true
}
if sn.Summary != nil {
data.Size = ui.FormatBytes(sn.Summary.TotalBytesProcessed)
}
tab.AddRow(data)
}
// Add timezone information to prevent confusion:
// Each snapshot can be registered in different timezones,
// but we display them all in local timezone on this output.
footer := fmt.Sprintf("%d snapshots", len(list))
zoneName, _ := time.Now().Local().Zone()
if zoneName != "" {
footer = fmt.Sprintf("Timestamps shown in %s timezone\n%s", zoneName, footer)
}
tab.AddFooter(footer)
if multiline {
// print an additional blank line between snapshots
var last int
tab.PrintData = func(w io.Writer, idx int, s string) error {
var err error
if idx == last {
_, err = fmt.Fprintf(w, "%s\n", s)
} else {
_, err = fmt.Fprintf(w, "\n%s\n", s)
}
last = idx
return err
}
}
return tab.Write(stdout)
}
// PrintSnapshotGroupHeader prints which group of the group-by option the
// following snapshots belong to.
// Prints nothing, if we did not group at all.
func PrintSnapshotGroupHeader(stdout io.Writer, groupKeyJSON string) error {
var key data.SnapshotGroupKey
err := json.Unmarshal([]byte(groupKeyJSON), &key)
if err != nil {
return err
}
if key.Hostname == "" && key.Tags == nil && key.Paths == nil {
return nil
}
// Info
header := "snapshots"
var infoStrings []string
if key.Hostname != "" {
infoStrings = append(infoStrings, "host ["+key.Hostname+"]")
}
if key.Tags != nil {
infoStrings = append(infoStrings, "tags ["+strings.Join(key.Tags, ", ")+"]")
}
if key.Paths != nil {
infoStrings = append(infoStrings, "paths ["+strings.Join(key.Paths, ", ")+"]")
}
if infoStrings != nil {
header += " for (" + strings.Join(infoStrings, ", ") + ")"
}
header += ":\n"
_, err = stdout.Write([]byte(header))
return err
}
// Snapshot helps to print Snapshots as JSON with their ID included.
type Snapshot struct {
*data.Snapshot
ID *restic.ID `json:"id"`
ShortID string `json:"short_id"` // deprecated
}
// SnapshotGroup helps to print SnapshotGroups as JSON with their GroupReasons included.
type SnapshotGroup struct {
GroupKey data.SnapshotGroupKey `json:"group_key"`
Snapshots []Snapshot `json:"snapshots"`
}
// printSnapshotGroupJSON writes the JSON representation of list to stdout.
func printSnapshotGroupJSON(stdout io.Writer, snGroups map[string]data.Snapshots, grouped bool) error {
if grouped {
snapshotGroups := []SnapshotGroup{}
for k, list := range snGroups {
var key data.SnapshotGroupKey
var err error
var snapshots []Snapshot
err = json.Unmarshal([]byte(k), &key)
if err != nil {
return err
}
for _, sn := range list {
k := Snapshot{
Snapshot: sn,
ID: sn.ID(),
ShortID: sn.ID().Str(),
}
snapshots = append(snapshots, k)
}
group := SnapshotGroup{
GroupKey: key,
Snapshots: snapshots,
}
snapshotGroups = append(snapshotGroups, group)
}
return json.NewEncoder(stdout).Encode(snapshotGroups)
}
// Old behavior
snapshots := []Snapshot{}
for _, list := range snGroups {
for _, sn := range list {
k := Snapshot{
Snapshot: sn,
ID: sn.ID(),
ShortID: sn.ID().Str(),
}
snapshots = append(snapshots, k)
}
}
return json.NewEncoder(stdout).Encode(snapshots)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_cache.go | cmd/restic/cmd_cache.go | package main
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/restic/restic/internal/backend/cache"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newCacheCommand(globalOptions *global.Options) *cobra.Command {
var opts CacheOptions
cmd := &cobra.Command{
Use: "cache",
Short: "Operate on local cache directories",
Long: `
The "cache" command allows listing and cleaning local cache directories.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
return runCache(opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// CacheOptions bundles all options for the snapshots command.
type CacheOptions struct {
Cleanup bool
MaxAge uint
NoSize bool
}
func (opts *CacheOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.Cleanup, "cleanup", false, "remove old cache directories")
f.UintVar(&opts.MaxAge, "max-age", 30, "max age in `days` for cache directories to be considered old")
f.BoolVar(&opts.NoSize, "no-size", false, "do not output the size of the cache directories")
}
func runCache(opts CacheOptions, gopts global.Options, args []string, term ui.Terminal) error {
printer := ui.NewProgressPrinter(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")
}
if gopts.NoCache {
return errors.Fatal("Refusing to do anything, the cache is disabled")
}
var (
cachedir = gopts.CacheDir
err error
)
if cachedir == "" {
cachedir, err = cache.DefaultDir()
if err != nil {
return err
}
}
if opts.Cleanup || gopts.CleanupCache {
oldDirs, err := cache.OlderThan(cachedir, time.Duration(opts.MaxAge)*24*time.Hour)
if err != nil {
return err
}
if len(oldDirs) == 0 {
printer.P("no old cache dirs found")
return nil
}
printer.P("remove %d old cache directories", len(oldDirs))
for _, item := range oldDirs {
dir := filepath.Join(cachedir, item.Name())
err = os.RemoveAll(dir)
if err != nil {
printer.E("unable to remove %v: %v", dir, err)
}
}
return nil
}
tab := table.New()
type data struct {
ID string
Last string
Old string
Size string
}
tab.AddColumn("Repo ID", "{{ .ID }}")
tab.AddColumn("Last Used", "{{ .Last }}")
tab.AddColumn("Old", "{{ .Old }}")
if !opts.NoSize {
tab.AddColumn("Size", "{{ .Size }}")
}
dirs, err := cache.All(cachedir)
if err != nil {
return err
}
if len(dirs) == 0 {
printer.S("no cache dirs found, basedir is %v", cachedir)
return nil
}
sort.Slice(dirs, func(i, j int) bool {
return dirs[i].ModTime().Before(dirs[j].ModTime())
})
for _, entry := range dirs {
var old string
if cache.IsOld(entry.ModTime(), time.Duration(opts.MaxAge)*24*time.Hour) {
old = "yes"
}
var size string
if !opts.NoSize {
bytes, err := dirSize(filepath.Join(cachedir, entry.Name()))
if err != nil {
return err
}
size = fmt.Sprintf("%11s", ui.FormatBytes(uint64(bytes)))
}
name := entry.Name()
if !strings.HasPrefix(name, "restic-check-cache-") {
name = name[:10]
}
tab.AddRow(data{
name,
fmt.Sprintf("%d days ago", uint(time.Since(entry.ModTime()).Hours()/24)),
old,
size,
})
}
_ = tab.Write(gopts.Term.OutputWriter())
printer.S("%d cache dirs in %s", len(dirs), cachedir)
return nil
}
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil || info == nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return nil
})
return size, err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_forget.go | cmd/restic/cmd_forget.go | package main
import (
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"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/spf13/cobra"
"github.com/spf13/pflag"
)
func newForgetCommand(globalOptions *global.Options) *cobra.Command {
var opts ForgetOptions
var pruneOpts PruneOptions
cmd := &cobra.Command{
Use: "forget [flags] [snapshot ID] [...]",
Short: "Remove snapshots from the repository",
Long: `
The "forget" command removes snapshots according to a policy. All snapshots are
first divided into groups according to "--group-by", and after that the policy
specified by the "--keep-*" options is applied to each group individually.
If there are not enough snapshots to keep one for each duration related
"--keep-{within-,}*" option, the oldest snapshot in the group is kept
additionally.
Please note that this command really only deletes the snapshot object in the
repository, which is a reference to data stored there. In order to remove the
unreferenced data after "forget" was run successfully, see the "prune" command.
Please also read the documentation for "forget" to learn about some important
security considerations.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 3 if there was an error removing one or more snapshots.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runForget(cmd.Context(), opts, pruneOpts, *globalOptions, globalOptions.Term, args)
},
}
opts.AddFlags(cmd.Flags())
pruneOpts.AddLimitedFlags(cmd.Flags())
return cmd
}
type ForgetPolicyCount int
var ErrNegativePolicyCount = errors.New("negative values not allowed, use 'unlimited' instead")
var ErrFailedToRemoveOneOrMoreSnapshots = errors.New("failed to remove one or more snapshots")
func (c *ForgetPolicyCount) Set(s string) error {
switch s {
case "unlimited":
*c = -1
default:
val, err := strconv.ParseInt(s, 10, 0)
if err != nil {
return err
}
if val < 0 {
return ErrNegativePolicyCount
}
*c = ForgetPolicyCount(val)
}
return nil
}
func (c *ForgetPolicyCount) String() string {
switch *c {
case -1:
return "unlimited"
default:
return strconv.FormatInt(int64(*c), 10)
}
}
func (c *ForgetPolicyCount) Type() string {
return "n"
}
// ForgetOptions collects all options for the forget command.
type ForgetOptions struct {
Last ForgetPolicyCount
Hourly ForgetPolicyCount
Daily ForgetPolicyCount
Weekly ForgetPolicyCount
Monthly ForgetPolicyCount
Yearly ForgetPolicyCount
Within data.Duration
WithinHourly data.Duration
WithinDaily data.Duration
WithinWeekly data.Duration
WithinMonthly data.Duration
WithinYearly data.Duration
KeepTags data.TagLists
UnsafeAllowRemoveAll bool
data.SnapshotFilter
Compact bool
// Grouping
GroupBy data.SnapshotGroupByOptions
DryRun bool
Prune bool
}
func (opts *ForgetOptions) AddFlags(f *pflag.FlagSet) {
f.VarP(&opts.Last, "keep-last", "l", "keep the last `n` snapshots (use 'unlimited' to keep all snapshots)")
f.VarP(&opts.Hourly, "keep-hourly", "H", "keep the last `n` hourly snapshots (use 'unlimited' to keep all hourly snapshots)")
f.VarP(&opts.Daily, "keep-daily", "d", "keep the last `n` daily snapshots (use 'unlimited' to keep all daily snapshots)")
f.VarP(&opts.Weekly, "keep-weekly", "w", "keep the last `n` weekly snapshots (use 'unlimited' to keep all weekly snapshots)")
f.VarP(&opts.Monthly, "keep-monthly", "m", "keep the last `n` monthly snapshots (use 'unlimited' to keep all monthly snapshots)")
f.VarP(&opts.Yearly, "keep-yearly", "y", "keep the last `n` yearly snapshots (use 'unlimited' to keep all yearly snapshots)")
f.VarP(&opts.Within, "keep-within", "", "keep snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.VarP(&opts.WithinHourly, "keep-within-hourly", "", "keep hourly snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.VarP(&opts.WithinDaily, "keep-within-daily", "", "keep daily snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.VarP(&opts.WithinWeekly, "keep-within-weekly", "", "keep weekly snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.VarP(&opts.WithinMonthly, "keep-within-monthly", "", "keep monthly snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.VarP(&opts.WithinYearly, "keep-within-yearly", "", "keep yearly snapshots that are newer than `duration` (eg. 1y5m7d2h) relative to the latest snapshot")
f.Var(&opts.KeepTags, "keep-tag", "keep snapshots with this `taglist` (can be specified multiple times)")
f.BoolVar(&opts.UnsafeAllowRemoveAll, "unsafe-allow-remove-all", false, "allow deleting all snapshots of a snapshot group")
f.StringArrayVar(&opts.Hosts, "hostname", nil, "only consider snapshots with the given `hostname` (can be specified multiple times)")
err := f.MarkDeprecated("hostname", "use --host")
if err != nil {
// MarkDeprecated only returns an error when the flag is not found
panic(err)
}
// must be defined after `--hostname` to not override the default value from the environment
initMultiSnapshotFilter(f, &opts.SnapshotFilter, false)
f.BoolVarP(&opts.Compact, "compact", "c", false, "use compact output format")
opts.GroupBy = data.SnapshotGroupByOptions{Host: true, Path: true}
f.VarP(&opts.GroupBy, "group-by", "g", "`group` snapshots by host, paths and/or tags, separated by comma (disable grouping with '')")
f.BoolVarP(&opts.DryRun, "dry-run", "n", false, "do not delete anything, just print what would be done")
f.BoolVar(&opts.Prune, "prune", false, "automatically run the 'prune' command if snapshots have been removed")
f.SortFlags = false
}
func verifyForgetOptions(opts *ForgetOptions) error {
if opts.Last < -1 || opts.Hourly < -1 || opts.Daily < -1 || opts.Weekly < -1 ||
opts.Monthly < -1 || opts.Yearly < -1 {
return errors.Fatal("negative values other than -1 are not allowed for --keep-*")
}
for _, d := range []data.Duration{opts.Within, opts.WithinHourly, opts.WithinDaily,
opts.WithinMonthly, opts.WithinWeekly, opts.WithinYearly} {
if d.Hours < 0 || d.Days < 0 || d.Months < 0 || d.Years < 0 {
return errors.Fatal("durations containing negative values are not allowed for --keep-within*")
}
}
return nil
}
func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOptions, gopts global.Options, term ui.Terminal, args []string) error {
err := verifyForgetOptions(&opts)
if err != nil {
return err
}
err = verifyPruneOptions(&pruneOptions)
if err != nil {
return err
}
if gopts.NoLock && !opts.DryRun {
return errors.Fatal("--no-lock is only applicable in combination with --dry-run for forget command")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithExclusiveLock(ctx, gopts, opts.DryRun && gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
var snapshots data.Snapshots
removeSnIDs := restic.NewIDSet()
for sn := range FindFilteredSnapshots(ctx, repo, repo, &opts.SnapshotFilter, args, printer) {
snapshots = append(snapshots, sn)
}
if ctx.Err() != nil {
return ctx.Err()
}
var jsonGroups []*ForgetGroup
if len(args) > 0 {
// When explicit snapshots args are given, remove them immediately.
for _, sn := range snapshots {
removeSnIDs.Insert(*sn.ID())
}
} else {
snapshotGroups, _, err := data.GroupSnapshots(snapshots, opts.GroupBy)
if err != nil {
return err
}
policy := data.ExpirePolicy{
Last: int(opts.Last),
Hourly: int(opts.Hourly),
Daily: int(opts.Daily),
Weekly: int(opts.Weekly),
Monthly: int(opts.Monthly),
Yearly: int(opts.Yearly),
Within: opts.Within,
WithinHourly: opts.WithinHourly,
WithinDaily: opts.WithinDaily,
WithinWeekly: opts.WithinWeekly,
WithinMonthly: opts.WithinMonthly,
WithinYearly: opts.WithinYearly,
Tags: opts.KeepTags,
}
if policy.Empty() {
if opts.UnsafeAllowRemoveAll {
if opts.SnapshotFilter.Empty() {
return errors.Fatal("--unsafe-allow-remove-all is not allowed unless a snapshot filter option is specified")
}
// UnsafeAllowRemoveAll together with snapshot filter is fine
} else {
return errors.Fatal("no policy was specified, no snapshots will be removed")
}
}
printer.P("Applying Policy: %v\n", policy)
for k, snapshotGroup := range snapshotGroups {
if ctx.Err() != nil {
return ctx.Err()
}
if gopts.Verbose >= 1 && !gopts.JSON {
err = PrintSnapshotGroupHeader(gopts.Term.OutputWriter(), k)
if err != nil {
return err
}
}
var key data.SnapshotGroupKey
if json.Unmarshal([]byte(k), &key) != nil {
return err
}
var fg ForgetGroup
fg.Tags = key.Tags
fg.Host = key.Hostname
fg.Paths = key.Paths
keep, remove, reasons := data.ApplyPolicy(snapshotGroup, policy)
if !policy.Empty() && len(keep) == 0 {
return fmt.Errorf("refusing to delete last snapshot of snapshot group \"%v\"", key.String())
}
if len(keep) != 0 && !gopts.Quiet && !gopts.JSON {
printer.P("keep %d snapshots:\n", len(keep))
if err := PrintSnapshots(gopts.Term.OutputWriter(), keep, reasons, opts.Compact); err != nil {
return err
}
printer.P("\n")
}
fg.Keep = asJSONSnapshots(keep)
if len(remove) != 0 && !gopts.Quiet && !gopts.JSON {
printer.P("remove %d snapshots:\n", len(remove))
if err := PrintSnapshots(gopts.Term.OutputWriter(), remove, nil, opts.Compact); err != nil {
return err
}
printer.P("\n")
}
fg.Remove = asJSONSnapshots(remove)
fg.Reasons = asJSONKeeps(reasons)
jsonGroups = append(jsonGroups, &fg)
for _, sn := range remove {
removeSnIDs.Insert(*sn.ID())
}
}
}
if ctx.Err() != nil {
return ctx.Err()
}
// these are the snapshots that failed to be removed
failedSnIDs := restic.NewIDSet()
if len(removeSnIDs) > 0 {
if !opts.DryRun {
bar := printer.NewCounter("files deleted")
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)
failedSnIDs.Insert(id)
} else {
printer.VV("removed %v/%v\n", restic.SnapshotFile, id)
}
return nil
}, bar)
bar.Done()
if err != nil {
return err
}
} else {
printer.P("Would have removed the following snapshots:\n%v\n\n", removeSnIDs)
}
}
if gopts.JSON && len(jsonGroups) > 0 {
err = printJSONForget(gopts.Term.OutputWriter(), jsonGroups)
if err != nil {
return err
}
}
if len(failedSnIDs) > 0 {
return ErrFailedToRemoveOneOrMoreSnapshots
}
if len(removeSnIDs) > 0 && opts.Prune {
if opts.DryRun {
printer.P("%d snapshots would be removed, running prune dry run\n", len(removeSnIDs))
} else {
printer.P("%d snapshots have been removed, running prune\n", len(removeSnIDs))
}
pruneOptions.DryRun = opts.DryRun
return runPruneWithRepo(ctx, pruneOptions, repo, removeSnIDs, printer)
}
return nil
}
// ForgetGroup helps to print what is forgotten in JSON.
type ForgetGroup struct {
Tags []string `json:"tags"`
Host string `json:"host"`
Paths []string `json:"paths"`
Keep []Snapshot `json:"keep"`
Remove []Snapshot `json:"remove"`
Reasons []KeepReason `json:"reasons"`
}
func asJSONSnapshots(list data.Snapshots) []Snapshot {
var resultList []Snapshot
for _, sn := range list {
k := Snapshot{
Snapshot: sn,
ID: sn.ID(),
ShortID: sn.ID().Str(),
}
resultList = append(resultList, k)
}
return resultList
}
// KeepReason helps to print KeepReasons as JSON with Snapshots with their ID included.
type KeepReason struct {
Snapshot Snapshot `json:"snapshot"`
Matches []string `json:"matches"`
}
func asJSONKeeps(list []data.KeepReason) []KeepReason {
var resultList []KeepReason
for _, keep := range list {
k := KeepReason{
Snapshot: Snapshot{
Snapshot: keep.Snapshot,
ID: keep.Snapshot.ID(),
ShortID: keep.Snapshot.ID().Str(),
},
Matches: keep.Matches,
}
resultList = append(resultList, k)
}
return resultList
}
func printJSONForget(stdout io.Writer, forgets []*ForgetGroup) error {
return json.NewEncoder(stdout).Encode(forgets)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key.go | cmd/restic/cmd_key.go | package main
import (
"github.com/restic/restic/internal/global"
"github.com/spf13/cobra"
)
func newKeyCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "key",
Short: "Manage keys (passwords)",
Long: `
The "key" command allows you to set multiple access keys or passwords
per repository.
`,
DisableAutoGenTag: true,
GroupID: cmdGroupDefault,
}
cmd.AddCommand(
newKeyAddCommand(globalOptions),
newKeyListCommand(globalOptions),
newKeyPasswdCommand(globalOptions),
newKeyRemoveCommand(globalOptions),
)
return cmd
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_ls.go | cmd/restic/cmd_ls.go | package main
import (
"cmp"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/walker"
)
func newLsCommand(globalOptions *global.Options) *cobra.Command {
var opts LsOptions
cmd := &cobra.Command{
Use: "ls [flags] snapshotID [dir...]",
Short: "List files in a snapshot",
Long: `
The "ls" command lists files and directories in a snapshot.
The special snapshot ID "latest" can be used to list files and
directories of the latest snapshot in the repository. The
--host flag can be used in conjunction to select the latest
snapshot originating from a certain host only.
File listings can optionally be filtered by directories. Any
positional arguments after the snapshot ID are interpreted as
absolute directory paths, and only files inside those directories
will be listed. If the --recursive flag is used, then the filter
will allow traversing into matching directories' subfolders.
Any directory paths specified must be absolute (starting with
a path separator); paths use the forward slash '/' as separator.
File listings can be sorted by specifying --sort followed by one of the
sort specifiers '(name|size|time=mtime|atime|ctime|extension)'.
The sorting can be reversed by specifying --reverse.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
GroupID: cmdGroupDefault,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runLs(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// LsOptions collects all options for the ls command.
type LsOptions struct {
ListLong bool
data.SnapshotFilter
Recursive bool
HumanReadable bool
Ncdu bool
Sort SortMode
Reverse bool
}
func (opts *LsOptions) AddFlags(f *pflag.FlagSet) {
initSingleSnapshotFilter(f, &opts.SnapshotFilter)
f.BoolVarP(&opts.ListLong, "long", "l", false, "use a long listing format showing size and mode")
f.BoolVar(&opts.Recursive, "recursive", false, "include files in subfolders of the listed directories")
f.BoolVar(&opts.HumanReadable, "human-readable", false, "print sizes in human readable format")
f.BoolVar(&opts.Ncdu, "ncdu", false, "output NCDU export format (pipe into 'ncdu -f -')")
f.VarP(&opts.Sort, "sort", "s", "sort output by (name|size|time=mtime|atime|ctime|extension)")
f.BoolVar(&opts.Reverse, "reverse", false, "reverse sorted output")
}
type lsPrinter interface {
Snapshot(sn *data.Snapshot) error
Node(path string, node *data.Node, isPrefixDirectory bool) error
LeaveDir(path string) error
Close() error
}
type jsonLsPrinter struct {
enc *json.Encoder
}
func (p *jsonLsPrinter) Snapshot(sn *data.Snapshot) error {
type lsSnapshot struct {
*data.Snapshot
ID *restic.ID `json:"id"`
ShortID string `json:"short_id"` // deprecated
MessageType string `json:"message_type"` // "snapshot"
StructType string `json:"struct_type"` // "snapshot", deprecated
}
return p.enc.Encode(lsSnapshot{
Snapshot: sn,
ID: sn.ID(),
ShortID: sn.ID().Str(),
MessageType: "snapshot",
StructType: "snapshot",
})
}
// 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)
}
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
size uint64 // Target for Size pointer.
}{
Name: node.Name,
Type: string(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,
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
}
return enc.Encode(n)
}
func (p *jsonLsPrinter) LeaveDir(_ string) error { return nil }
func (p *jsonLsPrinter) Close() error { return nil }
type ncduLsPrinter struct {
out io.Writer
depth int
}
// Snapshot prints a restic snapshot in Ncdu save format.
// It opens the JSON list. Nodes are added with lsNodeNcdu and the list is closed by lsCloseNcdu.
// Format documentation: https://dev.yorhel.nl/ncdu/jsonfmt
func (p *ncduLsPrinter) Snapshot(sn *data.Snapshot) error {
const NcduMajorVer = 1
const NcduMinorVer = 2
snapshotBytes, err := json.Marshal(sn)
if err != nil {
return err
}
p.depth++
_, err = fmt.Fprintf(p.out, "[%d, %d, %s, [{\"name\":\"/\"}", NcduMajorVer, NcduMinorVer, string(snapshotBytes))
return err
}
func lsNcduNode(_ string, node *data.Node) ([]byte, error) {
type NcduNode struct {
Name string `json:"name"`
Asize uint64 `json:"asize"`
Dsize uint64 `json:"dsize"`
Dev uint64 `json:"dev"`
Ino uint64 `json:"ino"`
NLink uint64 `json:"nlink"`
NotReg bool `json:"notreg"`
UID uint32 `json:"uid"`
GID uint32 `json:"gid"`
Mode uint16 `json:"mode"`
Mtime int64 `json:"mtime"`
}
const blockSize = 512
outNode := NcduNode{
Name: node.Name,
Asize: node.Size,
// round up to nearest full blocksize
Dsize: (node.Size + blockSize - 1) / blockSize * blockSize,
Dev: node.DeviceID,
Ino: node.Inode,
NLink: node.Links,
NotReg: node.Type != data.NodeTypeDir && node.Type != data.NodeTypeFile,
UID: node.UID,
GID: node.GID,
Mode: uint16(node.Mode & os.ModePerm),
Mtime: node.ModTime.Unix(),
}
// bits according to inode(7) manpage
if node.Mode&os.ModeSetuid != 0 {
outNode.Mode |= 0o4000
}
if node.Mode&os.ModeSetgid != 0 {
outNode.Mode |= 0o2000
}
if node.Mode&os.ModeSticky != 0 {
outNode.Mode |= 0o1000
}
if outNode.Mtime < 0 {
// ncdu does not allow negative times
outNode.Mtime = 0
}
return json.Marshal(outNode)
}
func (p *ncduLsPrinter) Node(path string, node *data.Node, _ bool) error {
out, err := lsNcduNode(path, node)
if err != nil {
return err
}
if node.Type == data.NodeTypeDir {
_, err = fmt.Fprintf(p.out, ",\n%s[\n%s%s", strings.Repeat(" ", p.depth), strings.Repeat(" ", p.depth+1), string(out))
p.depth++
} else {
_, err = fmt.Fprintf(p.out, ",\n%s%s", strings.Repeat(" ", p.depth), string(out))
}
return err
}
func (p *ncduLsPrinter) LeaveDir(_ string) error {
p.depth--
_, err := fmt.Fprintf(p.out, "\n%s]", strings.Repeat(" ", p.depth))
return err
}
func (p *ncduLsPrinter) Close() error {
_, err := fmt.Fprint(p.out, "\n]\n]\n")
return err
}
type textLsPrinter struct {
dirs []string
ListLong bool
HumanReadable bool
termPrinter interface {
P(msg string, args ...interface{})
S(msg string, args ...interface{})
}
}
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 {
if !isPrefixDirectory {
p.termPrinter.S("%s", formatNode(path, node, p.ListLong, p.HumanReadable))
}
return nil
}
func (p *textLsPrinter) LeaveDir(_ string) error {
return nil
}
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)
if len(args) == 0 {
return errors.Fatal("no snapshot ID specified, specify snapshot ID or use special ID 'latest'")
}
if opts.Ncdu && gopts.JSON {
return errors.Fatal("only either '--json' or '--ncdu' can be specified")
}
if opts.Sort != SortModeName && opts.Ncdu {
return errors.Fatal("--sort and --ncdu are mutually exclusive")
}
if opts.Reverse && opts.Ncdu {
return errors.Fatal("--reverse and --ncdu are mutually exclusive")
}
// extract any specific directories to walk
var dirs []string
if len(args) > 1 {
dirs = args[1:]
for _, dir := range dirs {
if !strings.HasPrefix(dir, "/") {
return errors.Fatal("All path filters must be absolute, starting with a forward slash '/'")
}
}
}
withinDir := func(nodepath string) bool {
if len(dirs) == 0 {
return true
}
for _, dir := range dirs {
// we're within one of the selected dirs, example:
// nodepath: "/test/foo"
// dir: "/test"
if fs.HasPathPrefix(dir, nodepath) {
return true
}
}
return false
}
approachingMatchingTree := func(nodepath string) bool {
if len(dirs) == 0 {
return true
}
for _, dir := range dirs {
// the current node path is a prefix for one of the
// directories, so we're interested in something deeper in the
// tree. Example:
// nodepath: "/test"
// dir: "/test/foo"
if fs.HasPathPrefix(nodepath, dir) {
return true
}
}
return false
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, termPrinter)
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
if err = repo.LoadIndex(ctx, termPrinter); err != nil {
return err
}
var printer lsPrinter
if gopts.JSON {
printer = &jsonLsPrinter{
enc: json.NewEncoder(gopts.Term.OutputWriter()),
}
} else if opts.Ncdu {
printer = &ncduLsPrinter{
out: gopts.Term.OutputWriter(),
}
} else {
printer = &textLsPrinter{
dirs: dirs,
ListLong: opts.ListLong,
HumanReadable: opts.HumanReadable,
termPrinter: termPrinter,
}
}
if opts.Sort != SortModeName || opts.Reverse {
printer = &sortedPrinter{
printer: printer,
sortMode: opts.Sort,
reverse: opts.Reverse,
}
}
sn, subfolder, err := (&data.SnapshotFilter{
Hosts: opts.Hosts,
Paths: opts.Paths,
Tags: opts.Tags,
}).FindLatest(ctx, snapshotLister, repo, args[0])
if err != nil {
return err
}
sn.Tree, err = data.FindTreeDirectory(ctx, repo, sn.Tree, subfolder)
if err != nil {
return err
}
if err := printer.Snapshot(sn); err != nil {
return err
}
processNode := func(_ restic.ID, nodepath string, node *data.Node, err error) error {
if err != nil {
return err
}
if node == nil {
return nil
}
printedDir := false
if withinDir(nodepath) {
// if we're within a target path, print the node
if err := printer.Node(nodepath, node, false); err != nil {
return err
}
printedDir = true
// if recursive listing is requested, signal the walker that it
// should continue walking recursively
if opts.Recursive {
return nil
}
}
// if there's an upcoming match deeper in the tree (but we're not
// there yet), signal the walker to descend into any subdirs
if approachingMatchingTree(nodepath) {
// print node leading up to the target paths
if !printedDir {
return printer.Node(nodepath, node, true)
}
return nil
}
// otherwise, signal the walker to not walk recursively into any
// subdirs
if node.Type == data.NodeTypeDir {
// immediately generate leaveDir if the directory is skipped
if printedDir {
if err := printer.LeaveDir(nodepath); err != nil {
return err
}
}
return walker.ErrSkipNode
}
return nil
}
err = walker.Walk(ctx, repo, *sn.Tree, walker.WalkVisitor{
ProcessNode: processNode,
LeaveDir: func(path string) error {
// the root path `/` has no corresponding node and is thus also skipped by processNode
if path != "/" {
return printer.LeaveDir(path)
}
return nil
},
})
if err != nil {
return err
}
return printer.Close()
}
type sortedPrinter struct {
printer lsPrinter
collector []toSortOutput
sortMode SortMode
reverse bool
}
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 {
if !isPrefixDirectory {
p.collector = append(p.collector, toSortOutput{path, node})
}
return nil
}
func (p *sortedPrinter) LeaveDir(_ string) error {
return nil
}
func (p *sortedPrinter) Close() error {
var comparator func(a, b toSortOutput) int
switch p.sortMode {
case SortModeName:
case SortModeSize:
comparator = func(a, b toSortOutput) int {
return cmp.Or(
cmp.Compare(a.node.Size, b.node.Size),
cmp.Compare(a.nodepath, b.nodepath),
)
}
case SortModeMtime:
comparator = func(a, b toSortOutput) int {
return cmp.Or(
a.node.ModTime.Compare(b.node.ModTime),
cmp.Compare(a.nodepath, b.nodepath),
)
}
case SortModeAtime:
comparator = func(a, b toSortOutput) int {
return cmp.Or(
a.node.AccessTime.Compare(b.node.AccessTime),
cmp.Compare(a.nodepath, b.nodepath),
)
}
case SortModeCtime:
comparator = func(a, b toSortOutput) int {
return cmp.Or(
a.node.ChangeTime.Compare(b.node.ChangeTime),
cmp.Compare(a.nodepath, b.nodepath),
)
}
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
}
comparator = func(a, b toSortOutput) int {
return cmp.Or(
cmp.Compare(mapExt[a.nodepath], mapExt[b.nodepath]),
cmp.Compare(a.nodepath, b.nodepath),
)
}
}
if comparator != nil {
slices.SortStableFunc(p.collector, comparator)
}
if p.reverse {
slices.Reverse(p.collector)
}
for _, elem := range p.collector {
if err := p.printer.Node(elem.nodepath, elem.node, false); err != nil {
return err
}
}
return nil
}
// SortMode defines the allowed sorting modes
type SortMode uint
// Allowed sort modes
const (
SortModeName SortMode = iota
SortModeSize
SortModeAtime
SortModeCtime
SortModeMtime
SortModeExt
SortModeInvalid
)
// Set implements the method needed for pflag command flag parsing.
func (c *SortMode) Set(s string) error {
switch s {
case "name":
*c = SortModeName
case "size":
*c = SortModeSize
case "atime":
*c = SortModeAtime
case "ctime":
*c = SortModeCtime
case "mtime", "time":
*c = SortModeMtime
case "extension":
*c = SortModeExt
default:
*c = SortModeInvalid
return fmt.Errorf("invalid sort mode %q, must be one of (name|size|time=mtime|atime|ctime|extension)", s)
}
return nil
}
func (c *SortMode) String() string {
switch *c {
case SortModeName:
return "name"
case SortModeSize:
return "size"
case SortModeAtime:
return "atime"
case SortModeCtime:
return "ctime"
case SortModeMtime:
return "mtime"
case SortModeExt:
return "extension"
default:
return "invalid"
}
}
func (c *SortMode) Type() string {
return "mode"
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/flags_test.go | cmd/restic/flags_test.go | package main
import (
"io"
"testing"
"github.com/restic/restic/internal/global"
)
// TestFlags checks for double defined flags, the commands will panic on
// ParseFlags() when a shorthand flag is defined twice.
func TestFlags(t *testing.T) {
for _, cmd := range newRootCommand(&global.Options{}).Commands() {
t.Run(cmd.Name(), func(t *testing.T) {
cmd.Flags().SetOutput(io.Discard)
err := cmd.ParseFlags([]string{"--help"})
if err.Error() == "pflag: help requested" {
err = nil
}
if err != nil {
t.Fatal(err)
}
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_find.go | cmd/restic/cmd_find.go | package main
import (
"context"
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"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/ui"
"github.com/restic/restic/internal/walker"
)
func newFindCommand(globalOptions *global.Options) *cobra.Command {
var opts FindOptions
cmd := &cobra.Command{
Use: "find [flags] PATTERN...",
Short: "Find a file, a directory or restic IDs",
Long: `
The "find" command searches for files or directories in snapshots stored in the
repo.
It can also be used to search for restic blobs or trees for troubleshooting.
The default sort option for the snapshots is youngest to oldest. To sort the
output from oldest to youngest specify --reverse.`,
Example: `restic find config.json
restic find --json "*.yml" "*.json"
restic find --json --blob 420f620f b46ebe8a ddd38656
restic find --show-pack-id --blob 420f620f
restic find --tree 577c2bc9 f81f2e22 a62827a9
restic find --pack 025c1d06
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runFind(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// FindOptions bundles all options for the find command.
type FindOptions struct {
Oldest string
Newest string
Snapshots []string
BlobID, TreeID bool
PackID, ShowPackID bool
CaseInsensitive bool
ListLong bool
HumanReadable bool
Reverse bool
data.SnapshotFilter
}
func (opts *FindOptions) AddFlags(f *pflag.FlagSet) {
f.StringVarP(&opts.Oldest, "oldest", "O", "", "oldest modification date/time")
f.StringVarP(&opts.Newest, "newest", "N", "", "newest modification date/time")
f.StringArrayVarP(&opts.Snapshots, "snapshot", "s", nil, "snapshot `id` to search in (can be given multiple times)")
f.BoolVar(&opts.BlobID, "blob", false, "pattern is a blob-ID")
f.BoolVar(&opts.TreeID, "tree", false, "pattern is a tree-ID")
f.BoolVar(&opts.PackID, "pack", false, "pattern is a pack-ID")
f.BoolVar(&opts.ShowPackID, "show-pack-id", false, "display the pack-ID the blobs belong to (with --blob or --tree)")
f.BoolVarP(&opts.CaseInsensitive, "ignore-case", "i", false, "ignore case for pattern")
f.BoolVarP(&opts.Reverse, "reverse", "R", false, "reverse sort order oldest to newest")
f.BoolVarP(&opts.ListLong, "long", "l", false, "use a long listing format showing size and mode")
f.BoolVar(&opts.HumanReadable, "human-readable", false, "print sizes in human readable format")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
type findPattern struct {
oldest, newest time.Time
pattern []string
ignoreCase bool
}
var timeFormats = []string{
"2006-01-02",
"2006-01-02 15:04",
"2006-01-02 15:04:05",
"2006-01-02 15:04:05 -0700",
"2006-01-02 15:04:05 MST",
"02.01.2006",
"02.01.2006 15:04",
"02.01.2006 15:04:05",
"02.01.2006 15:04:05 -0700",
"02.01.2006 15:04:05 MST",
"Mon Jan 2 15:04:05 -0700 MST 2006",
}
func parseTime(str string) (time.Time, error) {
for _, fmt := range timeFormats {
if t, err := time.ParseInLocation(fmt, str, time.Local); err == nil {
return t, nil
}
}
return time.Time{}, errors.Fatalf("unable to parse time: %q", str)
}
type statefulOutput struct {
ListLong bool
HumanReadable bool
JSON bool
inuse bool
newsn *data.Snapshot
oldsn *data.Snapshot
hits int
printer interface {
S(string, ...interface{})
P(string, ...interface{})
E(string, ...interface{})
}
stdout io.Writer
}
func (s *statefulOutput) PrintPatternJSON(path string, node *data.Node) {
type findNode data.Node
b, err := json.Marshal(struct {
// Add these attributes
Path string `json:"path,omitempty"`
Permissions string `json:"permissions,omitempty"`
*findNode
// Make the following attributes disappear
Name byte `json:"name,omitempty"`
ExtendedAttributes byte `json:"extended_attributes,omitempty"`
GenericAttributes byte `json:"generic_attributes,omitempty"`
Device byte `json:"device,omitempty"`
Content byte `json:"content,omitempty"`
Subtree byte `json:"subtree,omitempty"`
}{
Path: path,
Permissions: node.Mode.String(),
findNode: (*findNode)(node),
})
if err != nil {
s.printer.E("Marshall failed: %v", err)
return
}
if !s.inuse {
_, _ = s.stdout.Write([]byte("["))
s.inuse = true
}
if s.newsn != s.oldsn {
if s.oldsn != nil {
_, _ = fmt.Fprintf(s.stdout, "],\"hits\":%d,\"snapshot\":%q},", s.hits, s.oldsn.ID())
}
_, _ = s.stdout.Write([]byte(`{"matches":[`))
s.oldsn = s.newsn
s.hits = 0
}
if s.hits > 0 {
_, _ = s.stdout.Write([]byte(","))
}
_, _ = s.stdout.Write(b)
s.hits++
}
func (s *statefulOutput) PrintPatternNormal(path string, node *data.Node) {
if s.newsn != s.oldsn {
if s.oldsn != nil {
s.printer.P("")
}
s.oldsn = s.newsn
s.printer.P("Found matching entries in snapshot %s from %s", s.oldsn.ID().Str(), s.oldsn.Time.Local().Format(global.TimeFormat))
}
s.printer.S(formatNode(path, node, s.ListLong, s.HumanReadable))
}
func (s *statefulOutput) PrintPattern(path string, node *data.Node) {
if s.JSON {
s.PrintPatternJSON(path, node)
} else {
s.PrintPatternNormal(path, node)
}
}
func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn *data.Snapshot) {
b, err := json.Marshal(struct {
// Add these attributes
ObjectType string `json:"object_type"`
ID string `json:"id"`
Path string `json:"path"`
ParentTree string `json:"parent_tree,omitempty"`
SnapshotID string `json:"snapshot"`
Time time.Time `json:"time,omitempty"`
}{
ObjectType: kind,
ID: id,
Path: nodepath,
SnapshotID: sn.ID().String(),
ParentTree: treeID,
Time: sn.Time,
})
if err != nil {
s.printer.E("Marshall failed: %v", err)
return
}
if !s.inuse {
_, _ = s.stdout.Write([]byte("["))
s.inuse = true
}
if s.hits > 0 {
_, _ = s.stdout.Write([]byte(","))
}
_, _ = s.stdout.Write(b)
s.hits++
}
func (s *statefulOutput) PrintObjectNormal(kind, id, nodepath, treeID string, sn *data.Snapshot) {
s.printer.S("Found %s %s", kind, id)
if kind == "blob" {
s.printer.S(" ... in file %s", nodepath)
s.printer.S(" (tree %s)", treeID)
} else {
s.printer.S(" ... path %s", nodepath)
}
s.printer.S(" ... in snapshot %s (%s)", sn.ID().Str(), sn.Time.Local().Format(global.TimeFormat))
}
func (s *statefulOutput) PrintObject(kind, id, nodepath, treeID string, sn *data.Snapshot) {
if s.JSON {
s.PrintObjectJSON(kind, id, nodepath, treeID, sn)
} else {
s.PrintObjectNormal(kind, id, nodepath, treeID, sn)
}
}
func (s *statefulOutput) Finish() {
if s.JSON {
// do some finishing up
if s.oldsn != nil {
_, _ = fmt.Fprintf(s.stdout, "],\"hits\":%d,\"snapshot\":%q}", s.hits, s.oldsn.ID())
}
if s.inuse {
_, _ = s.stdout.Write([]byte("]\n"))
} else {
_, _ = s.stdout.Write([]byte("[]\n"))
}
return
}
}
// Finder bundles information needed to find a file or directory.
type Finder struct {
repo restic.Repository
pat findPattern
out statefulOutput
blobIDs map[string]struct{}
treeIDs map[string]struct{}
itemsFound int
printer interface {
S(string, ...interface{})
P(string, ...interface{})
E(string, ...interface{})
}
}
func (f *Finder) findInSnapshot(ctx context.Context, sn *data.Snapshot) error {
debug.Log("searching in snapshot %s\n for entries within [%s %s]", sn.ID(), f.pat.oldest, f.pat.newest)
if sn.Tree == nil {
return errors.Errorf("snapshot %v has no tree", sn.ID().Str())
}
f.out.newsn = sn
return walker.Walk(ctx, f.repo, *sn.Tree, walker.WalkVisitor{ProcessNode: func(parentTreeID restic.ID, nodepath string, node *data.Node, err error) error {
if err != nil {
debug.Log("Error loading tree %v: %v", parentTreeID, err)
f.printer.S("Unable to load tree %s", parentTreeID)
f.printer.S(" ... which belongs to snapshot %s", sn.ID())
return walker.ErrSkipNode
}
if node == nil {
return nil
}
normalizedNodepath := nodepath
if f.pat.ignoreCase {
normalizedNodepath = strings.ToLower(nodepath)
}
var foundMatch bool
for _, pat := range f.pat.pattern {
found, err := filter.Match(pat, normalizedNodepath)
if err != nil {
return err
}
if found {
foundMatch = true
break
}
}
var errIfNoMatch error
if node.Type == data.NodeTypeDir {
var childMayMatch bool
for _, pat := range f.pat.pattern {
mayMatch, err := filter.ChildMatch(pat, normalizedNodepath)
if err != nil {
return err
}
if mayMatch {
childMayMatch = true
break
}
}
if !childMayMatch {
errIfNoMatch = walker.ErrSkipNode
}
}
if !foundMatch {
return errIfNoMatch
}
if !f.pat.oldest.IsZero() && node.ModTime.Before(f.pat.oldest) {
debug.Log(" ModTime is older than %s\n", f.pat.oldest)
return errIfNoMatch
}
if !f.pat.newest.IsZero() && node.ModTime.After(f.pat.newest) {
debug.Log(" ModTime is newer than %s\n", f.pat.newest)
return errIfNoMatch
}
debug.Log(" found match\n")
f.out.PrintPattern(nodepath, node)
return nil
}})
}
func (f *Finder) findTree(treeID restic.ID, nodepath string) error {
found := false
if _, ok := f.treeIDs[treeID.String()]; ok {
found = true
} else if _, ok := f.treeIDs[treeID.Str()]; ok {
found = true
}
if found {
f.out.PrintObject("tree", treeID.String(), nodepath, "", f.out.newsn)
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 {
// Return an error to terminate the Walk
return errors.New("OK")
}
}
return nil
}
func (f *Finder) findIDs(ctx context.Context, sn *data.Snapshot) error {
debug.Log("searching IDs in snapshot %s", sn.ID())
if sn.Tree == nil {
return errors.Errorf("snapshot %v has no tree", sn.ID().Str())
}
f.out.newsn = sn
return walker.Walk(ctx, f.repo, *sn.Tree, walker.WalkVisitor{ProcessNode: func(parentTreeID restic.ID, nodepath string, node *data.Node, err error) error {
if err != nil {
debug.Log("Error loading tree %v: %v", parentTreeID, err)
f.printer.S("Unable to load tree %s", parentTreeID)
f.printer.S(" ... which belongs to snapshot %s", sn.ID())
return walker.ErrSkipNode
}
if node == nil {
if nodepath == "/" {
if err := f.findTree(parentTreeID, "/"); err != nil {
return err
}
}
return nil
}
if node.Type == "dir" && f.treeIDs != nil {
if err := f.findTree(*node.Subtree, nodepath); err != nil {
return err
}
}
if node.Type == data.NodeTypeFile && f.blobIDs != nil {
for _, id := range node.Content {
if ctx.Err() != nil {
return ctx.Err()
}
idStr := id.String()
if _, ok := f.blobIDs[idStr]; !ok {
// Look for short ID form
if _, ok := f.blobIDs[id.Str()]; !ok {
continue
}
// Replace the short ID with the long one
f.blobIDs[idStr] = struct{}{}
delete(f.blobIDs, id.Str())
}
f.out.PrintObject("blob", idStr, nodepath, parentTreeID.String(), sn)
}
}
return nil
}})
}
var errAllPacksFound = errors.New("all packs found")
// 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 {
packIDs := make(map[string]struct{})
for _, p := range packs {
packIDs[p] = struct{}{}
}
if f.blobIDs == nil {
f.blobIDs = make(map[string]struct{})
}
debug.Log("Looking for packs...")
err := f.repo.List(ctx, restic.PackFile, func(id restic.ID, size int64) error {
idStr := id.String()
if _, ok := packIDs[idStr]; !ok {
// Look for short ID form
if _, ok := packIDs[id.Str()]; !ok {
return nil
}
delete(packIDs, id.Str())
} else {
// forget found id
delete(packIDs, idStr)
}
debug.Log("Found pack %s", idStr)
blobs, _, err := f.repo.ListPack(ctx, id, size)
if err != nil {
return err
}
for _, b := range blobs {
f.blobIDs[b.ID.String()] = struct{}{}
}
// Stop searching when all packs have been found
if len(packIDs) == 0 {
return errAllPacksFound
}
return nil
})
if err != nil && err != errAllPacksFound {
return err
}
if err != errAllPacksFound {
// try to resolve unknown pack ids from the index
packIDs, err = f.indexPacksToBlobs(ctx, packIDs)
if err != nil {
return err
}
}
if len(packIDs) > 0 {
list := make([]string, 0, len(packIDs))
for h := range packIDs {
list = append(list, h)
}
sort.Strings(list)
return errors.Fatalf("unable to find pack(s): %v", list)
}
debug.Log("%d blobs found", len(f.blobIDs))
return nil
}
func (f *Finder) indexPacksToBlobs(ctx context.Context, packIDs map[string]struct{}) (map[string]struct{}, error) {
wctx, cancel := context.WithCancel(ctx)
defer cancel()
// 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()
// 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 {
// expand id
delete(packIDs, pb.PackID.Str())
packIDs[idStr] = struct{}{}
matchingID = true
}
}
if matchingID {
f.blobIDs[pb.ID.String()] = struct{}{}
indexPackIDs[idStr] = struct{}{}
}
})
if err != nil {
return nil, err
}
for id := range indexPackIDs {
delete(packIDs, id)
}
if len(indexPackIDs) > 0 {
list := make([]string, 0, len(indexPackIDs))
for h := range indexPackIDs {
list = append(list, h)
}
f.printer.E("some pack files are missing from the repository, getting their blobs from the repository index: %v\n\n", list)
}
return packIDs, nil
}
func (f *Finder) findObjectPack(id string, t restic.BlobType) {
rid, err := restic.ParseID(id)
if err != nil {
f.printer.S("Note: cannot find pack for object '%s', unable to parse ID: %v", id, err)
return
}
blobs := f.repo.LookupBlob(t, rid)
if len(blobs) == 0 {
f.printer.S("Object %s not found in the index", 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())
break
}
}
}
func (f *Finder) findObjectsPacks() {
for i := range f.blobIDs {
f.findObjectPack(i, restic.DataBlob)
}
for i := range f.treeIDs {
f.findObjectPack(i, restic.TreeBlob)
}
}
func runFind(ctx context.Context, opts FindOptions, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) == 0 {
return errors.Fatal("wrong number of arguments")
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
var err error
pat := findPattern{pattern: args}
if opts.CaseInsensitive {
for i := range pat.pattern {
pat.pattern[i] = strings.ToLower(pat.pattern[i])
}
pat.ignoreCase = true
}
if opts.Oldest != "" {
if pat.oldest, err = parseTime(opts.Oldest); err != nil {
return err
}
}
if opts.Newest != "" {
if pat.newest, err = parseTime(opts.Newest); err != nil {
return err
}
}
// Check at most only one kind of IDs is provided: currently we
// can't mix types
if (opts.BlobID && opts.TreeID) ||
(opts.BlobID && opts.PackID) ||
(opts.TreeID && opts.PackID) {
return errors.Fatal("cannot have several ID types")
}
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
f := &Finder{
repo: repo,
pat: pat,
out: statefulOutput{ListLong: opts.ListLong, HumanReadable: opts.HumanReadable, JSON: gopts.JSON, printer: printer, stdout: term.OutputRaw()},
printer: printer,
}
if opts.BlobID {
f.blobIDs = make(map[string]struct{})
for _, pat := range f.pat.pattern {
f.blobIDs[pat] = struct{}{}
}
}
if opts.TreeID {
f.treeIDs = make(map[string]struct{})
for _, pat := range f.pat.pattern {
f.treeIDs[pat] = struct{}{}
}
}
if opts.PackID {
err := f.packsToBlobs(ctx, f.pat.pattern)
if err != nil {
return err
}
}
var filteredSnapshots []*data.Snapshot
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, opts.Snapshots, printer) {
filteredSnapshots = append(filteredSnapshots, sn)
}
if ctx.Err() != nil {
return ctx.Err()
}
sort.Slice(filteredSnapshots, func(i, j int) bool {
if opts.Reverse {
return filteredSnapshots[i].Time.Before(filteredSnapshots[j].Time)
}
return filteredSnapshots[i].Time.After(filteredSnapshots[j].Time)
})
for _, sn := range filteredSnapshots {
if f.blobIDs != nil || f.treeIDs != nil {
if err = f.findIDs(ctx, sn); err != nil && err.Error() != "OK" {
return err
}
continue
}
if err = f.findInSnapshot(ctx, sn); err != nil {
return err
}
}
f.out.Finish()
if opts.ShowPackID && (f.blobIDs != nil || f.treeIDs != nil) {
f.findObjectsPacks()
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_init.go | cmd/restic/cmd_init.go | package main
import (
"context"
"encoding/json"
"strconv"
"github.com/restic/chunker"
"github.com/restic/restic/internal/backend/location"
"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"
)
func newInitCommand(globalOptions *global.Options) *cobra.Command {
var opts InitOptions
cmd := &cobra.Command{
Use: "init",
Short: "Initialize a new repository",
Long: `
The "init" command initializes a new repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runInit(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// InitOptions bundles all options for the init command.
type InitOptions struct {
global.SecondaryRepoOptions
CopyChunkerParameters bool
RepositoryVersion string
}
func (opts *InitOptions) AddFlags(f *pflag.FlagSet) {
opts.SecondaryRepoOptions.AddFlags(f, "secondary", "to copy chunker parameters from")
f.BoolVar(&opts.CopyChunkerParameters, "copy-chunker-params", false, "copy chunker parameters from the secondary repository (useful with the copy command)")
f.StringVar(&opts.RepositoryVersion, "repository-version", "stable", "repository format version to use, allowed values are a format version, 'latest' and 'stable'")
}
func runInit(ctx context.Context, opts InitOptions, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) > 0 {
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)
var version uint
switch opts.RepositoryVersion {
case "latest", "":
version = restic.MaxRepoVersion
case "stable":
version = restic.StableRepoVersion
default:
v, err := strconv.ParseUint(opts.RepositoryVersion, 10, 32)
if err != nil {
return errors.Fatal("invalid repository version")
}
version = uint(v)
}
chunkerPolynomial, err := maybeReadChunkerPolynomial(ctx, opts, gopts, printer)
if err != nil {
return err
}
s, err := global.CreateRepository(ctx, gopts, version, chunkerPolynomial, printer)
if err != nil {
return errors.Fatalf("%s", err)
}
if !gopts.JSON {
printer.P("created restic repository %v at %s", s.Config().ID[:10], location.StripPassword(gopts.Backends, gopts.Repo))
if opts.CopyChunkerParameters && chunkerPolynomial != nil {
printer.P(" with chunker parameters copied from secondary repository")
}
printer.P("")
printer.P("Please note that knowledge of your password is required to access")
printer.P("the repository. Losing your password means that your data is")
printer.P("irrecoverably lost.")
} else {
status := initSuccess{
MessageType: "initialized",
ID: s.Config().ID,
Repository: location.StripPassword(gopts.Backends, gopts.Repo),
}
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(status)
}
return nil
}
func maybeReadChunkerPolynomial(ctx context.Context, opts InitOptions, gopts global.Options, printer progress.Printer) (*chunker.Pol, error) {
if opts.CopyChunkerParameters {
otherGopts, _, err := opts.SecondaryRepoOptions.FillGlobalOpts(ctx, gopts, "secondary")
if err != nil {
return nil, err
}
otherRepo, err := global.OpenRepository(ctx, otherGopts, printer)
if err != nil {
return nil, err
}
pol := otherRepo.Config().ChunkerPolynomial
return &pol, nil
}
if opts.Repo != "" || opts.RepositoryFile != "" || opts.LegacyRepo != "" || opts.LegacyRepositoryFile != "" {
return nil, errors.Fatal("Secondary repository must only be specified when copying the chunker parameters")
}
return nil, nil
}
type initSuccess struct {
MessageType string `json:"message_type"` // "initialized"
ID string `json:"id"`
Repository string `json:"repository"`
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_key_list.go | cmd/restic/cmd_key_list.go | package main
import (
"context"
"encoding/json"
"fmt"
"sync"
"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/restic/restic/internal/ui/table"
"github.com/spf13/cobra"
)
func newKeyListCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List keys (passwords)",
Long: `
The "list" sub-command lists all the keys (passwords) associated with the repository.
Returns the key ID, username, hostname, created time and if it's the current key being
used to access the repository.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
return runKeyList(cmd.Context(), *globalOptions, args, globalOptions.Term)
},
}
return cmd
}
func runKeyList(ctx context.Context, gopts global.Options, args []string, term ui.Terminal) error {
if len(args) > 0 {
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)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
return listKeys(ctx, repo, gopts, printer)
}
func listKeys(ctx context.Context, s *repository.Repository, gopts global.Options, printer progress.Printer) error {
type keyInfo struct {
Current bool `json:"current"`
ID string `json:"id"`
ShortID string `json:"-"`
UserName string `json:"userName"`
HostName string `json:"hostName"`
Created string `json:"created"`
}
var m sync.Mutex
var keys []keyInfo
err := restic.ParallelList(ctx, s, restic.KeyFile, s.Connections(), func(ctx context.Context, id restic.ID, _ int64) error {
k, err := repository.LoadKey(ctx, s, id)
if err != nil {
printer.E("LoadKey() failed: %v", err)
return nil
}
key := keyInfo{
Current: id == s.KeyID(),
ID: id.String(),
ShortID: id.Str(),
UserName: k.Username,
HostName: k.Hostname,
Created: k.Created.Local().Format(global.TimeFormat),
}
m.Lock()
defer m.Unlock()
keys = append(keys, key)
return nil
})
if err != nil {
return err
}
if gopts.JSON {
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(keys)
}
tab := table.New()
tab.AddColumn(" ID", "{{if .Current}}*{{else}} {{end}}{{ .ShortID }}")
tab.AddColumn("User", "{{ .UserName }}")
tab.AddColumn("Host", "{{ .HostName }}")
tab.AddColumn("Created", "{{ .Created }}")
for _, key := range keys {
tab.AddRow(key)
}
return tab.Write(gopts.Term.OutputWriter())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_unlock.go | cmd/restic/cmd_unlock.go | package main
import (
"context"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newUnlockCommand(globalOptions *global.Options) *cobra.Command {
var opts UnlockOptions
cmd := &cobra.Command{
Use: "unlock",
Short: "Remove locks other processes created",
Long: `
The "unlock" command removes stale locks that have been created by other restic processes.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
return runUnlock(cmd.Context(), opts, *globalOptions, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
return cmd
}
// UnlockOptions collects all options for the unlock command.
type UnlockOptions struct {
RemoveAll bool
}
func (opts *UnlockOptions) AddFlags(f *pflag.FlagSet) {
f.BoolVar(&opts.RemoveAll, "remove-all", false, "remove all locks, even non-stale ones")
}
func runUnlock(ctx context.Context, opts UnlockOptions, gopts global.Options, term ui.Terminal) error {
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
repo, err := global.OpenRepository(ctx, gopts, printer)
if err != nil {
return err
}
fn := repository.RemoveStaleLocks
if opts.RemoveAll {
fn = repository.RemoveAllLocks
}
processed, err := fn(ctx, repo)
if err != nil {
return err
}
if processed > 0 {
printer.P("successfully removed %d locks", processed)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cmd_stats.go | cmd/restic/cmd_stats.go | package main
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"path/filepath"
"strings"
"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"
"github.com/restic/restic/internal/ui/table"
"github.com/restic/restic/internal/walker"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func newStatsCommand(globalOptions *global.Options) *cobra.Command {
var opts StatsOptions
cmd := &cobra.Command{
Use: "stats [flags] [snapshot ID] [...]",
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
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
just a single snapshot, while others are useful across all snapshots,
depending on what you are trying to calculate.
The modes are:
* restore-size: (default) Counts the size of the restored files.
* files-by-contents: Counts total size of unique files, where a file is
considered unique if it has unique contents.
* raw-data: Counts the size of blobs in the repository, regardless of
how many files reference them.
* blobs-per-file: A combination of files-by-contents and raw-data.
Refer to the online manual for more details about each mode.
EXIT STATUS
===========
Exit status is 0 if the command was successful.
Exit status is 1 if there was any error.
Exit status is 10 if the repository does not exist.
Exit status is 11 if the repository is already locked.
Exit status is 12 if the password is incorrect.
`,
GroupID: cmdGroupDefault,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
finalizeSnapshotFilter(&opts.SnapshotFilter)
return runStats(cmd.Context(), opts, *globalOptions, args, globalOptions.Term)
},
}
opts.AddFlags(cmd.Flags())
must(cmd.RegisterFlagCompletionFunc("mode", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{countModeRestoreSize, countModeUniqueFilesByContents, countModeBlobsPerFile, countModeRawData}, cobra.ShellCompDirectiveDefault
}))
return cmd
}
// StatsOptions collects all options for the stats command.
type StatsOptions struct {
// the mode of counting to perform (see consts for available modes)
countMode string
data.SnapshotFilter
}
func (opts *StatsOptions) AddFlags(f *pflag.FlagSet) {
f.StringVar(&opts.countMode, "mode", countModeRestoreSize, "counting mode: restore-size (default), files-by-contents, blobs-per-file or raw-data")
initMultiSnapshotFilter(f, &opts.SnapshotFilter, true)
}
func must(err error) {
if err != nil {
panic(fmt.Sprintf("error during setup: %v", err))
}
}
func runStats(ctx context.Context, opts StatsOptions, gopts global.Options, args []string, term ui.Terminal) error {
err := verifyStatsInput(opts)
if err != nil {
return err
}
printer := ui.NewProgressPrinter(gopts.JSON, gopts.Verbosity, term)
ctx, repo, unlock, err := openWithReadLock(ctx, gopts, gopts.NoLock, printer)
if err != nil {
return err
}
defer unlock()
snapshotLister, err := restic.MemorizeList(ctx, repo, restic.SnapshotFile)
if err != nil {
return err
}
if err = repo.LoadIndex(ctx, printer); err != nil {
return err
}
if opts.countMode == countModeDebug {
return statsDebug(ctx, repo, printer)
}
if !gopts.JSON {
printer.S("scanning...")
}
// create a container for the stats (and other needed state)
stats := &statsContainer{
uniqueFiles: make(map[fileID]struct{}),
fileBlobs: make(map[string]restic.IDSet),
blobs: repo.NewAssociatedBlobSet(),
SnapshotsCount: 0,
}
for sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, &opts.SnapshotFilter, args, printer) {
err = statsWalkSnapshot(ctx, sn, repo, opts, stats)
if err != nil {
return fmt.Errorf("error walking snapshot: %v", err)
}
}
if ctx.Err() != nil {
return ctx.Err()
}
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)
if len(pbs) == 0 {
return fmt.Errorf("blob %v not found", blobHandle)
}
stats.TotalSize += uint64(pbs[0].Length)
if repo.Config().Version >= 2 {
stats.TotalUncompressedSize += uint64(crypto.CiphertextLength(int(pbs[0].DataLength())))
if pbs[0].IsCompressed() {
stats.TotalCompressedBlobsSize += uint64(pbs[0].Length)
stats.TotalCompressedBlobsUncompressedSize += uint64(crypto.CiphertextLength(int(pbs[0].DataLength())))
}
}
stats.TotalBlobCount++
}
if stats.TotalCompressedBlobsSize > 0 {
stats.CompressionRatio = float64(stats.TotalCompressedBlobsUncompressedSize) / float64(stats.TotalCompressedBlobsSize)
}
if stats.TotalUncompressedSize > 0 {
stats.CompressionProgress = float64(stats.TotalCompressedBlobsUncompressedSize) / float64(stats.TotalUncompressedSize) * 100
stats.CompressionSpaceSaving = (1 - float64(stats.TotalSize)/float64(stats.TotalUncompressedSize)) * 100
}
}
if gopts.JSON {
err = json.NewEncoder(gopts.Term.OutputWriter()).Encode(stats)
if err != nil {
return fmt.Errorf("encoding output: %v", err)
}
return nil
}
printer.S("Stats in %s mode:", opts.countMode)
printer.S(" Snapshots processed: %d", stats.SnapshotsCount)
if stats.TotalBlobCount > 0 {
printer.S(" Total Blob Count: %d", stats.TotalBlobCount)
}
if stats.TotalFileCount > 0 {
printer.S(" Total File Count: %d", stats.TotalFileCount)
}
if stats.TotalUncompressedSize > 0 {
printer.S(" Total Uncompressed Size: %-5s", ui.FormatBytes(stats.TotalUncompressedSize))
}
printer.S(" Total Size: %-5s", ui.FormatBytes(stats.TotalSize))
if stats.CompressionProgress > 0 {
printer.S(" Compression Progress: %.2f%%", stats.CompressionProgress)
}
if stats.CompressionRatio > 0 {
printer.S(" Compression Ratio: %.2fx", stats.CompressionRatio)
}
if stats.CompressionSpaceSaving > 0 {
printer.S("Compression Space Saving: %.2f%%", stats.CompressionSpaceSaving)
}
return nil
}
func statsWalkSnapshot(ctx context.Context, snapshot *data.Snapshot, repo restic.Loader, opts StatsOptions, stats *statsContainer) error {
if snapshot.Tree == nil {
return fmt.Errorf("snapshot %s has nil tree", snapshot.ID().Str())
}
stats.SnapshotsCount++
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)
}
hardLinkIndex := restorer.NewHardlinkIndex[struct{}]()
err := walker.Walk(ctx, repo, *snapshot.Tree, walker.WalkVisitor{
ProcessNode: statsWalkTree(repo, opts, stats, hardLinkIndex),
})
if err != nil {
return fmt.Errorf("walking tree %s: %v", *snapshot.Tree, err)
}
return nil
}
func statsWalkTree(repo restic.Loader, opts StatsOptions, stats *statsContainer, hardLinkIndex *restorer.HardlinkIndex[struct{}]) walker.WalkFunc {
return func(parentTreeID restic.ID, npath string, node *data.Node, nodeErr error) error {
if nodeErr != nil {
return nodeErr
}
if node == nil {
return nil
}
if opts.countMode == countModeUniqueFilesByContents || opts.countMode == countModeBlobsPerFile {
// only count this file if we haven't visited it before
fid := makeFileIDByContents(node)
if _, ok := stats.uniqueFiles[fid]; !ok {
// mark the file as visited
stats.uniqueFiles[fid] = struct{}{}
if opts.countMode == countModeUniqueFilesByContents {
// simply count the size of each unique file (unique by contents only)
stats.TotalSize += node.Size
stats.TotalFileCount++
}
if opts.countMode == countModeBlobsPerFile {
// count the size of each unique blob reference, which is
// by unique file (unique by contents and file path)
for _, blobID := range node.Content {
// 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)
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)
if !found {
return fmt.Errorf("blob %s not found for tree %s", blobID, parentTreeID)
}
// count the blob's size, then add this blob by this
// file (path) so we don't double-count it
stats.TotalSize += uint64(blobSize)
stats.fileBlobs[nodePath].Insert(blobID)
// this mode also counts total unique blob _references_ per file
stats.TotalBlobCount++
}
}
}
}
}
if opts.countMode == countModeRestoreSize {
// as this is a file in the snapshot, we can simply count its
// size without worrying about uniqueness, since duplicate files
// will still be restored
stats.TotalFileCount++
if node.Links == 1 || node.Type == data.NodeTypeDir {
stats.TotalSize += node.Size
} else {
// if hardlinks are present only count each deviceID+inode once
if !hardLinkIndex.Has(node.Inode, node.DeviceID) || node.Inode == 0 {
hardLinkIndex.Add(node.Inode, node.DeviceID, struct{}{})
stats.TotalSize += node.Size
}
}
}
return nil
}
}
// makeFileIDByContents returns a hash of the blob IDs of the
// node's Content in sequence.
func makeFileIDByContents(node *data.Node) fileID {
var bb []byte
for _, c := range node.Content {
bb = append(bb, c[:]...)
}
return sha256.Sum256(bb)
}
func verifyStatsInput(opts StatsOptions) error {
// require a recognized counting mode
switch opts.countMode {
case countModeRestoreSize:
case countModeUniqueFilesByContents:
case countModeBlobsPerFile:
case countModeRawData:
case countModeDebug:
default:
return fmt.Errorf("unknown counting mode: %s (use the -h flag to get a list of supported modes)", opts.countMode)
}
return nil
}
// statsContainer holds information during a walk of a repository
// to collect information about it, as well as state needed
// for a successful and efficient walk.
type statsContainer struct {
TotalSize uint64 `json:"total_size"`
TotalUncompressedSize uint64 `json:"total_uncompressed_size,omitempty"`
TotalCompressedBlobsSize uint64 `json:"-"`
TotalCompressedBlobsUncompressedSize uint64 `json:"-"`
CompressionRatio float64 `json:"compression_ratio,omitempty"`
CompressionProgress float64 `json:"compression_progress,omitempty"`
CompressionSpaceSaving float64 `json:"compression_space_saving,omitempty"`
TotalFileCount uint64 `json:"total_file_count,omitempty"`
TotalBlobCount uint64 `json:"total_blob_count,omitempty"`
// holds count of all considered snapshots
SnapshotsCount int `json:"snapshots_count"`
// uniqueFiles marks visited files according to their
// contents (hashed sequence of content blob IDs)
uniqueFiles map[fileID]struct{}
// fileBlobs maps a file name (path) to the set of
// blobs that have been seen as a part of the file
fileBlobs map[string]restic.IDSet
// blobs is used to count individual unique blobs,
// independent of references to files
blobs restic.AssociatedBlobSet
}
// fileID is a 256-bit hash that distinguishes unique files.
type fileID [32]byte
const (
countModeRestoreSize = "restore-size"
countModeUniqueFilesByContents = "files-by-contents"
countModeBlobsPerFile = "blobs-per-file"
countModeRawData = "raw-data"
countModeDebug = "debug"
)
func statsDebug(ctx context.Context, repo restic.Repository, printer progress.Printer) error {
printer.E("Collecting size statistics\n\n")
for _, t := range []restic.FileType{restic.KeyFile, restic.LockFile, restic.IndexFile, restic.PackFile} {
hist, err := statsDebugFileType(ctx, repo, t)
if err != nil {
return err
}
printer.E("File Type: %v\n%v", t, hist)
}
hist, err := statsDebugBlobs(ctx, repo)
if err != nil {
return err
}
for _, t := range []restic.BlobType{restic.DataBlob, restic.TreeBlob} {
printer.E("Blob Type: %v\n%v\n\n", t, hist[t])
}
return nil
}
func statsDebugFileType(ctx context.Context, repo restic.Lister, tpe restic.FileType) (*sizeHistogram, error) {
hist := newSizeHistogram(2 * repository.MaxPackSize)
err := repo.List(ctx, tpe, func(_ restic.ID, size int64) error {
hist.Add(uint64(size))
return nil
})
return hist, err
}
func statsDebugBlobs(ctx context.Context, repo restic.Repository) ([restic.NumBlobTypes]*sizeHistogram, error) {
var hist [restic.NumBlobTypes]*sizeHistogram
for i := 0; i < len(hist); i++ {
hist[i] = newSizeHistogram(2 * chunker.MaxSize)
}
err := repo.ListBlobs(ctx, func(pb restic.PackedBlob) {
hist[pb.Type].Add(uint64(pb.Length))
})
return hist, err
}
type sizeClass struct {
lower, upper uint64
count int64
}
type sizeHistogram struct {
count int64
totalSize uint64
buckets []sizeClass
oversized []uint64
}
func newSizeHistogram(sizeLimit uint64) *sizeHistogram {
h := &sizeHistogram{}
h.buckets = append(h.buckets, sizeClass{0, 0, 0})
lowerBound := uint64(1)
growthFactor := uint64(10)
for lowerBound < sizeLimit {
upperBound := lowerBound*growthFactor - 1
if upperBound > sizeLimit {
upperBound = sizeLimit
}
h.buckets = append(h.buckets, sizeClass{lowerBound, upperBound, 0})
lowerBound *= growthFactor
}
return h
}
func (s *sizeHistogram) Add(size uint64) {
s.count++
s.totalSize += size
for i, bucket := range s.buckets {
if size >= bucket.lower && size <= bucket.upper {
s.buckets[i].count++
return
}
}
s.oversized = append(s.oversized, size)
}
func (s sizeHistogram) String() string {
var out strings.Builder
out.WriteString(fmt.Sprintf("Count: %d\n", s.count))
out.WriteString(fmt.Sprintf("Total Size: %s\n", ui.FormatBytes(s.totalSize)))
t := table.New()
t.AddColumn("Size", "{{.SizeRange}}")
t.AddColumn("Count", "{{.Count}}")
type line struct {
SizeRange string
Count int64
}
// only print up to the highest used bucket size
lastFilledIdx := 0
for i := 0; i < len(s.buckets); i++ {
if s.buckets[i].count != 0 {
lastFilledIdx = i
}
}
var lines []line
hasStarted := false
for i, b := range s.buckets {
if i > lastFilledIdx {
break
}
if b.count > 0 {
hasStarted = true
}
if hasStarted {
lines = append(lines, line{
SizeRange: fmt.Sprintf("%d - %d Byte", b.lower, b.upper),
Count: b.count,
})
}
}
longestRange := 0
for _, l := range lines {
if longestRange < len(l.SizeRange) {
longestRange = len(l.SizeRange)
}
}
for i := range lines {
lines[i].SizeRange = strings.Repeat(" ", longestRange-len(lines[i].SizeRange)) + lines[i].SizeRange
t.AddRow(lines[i])
}
_ = t.Write(&out)
if len(s.oversized) > 0 {
out.WriteString(fmt.Sprintf("Oversized: %v\n", s.oversized))
}
return out.String()
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/main.go | cmd/restic/main.go | package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"os"
"runtime"
godebug "runtime/debug"
"github.com/spf13/cobra"
"go.uber.org/automaxprocs/maxprocs"
"github.com/restic/restic/internal/backend/all"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"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"
)
func init() {
// don't import `go.uber.org/automaxprocs` to disable the log output
_, _ = maxprocs.Set()
}
var ErrOK = errors.New("ok")
var cmdGroupDefault = "default"
var cmdGroupAdvanced = "advanced"
func newRootCommand(globalOptions *global.Options) *cobra.Command {
cmd := &cobra.Command{
Use: "restic",
Short: "Backup and restore files",
Long: `
restic is a backup program which allows saving multiple revisions of files and
directories in an encrypted repository stored on different backends.
The full documentation can be found at https://restic.readthedocs.io/ .
`,
SilenceErrors: true,
SilenceUsage: true,
DisableAutoGenTag: true,
PersistentPreRunE: func(c *cobra.Command, _ []string) error {
return globalOptions.PreRun(needsPassword(c.Name()))
},
}
cmd.AddGroup(
&cobra.Group{
ID: cmdGroupDefault,
Title: "Available Commands:",
},
&cobra.Group{
ID: cmdGroupAdvanced,
Title: "Advanced Options:",
},
)
globalOptions.AddFlags(cmd.PersistentFlags())
// Use our "generate" command instead of the cobra provided "completion" command
cmd.CompletionOptions.DisableDefaultCmd = true
// globalOptions is passed to commands by reference to allow PersistentPreRunE to modify it
cmd.AddCommand(
newBackupCommand(globalOptions),
newCacheCommand(globalOptions),
newCatCommand(globalOptions),
newCheckCommand(globalOptions),
newCopyCommand(globalOptions),
newDiffCommand(globalOptions),
newDumpCommand(globalOptions),
newFeaturesCommand(globalOptions),
newFindCommand(globalOptions),
newForgetCommand(globalOptions),
newGenerateCommand(globalOptions),
newInitCommand(globalOptions),
newKeyCommand(globalOptions),
newListCommand(globalOptions),
newLsCommand(globalOptions),
newMigrateCommand(globalOptions),
newOptionsCommand(globalOptions),
newPruneCommand(globalOptions),
newRebuildIndexCommand(globalOptions),
newRecoverCommand(globalOptions),
newRepairCommand(globalOptions),
newRestoreCommand(globalOptions),
newRewriteCommand(globalOptions),
newSnapshotsCommand(globalOptions),
newStatsCommand(globalOptions),
newTagCommand(globalOptions),
newUnlockCommand(globalOptions),
newVersionCommand(globalOptions),
)
registerDebugCommand(cmd, globalOptions)
registerMountCommand(cmd, globalOptions)
registerSelfUpdateCommand(cmd, globalOptions)
global.RegisterProfiling(cmd, os.Stderr)
return cmd
}
// Distinguish commands that need the password from those that work without,
// so we don't run $RESTIC_PASSWORD_COMMAND for no reason (it might prompt the
// user for authentication).
func needsPassword(cmd string) bool {
switch cmd {
case "cache", "generate", "help", "options", "self-update", "version", "__complete":
return false
default:
return true
}
}
func tweakGoGC() {
// lower GOGC from 100 to 50, unless it was manually overwritten by the user
oldValue := godebug.SetGCPercent(50)
if oldValue != 100 {
godebug.SetGCPercent(oldValue)
}
}
func printExitError(globalOptions global.Options, code int, message string) {
if globalOptions.JSON {
type jsonExitError struct {
MessageType string `json:"message_type"` // exit_error
Code int `json:"code"`
Message string `json:"message"`
}
jsonS := jsonExitError{
MessageType: "exit_error",
Code: code,
Message: message,
}
err := json.NewEncoder(os.Stderr).Encode(jsonS)
if err != nil {
// ignore error as there's no good way to handle it
_, _ = fmt.Fprintf(os.Stderr, "JSON encode failed: %v\n", err)
debug.Log("JSON encode failed: %v\n", err)
return
}
} else {
_, _ = fmt.Fprintf(os.Stderr, "%v\n", message)
}
}
func main() {
tweakGoGC()
// install custom global logger into a buffer, if an error occurs
// we can show the logs
logBuffer := bytes.NewBuffer(nil)
log.SetOutput(logBuffer)
err := feature.Flag.Apply(os.Getenv("RESTIC_FEATURES"), func(s string) {
_, _ = fmt.Fprintln(os.Stderr, s)
})
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
Exit(1)
}
debug.Log("main %#v", os.Args)
debug.Log("restic %s compiled with %v on %v/%v",
global.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
globalOptions := global.Options{
Backends: all.Backends(),
}
func() {
term, cancel := termstatus.Setup(os.Stdin, os.Stdout, os.Stderr, globalOptions.Quiet)
defer cancel()
globalOptions.Term = term
ctx := createGlobalContext(os.Stderr)
err = newRootCommand(&globalOptions).ExecuteContext(ctx)
switch err {
case nil:
err = ctx.Err()
case ErrOK:
// ErrOK overwrites context cancellation errors
err = nil
}
}()
var exitMessage string
switch {
case restic.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)
case errors.IsFatal(err):
exitMessage = err.Error()
case errors.Is(err, repository.ErrNoKeyFound):
exitMessage = fmt.Sprintf("Fatal: %v", err)
case err != nil:
exitMessage = fmt.Sprintf("%+v", err)
if logBuffer.Len() > 0 {
exitMessage += "also, the following messages were logged by a library:\n"
sc := bufio.NewScanner(logBuffer)
for sc.Scan() {
exitMessage += fmt.Sprintln(sc.Text())
}
}
}
var exitCode int
switch {
case err == nil:
exitCode = 0
case err == ErrInvalidSourceData:
exitCode = 3
case errors.Is(err, ErrFailedToRemoveOneOrMoreSnapshots):
exitCode = 3
case errors.Is(err, global.ErrNoRepository):
exitCode = 10
case restic.IsAlreadyLocked(err):
exitCode = 11
case errors.Is(err, repository.ErrNoKeyFound):
exitCode = 12
case errors.Is(err, context.Canceled):
exitCode = 130
default:
exitCode = 1
}
if exitCode != 0 {
printExitError(globalOptions, exitCode, exitMessage)
}
Exit(exitCode)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/helpers/prepare-release/main.go | helpers/prepare-release/main.go | package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/spf13/pflag"
)
var opts = struct {
Version string
IgnoreBranchName bool
IgnoreUncommittedChanges bool
IgnoreChangelogVersion bool
IgnoreChangelogReleaseDate bool
IgnoreChangelogCurrent bool
IgnoreDockerBuildGoVersion bool
OutputDir string
}{}
var versionRegex = regexp.MustCompile(`^\d+\.\d+\.\d+$`)
func init() {
pflag.BoolVar(&opts.IgnoreBranchName, "ignore-branch-name", false, "allow releasing from other branches than 'master'")
pflag.BoolVar(&opts.IgnoreUncommittedChanges, "ignore-uncommitted-changes", false, "allow uncommitted changes")
pflag.BoolVar(&opts.IgnoreChangelogVersion, "ignore-changelog-version", false, "ignore missing entry in CHANGELOG.md")
pflag.BoolVar(&opts.IgnoreChangelogReleaseDate, "ignore-changelog-release-date", false, "ignore missing subdir with date in changelog/")
pflag.BoolVar(&opts.IgnoreChangelogCurrent, "ignore-changelog-current", false, "ignore check if CHANGELOG.md is up to date")
pflag.BoolVar(&opts.IgnoreDockerBuildGoVersion, "ignore-docker-build-go-version", false, "ignore check if docker builder go version is up to date")
pflag.StringVar(&opts.OutputDir, "output-dir", "", "use `dir` as output directory")
pflag.Parse()
}
func die(f string, args ...interface{}) {
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
f = "\x1b[31m" + f + "\x1b[0m"
fmt.Fprintf(os.Stderr, f, args...)
os.Exit(1)
}
func msg(f string, args ...interface{}) {
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
f = "\x1b[32m" + f + "\x1b[0m"
fmt.Printf(f, args...)
}
func run(cmd string, args ...string) {
c := exec.Command(cmd, args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
err := c.Run()
if err != nil {
die("error running %s %s: %v", cmd, args, err)
}
}
func replace(filename, from, to string) {
reg := regexp.MustCompile(from)
buf, err := os.ReadFile(filename)
if err != nil {
die("error reading file %v: %v", filename, err)
}
buf = reg.ReplaceAll(buf, []byte(to))
err = os.WriteFile(filename, buf, 0644)
if err != nil {
die("error writing file %v: %v", filename, err)
}
}
func rm(file string) {
err := os.Remove(file)
if err != nil {
die("error removing %v: %v", file, err)
}
}
func rmdir(dir string) {
err := os.RemoveAll(dir)
if err != nil {
die("error removing %v: %v", dir, err)
}
}
func mkdir(dir string) {
err := os.Mkdir(dir, 0755)
if err != nil {
die("mkdir %v: %v", dir, err)
}
}
func getwd() string {
pwd, err := os.Getwd()
if err != nil {
die("Getwd(): %v", err)
}
return pwd
}
func uncommittedChanges(dirs ...string) string {
args := []string{"status", "--porcelain", "--untracked-files=no"}
if len(dirs) > 0 {
args = append(args, dirs...)
}
changes, err := exec.Command("git", args...).Output()
if err != nil {
die("unable to run command: %v", err)
}
return string(changes)
}
func getBranchName() string {
branch, err := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD").Output()
if err != nil {
die("error running 'git': %v", err)
}
return strings.TrimSpace(string(branch))
}
func preCheckBranchMaster() {
if opts.IgnoreBranchName {
return
}
branch := getBranchName()
if branch != "master" {
die("wrong branch: %s", branch)
}
}
func preCheckUncommittedChanges() {
if opts.IgnoreUncommittedChanges {
return
}
changes := uncommittedChanges()
if len(changes) > 0 {
die("uncommitted changes found:\n%s\n", changes)
}
}
func preCheckVersionExists() {
buf, err := exec.Command("git", "tag", "-l").Output()
if err != nil {
die("error running 'git tag -l': %v", err)
}
sc := bufio.NewScanner(bytes.NewReader(buf))
for sc.Scan() {
if sc.Err() != nil {
die("error scanning version tags: %v", sc.Err())
}
if strings.TrimSpace(sc.Text()) == "v"+opts.Version {
die("tag v%v already exists", opts.Version)
}
}
}
func preCheckChangelogCurrent() {
if opts.IgnoreChangelogCurrent {
return
}
// regenerate changelog
run("calens", "--output", "CHANGELOG.md")
// check for uncommitted changes in changelog
if len(uncommittedChanges("CHANGELOG.md")) > 0 {
msg("committing file CHANGELOG.md")
run("git", "commit", "-m", fmt.Sprintf("Generate CHANGELOG.md for %v", opts.Version), "CHANGELOG.md")
}
}
func preCheckChangelogRelease() bool {
if opts.IgnoreChangelogReleaseDate {
return true
}
for _, name := range readdir("changelog") {
if strings.HasPrefix(name, opts.Version+"_") {
return true
}
}
return false
}
func createChangelogRelease() {
date := time.Now().Format("2006-01-02")
targetDir := filepath.Join("changelog", fmt.Sprintf("%s_%s", opts.Version, date))
unreleasedDir := filepath.Join("changelog", "unreleased")
mkdir(targetDir)
for _, name := range readdir(unreleasedDir) {
if name == ".gitignore" {
continue
}
src := filepath.Join("changelog", "unreleased", name)
dest := filepath.Join(targetDir, name)
err := os.Rename(src, dest)
if err != nil {
die("rename %v -> %v failed: %w", src, dest, err)
}
}
run("git", "add", targetDir)
run("git", "add", "-u", unreleasedDir)
msg := fmt.Sprintf("Prepare changelog for %v", opts.Version)
run("git", "commit", "-m", msg, targetDir, unreleasedDir)
}
func preCheckChangelogVersion() {
if opts.IgnoreChangelogVersion {
return
}
f, err := os.Open("CHANGELOG.md")
if err != nil {
die("unable to open CHANGELOG.md: %v", err)
}
defer func() {
_ = f.Close()
}()
sc := bufio.NewScanner(f)
for sc.Scan() {
if sc.Err() != nil {
die("error scanning: %v", sc.Err())
}
if strings.Contains(strings.TrimSpace(sc.Text()), fmt.Sprintf("Changelog for restic %v", opts.Version)) {
return
}
}
die("CHANGELOG.md does not contain version %v", opts.Version)
}
func preCheckDockerBuilderGoVersion() {
if opts.IgnoreDockerBuildGoVersion {
return
}
buf, err := exec.Command("go", "version").Output()
if err != nil {
die("unable to check local Go version: %v", err)
}
localVersion := strings.TrimSpace(string(buf))
msg("update docker container restic/builder")
run("docker", "pull", "restic/builder")
buf, err = exec.Command("docker", "run", "--rm", "restic/builder", "go", "version").Output()
if err != nil {
die("unable to check Go version in docker image: %v", err)
}
containerVersion := strings.TrimSpace(string(buf))
if localVersion != containerVersion {
die("version in docker container restic/builder is different:\n local: %v\n container: %v\n",
localVersion, containerVersion)
}
}
func generateFiles() {
msg("generate files")
run("go", "run", "build.go", "-o", "restic-generate.temp")
mandir := filepath.Join("doc", "man")
rmdir(mandir)
mkdir(mandir)
run("./restic-generate.temp", "generate",
"--man", "doc/man",
"--zsh-completion", "doc/zsh-completion.zsh",
"--powershell-completion", "doc/powershell-completion.ps1",
"--fish-completion", "doc/fish-completion.fish",
"--bash-completion", "doc/bash-completion.sh")
rm("restic-generate.temp")
run("git", "add", "doc")
changes := uncommittedChanges("doc")
if len(changes) > 0 {
msg("committing manpages and auto-completion")
run("git", "commit", "-m", "Update manpages and auto-completion", "doc")
}
}
var versionPattern = `const Version = ".*"`
const versionCodeFile = "internal/global/global.go"
func updateVersion() {
err := os.WriteFile("VERSION", []byte(opts.Version+"\n"), 0644)
if err != nil {
die("unable to write version to file: %v", err)
}
newVersion := fmt.Sprintf("const Version = %q", opts.Version)
replace(versionCodeFile, versionPattern, newVersion)
if len(uncommittedChanges("VERSION")) > 0 || len(uncommittedChanges(versionCodeFile)) > 0 {
msg("committing version files")
run("git", "commit", "-m", fmt.Sprintf("Add version for %v", opts.Version), "VERSION", versionCodeFile)
}
}
func updateVersionDev() {
err := os.WriteFile("VERSION", []byte(opts.Version+"-dev\n"), 0644)
if err != nil {
die("unable to write version to file: %v", err)
}
newVersion := fmt.Sprintf(`var version = "%s-dev (compiled manually)"`, opts.Version)
replace(versionCodeFile, versionPattern, newVersion)
msg("committing cmd/restic/global.go with dev version")
run("git", "commit", "-m", fmt.Sprintf("Set development version for %v", opts.Version), "VERSION", versionCodeFile)
}
func addTag() {
tagname := "v" + opts.Version
msg("add tag %v", tagname)
run("git", "tag", "-a", "-s", "-m", tagname, tagname)
}
func exportTar(version, tarFilename string) {
cmd := fmt.Sprintf("git archive --format=tar --prefix=restic-%s/ v%s | gzip -n > %s",
version, version, tarFilename)
run("sh", "-c", cmd)
msg("build restic-%s.tar.gz", version)
}
func extractTar(filename, outputDir string) {
msg("extract tar into %v", outputDir)
c := exec.Command("tar", "xz", "--strip-components=1", "-f", filename)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Dir = outputDir
err := c.Run()
if err != nil {
die("error extracting tar: %v", err)
}
}
func runBuild(sourceDir, outputDir, version string) {
msg("building binaries...")
run("docker", "run", "--rm",
"--volume", sourceDir+":/restic",
"--volume", outputDir+":/output",
"restic/builder",
"go", "run", "helpers/build-release-binaries/main.go",
"--version", version)
}
func readdir(dir string) []string {
fis, err := os.ReadDir(dir)
if err != nil {
die("readdir %v failed: %v", dir, err)
}
filenames := make([]string, 0, len(fis))
for _, fi := range fis {
filenames = append(filenames, fi.Name())
}
return filenames
}
func sha256sums(inputDir, outputFile string) {
msg("running sha256sum in %v", inputDir)
filenames := readdir(inputDir)
f, err := os.Create(outputFile)
if err != nil {
die("unable to create %v: %v", outputFile, err)
}
c := exec.Command("sha256sum", filenames...)
c.Stdout = f
c.Stderr = os.Stderr
c.Dir = inputDir
err = c.Run()
if err != nil {
die("error running sha256sums: %v", err)
}
err = f.Close()
if err != nil {
die("close %v: %v", outputFile, err)
}
}
func signFiles(filenames ...string) {
for _, filename := range filenames {
run("gpg", "--armor", "--detach-sign", filename)
}
}
func updateDocker(sourceDir, version string) string {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
builderName := fmt.Sprintf("restic-release-builder-%d", r.Int())
run("docker", "buildx", "create", "--name", builderName, "--driver", "docker-container", "--bootstrap")
buildCmd := fmt.Sprintf("docker buildx build --builder %s --platform linux/386,linux/amd64,linux/arm,linux/arm64 --pull -f docker/Dockerfile.release %q", builderName, sourceDir)
run("sh", "-c", buildCmd+" --no-cache")
publishCmds := ""
for _, tag := range []string{"restic/restic:latest", "restic/restic:" + version} {
publishCmds += buildCmd + fmt.Sprintf(" --tag %q --push\n", tag)
}
return publishCmds + "\ndocker buildx rm " + builderName
}
func tempdir(prefix string) string {
dir, err := os.MkdirTemp(getwd(), prefix)
if err != nil {
die("unable to create temp dir %q: %v", prefix, err)
}
return dir
}
func main() {
if len(pflag.Args()) == 0 {
die("USAGE: release-version [OPTIONS] VERSION")
}
opts.Version = pflag.Args()[0]
if !versionRegex.MatchString(opts.Version) {
die("invalid new version")
}
preCheckBranchMaster()
branch := getBranchName()
preCheckUncommittedChanges()
preCheckVersionExists()
preCheckDockerBuilderGoVersion()
if !preCheckChangelogRelease() {
createChangelogRelease()
}
preCheckChangelogCurrent()
preCheckChangelogVersion()
if opts.OutputDir == "" {
opts.OutputDir = tempdir("build-output-")
}
sourceDir := tempdir("source-")
msg("using output dir %v", opts.OutputDir)
msg("using source dir %v", sourceDir)
generateFiles()
updateVersion()
addTag()
updateVersionDev()
tarFilename := filepath.Join(opts.OutputDir, fmt.Sprintf("restic-%s.tar.gz", opts.Version))
exportTar(opts.Version, tarFilename)
extractTar(tarFilename, sourceDir)
runBuild(sourceDir, opts.OutputDir, opts.Version)
sha256sums(opts.OutputDir, filepath.Join(opts.OutputDir, "SHA256SUMS"))
signFiles(filepath.Join(opts.OutputDir, "SHA256SUMS"), tarFilename)
dockerCmds := updateDocker(sourceDir, opts.Version)
msg("done, output dir is %v", opts.OutputDir)
msg("now run:\n\ngit push --tags origin %s\n%s\n\nrm -rf %q", branch, dockerCmds, sourceDir)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/helpers/build-release-binaries/main.go | helpers/build-release-binaries/main.go | package main
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
)
var opts = struct {
Verbose bool
SourceDir string
OutputDir string
Tags string
PlatformSubset string
Platform string
SkipCompress bool
Version string
}{}
func init() {
pflag.BoolVarP(&opts.Verbose, "verbose", "v", false, "be verbose")
pflag.StringVarP(&opts.SourceDir, "source", "s", "/restic", "path to the source code `directory`")
pflag.StringVarP(&opts.OutputDir, "output", "o", "/output", "path to the output `directory`")
pflag.StringVar(&opts.Tags, "tags", "", "additional build `tags`")
pflag.StringVar(&opts.PlatformSubset, "platform-subset", "", "specify `n/t` to only build this subset")
pflag.StringVarP(&opts.Platform, "platform", "p", "", "specify `os/arch` to only build this specific platform")
pflag.BoolVar(&opts.SkipCompress, "skip-compress", false, "skip binary compression step")
pflag.StringVar(&opts.Version, "version", "", "use `x.y.z` as the version for output files")
pflag.Parse()
}
func die(f string, args ...interface{}) {
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
f = "\x1b[31m" + f + "\x1b[0m"
fmt.Fprintf(os.Stderr, f, args...)
os.Exit(1)
}
func msg(f string, args ...interface{}) {
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
f = "\x1b[32m" + f + "\x1b[0m"
fmt.Printf(f, args...)
}
func verbose(f string, args ...interface{}) {
if !opts.Verbose {
return
}
if !strings.HasSuffix(f, "\n") {
f += "\n"
}
f = "\x1b[32m" + f + "\x1b[0m"
fmt.Printf(f, args...)
}
func rm(file string) {
err := os.Remove(file)
if os.IsNotExist(err) {
err = nil
}
if err != nil {
die("error removing %v: %v", file, err)
}
}
func mkdir(dir string) {
err := os.MkdirAll(dir, 0755)
if err != nil {
die("mkdir %v: %v", dir, err)
}
}
func abs(dir string) string {
absDir, err := filepath.Abs(dir)
if err != nil {
die("unable to find absolute path for %v: %v", dir, err)
}
return absDir
}
func build(sourceDir, outputDir, goos, goarch string) (filename string) {
filename = fmt.Sprintf("%v_%v_%v", "restic", goos, goarch)
if opts.Version != "" {
filename = fmt.Sprintf("%v_%v_%v_%v", "restic", opts.Version, goos, goarch)
}
if goos == "windows" {
filename += ".exe"
}
outputFile := filepath.Join(outputDir, filename)
// disable_grpc_modules is necessary to reduce the binary size since cloud.google.com/go/storage v1.44.0
// see https://github.com/googleapis/google-cloud-go/issues/11448
tags := "selfupdate,disable_grpc_modules"
if opts.Tags != "" {
tags += "," + opts.Tags
}
c := exec.Command("go", "build",
"-o", outputFile,
"-ldflags", "-s -w",
"-tags", tags,
"./cmd/restic",
)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Dir = sourceDir
c.Env = append(os.Environ(),
"CGO_ENABLED=0",
"GOOS="+goos,
"GOARCH="+goarch,
)
if goarch == "arm" {
// the raspberry pi 1 only supports the ARMv6 instruction set
c.Env = append(c.Env, "GOARM=6")
}
verbose("run %v %v in %v", "go", c.Args, c.Dir)
err := c.Run()
if err != nil {
die("error building %v/%v: %v", goos, goarch, err)
}
return filename
}
func modTime(file string) time.Time {
fi, err := os.Lstat(file)
if err != nil {
die("unable to get modtime of %v: %v", file, err)
}
return fi.ModTime()
}
func touch(file string, t time.Time) {
err := os.Chtimes(file, t, t)
if err != nil {
die("unable to update timestamps for %v: %v", file, err)
}
}
func chmod(file string, mode os.FileMode) {
err := os.Chmod(file, mode)
if err != nil {
die("unable to chmod %v to %s: %v", file, mode, err)
}
}
func compress(goos, inputDir, filename string) (outputFile string) {
var c *exec.Cmd
switch goos {
case "windows":
outputFile = strings.TrimSuffix(filename, ".exe") + ".zip"
c = exec.Command("zip", "-q", "-X", outputFile, filename)
default:
outputFile = filename + ".bz2"
c = exec.Command("bzip2", filename)
}
rm(filepath.Join(inputDir, outputFile))
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Dir = inputDir
verbose("run %v %v in %v", "go", c.Args, c.Dir)
err := c.Run()
if err != nil {
die("error compressing: %v", err)
}
rm(filepath.Join(inputDir, filename))
return outputFile
}
func buildForTarget(sourceDir, outputDir, goos, goarch string) (filename string) {
mtime := modTime(filepath.Join(sourceDir, "VERSION"))
filename = build(sourceDir, outputDir, goos, goarch)
touch(filepath.Join(outputDir, filename), mtime)
chmod(filepath.Join(outputDir, filename), 0755)
if !opts.SkipCompress {
filename = compress(goos, outputDir, filename)
}
return filename
}
func buildTargets(sourceDir, outputDir string, targets map[string][]string) {
start := time.Now()
// the go compiler is already parallelized, thus reduce the concurrency a bit
workers := runtime.GOMAXPROCS(0) / 4
if workers < 1 {
workers = 1
}
msg("building with %d workers", workers)
type Job struct{ GOOS, GOARCH string }
var wg errgroup.Group
ch := make(chan Job)
for i := 0; i < workers; i++ {
wg.Go(func() error {
for job := range ch {
start := time.Now()
verbose("build %v/%v", job.GOOS, job.GOARCH)
buildForTarget(sourceDir, outputDir, job.GOOS, job.GOARCH)
msg("built %v/%v in %.3fs", job.GOOS, job.GOARCH, time.Since(start).Seconds())
}
return nil
})
}
wg.Go(func() error {
for goos, archs := range targets {
for _, goarch := range archs {
ch <- Job{goos, goarch}
}
}
close(ch)
return nil
})
_ = wg.Wait()
msg("build finished in %.3fs", time.Since(start).Seconds())
}
var defaultBuildTargets = map[string][]string{
"aix": {"ppc64"},
"darwin": {"amd64", "arm64"},
"dragonfly": {"amd64"},
"freebsd": {"386", "amd64", "arm"},
"linux": {"386", "amd64", "arm", "arm64", "ppc64le", "mips", "mipsle", "mips64", "mips64le", "riscv64", "s390x"},
"netbsd": {"386", "amd64"},
"openbsd": {"386", "amd64"},
"windows": {"386", "amd64"},
"solaris": {"amd64"},
}
func downloadModules(sourceDir string) {
c := exec.Command("go", "mod", "download")
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Dir = sourceDir
err := c.Run()
if err != nil {
die("error downloading modules: %v", err)
}
}
func selectSubset(subset string, target map[string][]string) (map[string][]string, error) {
t, n, _ := strings.Cut(subset, "/")
part, err := strconv.ParseInt(t, 10, 8)
if err != nil {
return nil, fmt.Errorf("failed to parse platform subset %q", subset)
}
total, err := strconv.ParseInt(n, 10, 8)
if err != nil {
return nil, fmt.Errorf("failed to parse platform subset %q", subset)
}
if total < 0 || part < 0 {
return nil, errors.New("platform subset out of range")
}
if part >= total {
return nil, errors.New("t must be in 0 <= t < n")
}
// flatten platform list
platforms := []string{}
for os, archs := range target {
for _, arch := range archs {
platforms = append(platforms, os+"/"+arch)
}
}
sort.Strings(platforms)
// select subset
lower := len(platforms) * int(part) / int(total)
upper := len(platforms) * int(part+1) / int(total)
platforms = platforms[lower:upper]
return buildPlatformList(platforms), nil
}
func buildPlatformList(platforms []string) map[string][]string {
fmt.Printf("Building for %v\n", platforms)
targets := make(map[string][]string)
for _, platform := range platforms {
os, arch, _ := strings.Cut(platform, "/")
targets[os] = append(targets[os], arch)
}
return targets
}
func main() {
if len(pflag.Args()) != 0 {
die("USAGE: build-release-binaries [OPTIONS]")
}
targets := defaultBuildTargets
if opts.PlatformSubset != "" {
var err error
targets, err = selectSubset(opts.PlatformSubset, targets)
if err != nil {
die("%s", err)
}
} else if opts.Platform != "" {
targets = buildPlatformList([]string{opts.Platform})
}
sourceDir := abs(opts.SourceDir)
outputDir := abs(opts.OutputDir)
mkdir(outputDir)
downloadModules(sourceDir)
buildTargets(sourceDir, outputDir, targets)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/verify.go | internal/selfupdate/verify.go | package selfupdate
import (
"bytes"
"fmt"
"golang.org/x/crypto/openpgp"
)
var key = []byte(`
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFRVIb8BEADUex/4rH/aeR3CN044zqFD45SKUh/8pC44Bw85iRSSE9xEZsLB
LUF6ZtT3HNXfxh7TRpTeHnXABnr8EtNwsmMjItDaSClf5jM0qKVfRIHBZ2N539oF
lHiCEsg+Q6kJEXHSbqder21goihfcjJBVKFX6ULgCbymOu03fzbhe/m5R57gDU2H
+gcgoI6a5ib11oq2pRdbC9NkEg7YXHbMlZ5s6fIAgklyDQqAlH8QNiRYcyC/4NrG
WXLwUTDssFn3hoJlAxZwj+dRZAit6Hgj2US05Ra/gJqZWzKyE2ywglO9sc2wD3sE
0Ti1tS9VJr7WNcZzVMXj1qBIlBkl4/E5tIiNEZ5BrAhmdSYbZvP2cb6RFn5clKh9
i+XpeBIGiuAUgXTcV/+OBHjLq+Aeastktk7zaZ9QQoRMHksG02hPI7Z7iIRrhhgD
xsM2XAkwZXp21lpZtkEGYc2qo5ddu+qdZ1tHf5HqJ4JHj2hoRdr4nL6cwA8TlCSc
9PIifkKWVhMSEnkF2PXi+FZqkPnt1sO27Xt5i3BuaWmWig6gB0qh+7sW4o371MpZ
8SPKZgoFA5kJlqkOoSwZyY4M7TRR+GbZuZARUS+BTLsAeJ5Gik9Lhe1saE5UGncf
wYmh+sOi4vRDyoSkPthnBvvlmHp7yo7MiNAUPWHiuv2FWU0rPwB05NOinQARAQAB
tChBbGV4YW5kZXIgTmV1bWFubiA8YWxleGFuZGVyQGJ1bXBlcm4uZGU+iQI6BBMB
CAAkAhsDBQsJCAcDBRUKCQgLBRYCAwEAAh4BAheABQJUVSmNAhkBAAoJEJGmhovT
96kHQUcQALfi9KohoE0JFkKfSXl5jbBJkTt38srMnZ6xKP45F0e/ir1duFVCSyhZ
+YS/n6aBMQl/qRWbzF+93RnGsTLvMi/8Oa72czlEPuYYfFPuJAatxvA/TFZHuI++
u6xAF4Oxlq0FAbEJfpw0uLSDuU9f9TlLYNP3hLudjFFd9sJGLLs+SCeomPRKFxRR
LL7/1EzdtmvvFhZZcuPsTamBb4oi+1usCO5RW1AQA5A4Qo4gHitBaSaBgolFZLN7
6UFBwBs/t0hDZPAAZa1T8EpjQrlmINFIeBYFdvjhMChGQc6NcfOOQofW5BDVn6Gs
BHYTvAgSK5G0eaB+bOAtv9LW9hDt05iEJaE5ojPT7ThicHoU65WL4yGAGCGcfNm+
EpuNGt1IgAFGGxX6wMZy59WqtMBZANjWQdrDbCPQa3pIID96iN0A1HZJg7eAl0y3
NM6nU7faAuW4QOoQRgxOTj0+fM6khaFmYCp5nuer3d5pkaH6SQG4ZDVOOSaak7Ql
T/EFSfz2B5FZN1OIdqw5/Aw7HugOehHund5QfgRuDLSqZKnuGrIo9OwJIirT/TDD
nsNWBTN3Pxf1h8Iut+R9Zt7LwsVjVN9+JPL8yEk4zzCxHEL4/2c6jANQdtbQCZiH
bU85JWe1NKFo/NNPpM2ysZMpKHe5RB3FLMare0IBs5BO06nyGpTmiEYEEBEIAAYF
AlRVKToACgkQFBE43aPkXWafmgCfcR+LfsAn6aZxjX46Km5tmWpDVrAAoJfHpfBG
5MEki2MOoKvEsWDZqhHSiQIcBBABCAAGBQJUZRF9AAoJEGo6ELMcEJUXrtIP/iJh
0i7VaQG2F+QqGW8Evqng33HeLzW9BvYxt3X1QNb4ylFIc51Hl33yh5ZkPmZk/I3m
BaDd23IE2rhzETxDGrAMnE6zeaQ+iTu6iySBxqHjtK0HwKObuBA4Sw803Hn31Owa
Z8a3TEUkyiHPh8NBuxbvXNuOrxsglATE4KCuUGjGdmNs1raG9mqSUXgZCh1q1kAI
NN6O9DFFS1RsAvNK0qmTZZMfHWZeu10O55MHsxTsfPY/v1Jphg+vHc2NItw0s23R
j6SJN5fgNSLhcKBdCRpw33YFy+EWA8lE2FRd5DStn2sNWvAOoWLrIHZo0UgrgFV2
gi4QpaN+b/T+QDiq7IcwLaMSWU3ODYIFN2C/TBKZRIC7LWQPG0cjFJd/kWDQWB+i
/MdYMOOuDo6ohh3vfkC7xNEo3lJArC3Zgf4SmO6OBMnIdYjdchDV8dn5lSbKq1A3
20FIUWIxdkfx4L88J3KOGMAmuZxmnWkKN6iEg+Pb/axuX0cHSx/j7vV01YY2Z6j6
98tKhP2XObH990Eqfr8zJcj0tCuKEHww7Pn8aH9BHvig5KeEAIbggW34jR9TUKXd
1ao5HX0pKSa/37OqlG4r+XUORCV7awNSuUHU8BR0emDCsgRdrQ4szRgJLOA8sP14
b9fz+xO3KKNrDXGYZLXFSVwGzrSC5zbh6QkC0qeYiQIcBBABCgAGBQJUamlAAAoJ
EFKZtJkEN6xByy4QAMQJ45eOJtVyGtCKtIr2mPZQ0VI60hfMB6PVFlb7DOpWIHoh
Nl6KWzZunENelXp+VNQcj6St5iZrdOiyiMOY/FdN0rhPAYWERchABd9WDS9ycBr8
n5kWmB36Wa2r/aTOlDYJ/botigS6To6bR6Gc9FEj4QuVnmqzMlawSz/O0HNS0Hej
DgUwgR3hCDAAp/Hw9PR1CRcHw2bo/B5+GEcl+w6iAkheGXuV2zSWXf6LRLRSEQ70
f6n4hs6vsuQQ35yd4UXy/t/q3l7/xeJ5TBWWiXviQK1tIOsUJ+/cCpWzms+IFvt+
UsTQBMMuKBFqjkl4oDgtv8vf1i2NZsNo/XbzPB4hua5HyBuhn0/ej9zMfmMvfqZG
6ZzaAGpZYRCVRcw3nc0yNnoW+g7pAJs1M3sL1BXpUGfROG/T3yFzL+sk62moG2tD
G2G7QsNVzOxRDi8bax5f3U7QW1i33o3qRbr9BfePyWtfVuWHisTw1rBdwwEAfYQs
YUSDMXcTB9LhUWAhJAtEeLz0GOaA+IlafVwqmIdLxTsUoNYfpgRi2Wic33oRI1UG
yENtzKUu1iaHvSCEd/obvrhpx353oI4Yq8Gkr8mWRptX9IGXa+qASZ9gMxJ1PoPA
dLG5/oECVC/ORaNAL3zY9SbmGWamcWgSAeIB3iJxQlyMYikLDzb390y+5AFXiQI3
BBMBCAAhBQJUVSG/AhsDBQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEJGmhovT
96kH8pAP/3PtPkxkYNaS+PXiHBDpDnUsBiwvZt3FsebexepAepzL8dP00oNyI7dP
F2XKm4e/PHJ0nnY+tD4KKRdBeiQOL5ZywHmxZX04P1/Z6uCbVpGCSovcWavBkP8A
k+/CjzJUA6Z/s17D6LIpDDntn6v0abRoTy3asexG277udP+iO+1q/mnxSiSZzNas
rh973gXSeqL3oV+oY6DCSPpOSJlbI85UMU5/WnCxPIVHvaDG8Fv5RF74d3+FVJKd
7TRnUsqZ4MLI++JNXwK0O8dCQ8NsB3NF2rDnND+zhzDlisvdiyGsQUNMnn1Czi4D
/MK2/2xkdoVzKNA0v3IHlnxMWhZVLaHqUiGYUGF6NsB+OgXEEJRGIpukYnd/+WkL
Qqfzyy6Y6uUDhkwz0G5aDGyNUg7+gfDMr5dy+HxtgEzkcoZJWuNBzO0Yp198QNNE
+QBxu9OkYw9A8wT58cHVuzFU0V+bTBrZtpbME8OWLy6+eDXn6CbVEu2Fc92ckQoz
EpRdZMdiWVtbQDY8L9qAiC+BOVqBgv5PoB8IVHrV1GmRZwxRdlplnzviWa5Qvke5
dcUy+DXmrCN+dWUql8fFt2g6EIncFYotwxz7r3+KdjCFKzG6zmMLHBCUz0exAxrH
4vXXB1LdEByddgjXcol+N73D4jUyYvs12ziecGitAU8z9nYK347XiQIcBBABAgAG
BQJWBrfPAAoJEB5F+Mqd4jsWKCoQAIgC4I+rQ1UivkF1sk0A6IUvWAP4yfNBM6UP
K5bxFLd/kjL9LiiWD74NVmQ8WAa1Y3cv/gVrmekcVhxXGf3bZcGKBnYmmpR0xWli
XxQJ9CGPwtoaN7ZDKPbOKFzOHX3DiCZ9ePrxwpgym5iu541X2aGH/cqh9bPS4vxv
Nez+5fwhSdDe6iJZ09/oiJuMkyir3SKx3SJRf3Yd2G2k2bPJae2NjiolKIJrgNMe
SSYahaMHF8i+UpUQMqXK4vAWPFML9DzwjJVbnJuJ8s9T/5wy3Lw33Fpe33a8bTon
bEk60+NwhlnRAho0J5At9LVpTUuA0+5LAT2kwAzk2dPzYJl9SVYOQWP8Zj4tEDGF
hQPfdnYMhQB2ECTrtLBLJbqnEbCgRA7VTlGnsb+PU+Ut1GLhglPFPRjfAhWRKBLe
9sDYn8icrhJqvEyc8YMjeBSMEuQUm65b0fjUUl9eBSdRxy2RkQiPTg+o8kLOOnt6
+ar3S+JXIcN4GpLfBt5cpBiU53TkuTJYHqIHqKyLgEfIIfNRrKTbK6sCfA5STKTf
JSmewY2vGM7D4njQ2Iz8a4SU/XFOWQP0zlehDe1jhLXqYBlYMyXoULkXLkMfmIZX
AHoVn7z1POa94NcKePpW2BFm4Q0OjrwY2/ufPF/RlB4qNiFsrVuWpL7eMzaMZ+JV
oZXxEPMRtChBbGV4YW5kZXIgTmV1bWFubiA8YWxleGFuZGVyQGRlYmlhbi5vcmc+
iQIfBDABCAAJBQJW9SIDAh0gAAoJEJGmhovT96kHrP0P/24pnzm7zUyMFjUuZbsc
JxNk31K/gSWQ6S5AMPeKB/ar5OMRMkmpZZmOX8c1Q1MxdGdRGPFzA++uWPiizc3Q
LQIrzI1Q2oarkjcb3FMOMpn4M5xZp/+dmuWSrgEEF3iPom/DjpE+U/DC6/YaeJJO
WLuiU799c8b9Qg+ZZcf5L1vUMT489kDL8FgwiThoAXQ4LgSylblguVNkSiyZAQ7g
0snYD93jdBvY2KSIQ1Y9mIZPZYcZacj+CVMMAQOAP6WmrOw6hREaYFo/0Z9tMC0Q
Fba2hwAISS/hrBPFCFalq9E0tqClryitXdJp0/k8QgU979pANJXmZCvmFhjcCIKg
9ok7+lykFmbo+UCmRRoYoLlaw4wNfuN3TIlDyWx7cfAVww+AwQD8E1k6jXJpqT5s
Y+NSbJ2bPRR+AQk3qkvU2dJqOIJxF02jp4a4QxypTAN+byCkJcnrl7XMcykAeCAf
XIA5xRoZu44WJhHmTIAMf5SLzk889MggQrGVKckOpvSaFDElqW54DY/erkwFiZKd
t0rOmvqY4/63Btw6x7Y63THp4xf5IvFf0REc/Eh5aC0gPilHPS9ZbuIh0tX4hrQY
J2SPQ5bU63XC+ucJrHde25dDEa9oQ/xny3Dd233j8ofdLuBKejXXjhD/Dv3nlAEZ
D9VQgaF4kQcpqkz+dsgzEA3IiQI3BBMBCAAhBQJUVSlqAhsDBQsJCAcDBRUKCQgL
BRYCAwEAAh4BAheAAAoJEJGmhovT96kH/JMQAIQLk13LPm2K7YvLrO0iq8MbM/YK
pUh97sms5ItVMZJm3tGmbc4bgOJ2zAfeRRoumMqIyv2KLuXNKdysoGIowKvukOEK
v3IFv1pIXYwQ7KrRa+Pn1kfpjgoOePN/gm5fbGZTgRe65a9XhkBPKB4emv3hrX2b
WFMxtkbzDyP03oshTO/tpBFMNV+XA/Zlz3fLzvICUzD1SHTzzTFACyFkiB68Yx4y
UXXAln7LCXzHsdiM/3EuloiDZtao5t1Ax0+GEbo7WL3bIoR8e1q4d/PgbKPQvASH
jw/s0S1gCwOnFeoShrn2ijp2/5XLVjx4hQ/CCv+RJxv1lNzmmZtBBMGHbl1U5rcE
Ys/Fpe1If1RyC83mimmMfGS5TTXOMWbqjNlRT9bLRM/+OLvS6FWuAuFogQkCc+pa
VKHSEQJiN2+2XbjfrrozubB6Icegp2RwKyi9BRre9V6NPfEm1C8d6hmloqsK5RHX
z62a25sH4mEufTxgYn7TCxx+wckBWOlDe3p2i1lJDv1SKQXN0ZANfmObdfUMYyhZ
/j/ariRx1uhSrgPzQoRBaDMa/klqGyWQ9Yh1nJdeKwPZo4zriZvK5LAgnWh2IRcG
iPtSdtdk5KaEAouUR8XNGEpL79+Awi3kjd5uEmnu+ZqDDM/hq3NgzbQ51PuwBeuH
pe+6S4onnc5Sh5yoiEYEEBEIAAYFAlRVKXwACgkQFBE43aPkXWYUtQCfW61UqGPh
e0atXSnkzEevKm6y99QAn1CZ4rCVg4u/Zp6nvKncdd3cs0/NiQIcBBABCAAGBQJU
ZRF9AAoJEGo6ELMcEJUXk0gP/RJg5pLpPNibz09kjwsOJAlpORyd6OBxE4tOn/bE
CT0mE6vBg0TdY+MO1IC0o5RkiAc9f5YizzYyLBVpfgwdrfCk+eD9mFKhn7szYI23
2AdXIO5ziC4pND+zdkSj37fxAcM4BIfeyHWKna/cmkM1tsmB1YYpxNpM56Y+ulAG
6YJBkU0hPoUjI7eNMsV/+V/IOSuP4Z/Lhw1fw4bKow0zVc20C+dbgrBz9uKGUrmT
jLMLoEiaxn7yrYug8kQeeKaEoczyQhivQrKFZsfRMkiGaRz7qeOWrw10MCPNa3LX
wswXpxM9FGLnflOwhUiYSgD1OdmBaEEntDPX75Dp0n8pdm5GNFCuD9RpJrGIiPm5
dsU8kRMeFbUQFNOkJE5Npxv7DrmTIjFd90U3kwcwEL0Y++W+q/lbrmxgOuYmc/c6
K8WVGjsOTpEuqFvmLmhIwxzH4QCtSUTb/O2bg7PIbAk2LVMbXi4H9Fxl8YCWb532
Tu2RQ73Odvmluhj+QTFnxglEd4xiOlttwIOwqQAgLBk/GSioFfgLaGla5iabGaWu
MB6zFiDp30IDHfIchUp/jaBvWJf33UaemryRrppVv1mgs6qvKxbGmYSOn7I8KBas
iyV2IXaUCHDdreFcCLJrl/Cso9qQcHroI127IQAB5upyN3TuS0RS/ZnAZc9yd0Jx
kFNHiQIcBBABCgAGBQJUammYAAoJEFKZtJkEN6xBoC8P/2ipNFdW6rMuISzGUcGs
CQVNcil/9mZ+iOqe+7DS356vJmENvof31r2/tTHUcJcRoh7ANkR0YuvZylD8MFXk
jrAj+X2ODSCsaugyjxWEg5XEYLnHipX7eFxzT39UJrgP/4wNu8tWDO6t/xhblHUi
chE1tvWZkUnWzhQrBKIiYGZnu0mxIEHR33PZauc4vFL2U0K8deKpo01jtbz9f8+n
grcTplCfCJ8H0SoR/8t4qyg2FNgcnJW7F/VVa3j6ctDBkB+NcPYjeRL8cybHV0VU
xbbG64D+WbqsspWDRj7799SELQ5emUnyok0j/e+3ffFkiKP0mpMX3RW2MfMxd1Bs
AoY3IqvIdlAjrtAY2tQ3sXAyPgmcp6kKRKixLTbBjGfrptNLO2nzADvHk3/4OnKl
tlYj406A7ZgeKDWku+yQ8VSPCeFh86KwiQBgoZOJiQSRWYGT2hy8xLb4im4W1cor
bfL+2+iVMu+EwQ6QFlyzaLgNPNWBXUWvK8vok55LNuHYKHxCJD3b53vBctmB08/U
piRMDT5JTolyfwc4zbFrgb4d5lvTP0bM2qIHoEde5GyDKaUZkHvbBKokkR7nMKhK
mfWs091mG5AP03NXdmt/mllv3bRPsbJJTP0m8BMliQjvPIhKk7ngbNHefzGCdv06
psDi8Q8apCdR2bLDaLp2HC4TiQIcBBABAgAGBQJWBrfPAAoJEB5F+Mqd4jsWMmYP
/0izNHAqY8HvpyM7SlWixvXI2tjWSlhiC8dLv77rDLTjW/XbKh8P+6abxaPBg9dF
xHGDBJli0U9J+Mp5AodB+b/xgA8ro/U5sGGvTVI02AE9ohPwR2W6xePOapmkyWxO
P4kfEP8bK2V/JnBdk8Rq6tce5onBWTrFQCcqs2OprlfPpbKZgQ6b/K7nNP9uv2ku
twhSxmw4NpKJmvGzf1HnWVQKaE4yqCoH9pJGyQmn+v8JBytkRIsAhlV/HKC8Toz5
x933qAHVMW/Xf7hYWu9a15rS8NSBMOEFmvKubxYbqEPYM5uXENDCa+oGSbx52crf
IoOfiWWSiDyV502kZ4WB0jOdwITCDp6D/Hq4HZMnoquZ9Kk7mRuOP3FGXtAmp3rY
9TGBcjH2hjA1xen0N59uaE+zNeU0wEhrSMbwUvsFt6Z/p8aS8TMZIayVbmGi/0Vf
UonjIx3OPsd08CfXTk9cY+R3RKoFaJBBa2ZK2XnXj7VgbdcYx7IV4G41cxOHCgCl
BAMyzKI+UHuN4H39sQixFJW7tF0QJrYaXamuzIyh99qy5b0NvWxCiStZOKglmq2P
61ryqzyPcbwEn+1OeXUXayZslU8M2SMRfA3qXaBUuH5fQgVzCm8DndwdGRbh0ceo
E4BtZkZ3hmWvpPgt177eLcg7plL176bnjV0llspg+ji5uQINBFRVIb8BEADo4td9
MrPJd0wt2Q0OPgdAOyxpwGgu2vh8TTL5sUsMpJEKRQdc5AyEI1/mrTINDVgTSjTd
VPQE8fb4w3GHAUg4iBPucyGLUpQd+pxYya/aqVurKjynVZPHpZzCylsdVv8WR1Bb
bVIbmPiJxmRi3irjNzsmCeUV1V8JPpMxWBdV14NTcRkeJA2JpRXp8ZHhO9WryZV9
uxxMiDS8NIlAI6Ljt1swrJQOv2sHk9Gbrgmpd1zTYjJzORXZHsQdQ6XAy/4yWwt8
Gl+eg5ZRSyAE80TEIH0FFJcQ/9YZK/j9bxN+wGiuW4goNdBl84NJ8aq1G0NXDjyH
9WWypWfgURUoNBVmSek2ibRxSriqdFH8Tt+98w1a8EdLJKbPb0A5sV6PqqKUP59a
1AZ1kA0tLjh89Wz6+qjg9YhiCN7SO6eikdPWT/0r3SHtiztgDjgcqTFDNoFZdmZc
jb6eD0nuoRRfWXVZ57aX8WwD37xljKt7e06W7gsq4fXyRYZvQpNHga+83YCkVbxu
pPgPjgq4F/JquIUVfOx3CMmLsvE5p2U0zLGzG1WYgW5AShDfo2LXtjOz4wmRFnfY
pFO+CreWiG3OElwae77JiHXSc7+8pCOE3Buh9SRI8ioJPhb4uxV3paFH9uDTQjpC
nVMI5uOHg0tmWZgTShB/tzDV1KFVTZCw3fABxwARAQABiQIfBBgBCAAJBQJUVSG/
AhsMAAoJEJGmhovT96kHb/0P/0LXAOXeyTDWOHEoPFKIXS4y9tl2PA6hq1HOgthP
1B2P6eIjpB7UGTSieWpKeqkkv7SZFTol2H0JlhZlhh1IkxS/aHHAl2Km6TLkk6QL
GGkKOFFAiU51iVkJQumbTKMlx11DXA0Jy6mVsUWoz3Ua9cFwrhuCRpKxW61xTEaX
dksgOUBKWH+mF8MtJtRedwHXjmNxaKTAKEsjmPFPn8i75D48JIbq9L+rHLxFTeSR
LShj7lZR1I24+UofA2Tllh4V14rSsUkfIYsKuwCGenJ+sPhpwqHohfJzTewXk+TK
wkilwVgTg7AYCeywP7XqkhA4om9aJRc1cqPcrknsXJLz4Vp7JX8bCtRqF2JT7wsM
wtHMNAtItLa+WYnkvt9/ng9Zt5i0fHZBwfVazWP+/4LAkb9fE4vO2IusV0jK00Sk
7Gt65A32qY75Lze6NRUk2gwizMLIdMvag9AuIUH52RScNVoVXIkmw1q57KshBL1M
VWRd7DUpFGpw8HKkqNlJKPAv+UsJAp7rSkfH9CAYwFzjbs7BST5Cuynac0CgZGQO
F0793mKAsbMePuEIzkR0ZdA/F0Mar9/tQLAtU3pXRrThkLUNmr8Qm9rPGTjrNv7k
ANWsgd4bu0PW5SVm+eFjoTRpNI9P/xrCF8fgLcZ2JPO/wKqyIDcKxEZq978lxWDm
CwGc
=AV20
-----END PGP PUBLIC KEY BLOCK-----
`)
// GPGVerify checks the authenticity of data by verifying the signature sig,
// which must be ASCII armored (base64). When the signature matches, GPGVerify
// returns true and a nil error.
func GPGVerify(data, sig []byte) (ok bool, err error) {
keyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(key))
if err != nil {
return false, fmt.Errorf("reading keyring failed: %w", err)
}
_, err = openpgp.CheckArmoredDetachedSignature(keyring, bytes.NewReader(data), bytes.NewReader(sig))
if err != nil {
return false, err
}
return true, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/download_unix.go | internal/selfupdate/download_unix.go | //go:build !windows
package selfupdate
// Remove the target binary.
func removeResticBinary(_, _ string) error {
// removed on rename on this platform
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/download_windows.go | internal/selfupdate/download_windows.go | //go:build windows
package selfupdate
import (
"fmt"
"os"
"path/filepath"
"github.com/restic/restic/internal/errors"
)
// Rename (rather than remove) the running version. The running binary will be locked
// on Windows and cannot be removed while still executing.
func removeResticBinary(dir, target string) error {
// nothing to do if the target does not exist
if _, err := os.Stat(target); errors.Is(err, os.ErrNotExist) {
return nil
}
backup := filepath.Join(dir, filepath.Base(target)+".bak")
if _, err := os.Stat(backup); err == nil {
_ = os.Remove(backup)
}
if err := os.Rename(target, backup); err != nil {
return fmt.Errorf("unable to rename target file: %v", err)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/github_test.go | internal/selfupdate/github_test.go | package selfupdate
import (
"context"
"net/http"
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestNewGitHubRequest(t *testing.T) {
ctx := context.Background()
url := "https://api.github.com/repos/restic/restic/releases/latest"
acceptHeader := "application/vnd.github.v3+json"
t.Run("With GITHUB_ACCESS_TOKEN", func(t *testing.T) {
expectedToken := "testtoken123"
t.Setenv("GITHUB_ACCESS_TOKEN", expectedToken)
req, err := newGitHubRequest(ctx, url, acceptHeader)
rtest.OK(t, err)
rtest.Assert(t, req.Method == http.MethodGet, "expected method %s, got %s", http.MethodGet, req.Method)
rtest.Assert(t, req.URL.String() == url, "expected URL %s, got %s", url, req.URL.String())
rtest.Assert(t, req.Header.Get("Accept") == acceptHeader, "expected Accept header %s, got %s", acceptHeader, req.Header.Get("Accept"))
rtest.Assert(t, req.Header.Get("Authorization") == "token "+expectedToken, "expected Authorization header 'token %s', got %s", expectedToken, req.Header.Get("Authorization"))
})
t.Run("Without GITHUB_ACCESS_TOKEN", func(t *testing.T) {
t.Setenv("GITHUB_ACCESS_TOKEN", "")
req, err := newGitHubRequest(ctx, url, acceptHeader)
rtest.OK(t, err)
rtest.Assert(t, req.Header.Get("Authorization") == "", "expected no Authorization header, got %s", req.Header.Get("Authorization"))
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/download_test.go | internal/selfupdate/download_test.go | package selfupdate
import (
"archive/zip"
"bytes"
"os"
"path/filepath"
"testing"
rtest "github.com/restic/restic/internal/test"
)
func TestExtractToFileZip(t *testing.T) {
printf := func(string, ...interface{}) {}
dir := t.TempDir()
ext := "zip"
data := []byte("Hello World!")
// create dummy archive
var archive bytes.Buffer
zw := zip.NewWriter(&archive)
w, err := zw.CreateHeader(&zip.FileHeader{
Name: "example.exe",
UncompressedSize64: uint64(len(data)),
})
rtest.OK(t, err)
_, err = w.Write(data[:])
rtest.OK(t, err)
rtest.OK(t, zw.Close())
// run twice to test creating a new file and overwriting
for i := 0; i < 2; i++ {
outfn := filepath.Join(dir, ext+"-out")
rtest.OK(t, extractToFile(archive.Bytes(), "src."+ext, outfn, printf))
outdata, err := os.ReadFile(outfn)
rtest.OK(t, err)
rtest.Assert(t, bytes.Equal(data[:], outdata), "%v contains wrong data", outfn)
// overwrite to test the file is properly overwritten
rtest.OK(t, os.WriteFile(outfn, []byte{1, 2, 3}, 0))
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/github.go | internal/selfupdate/github.go | package selfupdate
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/pkg/errors"
)
// Release collects data about a single release on GitHub.
type Release struct {
Name string `json:"name"`
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
PreRelease bool `json:"prerelease"`
PublishedAt time.Time `json:"published_at"`
Assets []Asset `json:"assets"`
Version string `json:"-"` // set manually in the code
}
// Asset is a file uploaded and attached to a release.
type Asset struct {
ID int `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
}
func (r Release) String() string {
return fmt.Sprintf("%v %v, %d assets",
r.TagName,
r.PublishedAt.Local().Format("2006-01-02 15:04:05"),
len(r.Assets))
}
const githubAPITimeout = 30 * time.Second
// githubError is returned by the GitHub API, e.g. for rate-limiting.
type githubError struct {
Message string
}
func newGitHubRequest(ctx context.Context, url, acceptHeader string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
// Set the Accept header to pin the API version
req.Header.Set("Accept", acceptHeader)
// Add Authorization header if token is available
if token := os.Getenv("GITHUB_ACCESS_TOKEN"); token != "" {
req.Header.Set("Authorization", "token "+token)
}
return req, nil
}
// GitHubLatestRelease uses the GitHub API to get information about the latest
// release of a repository.
func GitHubLatestRelease(ctx context.Context, owner, repo string) (Release, error) {
ctx, cancel := context.WithTimeout(ctx, githubAPITimeout)
defer cancel()
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
req, err := newGitHubRequest(ctx, url, "application/vnd.github.v3+json")
if err != nil {
return Release{}, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return Release{}, err
}
if res.StatusCode != http.StatusOK {
content := res.Header.Get("Content-Type")
if strings.Contains(content, "application/json") {
// try to decode error message
var msg githubError
jerr := json.NewDecoder(res.Body).Decode(&msg)
if jerr == nil {
return Release{}, fmt.Errorf("unexpected status %v (%v) returned, message:\n %v", res.StatusCode, res.Status, msg.Message)
}
}
_ = res.Body.Close()
return Release{}, fmt.Errorf("unexpected status %v (%v) returned", res.StatusCode, res.Status)
}
buf, err := io.ReadAll(res.Body)
if err != nil {
_ = res.Body.Close()
return Release{}, err
}
err = res.Body.Close()
if err != nil {
return Release{}, err
}
var release Release
err = json.Unmarshal(buf, &release)
if err != nil {
return Release{}, err
}
if release.TagName == "" {
return Release{}, errors.New("tag name for latest release is empty")
}
if !strings.HasPrefix(release.TagName, "v") {
return Release{}, errors.Errorf("tag name %q is invalid, does not start with 'v'", release.TagName)
}
release.Version = release.TagName[1:]
return release, nil
}
func getGithubData(ctx context.Context, url string) ([]byte, error) {
req, err := newGitHubRequest(ctx, url, "application/octet-stream")
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status %v (%v) returned", res.StatusCode, res.Status)
}
buf, err := io.ReadAll(res.Body)
if err != nil {
_ = res.Body.Close()
return nil, err
}
err = res.Body.Close()
if err != nil {
return nil, err
}
return buf, nil
}
func getGithubDataFile(ctx context.Context, assets []Asset, suffix string, printf func(string, ...interface{})) (filename string, data []byte, err error) {
var url string
for _, a := range assets {
if strings.HasSuffix(a.Name, suffix) {
url = a.URL
filename = a.Name
break
}
}
if url == "" {
return "", nil, fmt.Errorf("unable to find file with suffix %v", suffix)
}
printf("download %v\n", filename)
data, err = getGithubData(ctx, url)
if err != nil {
return "", nil, err
}
return filename, data, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/selfupdate/download.go | internal/selfupdate/download.go | package selfupdate
import (
"archive/zip"
"bufio"
"bytes"
"compress/bzip2"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/pkg/errors"
)
func findHash(buf []byte, filename string) (hash []byte, err error) {
sc := bufio.NewScanner(bytes.NewReader(buf))
for sc.Scan() {
data := strings.Split(sc.Text(), " ")
if len(data) != 2 {
continue
}
if data[1] == filename {
h, err := hex.DecodeString(data[0])
if err != nil {
return nil, err
}
return h, nil
}
}
return nil, fmt.Errorf("hash for file %v not found", filename)
}
func extractToFile(buf []byte, filename, target string, printf func(string, ...interface{})) error {
var rd io.Reader = bytes.NewReader(buf)
switch filepath.Ext(filename) {
case ".bz2":
rd = bzip2.NewReader(rd)
case ".zip":
zrd, err := zip.NewReader(bytes.NewReader(buf), int64(len(buf)))
if err != nil {
return err
}
if len(zrd.File) != 1 {
return errors.New("ZIP archive contains more than one file")
}
file, err := zrd.File[0].Open()
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
rd = file
}
// Write everything to a temp file
dir := filepath.Dir(target)
newFile, err := os.CreateTemp(dir, "restic")
if err != nil {
return err
}
n, err := io.Copy(newFile, rd)
if err != nil {
_ = newFile.Close()
_ = os.Remove(newFile.Name())
return err
}
if err = newFile.Sync(); err != nil {
return err
}
if err = newFile.Close(); err != nil {
return err
}
mode := os.FileMode(0755)
// attempt to find the original mode
if fi, err := os.Lstat(target); err == nil {
mode = fi.Mode()
}
// Remove the original binary.
if err := removeResticBinary(dir, target); err != nil {
return err
}
// Rename the temp file to the final location atomically.
if err := os.Rename(newFile.Name(), target); err != nil {
return err
}
printf("saved %d bytes in %v\n", n, target)
return os.Chmod(target, mode)
}
// DownloadLatestStableRelease downloads the latest stable released version of
// restic and saves it to target. It returns the version string for the newest
// version. The function printf is used to print progress information.
func DownloadLatestStableRelease(ctx context.Context, target, currentVersion string, printf func(string, ...interface{})) (version string, err error) {
if printf == nil {
printf = func(string, ...interface{}) {}
}
printf("find latest release of restic at GitHub\n")
rel, err := GitHubLatestRelease(ctx, "restic", "restic")
if err != nil {
return "", err
}
if rel.Version == currentVersion {
printf("restic is up to date\n")
return currentVersion, nil
}
printf("latest version is %v\n", rel.Version)
_, sha256sums, err := getGithubDataFile(ctx, rel.Assets, "SHA256SUMS", printf)
if err != nil {
return "", err
}
_, sig, err := getGithubDataFile(ctx, rel.Assets, "SHA256SUMS.asc", printf)
if err != nil {
return "", err
}
ok, err := GPGVerify(sha256sums, sig)
if err != nil {
return "", err
}
if !ok {
return "", errors.New("GPG signature verification of the file SHA256SUMS failed")
}
printf("GPG signature verification succeeded\n")
ext := "bz2"
if runtime.GOOS == "windows" {
ext = "zip"
}
suffix := fmt.Sprintf("%s_%s.%s", runtime.GOOS, runtime.GOARCH, ext)
downloadFilename, buf, err := getGithubDataFile(ctx, rel.Assets, suffix, printf)
if err != nil {
return "", err
}
printf("downloaded %v\n", downloadFilename)
wantHash, err := findHash(sha256sums, downloadFilename)
if err != nil {
return "", err
}
gotHash := sha256.Sum256(buf)
if !bytes.Equal(wantHash, gotHash[:]) {
return "", fmt.Errorf("SHA256 hash mismatch, want hash %02x, got %02x", wantHash, gotHash)
}
err = extractToFile(buf, downloadFilename, target, printf)
if err != nil {
return "", err
}
return rel.Version, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/truncate_windows.go | internal/restorer/truncate_windows.go | package restorer
import (
"os"
"github.com/restic/restic/internal/debug"
"golang.org/x/sys/windows"
)
func truncateSparse(f *os.File, size int64) error {
// try setting the sparse file attribute, but ignore the error if it fails
var t uint32
err := windows.DeviceIoControl(windows.Handle(f.Fd()), windows.FSCTL_SET_SPARSE, nil, 0, nil, 0, &t, nil)
if err != nil {
debug.Log("failed to set sparse attribute for %v: %v", f.Name(), err)
}
return f.Truncate(size)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/fileswriter_other_test.go | internal/restorer/fileswriter_other_test.go | //go:build !windows
package restorer
import "syscall"
func notEmptyDirError() error {
return syscall.ENOTEMPTY
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/restorer_test.go | internal/restorer/restorer_test.go | package restorer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"syscall"
"testing"
"time"
"github.com/restic/restic/internal/archiver"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
"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"
restoreui "github.com/restic/restic/internal/ui/restore"
)
type Node interface{}
type Snapshot struct {
Nodes map[string]Node
}
type File struct {
Data string
DataParts []string
Links uint64
Inode uint64
Mode os.FileMode
ModTime time.Time
attributes *FileAttributes
}
type Symlink struct {
Target string
ModTime time.Time
}
type Dir struct {
Nodes map[string]Node
Mode os.FileMode
ModTime time.Time
attributes *FileAttributes
}
type FileAttributes struct {
ReadOnly bool
Hidden bool
System bool
Archive bool
Encrypted bool
}
func saveFile(t testing.TB, repo restic.BlobSaver, data string) restic.ID {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
id, _, _, err := repo.SaveBlob(ctx, restic.DataBlob, []byte(data), restic.ID{}, false)
if err != nil {
t.Fatal(err)
}
return id
}
func saveDir(t testing.TB, repo restic.BlobSaver, nodes map[string]Node, inode uint64, getGenericAttributes func(attr *FileAttributes, isDir bool) (genericAttributes map[data.GenericAttributeType]json.RawMessage)) restic.ID {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
tree := &data.Tree{}
for name, n := range nodes {
inode++
switch node := n.(type) {
case File:
fi := node.Inode
if fi == 0 {
fi = inode
}
lc := node.Links
if lc == 0 {
lc = 1
}
fc := []restic.ID{}
size := 0
if len(node.Data) > 0 {
size = len(node.Data)
fc = append(fc, saveFile(t, repo, node.Data))
} else if len(node.DataParts) > 0 {
for _, part := range node.DataParts {
fc = append(fc, saveFile(t, repo, part))
size += len(part)
}
}
mode := node.Mode
if mode == 0 {
mode = 0644
}
err := tree.Insert(&data.Node{
Type: data.NodeTypeFile,
Mode: mode,
ModTime: node.ModTime,
Name: name,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Content: fc,
Size: uint64(size),
Inode: fi,
Links: lc,
GenericAttributes: getGenericAttributes(node.attributes, false),
})
rtest.OK(t, err)
case Symlink:
err := tree.Insert(&data.Node{
Type: data.NodeTypeSymlink,
Mode: os.ModeSymlink | 0o777,
ModTime: node.ModTime,
Name: name,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
LinkTarget: node.Target,
Inode: inode,
Links: 1,
})
rtest.OK(t, err)
case Dir:
id := saveDir(t, repo, node.Nodes, inode, getGenericAttributes)
mode := node.Mode
if mode == 0 {
mode = 0755
}
err := tree.Insert(&data.Node{
Type: data.NodeTypeDir,
Mode: mode,
ModTime: node.ModTime,
Name: name,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Subtree: &id,
GenericAttributes: getGenericAttributes(node.attributes, false),
})
rtest.OK(t, err)
default:
t.Fatalf("unknown node type %T", node)
}
}
id, err := data.SaveTree(ctx, repo, tree)
if err != nil {
t.Fatal(err)
}
return id
}
func saveSnapshot(t testing.TB, repo restic.Repository, snapshot Snapshot, getGenericAttributes func(attr *FileAttributes, isDir bool) (genericAttributes map[data.GenericAttributeType]json.RawMessage)) (*data.Snapshot, restic.ID) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var treeID restic.ID
rtest.OK(t, repo.WithBlobUploader(ctx, func(ctx context.Context, uploader restic.BlobSaverWithAsync) error {
treeID = saveDir(t, uploader, snapshot.Nodes, 1000, getGenericAttributes)
return nil
}))
sn, err := data.NewSnapshot([]string{"test"}, nil, "", time.Now())
if err != nil {
t.Fatal(err)
}
sn.Tree = &treeID
id, err := data.SaveSnapshot(ctx, repo, sn)
if err != nil {
t.Fatal(err)
}
return sn, id
}
var noopGetGenericAttributes = func(attr *FileAttributes, isDir bool) (genericAttributes map[data.GenericAttributeType]json.RawMessage) {
// No-op
return nil
}
func TestRestorer(t *testing.T) {
var tests = []struct {
Snapshot
Files map[string]string
ErrorsMust map[string]map[string]struct{}
ErrorsMay map[string]map[string]struct{}
Select func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool)
}{
// valid test cases
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: foo\n"},
"dirtest": Dir{
Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
},
},
},
},
Files: map[string]string{
"foo": "content: foo\n",
"dirtest/file": "content: file\n",
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"top": File{Data: "toplevel file"},
"dir": Dir{
Nodes: map[string]Node{
"file": File{Data: "file in dir"},
"subdir": Dir{
Nodes: map[string]Node{
"file": File{Data: "file in subdir"},
},
},
},
},
},
},
Files: map[string]string{
"top": "toplevel file",
"dir/file": "file in dir",
"dir/subdir/file": "file in subdir",
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{
Mode: 0444,
},
"file": File{Data: "top-level file"},
},
},
Files: map[string]string{
"file": "top-level file",
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{
Mode: 0555,
Nodes: map[string]Node{
"file": File{Data: "file in dir"},
},
},
},
},
Files: map[string]string{
"dir/file": "file in dir",
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"topfile": File{Data: "top-level file"},
},
},
Files: map[string]string{
"topfile": "top-level file",
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{
Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
},
},
},
},
Files: map[string]string{
"dir/file": "content: file\n",
},
Select: func(item string, isDir bool) (selectedForRestore bool, childMayBeSelected bool) {
switch item {
case filepath.FromSlash("/dir"):
childMayBeSelected = true
case filepath.FromSlash("/dir/file"):
selectedForRestore = true
childMayBeSelected = true
}
return selectedForRestore, childMayBeSelected
},
},
// test cases with invalid/constructed names
{
Snapshot: Snapshot{
Nodes: map[string]Node{
`..\test`: File{Data: "foo\n"},
`..\..\foo\..\bar\..\xx\test2`: File{Data: "test2\n"},
},
},
ErrorsMay: map[string]map[string]struct{}{
`/`: {
`invalid child node name ..\test`: struct{}{},
`invalid child node name ..\..\foo\..\bar\..\xx\test2`: struct{}{},
},
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
`../test`: File{Data: "foo\n"},
`../../foo/../bar/../xx/test2`: File{Data: "test2\n"},
},
},
ErrorsMay: map[string]map[string]struct{}{
`/`: {
`invalid child node name ../test`: struct{}{},
`invalid child node name ../../foo/../bar/../xx/test2`: struct{}{},
},
},
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"top": File{Data: "toplevel file"},
"x": Dir{
Nodes: map[string]Node{
"file1": File{Data: "file1"},
"..": Dir{
Nodes: map[string]Node{
"file2": File{Data: "file2"},
"..": Dir{
Nodes: map[string]Node{
"file2": File{Data: "file2"},
},
},
},
},
},
},
},
},
Files: map[string]string{
"top": "toplevel file",
},
ErrorsMust: map[string]map[string]struct{}{
`/x`: {
`invalid child node name ..`: struct{}{},
},
},
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
repo := repository.TestRepository(t)
sn, id := saveSnapshot(t, repo, test.Snapshot, noopGetGenericAttributes)
t.Logf("snapshot saved as %v", id.Str())
res := NewRestorer(repo, sn, Options{})
tempdir := rtest.TempDir(t)
// make sure we're creating a new subdir of the tempdir
tempdir = filepath.Join(tempdir, "target")
res.SelectFilter = func(item string, isDir bool) (selectedForRestore bool, childMayBeSelected bool) {
t.Logf("restore %v", item)
if test.Select != nil {
return test.Select(item, isDir)
}
return true, true
}
errors := make(map[string]map[string]struct{})
res.Error = func(location string, err error) error {
location = filepath.ToSlash(location)
t.Logf("restore returned error for %q: %v", location, err)
if errors[location] == nil {
errors[location] = make(map[string]struct{})
}
errors[location][err.Error()] = struct{}{}
return nil
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
countRestoredFiles, err := res.RestoreTo(ctx, tempdir)
if err != nil {
t.Fatal(err)
}
if len(test.ErrorsMust)+len(test.ErrorsMay) == 0 {
_, err = res.VerifyFiles(ctx, tempdir, countRestoredFiles, nil)
rtest.OK(t, err)
}
for location, expectedErrors := range test.ErrorsMust {
actualErrors, ok := errors[location]
if !ok {
t.Errorf("expected error(s) for %v, found none", location)
continue
}
rtest.Equals(t, expectedErrors, actualErrors)
delete(errors, location)
}
for location, expectedErrors := range test.ErrorsMay {
actualErrors, ok := errors[location]
if !ok {
continue
}
rtest.Equals(t, expectedErrors, actualErrors)
delete(errors, location)
}
for filename, err := range errors {
t.Errorf("unexpected error for %v found: %v", filename, err)
}
for filename, content := range test.Files {
data, err := os.ReadFile(filepath.Join(tempdir, filepath.FromSlash(filename)))
if err != nil {
t.Errorf("unable to read file %v: %v", filename, err)
continue
}
if !bytes.Equal(data, []byte(content)) {
t.Errorf("file %v has wrong content: want %q, got %q", filename, content, data)
}
}
})
}
}
func TestRestorerRelative(t *testing.T) {
var tests = []struct {
Snapshot
Files map[string]string
}{
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: foo\n"},
"dirtest": Dir{
Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
},
},
},
},
Files: map[string]string{
"foo": "content: foo\n",
"dirtest/file": "content: file\n",
},
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
repo := repository.TestRepository(t)
sn, id := saveSnapshot(t, repo, test.Snapshot, noopGetGenericAttributes)
t.Logf("snapshot saved as %v", id.Str())
res := NewRestorer(repo, sn, Options{})
tempdir := rtest.TempDir(t)
cleanup := rtest.Chdir(t, tempdir)
defer cleanup()
errors := make(map[string]string)
res.Error = func(location string, err error) error {
t.Logf("restore returned error for %q: %v", location, err)
errors[location] = err.Error()
return nil
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
countRestoredFiles, err := res.RestoreTo(ctx, "restore")
if err != nil {
t.Fatal(err)
}
p := progress.NewCounter(time.Second, countRestoredFiles, func(value uint64, total uint64, runtime time.Duration, final bool) {})
defer p.Done()
nverified, err := res.VerifyFiles(ctx, "restore", countRestoredFiles, p)
rtest.OK(t, err)
rtest.Equals(t, len(test.Files), nverified)
counterValue, maxValue := p.Get()
rtest.Equals(t, counterValue, uint64(2))
rtest.Equals(t, maxValue, uint64(2))
for filename, err := range errors {
t.Errorf("unexpected error for %v found: %v", filename, err)
}
for filename, content := range test.Files {
data, err := os.ReadFile(filepath.Join(tempdir, "restore", filepath.FromSlash(filename)))
if err != nil {
t.Errorf("unable to read file %v: %v", filename, err)
continue
}
if !bytes.Equal(data, []byte(content)) {
t.Errorf("file %v has wrong content: want %q, got %q", filename, content, data)
}
}
// verify that restoring the same snapshot again results in countRestoredFiles == 0
countRestoredFiles, err = res.RestoreTo(ctx, "restore")
if err != nil {
t.Fatal(err)
}
rtest.Equals(t, uint64(0), countRestoredFiles)
})
}
}
type TraverseTreeCheck func(testing.TB) treeVisitor
type TreeVisit struct {
funcName string // name of the function
location string // location passed to the function
files []string // file list passed to the function
}
func checkVisitOrder(list []TreeVisit) TraverseTreeCheck {
var pos int
return func(t testing.TB) treeVisitor {
check := func(funcName string) func(*data.Node, string, string, []string) error {
return func(node *data.Node, target, location string, expectedFilenames []string) error {
if pos >= len(list) {
t.Errorf("step %v, %v(%v): expected no more than %d function calls", pos, funcName, location, len(list))
pos++
return nil
}
v := list[pos]
if v.funcName != funcName {
t.Errorf("step %v, location %v: want function %v, but %v was called",
pos, location, v.funcName, funcName)
}
if location != filepath.FromSlash(v.location) {
t.Errorf("step %v: want location %v, got %v", pos, list[pos].location, location)
}
if !reflect.DeepEqual(expectedFilenames, v.files) {
t.Errorf("step %v: want files %v, got %v", pos, list[pos].files, expectedFilenames)
}
pos++
return nil
}
}
checkNoFilename := func(funcName string) func(*data.Node, string, string) error {
f := check(funcName)
return func(node *data.Node, target, location string) error {
return f(node, target, location, nil)
}
}
return treeVisitor{
enterDir: checkNoFilename("enterDir"),
visitNode: checkNoFilename("visitNode"),
leaveDir: check("leaveDir"),
}
}
}
func TestRestorerTraverseTree(t *testing.T) {
var tests = []struct {
Snapshot
Select func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool)
Visitor TraverseTreeCheck
}{
{
// select everything
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{Nodes: map[string]Node{
"otherfile": File{Data: "x"},
"subdir": Dir{Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
}},
}},
"foo": File{Data: "content: foo\n"},
},
},
Select: func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool) {
return true, true
},
Visitor: checkVisitOrder([]TreeVisit{
{"enterDir", "/", nil},
{"enterDir", "/dir", nil},
{"visitNode", "/dir/otherfile", nil},
{"enterDir", "/dir/subdir", nil},
{"visitNode", "/dir/subdir/file", nil},
{"leaveDir", "/dir/subdir", []string{"file"}},
{"leaveDir", "/dir", []string{"otherfile", "subdir"}},
{"visitNode", "/foo", nil},
{"leaveDir", "/", []string{"dir", "foo"}},
}),
},
// select only the top-level file
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{Nodes: map[string]Node{
"otherfile": File{Data: "x"},
"subdir": Dir{Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
}},
}},
"foo": File{Data: "content: foo\n"},
},
},
Select: func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool) {
if item == "/foo" {
return true, false
}
return false, false
},
Visitor: checkVisitOrder([]TreeVisit{
{"enterDir", "/", nil},
{"visitNode", "/foo", nil},
{"leaveDir", "/", []string{"dir", "foo"}},
}),
},
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"aaa": File{Data: "content: foo\n"},
"dir": Dir{Nodes: map[string]Node{
"otherfile": File{Data: "x"},
"subdir": Dir{Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
}},
}},
},
},
Select: func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool) {
if item == "/aaa" {
return true, false
}
return false, false
},
Visitor: checkVisitOrder([]TreeVisit{
{"enterDir", "/", nil},
{"visitNode", "/aaa", nil},
{"leaveDir", "/", []string{"aaa", "dir"}},
}),
},
// select dir/
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{Nodes: map[string]Node{
"otherfile": File{Data: "x"},
"subdir": Dir{Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
}},
}},
"foo": File{Data: "content: foo\n"},
},
},
Select: func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool) {
if strings.HasPrefix(item, "/dir") {
return true, true
}
return false, false
},
Visitor: checkVisitOrder([]TreeVisit{
{"enterDir", "/", nil},
{"enterDir", "/dir", nil},
{"visitNode", "/dir/otherfile", nil},
{"enterDir", "/dir/subdir", nil},
{"visitNode", "/dir/subdir/file", nil},
{"leaveDir", "/dir/subdir", []string{"file"}},
{"leaveDir", "/dir", []string{"otherfile", "subdir"}},
{"leaveDir", "/", []string{"dir", "foo"}},
}),
},
// select only dir/otherfile
{
Snapshot: Snapshot{
Nodes: map[string]Node{
"dir": Dir{Nodes: map[string]Node{
"otherfile": File{Data: "x"},
"subdir": Dir{Nodes: map[string]Node{
"file": File{Data: "content: file\n"},
}},
}},
"foo": File{Data: "content: foo\n"},
},
},
Select: func(item string, isDir bool) (selectForRestore bool, childMayBeSelected bool) {
switch item {
case "/dir":
return false, true
case "/dir/otherfile":
return true, false
default:
return false, false
}
},
Visitor: checkVisitOrder([]TreeVisit{
{"enterDir", "/", nil},
{"visitNode", "/dir/otherfile", nil},
{"leaveDir", "/dir", []string{"otherfile", "subdir"}},
{"leaveDir", "/", []string{"dir", "foo"}},
}),
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
repo := repository.TestRepository(t)
sn, _ := saveSnapshot(t, repo, test.Snapshot, noopGetGenericAttributes)
// set Delete option to enable tracking filenames in a directory
res := NewRestorer(repo, sn, Options{Delete: true})
res.SelectFilter = test.Select
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// make sure we're creating a new subdir of the tempdir
target := filepath.Join(tempdir, "target")
err := res.traverseTree(ctx, target, *sn.Tree, test.Visitor(t))
if err != nil {
t.Fatal(err)
}
})
}
}
func normalizeFileMode(mode os.FileMode) os.FileMode {
if runtime.GOOS == "windows" {
if mode.IsDir() {
return 0555 | os.ModeDir
}
return os.FileMode(0444)
}
return mode
}
func checkConsistentInfo(t testing.TB, file string, fi os.FileInfo, modtime time.Time, mode os.FileMode) {
if fi.Mode() != mode {
t.Errorf("checking %q, Mode() returned wrong value, want 0%o, got 0%o", file, mode, fi.Mode())
}
if !fi.ModTime().Equal(modtime) {
t.Errorf("checking %s, ModTime() returned wrong value, want %v, got %v", file, modtime, fi.ModTime())
}
}
// test inspired from test case https://github.com/restic/restic/issues/1212
func TestRestorerConsistentTimestampsAndPermissions(t *testing.T) {
timeForTest := time.Date(2019, time.January, 9, 1, 46, 40, 0, time.UTC)
repo := repository.TestRepository(t)
sn, _ := saveSnapshot(t, repo, Snapshot{
Nodes: map[string]Node{
"dir": Dir{
Mode: normalizeFileMode(0750 | os.ModeDir),
ModTime: timeForTest,
Nodes: map[string]Node{
"file1": File{
Mode: normalizeFileMode(os.FileMode(0700)),
ModTime: timeForTest,
Data: "content: file\n",
},
"anotherfile": File{
Data: "content: file\n",
},
"subdir": Dir{
Mode: normalizeFileMode(0700 | os.ModeDir),
ModTime: timeForTest,
Nodes: map[string]Node{
"file2": File{
Mode: normalizeFileMode(os.FileMode(0666)),
ModTime: timeForTest,
Links: 2,
Inode: 1,
},
},
},
},
},
},
}, noopGetGenericAttributes)
res := NewRestorer(repo, sn, Options{})
res.SelectFilter = func(item string, isDir bool) (selectedForRestore bool, childMayBeSelected bool) {
switch filepath.ToSlash(item) {
case "/dir":
childMayBeSelected = true
case "/dir/file1":
selectedForRestore = true
childMayBeSelected = false
case "/dir/subdir":
selectedForRestore = true
childMayBeSelected = true
case "/dir/subdir/file2":
selectedForRestore = true
childMayBeSelected = false
}
return selectedForRestore, childMayBeSelected
}
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
var testPatterns = []struct {
path string
modtime time.Time
mode os.FileMode
}{
{"dir", timeForTest, normalizeFileMode(0750 | os.ModeDir)},
{filepath.Join("dir", "file1"), timeForTest, normalizeFileMode(os.FileMode(0700))},
{filepath.Join("dir", "subdir"), timeForTest, normalizeFileMode(0700 | os.ModeDir)},
{filepath.Join("dir", "subdir", "file2"), timeForTest, normalizeFileMode(os.FileMode(0666))},
}
for _, test := range testPatterns {
f, err := os.Stat(filepath.Join(tempdir, test.path))
rtest.OK(t, err)
checkConsistentInfo(t, test.path, f, test.modtime, test.mode)
}
}
// VerifyFiles must not report cancellation of its context through res.Error.
func TestVerifyCancel(t *testing.T) {
snapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: foo\n"},
},
}
repo := repository.TestRepository(t)
sn, _ := saveSnapshot(t, repo, snapshot, noopGetGenericAttributes)
res := NewRestorer(repo, sn, Options{})
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
countRestoredFiles, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
err = os.WriteFile(filepath.Join(tempdir, "foo"), []byte("bar"), 0644)
rtest.OK(t, err)
var errs []error
res.Error = func(filename string, err error) error {
errs = append(errs, err)
return err
}
nverified, err := res.VerifyFiles(ctx, tempdir, countRestoredFiles, nil)
rtest.Equals(t, 0, nverified)
rtest.Assert(t, err != nil, "nil error from VerifyFiles")
rtest.Equals(t, 1, len(errs))
rtest.Assert(t, strings.Contains(errs[0].Error(), "Invalid file size for"), "wrong error %q", errs[0].Error())
}
func TestRestorerSparseFiles(t *testing.T) {
repo := repository.TestRepository(t)
var zeros [1<<20 + 13]byte
target, err := fs.NewReader("/zeros", io.NopCloser(bytes.NewReader(zeros[:])), fs.ReaderOptions{
Mode: 0600,
})
rtest.OK(t, err)
sc := archiver.NewScanner(target)
err = sc.Scan(context.TODO(), []string{"/zeros"})
rtest.OK(t, err)
arch := archiver.New(repo, target, archiver.Options{})
sn, _, _, err := arch.Snapshot(context.Background(), []string{"/zeros"},
archiver.SnapshotOptions{})
rtest.OK(t, err)
res := NewRestorer(repo, sn, Options{Sparse: true})
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err = res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
filename := filepath.Join(tempdir, "zeros")
content, err := os.ReadFile(filename)
rtest.OK(t, err)
rtest.Equals(t, len(zeros[:]), len(content))
rtest.Equals(t, zeros[:], content)
blocks := getBlockCount(t, filename)
if blocks < 0 {
return
}
// st.Blocks is the size in 512-byte blocks.
denseBlocks := math.Ceil(float64(len(zeros)) / 512)
sparsity := 1 - float64(blocks)/denseBlocks
// This should report 100% sparse. We don't assert that,
// as the behavior of sparse writes depends on the underlying
// file system as well as the OS.
t.Logf("wrote %d zeros as %d blocks, %.1f%% sparse",
len(zeros), blocks, 100*sparsity)
}
func saveSnapshotsAndOverwrite(t *testing.T, baseSnapshot Snapshot, overwriteSnapshot Snapshot, baseOptions, overwriteOptions Options) string {
repo := repository.TestRepository(t)
tempdir := filepath.Join(rtest.TempDir(t), "target")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// base snapshot
sn, id := saveSnapshot(t, repo, baseSnapshot, noopGetGenericAttributes)
t.Logf("base snapshot saved as %v", id.Str())
res := NewRestorer(repo, sn, baseOptions)
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
// overwrite snapshot
sn, id = saveSnapshot(t, repo, overwriteSnapshot, noopGetGenericAttributes)
t.Logf("overwrite snapshot saved as %v", id.Str())
res = NewRestorer(repo, sn, overwriteOptions)
countRestoredFiles, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
_, err = res.VerifyFiles(ctx, tempdir, countRestoredFiles, nil)
rtest.OK(t, err)
return tempdir
}
func TestRestorerSparseOverwrite(t *testing.T) {
baseSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: new\n"},
},
}
var zero [14]byte
sparseSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: string(zero[:])},
},
}
opts := Options{Sparse: true, Overwrite: OverwriteAlways}
saveSnapshotsAndOverwrite(t, baseSnapshot, sparseSnapshot, opts, opts)
}
type printerMock struct {
s restoreui.State
progress.NoopPrinter
}
func (p *printerMock) Update(_ restoreui.State, _ time.Duration) {
}
func (p *printerMock) Error(_ string, _ error) error {
return nil
}
func (p *printerMock) CompleteItem(_ restoreui.ItemAction, _ string, _ uint64) {
}
func (p *printerMock) Finish(s restoreui.State, _ time.Duration) {
p.s = s
}
func TestRestorerOverwriteBehavior(t *testing.T) {
baseTime := time.Now()
baseSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: foo\n", ModTime: baseTime},
"dirtest": Dir{
Nodes: map[string]Node{
"file": File{Data: "content: file\n", ModTime: baseTime},
"foo": File{Data: "content: foobar", ModTime: baseTime},
},
ModTime: baseTime,
},
},
}
overwriteSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: new\n", ModTime: baseTime.Add(time.Second)},
"dirtest": Dir{
Nodes: map[string]Node{
"file": File{Data: "content: file2\n", ModTime: baseTime.Add(-time.Second)},
"foo": File{Data: "content: foo", ModTime: baseTime},
},
},
},
}
var tests = []struct {
Overwrite OverwriteBehavior
Files map[string]string
Progress restoreui.State
}{
{
Overwrite: OverwriteAlways,
Files: map[string]string{
"foo": "content: new\n",
"dirtest/file": "content: file2\n",
"dirtest/foo": "content: foo",
},
Progress: restoreui.State{
FilesFinished: 4,
FilesTotal: 4,
FilesSkipped: 0,
AllBytesWritten: 40,
AllBytesTotal: 40,
AllBytesSkipped: 0,
},
},
{
Overwrite: OverwriteIfChanged,
Files: map[string]string{
"foo": "content: new\n",
"dirtest/file": "content: file2\n",
"dirtest/foo": "content: foo",
},
Progress: restoreui.State{
FilesFinished: 4,
FilesTotal: 4,
FilesSkipped: 0,
AllBytesWritten: 40,
AllBytesTotal: 40,
AllBytesSkipped: 0,
},
},
{
Overwrite: OverwriteIfNewer,
Files: map[string]string{
"foo": "content: new\n",
"dirtest/file": "content: file\n",
"dirtest/foo": "content: foobar",
},
Progress: restoreui.State{
FilesFinished: 2,
FilesTotal: 2,
FilesSkipped: 2,
AllBytesWritten: 13,
AllBytesTotal: 13,
AllBytesSkipped: 27,
},
},
{
Overwrite: OverwriteNever,
Files: map[string]string{
"foo": "content: foo\n",
"dirtest/file": "content: file\n",
"dirtest/foo": "content: foobar",
},
Progress: restoreui.State{
FilesFinished: 1,
FilesTotal: 1,
FilesSkipped: 3,
AllBytesWritten: 0,
AllBytesTotal: 0,
AllBytesSkipped: 40,
},
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
mock := &printerMock{}
progress := restoreui.NewProgress(mock, 0)
tempdir := saveSnapshotsAndOverwrite(t, baseSnapshot, overwriteSnapshot, Options{}, Options{Overwrite: test.Overwrite, Progress: progress})
for filename, content := range test.Files {
data, err := os.ReadFile(filepath.Join(tempdir, filepath.FromSlash(filename)))
if err != nil {
t.Errorf("unable to read file %v: %v", filename, err)
continue
}
if !bytes.Equal(data, []byte(content)) {
t.Errorf("file %v has wrong content: want %q, got %q", filename, content, data)
}
}
progress.Finish()
rtest.Equals(t, test.Progress, mock.s)
})
}
}
func TestRestorerOverwritePartial(t *testing.T) {
parts := make([]string, 100)
size := 0
for i := 0; i < len(parts); i++ {
parts[i] = fmt.Sprint(i)
size += len(parts[i])
if i < 8 {
// small file
size += len(parts[i])
}
}
// the data of both snapshots is stored in different pack files
// thus both small an foo in the overwriteSnapshot contain blobs from
// two different pack files. This tests basic handling of blobs from
// different pack files.
baseTime := time.Now()
baseSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{DataParts: parts[0:5], ModTime: baseTime},
"small": File{DataParts: parts[0:5], ModTime: baseTime},
},
}
overwriteSnapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{DataParts: parts, ModTime: baseTime},
"small": File{DataParts: parts[0:8], ModTime: baseTime},
},
}
mock := &printerMock{}
progress := restoreui.NewProgress(mock, 0)
saveSnapshotsAndOverwrite(t, baseSnapshot, overwriteSnapshot, Options{}, Options{Overwrite: OverwriteAlways, Progress: progress})
progress.Finish()
rtest.Equals(t, restoreui.State{
FilesFinished: 2,
FilesTotal: 2,
FilesSkipped: 0,
AllBytesWritten: uint64(size),
AllBytesTotal: uint64(size),
AllBytesSkipped: 0,
}, mock.s)
}
func TestRestorerOverwriteSpecial(t *testing.T) {
baseTime := time.Now()
baseSnapshot := Snapshot{
Nodes: map[string]Node{
"dirtest": Dir{ModTime: baseTime},
"link": Symlink{Target: "foo", ModTime: baseTime},
"file": File{Data: "content: file\n", Inode: 42, Links: 2, ModTime: baseTime},
"hardlink": File{Data: "content: file\n", Inode: 42, Links: 2, ModTime: baseTime},
"newdir": File{Data: "content: dir\n", ModTime: baseTime},
},
}
overwriteSnapshot := Snapshot{
Nodes: map[string]Node{
"dirtest": Symlink{Target: "foo", ModTime: baseTime},
"link": File{Data: "content: link\n", Inode: 42, Links: 2, ModTime: baseTime.Add(time.Second)},
"file": Symlink{Target: "foo2", ModTime: baseTime},
"hardlink": File{Data: "content: link\n", Inode: 42, Links: 2, ModTime: baseTime.Add(time.Second)},
"newdir": Dir{ModTime: baseTime},
},
}
files := map[string]string{
"link": "content: link\n",
"hardlink": "content: link\n",
}
links := map[string]string{
"dirtest": "foo",
"file": "foo2",
}
opts := Options{Overwrite: OverwriteAlways}
tempdir := saveSnapshotsAndOverwrite(t, baseSnapshot, overwriteSnapshot, opts, opts)
for filename, content := range files {
data, err := os.ReadFile(filepath.Join(tempdir, filepath.FromSlash(filename)))
if err != nil {
t.Errorf("unable to read file %v: %v", filename, err)
continue
}
if !bytes.Equal(data, []byte(content)) {
t.Errorf("file %v has wrong content: want %q, got %q", filename, content, data)
}
}
for filename, target := range links {
link, err := os.Readlink(filepath.Join(tempdir, filepath.FromSlash(filename)))
rtest.OK(t, err)
rtest.Equals(t, link, target, "wrong symlink target")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | true |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/truncate_other.go | internal/restorer/truncate_other.go | //go:build !windows
package restorer
import "os"
func truncateSparse(f *os.File, size int64) error {
return f.Truncate(size)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/fileswriter.go | internal/restorer/fileswriter.go | package restorer
import (
"fmt"
"os"
"sync"
"syscall"
"github.com/cespare/xxhash/v2"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/fs"
)
// writes blobs to target files.
// multiple files can be written to concurrently.
// multiple blobs can be concurrently written to the same file.
// TODO I am not 100% convinced this is necessary, i.e. it may be okay
// to use multiple os.File to write to the same target file
type filesWriter struct {
buckets []filesWriterBucket
allowRecursiveDelete bool
}
type filesWriterBucket struct {
lock sync.Mutex
files map[string]*partialFile
}
type partialFile struct {
*os.File
users int // Reference count.
sparse bool
}
func newFilesWriter(count int, allowRecursiveDelete bool) *filesWriter {
buckets := make([]filesWriterBucket, count)
for b := 0; b < count; b++ {
buckets[b].files = make(map[string]*partialFile)
}
return &filesWriter{
buckets: buckets,
allowRecursiveDelete: allowRecursiveDelete,
}
}
func openFile(path string) (*os.File, error) {
f, err := fs.OpenFile(path, fs.O_WRONLY|fs.O_NOFOLLOW, 0600)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
_ = f.Close()
return nil, err
}
if !fi.Mode().IsRegular() {
_ = f.Close()
return nil, fmt.Errorf("unexpected file type %v at %q", fi.Mode().Type(), path)
}
return f, nil
}
func createFile(path string, createSize int64, sparse bool, allowRecursiveDelete bool) (*os.File, error) {
f, err := fs.OpenFile(path, fs.O_CREATE|fs.O_WRONLY|fs.O_NOFOLLOW, 0600)
if err != nil && fs.IsAccessDenied(err) {
// If file is readonly, clear the readonly flag by resetting the
// permissions of the file and try again
// as the metadata will be set again in the second pass and the
// readonly flag will be applied again if needed.
if err = fs.ResetPermissions(path); err != nil {
return nil, err
}
if f, err = fs.OpenFile(path, fs.O_WRONLY|fs.O_NOFOLLOW, 0600); err != nil {
return nil, err
}
} else if err != nil && (errors.Is(err, syscall.ELOOP) || errors.Is(err, syscall.EISDIR)) {
// symlink or directory, try to remove it later on
f = nil
} else if err != nil {
return nil, err
}
var fi os.FileInfo
if f != nil {
// stat to check that we've opened a regular file
fi, err = f.Stat()
if err != nil {
_ = f.Close()
return nil, err
}
}
mustReplace := f == nil || !fi.Mode().IsRegular()
if !mustReplace {
ex := fs.ExtendedStat(fi)
if ex.Links > 1 {
// there is no efficient way to find out which other files might be linked to this file
// thus nuke the existing file and start with a fresh one
mustReplace = true
}
}
if mustReplace {
// close handle if we still have it
if f != nil {
if err := f.Close(); err != nil {
return nil, err
}
}
// not what we expected, try to get rid of it
if allowRecursiveDelete {
if err := fs.RemoveAll(path); err != nil {
return nil, err
}
} else {
if err := fs.Remove(path); err != nil {
return nil, err
}
}
// create a new file, pass O_EXCL to make sure there are no surprises
f, err = fs.OpenFile(path, fs.O_CREATE|fs.O_WRONLY|fs.O_EXCL|fs.O_NOFOLLOW, 0600)
if err != nil {
return nil, err
}
fi, err = f.Stat()
if err != nil {
_ = f.Close()
return nil, err
}
}
return ensureSize(f, fi, createSize, sparse)
}
func ensureSize(f *os.File, fi os.FileInfo, createSize int64, sparse bool) (*os.File, error) {
if sparse {
err := truncateSparse(f, createSize)
if err != nil {
_ = f.Close()
return nil, err
}
} else if fi.Size() > createSize {
// file is too long must shorten it
err := f.Truncate(createSize)
if err != nil {
_ = f.Close()
return nil, err
}
} else if createSize > 0 {
err := fs.PreallocateFile(f, createSize)
if err != nil {
// Just log the preallocate error but don't let it cause the restore process to fail.
// Preallocate might return an error if the filesystem (implementation) does not
// support preallocation or our parameters combination to the preallocate call
// This should yield a syscall.ENOTSUP error, but some other errors might also
// show up.
debug.Log("Failed to preallocate %v with size %v: %v", f.Name(), createSize, err)
}
}
return f, nil
}
func (w *filesWriter) writeToFile(path string, blob []byte, offset int64, createSize int64, sparse bool) error {
bucket := &w.buckets[uint(xxhash.Sum64String(path))%uint(len(w.buckets))]
acquireWriter := func() (*partialFile, error) {
bucket.lock.Lock()
defer bucket.lock.Unlock()
if wr, ok := bucket.files[path]; ok {
bucket.files[path].users++
return wr, nil
}
var f *os.File
var err error
if createSize >= 0 {
f, err = createFile(path, createSize, sparse, w.allowRecursiveDelete)
if err != nil {
return nil, err
}
} else if f, err = openFile(path); err != nil {
return nil, err
}
wr := &partialFile{File: f, users: 1, sparse: sparse}
bucket.files[path] = wr
return wr, nil
}
releaseWriter := func(wr *partialFile) error {
bucket.lock.Lock()
defer bucket.lock.Unlock()
if bucket.files[path].users == 1 {
delete(bucket.files, path)
return wr.Close()
}
bucket.files[path].users--
return nil
}
wr, err := acquireWriter()
if err != nil {
return err
}
_, err = wr.WriteAt(blob, offset)
if err != nil {
// ignore subsequent errors
_ = releaseWriter(wr)
return err
}
return releaseWriter(wr)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/restorer_unix_test.go | internal/restorer/restorer_unix_test.go | //go:build !windows
package restorer
import (
"context"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
"time"
"github.com/restic/restic/internal/repository"
rtest "github.com/restic/restic/internal/test"
restoreui "github.com/restic/restic/internal/ui/restore"
)
func TestRestorerRestoreEmptyHardlinkedFields(t *testing.T) {
repo := repository.TestRepository(t)
sn, _ := saveSnapshot(t, repo, Snapshot{
Nodes: map[string]Node{
"dirtest": Dir{
Nodes: map[string]Node{
"file1": File{Links: 2, Inode: 1},
"file2": File{Links: 2, Inode: 1},
},
},
},
}, noopGetGenericAttributes)
res := NewRestorer(repo, sn, Options{})
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
f1, err := os.Stat(filepath.Join(tempdir, "dirtest/file1"))
rtest.OK(t, err)
rtest.Equals(t, int64(0), f1.Size())
s1, ok1 := f1.Sys().(*syscall.Stat_t)
f2, err := os.Stat(filepath.Join(tempdir, "dirtest/file2"))
rtest.OK(t, err)
rtest.Equals(t, int64(0), f2.Size())
s2, ok2 := f2.Sys().(*syscall.Stat_t)
if ok1 && ok2 {
rtest.Equals(t, s1.Ino, s2.Ino)
}
}
func getBlockCount(t *testing.T, filename string) int64 {
fi, err := os.Stat(filename)
rtest.OK(t, err)
st := fi.Sys().(*syscall.Stat_t)
if st == nil {
return -1
}
return st.Blocks
}
func TestRestorerProgressBar(t *testing.T) {
testRestorerProgressBar(t, false)
}
func TestRestorerProgressBarDryRun(t *testing.T) {
testRestorerProgressBar(t, true)
}
func testRestorerProgressBar(t *testing.T, dryRun bool) {
repo := repository.TestRepository(t)
sn, _ := saveSnapshot(t, repo, Snapshot{
Nodes: map[string]Node{
"dirtest": Dir{
Nodes: map[string]Node{
"file1": File{Links: 2, Inode: 1, Data: "foo"},
"file2": File{Links: 2, Inode: 1, Data: "foo"},
},
},
"file2": File{Links: 1, Inode: 2, Data: "example"},
},
}, noopGetGenericAttributes)
mock := &printerMock{}
progress := restoreui.NewProgress(mock, 0)
res := NewRestorer(repo, sn, Options{Progress: progress, DryRun: dryRun})
tempdir := rtest.TempDir(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
progress.Finish()
rtest.Equals(t, restoreui.State{
FilesFinished: 4,
FilesTotal: 4,
FilesSkipped: 0,
AllBytesWritten: 10,
AllBytesTotal: 10,
AllBytesSkipped: 0,
}, mock.s)
}
func TestRestorePermissions(t *testing.T) {
snapshot := Snapshot{
Nodes: map[string]Node{
"foo": File{Data: "content: foo\n", Mode: 0o600, ModTime: time.Now()},
},
}
repo := repository.TestRepository(t)
tempdir := filepath.Join(rtest.TempDir(t), "target")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sn, id := saveSnapshot(t, repo, snapshot, noopGetGenericAttributes)
t.Logf("snapshot saved as %v", id.Str())
res := NewRestorer(repo, sn, Options{})
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
for _, overwrite := range []OverwriteBehavior{OverwriteIfChanged, OverwriteAlways} {
// tamper with permissions
path := filepath.Join(tempdir, "foo")
rtest.OK(t, os.Chmod(path, 0o700))
res = NewRestorer(repo, sn, Options{Overwrite: overwrite})
_, err := res.RestoreTo(ctx, tempdir)
rtest.OK(t, err)
fi, err := os.Stat(path)
rtest.OK(t, err)
rtest.Equals(t, fs.FileMode(0o600), fi.Mode().Perm(), "unexpected permissions")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/hardlinks_index.go | internal/restorer/hardlinks_index.go | package restorer
import (
"sync"
)
// HardlinkKey is a composed key for finding inodes on a specific device.
type HardlinkKey struct {
Inode, Device uint64
}
// HardlinkIndex contains a list of inodes, devices these inodes are one, and associated file names.
type HardlinkIndex[T any] struct {
m sync.Mutex
Index map[HardlinkKey]T
}
// NewHardlinkIndex create a new index for hard links
func NewHardlinkIndex[T any]() *HardlinkIndex[T] {
return &HardlinkIndex[T]{
Index: make(map[HardlinkKey]T),
}
}
// Has checks whether the link already exist in the index.
func (idx *HardlinkIndex[T]) Has(inode uint64, device uint64) bool {
idx.m.Lock()
defer idx.m.Unlock()
_, ok := idx.Index[HardlinkKey{inode, device}]
return ok
}
// Add adds a link to the index.
func (idx *HardlinkIndex[T]) Add(inode uint64, device uint64, value T) {
idx.m.Lock()
defer idx.m.Unlock()
_, ok := idx.Index[HardlinkKey{inode, device}]
if !ok {
idx.Index[HardlinkKey{inode, device}] = value
}
}
// Value obtains the filename from the index.
func (idx *HardlinkIndex[T]) Value(inode uint64, device uint64) T {
idx.m.Lock()
defer idx.m.Unlock()
return idx.Index[HardlinkKey{inode, device}]
}
// Remove removes a link from the index.
func (idx *HardlinkIndex[T]) Remove(inode uint64, device uint64) {
idx.m.Lock()
defer idx.m.Unlock()
delete(idx.Index, HardlinkKey{inode, device})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/filerestorer_test.go | internal/restorer/filerestorer_test.go | package restorer
import (
"bytes"
"context"
"fmt"
"os"
"sort"
"testing"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/feature"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
type TestBlob struct {
data string
pack string
}
type TestFile struct {
name string
blobs []TestBlob
}
type TestWarmupJob struct {
handlesCount int
waitCalled bool
}
type TestRepo struct {
packsIDToData map[restic.ID][]byte
// blobs and files
blobs map[restic.ID][]restic.PackedBlob
files []*fileInfo
filesPathToContent map[string]string
warmupJobs []*TestWarmupJob
//
loader blobsLoaderFn
}
func (i *TestRepo) Lookup(_ restic.BlobType, id restic.ID) []restic.PackedBlob {
packs := i.blobs[id]
return packs
}
func (i *TestRepo) fileContent(file *fileInfo) string {
return i.filesPathToContent[file.location]
}
func (i *TestRepo) StartWarmup(_ context.Context, packs restic.IDSet) (restic.WarmupJob, error) {
job := TestWarmupJob{handlesCount: len(packs)}
i.warmupJobs = append(i.warmupJobs, &job)
return &job, nil
}
func (job *TestWarmupJob) HandleCount() int {
return job.handlesCount
}
func (job *TestWarmupJob) Wait(_ context.Context) error {
job.waitCalled = true
return nil
}
func newTestRepo(content []TestFile) *TestRepo {
type Pack struct {
name string
data []byte
blobs map[restic.ID]restic.Blob
}
packs := make(map[string]Pack)
filesPathToContent := make(map[string]string)
for _, file := range content {
var content string
for _, blob := range file.blobs {
content += blob.data
// get the pack, create as necessary
var pack Pack
var found bool
if pack, found = packs[blob.pack]; !found {
pack = Pack{name: blob.pack, blobs: make(map[restic.ID]restic.Blob)}
}
// calculate blob id and add to the pack as necessary
blobID := restic.Hash([]byte(blob.data))
if _, found := pack.blobs[blobID]; !found {
blobData := []byte(blob.data)
pack.blobs[blobID] = restic.Blob{
BlobHandle: restic.BlobHandle{
Type: restic.DataBlob,
ID: blobID,
},
Length: uint(len(blobData)),
UncompressedLength: uint(len(blobData)),
Offset: uint(len(pack.data)),
}
pack.data = append(pack.data, blobData...)
}
packs[blob.pack] = pack
}
filesPathToContent[file.name] = content
}
blobs := make(map[restic.ID][]restic.PackedBlob)
packsIDToData := make(map[restic.ID][]byte)
for _, pack := range packs {
packID := restic.Hash(pack.data)
packsIDToData[packID] = pack.data
for blobID, blob := range pack.blobs {
blobs[blobID] = append(blobs[blobID], restic.PackedBlob{Blob: blob, PackID: packID})
}
}
var files []*fileInfo
for _, file := range content {
content := restic.IDs{}
for _, blob := range file.blobs {
content = append(content, restic.Hash([]byte(blob.data)))
}
files = append(files, &fileInfo{location: file.name, blobs: content})
}
repo := &TestRepo{
packsIDToData: packsIDToData,
blobs: blobs,
files: files,
filesPathToContent: filesPathToContent,
warmupJobs: []*TestWarmupJob{},
}
repo.loader = func(ctx context.Context, packID restic.ID, blobs []restic.Blob, handleBlobFn func(blob restic.BlobHandle, buf []byte, err error) error) error {
blobs = append([]restic.Blob{}, blobs...)
sort.Slice(blobs, func(i, j int) bool {
return blobs[i].Offset < blobs[j].Offset
})
for _, blob := range blobs {
found := false
for _, e := range repo.blobs[blob.ID] {
if packID == e.PackID {
found = true
buf := repo.packsIDToData[packID][e.Offset : e.Offset+e.Length]
err := handleBlobFn(e.BlobHandle, buf, nil)
if err != nil {
return err
}
}
}
if !found {
return fmt.Errorf("missing blob: %v", blob)
}
}
return nil
}
return repo
}
func restoreAndVerify(t *testing.T, tempdir string, content []TestFile, files map[string]bool, sparse bool) {
defer feature.TestSetFlag(t, feature.Flag, feature.S3Restore, true)()
t.Helper()
repo := newTestRepo(content)
r := newFileRestorer(tempdir, repo.loader, repo.Lookup, 2, sparse, false, repo.StartWarmup, nil)
if files == nil {
r.files = repo.files
} else {
for _, file := range repo.files {
if files[file.location] {
r.files = append(r.files, file)
}
}
}
err := r.restoreFiles(context.TODO())
rtest.OK(t, err)
verifyRestore(t, r, repo)
}
func verifyRestore(t *testing.T, r *fileRestorer, repo *TestRepo) {
t.Helper()
for _, file := range r.files {
target := r.targetPath(file.location)
data, err := os.ReadFile(target)
if err != nil {
t.Errorf("unable to read file %v: %v", file.location, err)
continue
}
content := repo.fileContent(file)
if !bytes.Equal(data, []byte(content)) {
t.Errorf("file %v has wrong content: want %q, got %q", file.location, content, data)
}
}
if len(repo.warmupJobs) == 0 {
t.Errorf("warmup did not occur")
}
for i, warmupJob := range repo.warmupJobs {
if !warmupJob.waitCalled {
t.Errorf("warmup job %d was not waited", i)
}
}
}
func TestFileRestorerBasic(t *testing.T) {
tempdir := rtest.TempDir(t)
for _, sparse := range []bool{false, true} {
restoreAndVerify(t, tempdir, []TestFile{
{
name: "file1",
blobs: []TestBlob{
{"data1-1", "pack1-1"},
{"data1-2", "pack1-2"},
},
},
{
name: "file2",
blobs: []TestBlob{
{"data2-1", "pack2-1"},
{"data2-2", "pack2-2"},
},
},
{
name: "file3",
blobs: []TestBlob{
// same blob multiple times
{"data3-1", "pack3-1"},
{"data3-1", "pack3-1"},
},
},
{
name: "empty",
blobs: []TestBlob{},
},
}, nil, sparse)
}
}
func TestFileRestorerPackSkip(t *testing.T) {
tempdir := rtest.TempDir(t)
files := make(map[string]bool)
files["file2"] = true
for _, sparse := range []bool{false, true} {
restoreAndVerify(t, tempdir, []TestFile{
{
name: "file1",
blobs: []TestBlob{
{"data1-1", "pack1"},
{"data1-2", "pack1"},
{"data1-3", "pack1"},
{"data1-4", "pack1"},
{"data1-5", "pack1"},
{"data1-6", "pack1"},
},
},
{
name: "file2",
blobs: []TestBlob{
// file is contained in pack1 but need pack parts to be skipped
{"data1-2", "pack1"},
{"data1-4", "pack1"},
{"data1-6", "pack1"},
},
},
}, files, sparse)
}
}
func TestFileRestorerFrequentBlob(t *testing.T) {
tempdir := rtest.TempDir(t)
for _, sparse := range []bool{false, true} {
blobs := []TestBlob{
{"data1-1", "pack1-1"},
}
for i := 0; i < 10000; i++ {
blobs = append(blobs, TestBlob{"a", "pack1-1"})
}
blobs = append(blobs, TestBlob{"end", "pack1-1"})
restoreAndVerify(t, tempdir, []TestFile{
{
name: "file1",
blobs: blobs,
},
}, nil, sparse)
}
}
func TestErrorRestoreFiles(t *testing.T) {
tempdir := rtest.TempDir(t)
content := []TestFile{
{
name: "file1",
blobs: []TestBlob{
{"data1-1", "pack1-1"},
},
}}
repo := newTestRepo(content)
loadError := errors.New("load error")
// loader always returns an error
repo.loader = func(ctx context.Context, packID restic.ID, blobs []restic.Blob, handleBlobFn func(blob restic.BlobHandle, buf []byte, err error) error) error {
return loadError
}
r := newFileRestorer(tempdir, repo.loader, repo.Lookup, 2, false, false, repo.StartWarmup, nil)
r.files = repo.files
err := r.restoreFiles(context.TODO())
rtest.Assert(t, errors.Is(err, loadError), "got %v, expected contained error %v", err, loadError)
}
func TestFatalDownloadError(t *testing.T) {
tempdir := rtest.TempDir(t)
content := []TestFile{
{
name: "file1",
blobs: []TestBlob{
{"data1-1", "pack1"},
{"data1-2", "pack1"},
},
},
{
name: "file2",
blobs: []TestBlob{
{"data2-1", "pack1"},
{"data2-2", "pack1"},
{"data2-3", "pack1"},
},
}}
repo := newTestRepo(content)
loader := repo.loader
repo.loader = func(ctx context.Context, packID restic.ID, blobs []restic.Blob, handleBlobFn func(blob restic.BlobHandle, buf []byte, err error) error) error {
ctr := 0
return loader(ctx, packID, blobs, func(blob restic.BlobHandle, buf []byte, err error) error {
if ctr < 2 {
ctr++
return handleBlobFn(blob, buf, err)
}
// break file2
return errors.New("failed to load blob")
})
}
r := newFileRestorer(tempdir, repo.loader, repo.Lookup, 2, false, false, repo.StartWarmup, nil)
r.files = repo.files
var errors []string
r.Error = func(s string, e error) error {
// ignore errors as in the `restore` command
errors = append(errors, s)
return nil
}
err := r.restoreFiles(context.TODO())
rtest.OK(t, err)
rtest.Assert(t, len(errors) == 1, "unexpected number of restore errors, expected: 1, got: %v", len(errors))
rtest.Assert(t, errors[0] == "file2", "expected error for file2, got: %v", errors[0])
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/restorer/fileswriter_test.go | internal/restorer/fileswriter_test.go | package restorer
import (
"fmt"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/restic/restic/internal/errors"
rtest "github.com/restic/restic/internal/test"
)
func TestFilesWriterBasic(t *testing.T) {
dir := rtest.TempDir(t)
w := newFilesWriter(1, false)
f1 := dir + "/f1"
f2 := dir + "/f2"
rtest.OK(t, w.writeToFile(f1, []byte{1}, 0, 2, false))
rtest.Equals(t, 0, len(w.buckets[0].files))
rtest.OK(t, w.writeToFile(f2, []byte{2}, 0, 2, false))
rtest.Equals(t, 0, len(w.buckets[0].files))
rtest.OK(t, w.writeToFile(f1, []byte{1}, 1, -1, false))
rtest.Equals(t, 0, len(w.buckets[0].files))
rtest.OK(t, w.writeToFile(f2, []byte{2}, 1, -1, false))
rtest.Equals(t, 0, len(w.buckets[0].files))
buf, err := os.ReadFile(f1)
rtest.OK(t, err)
rtest.Equals(t, []byte{1, 1}, buf)
buf, err = os.ReadFile(f2)
rtest.OK(t, err)
rtest.Equals(t, []byte{2, 2}, buf)
}
func TestFilesWriterRecursiveOverwrite(t *testing.T) {
path := filepath.Join(t.TempDir(), "test")
// create filled directory
rtest.OK(t, os.Mkdir(path, 0o700))
rtest.OK(t, os.WriteFile(filepath.Join(path, "file"), []byte("data"), 0o400))
// must error if recursive delete is not allowed
w := newFilesWriter(1, false)
err := w.writeToFile(path, []byte{1}, 0, 2, false)
rtest.Assert(t, errors.Is(err, notEmptyDirError()), "unexpected error got %v", err)
rtest.Equals(t, 0, len(w.buckets[0].files))
// must replace directory
w = newFilesWriter(1, true)
rtest.OK(t, w.writeToFile(path, []byte{1, 1}, 0, 2, false))
rtest.Equals(t, 0, len(w.buckets[0].files))
buf, err := os.ReadFile(path)
rtest.OK(t, err)
rtest.Equals(t, []byte{1, 1}, buf)
}
func TestCreateFile(t *testing.T) {
basepath := filepath.Join(t.TempDir(), "test")
scenarios := []struct {
name string
create func(t testing.TB, path string)
check func(t testing.TB, path string)
err error
}{
{
name: "file",
create: func(t testing.TB, path string) {
rtest.OK(t, os.WriteFile(path, []byte("test-test-test-data"), 0o400))
},
},
{
name: "empty dir",
create: func(t testing.TB, path string) {
rtest.OK(t, os.Mkdir(path, 0o400))
},
},
{
name: "symlink",
create: func(t testing.TB, path string) {
rtest.OK(t, os.Symlink("./something", path))
},
},
{
name: "filled dir",
create: func(t testing.TB, path string) {
rtest.OK(t, os.Mkdir(path, 0o700))
rtest.OK(t, os.WriteFile(filepath.Join(path, "file"), []byte("data"), 0o400))
},
err: notEmptyDirError(),
},
{
name: "hardlinks",
create: func(t testing.TB, path string) {
rtest.OK(t, os.WriteFile(path, []byte("test-test-test-data"), 0o400))
rtest.OK(t, os.Link(path, path+"h"))
},
check: func(t testing.TB, path string) {
if runtime.GOOS == "windows" {
// hardlinks are not supported on windows
return
}
data, err := os.ReadFile(path + "h")
rtest.OK(t, err)
rtest.Equals(t, "test-test-test-data", string(data), "unexpected content change")
},
},
}
tests := []struct {
size int64
isSparse bool
}{
{5, false},
{21, false},
{100, false},
{5, true},
{21, true},
{100, true},
}
for i, sc := range scenarios {
t.Run(sc.name, func(t *testing.T) {
for j, test := range tests {
path := basepath + fmt.Sprintf("%v%v", i, j)
sc.create(t, path)
f, err := createFile(path, test.size, test.isSparse, false)
if sc.err == nil {
rtest.OK(t, err)
fi, err := f.Stat()
rtest.OK(t, err)
rtest.Assert(t, fi.Mode().IsRegular(), "wrong filetype %v", fi.Mode())
rtest.Assert(t, fi.Size() <= test.size, "unexpected file size expected %v, got %v", test.size, fi.Size())
rtest.OK(t, f.Close())
if sc.check != nil {
sc.check(t, path)
}
} else {
rtest.Assert(t, errors.Is(err, sc.err), "unexpected error got %v expected %v", err, sc.err)
}
rtest.OK(t, os.RemoveAll(path))
}
})
}
}
func TestCreateFileRecursiveDelete(t *testing.T) {
path := filepath.Join(t.TempDir(), "test")
// create filled directory
rtest.OK(t, os.Mkdir(path, 0o700))
rtest.OK(t, os.WriteFile(filepath.Join(path, "file"), []byte("data"), 0o400))
// replace it
f, err := createFile(path, 42, false, true)
rtest.OK(t, err)
fi, err := f.Stat()
rtest.OK(t, err)
rtest.Assert(t, fi.Mode().IsRegular(), "wrong filetype %v", fi.Mode())
rtest.OK(t, f.Close())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.