always quote paths in error messages

This commit is contained in:
Michael Eischer committed 2026-11-28 20:27:06 +01:00
1 parent 2518cd4a75
commit 76925aeb63
30 files changed
+126 -128

No files matched your search

+1 -1
View File
@@ -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)
+7 -7
View File
@@ -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
}
+5 -5
View File
@@ -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
}
+2 -2
View File
@@ -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
}
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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
}
+7 -3
View File
@@ -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)
}
}
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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()
+3 -3
View File
@@ -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 {
+7 -14
View File
@@ -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 "":`,
},
},
}
+2 -2
View File
@@ -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")
}
+17 -17
View File
@@ -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)
}
}
}
+14 -14
View File
@@ -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 {
+1 -1
View File
@@ -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{
+4 -4
View File
@@ -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
}
+3 -3
View File
@@ -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)
}
+14 -14
View File
@@ -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)
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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")
}
+1 -1
View File
@@ -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 {
+3 -3
View File
@@ -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 {
+9 -9
View File
@@ -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
+2 -1
View File
@@ -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)
})
}
}
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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)
+5 -5
View File
@@ -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{}{},
},
},
},
+1 -1
View File
@@ -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)