From 76925aeb636fde9f385abc7ffa8069ad0c08d823 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 13:45:14 +0100 Subject: [PATCH] always quote paths in error messages --- cmd/restic/cmd_backup.go | 2 +- cmd/restic/cmd_mount.go | 14 +++++------ internal/archiver/archiver.go | 10 ++++---- internal/archiver/exclude.go | 4 +-- internal/archiver/file_saver.go | 2 +- internal/archiver/tree.go | 2 +- internal/data/tree.go | 10 ++++---- internal/data/tree_test.go | 10 +++++--- internal/dump/tar_test.go | 2 +- internal/dump/zip_test.go | 2 +- internal/fs/file.go | 2 +- internal/fs/fs_local_vss.go | 6 ++--- internal/fs/fs_local_vss_test.go | 21 ++++++---------- internal/fs/node_test.go | 4 +-- internal/fs/node_windows.go | 34 +++++++++++++------------- internal/fs/node_windows_test.go | 28 ++++++++++----------- internal/fs/node_xattr.go | 2 +- internal/fs/priv_windows_test.go | 8 +++--- internal/fs/sd_windows_test.go | 6 ++--- internal/fs/sd_windows_test_helpers.go | 28 ++++++++++----------- internal/fs/stat_darwin.go | 2 +- internal/fs/stat_darwin_test.go | 2 +- internal/fs/stat_windows.go | 2 +- internal/fs/vss_windows.go | 6 ++--- internal/global/global.go | 18 +++++++------- internal/global/global_test.go | 3 ++- internal/repository/upgrade_repo.go | 2 +- internal/restorer/restorer.go | 10 ++++---- internal/restorer/restorer_test.go | 10 ++++---- internal/walker/walker.go | 2 +- 30 files changed, 126 insertions(+), 128 deletions(-) diff --git a/cmd/restic/cmd_backup.go b/cmd/restic/cmd_backup.go index 35e2ec5be..1101f9c70 100644 --- a/cmd/restic/cmd_backup.go +++ b/cmd/restic/cmd_backup.go @@ -424,7 +424,7 @@ func collectTargets(opts BackupOptions, args []string, warnf func(msg string, ar var expanded []string expanded, err := filepath.Glob(line) if err != nil { - return nil, fmt.Errorf("pattern: %s: %w", line, err) + return nil, fmt.Errorf("pattern: %q: %w", line, err) } if len(expanded) == 0 { warnf("pattern %q does not match any files, skipping\n", line) diff --git a/cmd/restic/cmd_mount.go b/cmd/restic/cmd_mount.go index e761f2254..eed2a7b1a 100644 --- a/cmd/restic/cmd_mount.go +++ b/cmd/restic/cmd_mount.go @@ -227,16 +227,16 @@ func validateMountpoint(mountpoint string, gopts global.Options) error { // prevent unnecessary computations while opening the repository. stat, err := os.Stat(mountpoint) if errors.Is(err, os.ErrNotExist) { - return errors.Fatal(fmt.Sprintf("mountpoint %s does not exist", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q does not exist", mountpoint)) } else if err != nil { - return errors.Fatal(fmt.Sprintf("mountpoint %s is inaccessible: %v", mountpoint, err)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is inaccessible: %v", mountpoint, err)) } else if !stat.IsDir() { - return errors.Fatal(fmt.Sprintf("mountpoint %s is not a directory", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is not a directory", mountpoint)) } err = unix.Access(mountpoint, unix.W_OK|unix.X_OK) if err != nil { - return errors.Fatal(fmt.Sprintf("mountpoint %s is not writeable or not executable", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is not writeable or not executable", mountpoint)) } // Refuse to mount onto (or under, or over) the local repository directory. @@ -271,11 +271,11 @@ func checkMountpointOverlap(repoPath, mountpoint string) error { const tail = "; refusing to mount to avoid deadlocking the FUSE server" switch { case rp == mp: - return errors.Fatal(fmt.Sprintf("mountpoint %s is the local repository directory%s", mp, tail)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is the local repository directory%s", mp, tail)) case fs.HasPathPrefix(rp, mp): - return errors.Fatal(fmt.Sprintf("mountpoint %s is inside the local repository directory %s%s", mp, rp, tail)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is inside the local repository directory %q%s", mp, rp, tail)) case fs.HasPathPrefix(mp, rp): - return errors.Fatal(fmt.Sprintf("local repository directory %s is inside the mountpoint %s%s", rp, mp, tail)) + return errors.Fatal(fmt.Sprintf("local repository directory %q is inside the mountpoint %q%s", rp, mp, tail)) } return nil } diff --git a/internal/archiver/archiver.go b/internal/archiver/archiver.go index 1aec70785..4d2292ed4 100644 --- a/internal/archiver/archiver.go +++ b/internal/archiver/archiver.go @@ -272,7 +272,7 @@ func (arch *Archiver) nodeFromFileInfo(snPath, filename string, meta toNoder, ig node.Name = path.Base(snPath) // do not filter error for nodes of irregular or invalid type if node.Type != data.NodeTypeIrregular && node.Type != data.NodeTypeInvalid && err != nil { - err = fmt.Errorf("incomplete metadata for %v: %w", filename, err) + err = fmt.Errorf("incomplete metadata for %q: %w", filename, err) return node, arch.error(filename, err) } return node, err @@ -383,7 +383,7 @@ func (arch *Archiver) dirToNodeAndEntries(snPath, dir string, meta fs.File) (nod names, err = meta.Readdirnames(-1) if err != nil { - return nil, nil, fmt.Errorf("readdirnames %v failed: %w", dir, err) + return nil, nil, fmt.Errorf("readdirnames %q failed: %w", dir, err) } sort.Strings(names) @@ -547,7 +547,7 @@ func (arch *Archiver) save(ctx context.Context, snPath, target string, previous debug.Log("%v hasn't changed, but contents are missing!", target) // There are contents missing - inform user! - err := errors.Errorf("parts of %v not found in the repository index; storing the file again", target) + err := errors.Errorf("parts of %q not found in the repository index; storing the file again", target) err = arch.error(abstarget, err) if err != nil { return futureNode{}, false, err @@ -670,7 +670,7 @@ func (arch *Archiver) saveTree(ctx context.Context, snPath string, atree *tree, var node *data.Node if snPath != "/" { if atree.FileInfoPath == "" { - return futureNode{}, 0, errors.Errorf("FileInfoPath for %v is empty", snPath) + return futureNode{}, 0, errors.Errorf("FileInfoPath for %q is empty", snPath) } var err error @@ -780,7 +780,7 @@ func (arch *Archiver) dirPathToNode(snPath, target string) (node *data.Node, err return nil, err } if node.Type != data.NodeTypeDir { - return nil, errors.Errorf("path is not a directory: %v", target) + return nil, errors.Errorf("path is not a directory: %q", target) } return node, err } diff --git a/internal/archiver/exclude.go b/internal/archiver/exclude.go index 571680929..c6ec039af 100644 --- a/internal/archiver/exclude.go +++ b/internal/archiver/exclude.go @@ -242,7 +242,7 @@ func (m deviceMap) IsAllowed(item string, deviceID uint64, fs fs.FS) (bool, erro return true, nil } - return false, fmt.Errorf("item %v (device ID %v) not found, deviceMap: %v", item, deviceID, m) + return false, fmt.Errorf("item %q (device ID %v) not found, deviceMap: %v", item, deviceID, m) } // RejectByDevice returns a RejectFunc that rejects files which are on a @@ -322,7 +322,7 @@ func RejectCloudFiles(warnf func(msg string, args ...any)) (RejectFunc, error) { return func(item string, fi *fs.ExtendedFileInfo, _ fs.FS) bool { recall, err := fi.RecallOnDataAccess() if err != nil { - warnf("item %v: error checking online-only status: %v", item, err) + warnf("item %q: error checking online-only status: %v", item, err) return false } diff --git a/internal/archiver/file_saver.go b/internal/archiver/file_saver.go index ab6a9b32f..a5526534b 100644 --- a/internal/archiver/file_saver.go +++ b/internal/archiver/file_saver.go @@ -193,7 +193,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt panic("completed twice") } isCompleted = true - fnr.err = fmt.Errorf("failed to save %v: %w", target, err) + fnr.err = fmt.Errorf("failed to save %q: %w", target, err) fnr.node = nil fnr.stats = ItemStats{} finish(fnr) diff --git a/internal/archiver/tree.go b/internal/archiver/tree.go index 9e760752b..2303e9c53 100644 --- a/internal/archiver/tree.go +++ b/internal/archiver/tree.go @@ -175,7 +175,7 @@ func (t *tree) add(fs fs.FS, target, root string, pc []string, explicit bool) er } if node.Path != "" { - return errors.Errorf("path is already set for target %v", target) + return errors.Errorf("path is already set for target %q", target) } node.Path = target node.Explicit = explicit diff --git a/internal/data/tree.go b/internal/data/tree.go index 1c9e76a19..45c3400e9 100644 --- a/internal/data/tree.go +++ b/internal/data/tree.go @@ -341,22 +341,22 @@ func FindTreeDirectory(ctx context.Context, repo restic.BlobLoader, id *restic.I subfolder = path.Join(subfolder, name) tree, err := LoadTree(ctx, repo, *id) if err != nil { - return nil, fmt.Errorf("path %s: %w", subfolder, err) + return nil, fmt.Errorf("path %q: %w", subfolder, err) } finder := NewTreeFinder(tree) node, err := finder.Find(name) finder.Close() if err != nil { - return nil, fmt.Errorf("path %s: %w", subfolder, err) + return nil, fmt.Errorf("path %q: %w", subfolder, err) } if node == nil { if runtime.GOOS == "windows" && strings.Contains(dir, "\\") { - return nil, fmt.Errorf("path %s: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder) + return nil, fmt.Errorf("path %q: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder) } - return nil, fmt.Errorf("path %s: not found", subfolder) + return nil, fmt.Errorf("path %q: not found", subfolder) } if node.Type != NodeTypeDir || node.Subtree == nil { - return nil, fmt.Errorf("path %s: not a directory", subfolder) + return nil, fmt.Errorf("path %q: not a directory", subfolder) } id = node.Subtree } diff --git a/internal/data/tree_test.go b/internal/data/tree_test.go index e0e1be9aa..337f4eedc 100644 --- a/internal/data/tree_test.go +++ b/internal/data/tree_test.go @@ -471,8 +471,8 @@ func TestFindTreeDirectory(t *testing.T) { {"", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, {"/", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, {".", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, - {"..", restic.ID{}, errors.New("path ..: not found")}, - {"file-1", restic.ID{}, errors.New("path file-1: not a directory")}, + {"..", restic.ID{}, errors.New(`path "..": not found`)}, + {"file-1", restic.ID{}, errors.New(`path "file-1": not a directory`)}, {"dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, {"/dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, {"dir-7/", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, @@ -491,6 +491,10 @@ func TestFindTreeDirectory(t *testing.T) { _, err := data.FindTreeDirectory(context.TODO(), repo, nil, "") rtest.Assert(t, err != nil, "missing error on null tree id") + + _, err = data.FindTreeDirectory(context.TODO(), repo, sn.Tree, "a\nb") + rtest.Assert(t, err != nil && strings.Contains(err.Error(), strconv.Quote("a\nb")), + "hostile path was not quoted: %v", err) } func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) { @@ -504,7 +508,7 @@ func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) { rtest.Assert(t, strings.Contains(err.Error(), "forward slashes"), "expected backslash hint on Windows, got %v", err) } else { - rtest.Assert(t, err.Error() == `path missing\path: not found`, + rtest.Assert(t, err.Error() == `path "missing\\path": not found`, "unexpected err: %v", err) } } diff --git a/internal/dump/tar_test.go b/internal/dump/tar_test.go index 06e49c828..dd164028d 100644 --- a/internal/dump/tar_test.go +++ b/internal/dump/tar_test.go @@ -87,7 +87,7 @@ func checkTar(t *testing.T, testDir string, srcTar *bytes.Buffer) error { return err } if target != hdr.Linkname { - return fmt.Errorf("symlink target does not match, got %s want %s", target, hdr.Linkname) + return fmt.Errorf("symlink target does not match, got %q want %q", target, hdr.Linkname) } default: if match.Size() != hdr.Size { diff --git a/internal/dump/zip_test.go b/internal/dump/zip_test.go index c6eb04206..64c85568f 100644 --- a/internal/dump/zip_test.go +++ b/internal/dump/zip_test.go @@ -98,7 +98,7 @@ func checkZip(t *testing.T, testDir string, srcZip *bytes.Buffer) error { t.Fatal(err) } if target != string(linkName) { - return fmt.Errorf("symlink target does not match, got %s want %s", string(linkName), target) + return fmt.Errorf("symlink target does not match, got %q want %q", string(linkName), target) } default: if f.Method != zip.Deflate { diff --git a/internal/fs/file.go b/internal/fs/file.go index 21ba4244a..509664a78 100644 --- a/internal/fs/file.go +++ b/internal/fs/file.go @@ -75,7 +75,7 @@ func Readdirnames(filesystem FS, dir string, flags int) ([]string, error) { entries, err := f.Readdirnames(-1) if err != nil { _ = f.Close() - return nil, fmt.Errorf("readdirnames %v failed: %w", dir, err) + return nil, fmt.Errorf("readdirnames %q failed: %w", dir, err) } err = f.Close() diff --git a/internal/fs/fs_local_vss.go b/internal/fs/fs_local_vss.go index e0b04ac8f..c4462ea4f 100644 --- a/internal/fs/fs_local_vss.go +++ b/internal/fs/fs_local_vss.go @@ -74,7 +74,7 @@ func parseMountPoints(list string, msgError ErrorHandler) (volumes map[string]st } for s := range strings.SplitSeq(list, ";") { if v, err := getVolumeNameForVolumeMountPoint(s); err != nil { - msgError(s, errors.Errorf("failed to parse vss.exclude-volumes [%s]: %s", s, err)) + msgError(s, errors.Errorf("failed to parse vss.exclude-volumes %q: %s", s, err)) } else { if volumes == nil { volumes = make(map[string]struct{}) @@ -137,7 +137,7 @@ func (fs *LocalVss) isMountPointIncluded(mountPoint string) bool { volume, err := getVolumeNameForVolumeMountPoint(mountPoint) if err != nil { - fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point [%s]: %s", mountPoint, err)) + fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point %q: %s", mountPoint, err)) return true } @@ -193,7 +193,7 @@ func (fs *LocalVss) snapshotPath(path string) string { } if snapshot, err := newVssSnapshot(fs.provider, vssVolume, fs.timeout, includeVolume, fs.msgError); err != nil { - fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for [%s]: %s", + fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for %q: %s", vssVolume, err)) fs.failedSnapshots[volumeNameLower] = struct{}{} } else { diff --git a/internal/fs/fs_local_vss_test.go b/internal/fs/fs_local_vss_test.go index 15536804e..7e7e3d936 100644 --- a/internal/fs/fs_local_vss_test.go +++ b/internal/fs/fs_local_vss_test.go @@ -24,14 +24,7 @@ func matchStrings(ptrs []string, strs []string) bool { } for i, p := range ptrs { - if p == "" { - return false - } - matched, err := regexp.MatchString(p, strs[i]) - if err != nil { - panic(err) - } - if !matched { + if p == "" || !strings.HasPrefix(strs[i], p) { return false } } @@ -180,12 +173,12 @@ func TestParseMountPoints(t *testing.T) { {``, true}, }, []string{ - `failed to parse vss\.exclude-volumes \[z:\\nonexistent\]:.*`, - `failed to parse vss\.exclude-volumes \[c:\\windows\\\]:.*`, - `failed to parse vss\.exclude-volumes \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`, - `failed to get volume from mount point \[c:\\windows\\\]:.*`, - `failed to get volume from mount point \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`, - `failed to get volume from mount point \[\]:.*`, + `failed to parse vss.exclude-volumes "z:\\nonexistent":`, + `failed to parse vss.exclude-volumes "c:\\windows\\":`, + `failed to parse vss.exclude-volumes "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`, + `failed to get volume from mount point "c:\\windows\\":`, + `failed to get volume from mount point "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`, + `failed to get volume from mount point "":`, }, }, } diff --git a/internal/fs/node_test.go b/internal/fs/node_test.go index 4f087635e..3792d3ed2 100644 --- a/internal/fs/node_test.go +++ b/internal/fs/node_test.go @@ -219,7 +219,7 @@ func TestNodeRestoreAt(t *testing.T) { } rtest.OK(t, NodeCreateAt(&test, nodePath)) // Restore metadata, restoring all xattrs - rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) }, + rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) }, func(_ string) bool { return true }, ownershipByName)) fs := NewLocal() @@ -296,7 +296,7 @@ func TestNodeRestoreMetadataError(t *testing.T) { nodePath := filepath.Join(tempdir, node.Name) // This will fail because the target file does not exist - err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) }, + err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) }, func(_ string) bool { return true }, false) rtest.Assert(t, errors.Is(err, os.ErrNotExist), "failed for an unexpected reason") } diff --git a/internal/fs/node_windows.go b/internal/fs/node_windows.go index 1d4c3f801..4f6d74442 100644 --- a/internal/fs/node_windows.go +++ b/internal/fs/node_windows.go @@ -115,7 +115,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for return nil } if err != nil { - return errors.Errorf("get EA failed while opening file handle for path %v, with: %v", path, err) + return errors.Errorf("get EA failed while opening file handle for path %q, with: %v", path, err) } defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call //Get the windows Extended Attributes using the file handle @@ -123,7 +123,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for extAtts, err = fgetEA(fileHandle) debug.Log("fillExtendedAttributes(%v) %v", path, extAtts) if err != nil { - return errors.Errorf("get EA failed for path %v, with: %v", path, err) + return errors.Errorf("get EA failed for path %q, with: %v", path, err) } if len(extAtts) == 0 { return nil @@ -157,7 +157,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend return nil } if err != nil { - return errors.Errorf("set EA failed while opening file handle for path %v, with: %v", path, err) + return errors.Errorf("set EA failed while opening file handle for path %q, with: %v", path, err) } defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call @@ -182,7 +182,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend } if err = fsetEA(fileHandle, eas); err != nil { - return errors.Errorf("set EA failed for path %v, with: %v", path, err) + return errors.Errorf("set EA failed for path %q, with: %v", path, err) } return nil } @@ -195,21 +195,21 @@ func nodeRestoreGenericAttributes(node *data.Node, path string, warn func(msg st var errs []error windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes) if err != nil { - return fmt.Errorf("error parsing generic attribute for: %s : %v", path, err) + return fmt.Errorf("error parsing generic attribute for: %q : %v", path, err) } if windowsAttributes.CreationTime != nil { if err := restoreCreationTime(path, windowsAttributes.CreationTime); err != nil { - errs = append(errs, fmt.Errorf("error restoring creation time for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring creation time for: %q : %v", path, err)) } } if windowsAttributes.FileAttributes != nil { if err := restoreFileAttributes(path, windowsAttributes.FileAttributes); err != nil { - errs = append(errs, fmt.Errorf("error restoring file attributes for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring file attributes for: %q : %v", path, err)) } } if windowsAttributes.SecurityDescriptor != nil { if err := setSecurityDescriptor(path, windowsAttributes.SecurityDescriptor); err != nil { - errs = append(errs, fmt.Errorf("error restoring security descriptor for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring security descriptor for: %q : %v", path, err)) } } @@ -272,24 +272,24 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er // The readonly and system flags will be set again at the end of this func if they are needed. err = ResetPermissions(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err) } err = clearSystem(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to clear system flag: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to clear system flag: %q : %v", path, err) } err = encryptFile(pathPointer) if err != nil { - return fmt.Errorf("failed retry to encrypt file: %s : %v", path, err) + return fmt.Errorf("failed retry to encrypt file: %q : %v", path, err) } } else { - return fmt.Errorf("failed to encrypt file: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: %q : %v", path, err) } } } else { existingAttrs, err := windows.GetFileAttributes(pathPointer) if err != nil { - return fmt.Errorf("failed to get file attributes for existing file: %s : %v", path, err) + return fmt.Errorf("failed to get file attributes for existing file: %q : %v", path, err) } if existingAttrs&windows.FILE_ATTRIBUTE_ENCRYPTED != 0 { // File should not be encrypted, but it's already encrypted. Decrypt it. @@ -300,18 +300,18 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er // The readonly and system flags will be set again after this func if they are needed. err = ResetPermissions(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err) } err = clearSystem(path) if err != nil { - return fmt.Errorf("failed to decrypt file: failed to clear system flag: %s : %v", path, err) + return fmt.Errorf("failed to decrypt file: failed to clear system flag: %q : %v", path, err) } err = decryptFile(pathPointer) if err != nil { - return fmt.Errorf("failed retry to decrypt file: %s : %v", path, err) + return fmt.Errorf("failed retry to decrypt file: %q : %v", path, err) } } else { - return fmt.Errorf("failed to decrypt file: %s : %v", path, err) + return fmt.Errorf("failed to decrypt file: %q : %v", path, err) } } } diff --git a/internal/fs/node_windows_test.go b/internal/fs/node_windows_test.go index 174c637bd..a7c5feaa7 100644 --- a/internal/fs/node_windows_test.go +++ b/internal/fs/node_windows_test.go @@ -33,10 +33,10 @@ func TestRestoreSecurityDescriptors(t *testing.T) { func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, fileType data.NodeType, fileName string) { // Decode the encoded string SD to get the security descriptor input in bytes. sdInputBytes, err := base64.StdEncoding.DecodeString(sd) - test.OK(t, errors.Wrapf(err, "Error decoding SD for: %s", fileName)) + test.OK(t, errors.Wrapf(err, "Error decoding SD for: %q", fileName)) // Wrap the security descriptor bytes in windows attributes and convert to generic attributes. genericAttributes, err := data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{CreationTime: nil, FileAttributes: nil, SecurityDescriptor: &sdInputBytes}) - test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %s", fileName)) + test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %q", fileName)) // Construct a Node with the generic attributes. expectedNode := getNode(fileName, fileType, genericAttributes) @@ -47,7 +47,7 @@ func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, file // Get the security descriptor for the test path after the restore. sdBytesFromRestoredPath, err := getSecurityDescriptor(testPath) - test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %q", testPath)) // Compare the input SD and the SD got from the restored file. compareSecurityDescriptors(t, testPath, sdInputBytes, *sdBytesFromRestoredPath) @@ -239,7 +239,7 @@ func getNode(name string, fileType data.NodeType, genericAttributes map[data.Gen func getWindowsAttr(t *testing.T, testPath string, node *data.Node) data.WindowsAttributes { windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes) - test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %q", testPath)) test.Assert(t, len(unknownAttribs) == 0, "Unknown attribs found: %s for: %s", unknownAttribs, testPath) return windowsAttributes } @@ -248,7 +248,7 @@ func TestRestoreCreationTime(t *testing.T) { t.Parallel() path := t.TempDir() fi, err := os.Lstat(path) - test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %s", path)) + test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %q", path)) attr := fi.Sys().(*syscall.Win32FileAttributeData) creationTimeAttribute := attr.CreationTime //Using the temp dir creation time as the test creation time for the test file and folder @@ -367,17 +367,17 @@ func runGenericAttributesTestForNodes(t *testing.T, expectedNodes []data.Node, t func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warningExpected bool) (string, *data.Node) { testPath := filepath.Join(tempDir, "001", testNode.Name) err := os.MkdirAll(filepath.Dir(testPath), testNode.Mode) - test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %q", testPath)) if testNode.Type == data.NodeTypeFile { testFile, err := os.Create(testPath) - test.OK(t, errors.Wrapf(err, "Failed to create test file: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create test file: %q", testPath)) testFile.Close() } else if testNode.Type == data.NodeTypeDir { err := os.Mkdir(testPath, testNode.Mode) - test.OK(t, errors.Wrapf(err, "Failed to create test directory: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create test directory: %q", testPath)) } err = NodeRestoreMetadata(testNode, testPath, func(msg string) { @@ -385,16 +385,16 @@ func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warnin test.Assert(t, warningExpected, "Warning triggered as expected: %s", msg) } else { // If warning is not expected, this code should not get triggered. - test.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", testPath, msg)) + test.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", testPath, msg)) } }, func(_ string) bool { return true }, false) - test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %q", testPath)) fs := NewLocal() meta, err := fs.OpenFile(testPath, O_NOFOLLOW, true) test.OK(t, err) nodeFromFileInfo, err := meta.ToNode(false, t.Logf) - test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %q", testPath)) test.OK(t, meta.Close()) return testPath, nodeFromFileInfo @@ -474,14 +474,14 @@ func TestRestoreExtendedAttributes(t *testing.T) { if node.Type == data.NodeTypeFile || node.Type == data.NodeTypeDir { handle, err = windows.CreateFile(utf16Path, windows.FILE_READ_EA, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) } - test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %q", testPath)) defer func() { err := windows.Close(handle) - test.OK(t, errors.Wrapf(err, "Error closing file for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error closing file for: %q", testPath)) }() extAttr, err := fgetEA(handle) - test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %q", testPath)) test.Equals(t, len(node.ExtendedAttributes), len(extAttr)) for _, expectedExtAttr := range node.ExtendedAttributes { diff --git a/internal/fs/node_xattr.go b/internal/fs/node_xattr.go index 71ecf92c1..016ec6e3a 100644 --- a/internal/fs/node_xattr.go +++ b/internal/fs/node_xattr.go @@ -109,7 +109,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, ignoreListError bo for _, attr := range xattrs { attrVal, err := getxattr(path, attr) if err != nil { - warnf("can not obtain extended attribute %v for %v: %v\n", attr, path, err) + warnf("can not obtain extended attribute %q for %q: %v\n", attr, path, err) continue } attr := data.ExtendedAttribute{ diff --git a/internal/fs/priv_windows_test.go b/internal/fs/priv_windows_test.go index 504cc678f..9ed5bc913 100644 --- a/internal/fs/priv_windows_test.go +++ b/internal/fs/priv_windows_test.go @@ -17,7 +17,7 @@ func TestBackupPrivilegeBypassACL(t *testing.T) { // Read-only Open/OpenFile should automatically use FILE_FLAG_BACKUP_SEMANTICS since Go v1.20. testfile, err := os.Open(testPath) - test.OK(t, errors.Wrapf(err, "failed to open file for reading: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to open file for reading: %q", testPath)) test.OK(t, testfile.Close()) } @@ -26,7 +26,7 @@ func TestRestorePrivilegeBypassACL(t *testing.T) { // Writable OpenFile needs explicit FILE_FLAG_BACKUP_SEMANTICS. testfile, err := os.OpenFile(testPath, os.O_WRONLY|windows.O_FILE_FLAG_BACKUP_SEMANTICS, 0) - test.OK(t, errors.Wrapf(err, "failed to open file for writing: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to open file for writing: %q", testPath)) test.OK(t, testfile.Close()) } @@ -43,7 +43,7 @@ func testGetRestrictedFilePath(t *testing.T) string { testPath := filepath.Join(tempDir, "testfile.txt") testfile, err := os.Create(testPath) - test.OK(t, errors.Wrapf(err, "failed to create temporary file: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to create temporary file: %q", testPath)) test.OK(t, testfile.Close()) // Set restricted permissions. @@ -53,7 +53,7 @@ func testGetRestrictedFilePath(t *testing.T) string { dacl, _, err := sd.DACL() test.OK(t, errors.Wrap(err, "failed to extract SD DACL")) err = windows.SetNamedSecurityInfo(testPath, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) - test.OK(t, errors.Wrapf(err, "failed to set SD: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to set SD: %q", testPath)) return testPath } diff --git a/internal/fs/sd_windows_test.go b/internal/fs/sd_windows_test.go index 56e5fde07..93efc5f96 100644 --- a/internal/fs/sd_windows_test.go +++ b/internal/fs/sd_windows_test.go @@ -45,14 +45,14 @@ func TestSetGetFolderSecurityDescriptors(t *testing.T) { func testSecurityDescriptors(t *testing.T, testSDs []string, testPath string) { for _, testSD := range testSDs { sdInputBytes, err := base64.StdEncoding.DecodeString(testSD) - test.OK(t, errors.Wrapf(err, "Error decoding SD: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error decoding SD: %q", testPath)) err = setSecurityDescriptor(testPath, &sdInputBytes) - test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %q", testPath)) var sdOutputBytes *[]byte sdOutputBytes, err = getSecurityDescriptor(testPath) - test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %q", testPath)) compareSecurityDescriptors(t, testPath, sdInputBytes, *sdOutputBytes) } diff --git a/internal/fs/sd_windows_test_helpers.go b/internal/fs/sd_windows_test_helpers.go index 14f3ead3a..2b9d259a1 100644 --- a/internal/fs/sd_windows_test_helpers.go +++ b/internal/fs/sd_windows_test_helpers.go @@ -42,13 +42,13 @@ func isAdmin() (isAdmin bool, err error) { // compareSecurityDescriptors runs tests for comparing 2 security descriptors in []byte format. func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdOutputBytes []byte) { sdInput, err := securityDescriptorBytesToStruct(sdInputBytes) - test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath)) sdOutput, err := securityDescriptorBytesToStruct(sdOutputBytes) - test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath)) isAdmin, err := isAdmin() - test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %q", testPath)) var ownerExpected *windows.SID var defaultedOwnerExpected bool @@ -61,28 +61,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO // The Dacl is set correctly whether or not application is running as admin. daclExpected, defaultedDaclExpected, err = sdInput.DACL() - test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %q", testPath)) if isAdmin { // If application is running as admin, all sd values including owner, group, dacl, sacl are set correctly during restore. // Hence we will use the input values for comparison with the output values. ownerExpected, defaultedOwnerExpected, err = sdInput.Owner() - test.OK(t, errors.Wrapf(err, "Error getting input owner for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input owner for: %q", testPath)) groupExpected, defaultedGroupExpected, err = sdInput.Group() - test.OK(t, errors.Wrapf(err, "Error getting input group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input group for: %q", testPath)) saclExpected, defaultedSaclExpected, err = sdInput.SACL() - test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %q", testPath)) } else { // If application is not running as admin, owner and group are set as current user's SID/GID during restore and sacl is empty. // Get the current user user, err := user.Current() - test.OK(t, errors.Wrapf(err, "Could not get current user for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Could not get current user for: %q", testPath)) // Get current user's SID currentUserSID, err := windows.StringToSid(user.Uid) - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Get current user's Group SID currentGroupSID, err := windows.StringToSid(user.Gid) - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Set owner and group as current user's SID and GID during restore. ownerExpected = currentUserSID @@ -97,28 +97,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO // Now do all the comparisons // Get owner SID from output file ownerOut, defaultedOwnerOut, err := sdOutput.Owner() - test.OK(t, errors.Wrapf(err, "Error getting output owner for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output owner for: %q", testPath)) // Compare owner SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs. test.Assert(t, ownerExpected.Equals(ownerOut), "Owner from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, ownerExpected.String(), ownerOut.String()) test.Equals(t, defaultedOwnerExpected, defaultedOwnerOut, "Defaulted for owner from SDs read from test path don't match: %s", testPath) // Get group SID from output file groupOut, defaultedGroupOut, err := sdOutput.Group() - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Compare group SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs. test.Assert(t, groupExpected.Equals(groupOut), "Group from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, groupExpected.String(), groupOut.String()) test.Equals(t, defaultedGroupExpected, defaultedGroupOut, "Defaulted for group from SDs read from test path don't match: %s", testPath) // Get dacl from output file daclOut, defaultedDaclOut, err := sdOutput.DACL() - test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %q", testPath)) // Compare dacls test.Equals(t, daclExpected, daclOut, "DACL from SDs read from test path don't match: %s", testPath) test.Equals(t, defaultedDaclExpected, defaultedDaclOut, "Defaulted for DACL from SDs read from test path don't match: %s", testPath) // Get sacl from output file saclOut, defaultedSaclOut, err := sdOutput.SACL() - test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %q", testPath)) // Compare sacls test.Equals(t, saclExpected, saclOut, "DACL from SDs read from test path don't match: %s", testPath) test.Equals(t, defaultedSaclExpected, defaultedSaclOut, "Defaulted for SACL from SDs read from test path don't match: %s", testPath) diff --git a/internal/fs/stat_darwin.go b/internal/fs/stat_darwin.go index ec94d9f8b..a9d07ee6b 100644 --- a/internal/fs/stat_darwin.go +++ b/internal/fs/stat_darwin.go @@ -44,7 +44,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo { func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) { extAttribute, ok := fi.sys.(*syscall.Stat_t) if !ok { - return false, fmt.Errorf("could not determine file attributes: %s", fi.Name) + return false, fmt.Errorf("could not determine file attributes: %q", fi.Name) } const mask uint32 = unix.SF_DATALESS // 0x40000000 if extAttribute.Flags&mask == mask { diff --git a/internal/fs/stat_darwin_test.go b/internal/fs/stat_darwin_test.go index c8768e29d..6d9cfc715 100644 --- a/internal/fs/stat_darwin_test.go +++ b/internal/fs/stat_darwin_test.go @@ -86,6 +86,6 @@ func TestRecallOnDataAccessMockError(t *testing.T) { recall, err := efi.RecallOnDataAccess() rtest.Assert(t, err != nil, "err should be set", err) - rtest.Assert(t, err.Error() == "could not determine file attributes: test-file-name", "err message not correct", err) + rtest.Assert(t, err.Error() == `could not determine file attributes: "test-file-name"`, "err message not correct", err) rtest.Assert(t, recall == false, "RecallOnDataAccess should be false") } diff --git a/internal/fs/stat_windows.go b/internal/fs/stat_windows.go index bc4092df8..2e06b864a 100644 --- a/internal/fs/stat_windows.go +++ b/internal/fs/stat_windows.go @@ -45,7 +45,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo { func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) { attrs, ok := fi.sys.(*syscall.Win32FileAttributeData) if !ok { - return false, fmt.Errorf("could not determine file attributes: %s", fi.Name) + return false, fmt.Errorf("could not determine file attributes: %q", fi.Name) } if attrs.FileAttributes&windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS > 0 { diff --git a/internal/fs/vss_windows.go b/internal/fs/vss_windows.go index 01ca86774..f6378f1b3 100644 --- a/internal/fs/vss_windows.go +++ b/internal/fs/vss_windows.go @@ -969,7 +969,7 @@ func newVssSnapshot(provider string, } else if !isSupported { iVssBackupComponents.Release() return vssSnapshot{}, newVssTextError(fmt.Sprintf("Snapshots are not supported for volume "+ - "%s", volume)) + "%q", volume)) } const retryStartSnapshotSetSleep = 5 * time.Second @@ -1005,7 +1005,7 @@ func newVssSnapshot(provider string, iVssBackupComponents.Release() return vssSnapshot{}, newVssTextError(fmt.Sprintf( - "failed to enumerate mount points for volume %s: %s", volume, err)) + "failed to enumerate mount points for volume %q: %s", volume, err)) } for _, mp := range mountPoints { @@ -1072,7 +1072,7 @@ func newVssSnapshot(provider string, &info.snapshotProperties) if err != nil { msgError(mountPoint, errors.Errorf( - "VSS error: GetSnapshotProperties() for mount point %s returned error: ", + "VSS error: GetSnapshotProperties() for mount point %q returned error: ", mountPoint, err)) info.isSnapshotted = false } else { diff --git a/internal/global/global.go b/internal/global/global.go index 547f7da9e..b46723a08 100644 --- a/internal/global/global.go +++ b/internal/global/global.go @@ -215,7 +215,7 @@ func resolvePassword(opts *Options, envStr string) (string, error) { func LoadPasswordFromFile(pwdFile string) (string, error) { s, err := textfile.Read(pwdFile) if errors.Is(err, os.ErrNotExist) { - return "", errors.Fatalf("%s does not exist", pwdFile) + return "", errors.Fatalf("%q does not exist", pwdFile) } return strings.TrimSpace(string(s)), errors.Wrap(err, "Readfile") } @@ -282,7 +282,7 @@ func readRepo(gopts Options) (string, error) { s, err := textfile.Read(gopts.RepositoryFile) if errors.Is(err, os.ErrNotExist) { - return "", errors.Fatalf("%s does not exist", gopts.RepositoryFile) + return "", errors.Fatalf("%q does not exist", gopts.RepositoryFile) } if err != nil { return "", err @@ -290,7 +290,7 @@ func readRepo(gopts Options) (string, error) { repo = strings.TrimSpace(string(s)) if repo == "" { - return "", errors.Fatalf("repository file %s is empty", gopts.RepositoryFile) + return "", errors.Fatalf("repository file %q is empty", gopts.RepositoryFile) } } @@ -344,10 +344,10 @@ func hasRepositoryConfig(ctx context.Context, be backend.Backend, repo string, g fi, err := be.Stat(ctx, backend.Handle{Type: backend.ConfigFile}) if be.IsNotExist(err) { //nolint:staticcheck // capitalized error string is intentional - return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%v", ErrNoRepository, err, location.StripPassword(gopts.Backends, repo)) + return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%q", ErrNoRepository, err, location.StripPassword(gopts.Backends, repo)) } if err != nil { - return errors.Fatalf("unable to open config file: %v\n%v", err, location.StripPassword(gopts.Backends, repo)) + return errors.Fatalf("unable to open config file: %v\n%q", err, location.StripPassword(gopts.Backends, repo)) } if fi.Size == 0 { @@ -479,7 +479,7 @@ func CreateRepository(ctx context.Context, gopts Options, version uint, chunkerP be, err := innerOpenBackend(ctx, repo, gopts, gopts.Extended, true, printer) if err != nil { - return nil, errors.Fatalf("create repository at %s failed: %v", location.StripPassword(gopts.Backends, repo), err) + return nil, errors.Fatalf("create repository at %q failed: %v", location.StripPassword(gopts.Backends, repo), err) } s, err := createRepositoryInstance(be, gopts) @@ -489,7 +489,7 @@ func CreateRepository(ctx context.Context, gopts Options, version uint, chunkerP err = s.Init(ctx, version, gopts.Password, chunkerPolynomial) if err != nil { - return nil, errors.Fatalf("create key in repository at %s failed: %v", location.StripPassword(gopts.Backends, repo), err) + return nil, errors.Fatalf("create key in repository at %q failed: %v", location.StripPassword(gopts.Backends, repo), err) } return s, nil @@ -574,14 +574,14 @@ func createOrOpenBackend(ctx context.Context, scheme string, cfg any, rt http.Ro if errors.Is(err, backend.ErrNoRepository) { //nolint:staticcheck // capitalized error string is intentional - return nil, fmt.Errorf("Fatal: %w at %v: %v", ErrNoRepository, location.StripPassword(gopts.Backends, s), err) + return nil, fmt.Errorf("Fatal: %w at %q: %v", ErrNoRepository, location.StripPassword(gopts.Backends, s), err) } if err != nil { if create { // init already wraps the error message return nil, err } - return nil, errors.Fatalf("unable to open repository at %v: %v", location.StripPassword(gopts.Backends, s), err) + return nil, errors.Fatalf("unable to open repository at %q: %v", location.StripPassword(gopts.Backends, s), err) } return be, nil diff --git a/internal/global/global_test.go b/internal/global/global_test.go index 62a5cecfb..3c172d7d5 100644 --- a/internal/global/global_test.go +++ b/internal/global/global_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "strconv" "strings" "testing" @@ -59,7 +60,7 @@ func TestReadRepoEmptyFile(t *testing.T) { repo, err := readRepo(Options{RepositoryFile: filename}) rtest.Assert(t, errors.IsFatal(err), "expected fatal error for empty repository file, got %v", err) rtest.Equals(t, "", repo) - rtest.Assert(t, strings.Contains(err.Error(), filename), "error should identify repository file, got %v", err) + rtest.Assert(t, strings.Contains(err.Error(), strconv.Quote(filename)), "error should identify repository file, got %v", err) }) } } diff --git a/internal/repository/upgrade_repo.go b/internal/repository/upgrade_repo.go index e2419e6eb..e52a77f76 100644 --- a/internal/repository/upgrade_repo.go +++ b/internal/repository/upgrade_repo.go @@ -74,7 +74,7 @@ func UpgradeRepo(ctx context.Context, repo *Repository, tempBaseDir string) erro backupFileName := filepath.Join(tempdir, "config") err = os.WriteFile(backupFileName, rawConfigFile, 0600) if err != nil { - return fmt.Errorf("write config file backup to %v failed: %w", tempdir, err) + return fmt.Errorf("write config file backup to %q failed: %w", tempdir, err) } // run the upgrade diff --git a/internal/restorer/restorer.go b/internal/restorer/restorer.go index 1c3482979..2fcee799e 100644 --- a/internal/restorer/restorer.go +++ b/internal/restorer/restorer.go @@ -202,7 +202,7 @@ func (res *Restorer) traverseTreeInner(ctx context.Context, target, location str nodeName := filepath.Base(filepath.Join(string(filepath.Separator), node.Name)) if nodeName != node.Name { debug.Log("node %q has invalid name %q", node.Name, nodeName) - err := res.sanitizeError(location, errors.Errorf("invalid child node name %s", node.Name)) + err := res.sanitizeError(location, errors.Errorf("invalid child node name %q", node.Name)) if err != nil { return nil, hasRestored, err } @@ -531,7 +531,7 @@ func (res *Restorer) removeUnexpectedFiles(ctx context.Context, target, location nodeLocation := filepath.Join(location, entry) if target == nodeTarget || !fs.HasPathPrefix(target, nodeTarget) { - return fmt.Errorf("skipping deletion due to invalid filename: %v", entry) + return fmt.Errorf("skipping deletion due to invalid filename: %q", entry) } // TODO pass a proper value to the isDir parameter once this becomes relevant for the filters @@ -743,10 +743,10 @@ func (res *Restorer) verifyFile(ctx context.Context, target string, node *data.N case err != nil: return nil, buf, err case !fi.Mode().IsRegular(): - return nil, buf, errors.Errorf("Expected %s to be a regular file", target) + return nil, buf, errors.Errorf("Expected %q to be a regular file", target) case int64(node.Size) != fi.Size(): if failFast { - return nil, buf, errors.Errorf("Invalid file size for %s: expected %d, got %d", + return nil, buf, errors.Errorf("Invalid file size for %q: expected %d, got %d", target, node.Size, fi.Size()) } sizeMatches = false @@ -783,7 +783,7 @@ func (res *Restorer) verifyFile(ctx context.Context, target string, node *data.N matches[i] = blobID.Equal(restic.Hash(buf)) if failFast && !matches[i] { return nil, buf, errors.Errorf( - "Unexpected content in %s, starting at offset %d", + "Unexpected content in %q, starting at offset %d", target, offset) } offset += int64(length) diff --git a/internal/restorer/restorer_test.go b/internal/restorer/restorer_test.go index 39ad6554a..117c41b1b 100644 --- a/internal/restorer/restorer_test.go +++ b/internal/restorer/restorer_test.go @@ -307,8 +307,8 @@ func TestRestorer(t *testing.T) { }, ErrorsMay: map[string]map[string]struct{}{ `/`: { - `invalid child node name ..\test`: struct{}{}, - `invalid child node name ..\..\foo\..\bar\..\xx\test2`: struct{}{}, + `invalid child node name "..\\test"`: struct{}{}, + `invalid child node name "..\\..\\foo\\..\\bar\\..\\xx\\test2"`: struct{}{}, }, }, }, @@ -321,8 +321,8 @@ func TestRestorer(t *testing.T) { }, ErrorsMay: map[string]map[string]struct{}{ `/`: { - `invalid child node name ../test`: struct{}{}, - `invalid child node name ../../foo/../bar/../xx/test2`: struct{}{}, + `invalid child node name "../test"`: struct{}{}, + `invalid child node name "../../foo/../bar/../xx/test2"`: struct{}{}, }, }, }, @@ -352,7 +352,7 @@ func TestRestorer(t *testing.T) { }, ErrorsMust: map[string]map[string]struct{}{ `/x`: { - `invalid child node name ..`: struct{}{}, + `invalid child node name ".."`: struct{}{}, }, }, }, diff --git a/internal/walker/walker.go b/internal/walker/walker.go index 0ff2f8ebb..b840a061b 100644 --- a/internal/walker/walker.go +++ b/internal/walker/walker.go @@ -100,7 +100,7 @@ func walk(ctx context.Context, repo restic.BlobLoader, prefix string, parentTree } if node.Subtree == nil { - return errors.Errorf("subtree for node %v in tree %v is nil", node.Name, p) + return errors.Errorf("subtree for node %q in tree %q is nil", node.Name, p) } subtree, err := data.LoadTree(ctx, repo, *node.Subtree)