quote paths in direct command output

This commit is contained in:
Michael Eischer committed 2026-11-28 18:18:59 +01:00
1 parent 0e50a959d5
commit 584ec23160
18 files changed
+110 -35

No files matched your search

+4 -4
View File
@@ -187,9 +187,9 @@ func filterExisting(items []string, warnf func(msg string, args ...any)) (result
_, err := fs.Lstat(item)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
warnf("%v does not exist, skipping\n", item)
warnf("%v does not exist, skipping\n", ui.Quote(item))
} else {
warnf("%v cannot be accessed, skipping\n", item)
warnf("%v cannot be accessed, skipping\n", ui.Quote(item))
}
continue
}
@@ -646,7 +646,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
sc.Result = progressReporter.ReportTotal
if !gopts.JSON {
printer.V("start scan on %v", targets)
printer.V("start scan on %v", ui.QuoteSlice(targets))
}
wg.Go(func() error { return sc.Scan(cancelCtx, targets) })
}
@@ -692,7 +692,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te
}
if !gopts.JSON {
printer.V("start backup on %v", targets)
printer.V("start backup on %v", ui.QuoteSlice(targets))
}
_, id, summary, err := arch.Snapshot(ctx, targets, snapshotOpts)
+5 -1
View File
@@ -97,6 +97,10 @@ func NewChange(path string, mode string) *Change {
return &Change{MessageType: "change", Path: path, Modifier: mode}
}
func printTextDiffChange(S func(string, ...any), change *Change) {
S("%-5s%v", change.Modifier, ui.Quote(change.Path))
}
// DiffStat collects stats for all types of items.
type DiffStat struct {
Files int `json:"files"`
@@ -412,7 +416,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args [
opts: opts,
printError: printer.E,
printChange: func(change *Change) {
printer.S("%-5s%v", change.Modifier, change.Path)
printTextDiffChange(printer.S, change)
},
}
+21
View File
@@ -0,0 +1,21 @@
package main
import (
"strconv"
"testing"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func TestPrintTextDiffChangeQuotesPath(t *testing.T) {
term := &ui.MockTerminal{}
printer := progress.NewTerminalPrinter(false, 1, term)
printTextDiffChange(printer.S, NewChange("dir\nfile", "+"))
rtest.Equals(t, []string{"+ " + strconv.Quote("dir\nfile")}, term.Output)
term.Output = nil
printTextDiffChange(printer.S, NewChange("/ordinary/file", "+"))
rtest.Equals(t, []string{"+ /ordinary/file"}, term.Output)
}
+1 -1
View File
@@ -209,7 +209,7 @@ func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args [
totalErrors := 0
d.Error = func(nodePath string, err error) {
totalErrors++
printer.E("ignoring error for %s: %s\n", nodePath, err)
printer.E("ignoring error for %s: %s\n", ui.Quote(nodePath), err)
}
err = printFromTree(ctx, tree, repo, "/", splittedPath, d, canWriteArchiveFunc)
if err != nil {
+2 -2
View File
@@ -217,10 +217,10 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn *
func (s *statefulOutput) PrintObjectNormal(kind, id, nodepath, treeID string, sn *data.Snapshot) {
s.printer.S("Found %s %s", kind, id)
if kind == "blob" {
s.printer.S(" ... in file %s", nodepath)
s.printer.S(" ... in file %s", ui.Quote(nodepath))
s.printer.S(" (tree %s)", treeID)
} else {
s.printer.S(" ... path %s", nodepath)
s.printer.S(" ... path %s", ui.Quote(nodepath))
}
s.printer.S(" ... in snapshot %s (%s)", sn.ID().Str(), sn.Time.Local().Format(global.TimeFormat))
}
+30
View File
@@ -0,0 +1,30 @@
package main
import (
"strconv"
"strings"
"testing"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/progress"
)
func TestPrintObjectQuotesPath(t *testing.T) {
term := &ui.MockTerminal{}
out := &statefulOutput{
printer: progress.NewTerminalPrinter(false, 1, term),
}
out.PrintObjectNormal("file", "abcd", "dir\nfile", "", &data.Snapshot{})
rtest.Equals(t, " ... path "+strconv.Quote("dir\nfile"), term.Output[1])
for _, line := range term.Output {
rtest.Assert(t, !strings.Contains(line, "\n"), "raw newline in %q", line)
}
term = &ui.MockTerminal{}
out.printer = progress.NewTerminalPrinter(false, 1, term)
out.PrintObjectNormal("blob", "abcd", "/ordinary/file", "tree", &data.Snapshot{})
rtest.Equals(t, " ... in file /ordinary/file", term.Output[1])
}
+5
View File
@@ -99,6 +99,11 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts global.Option
return json.NewEncoder(gopts.Term.OutputWriter()).Encode(keys)
}
for i := range keys {
keys[i].UserName = ui.Quote(keys[i].UserName)
keys[i].HostName = ui.Quote(keys[i].HostName)
}
tab := table.New()
tab.AddColumn(" ID", "{{if .Current}}*{{else}} {{end}}{{ .ShortID }}")
tab.AddColumn("User", "{{ .UserName }}")
+1 -1
View File
@@ -296,7 +296,7 @@ type textLsPrinter struct {
}
func (p *textLsPrinter) Snapshot(sn *data.Snapshot) error {
p.termPrinter.P("%v filtered by %v:", sn, p.dirs)
p.termPrinter.P("%v filtered by %v:", sn, ui.QuoteSlice(p.dirs))
return nil
}
func (p *textLsPrinter) NodeOutput(node lsNodeOutput, isPrefixDirectory bool) error {
+1 -1
View File
@@ -201,7 +201,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args
err = fusefs.Serve(c, root)
}()
printer.S("Now serving the repository at %s", mountpoint)
printer.S("Now serving the repository at %s", ui.Quote(mountpoint))
printer.S("Use another terminal or tool to browse the contents of this folder.")
printer.S("When finished, quit with Ctrl-c here or umount the mountpoint.")
debug.Log("serving mount at %v", mountpoint)
+3 -3
View File
@@ -243,7 +243,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
}
if !gopts.JSON {
printer.P("restoring %s to %s\n", res.Snapshot(), opts.Target)
printer.P("restoring %s to %s\n", res.Snapshot(), ui.Quote(opts.Target))
}
countRestoredFiles, err := res.RestoreTo(ctx, opts.Target)
@@ -259,7 +259,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
if opts.Verify {
if !gopts.JSON {
printer.P("verifying files in %s\n", opts.Target)
printer.P("verifying files in %s\n", ui.Quote(opts.Target))
}
var count int
t0 := time.Now()
@@ -273,7 +273,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options,
}
if !gopts.JSON {
printer.P("finished verifying %d files in %s (took %s)\n", count, opts.Target,
printer.P("finished verifying %d files in %s (took %s)\n", count, ui.Quote(opts.Target),
time.Since(t0).Round(time.Millisecond))
}
}
+2 -2
View File
@@ -245,7 +245,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("would set hostname to %s", newMetadata.Hostname)
printer.P("would set hostname to %s", ui.Quote(newMetadata.Hostname))
}
return true, nil
@@ -268,7 +268,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d
}
if newMetadata != nil && newMetadata.Hostname != "" {
printer.P("setting host to %s", newMetadata.Hostname)
printer.P("setting host to %s", ui.Quote(newMetadata.Hostname))
sn.Hostname = newMetadata.Hostname
}
+6 -6
View File
@@ -275,9 +275,9 @@ func printSnapshotsTable(stdout io.Writer, list data.Snapshots, reasons []data.K
data := snapshot{
ID: sn.ID().Str(),
Timestamp: sn.Time.Local().Format(global.TimeFormat),
Hostname: sn.Hostname,
Tags: sn.Tags,
Paths: sn.Paths,
Hostname: ui.Quote(sn.Hostname),
Tags: ui.QuoteSlice(sn.Tags),
Paths: ui.QuoteSlice(sn.Paths),
}
if len(reasons) > 0 {
@@ -344,13 +344,13 @@ func PrintSnapshotGroupHeader(stdout io.Writer, groupKeyJSON string) error {
header := "snapshots"
var infoStrings []string
if key.Hostname != "" {
infoStrings = append(infoStrings, "host ["+key.Hostname+"]")
infoStrings = append(infoStrings, "host ["+ui.Quote(key.Hostname)+"]")
}
if key.Tags != nil {
infoStrings = append(infoStrings, "tags ["+strings.Join(key.Tags, ", ")+"]")
infoStrings = append(infoStrings, "tags ["+strings.Join(ui.QuoteSlice(key.Tags), ", ")+"]")
}
if key.Paths != nil {
infoStrings = append(infoStrings, "paths ["+strings.Join(key.Paths, ", ")+"]")
infoStrings = append(infoStrings, "paths ["+strings.Join(ui.QuoteSlice(key.Paths), ", ")+"]")
}
if infoStrings != nil {
header += " for (" + strings.Join(infoStrings, ", ") + ")"
+2 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/debug"
)
@@ -400,7 +401,7 @@ func handleUnknownGenericAttributeFound(genericAttributeType GenericAttributeTyp
debug.Log("Ignoring a generic attribute found in the repository: %s which may not be compatible with your OS. Compatible OS: %s", genericAttributeType, os)
} else {
// If genericAttributesForOS in node.go does not know about this attribute, then the repository may have been created by a newer version which has a newer GenericAttributeType.
warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", genericAttributeType))
warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", ui.Quote(string(genericAttributeType))))
}
}
}
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"os"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/ui"
)
func lchown(name string, node *data.Node, lookupByName bool, warn func(msg string)) error {
@@ -19,14 +20,14 @@ func lchown(name string, node *data.Node, lookupByName bool, warn func(msg strin
if id, ok := lookupUid(node.User); ok {
uid = id
} else if warn != nil {
warn(fmt.Sprintf("cannot resolve user %q for %v, using uid %d", node.User, name, uid))
warn(fmt.Sprintf("cannot resolve user %q for %s, using uid %d", node.User, ui.Quote(name), uid))
}
}
if node.Group != "" {
if id, ok := lookupGid(node.Group); ok {
gid = id
} else if warn != nil {
warn(fmt.Sprintf("cannot resolve group %q for %v, using gid %d", node.Group, name, gid))
warn(fmt.Sprintf("cannot resolve group %q for %s, using gid %d", node.Group, ui.Quote(name), gid))
}
}
}
+1 -1
View File
@@ -160,5 +160,5 @@ func (b *textProgress) Finish(id restic.ID, summary *archiver.Summary, dryRun bo
}
func (b *textProgress) ExcludedItem(path string) {
b.VV("excluded %s", path)
b.VV("excluded %s", ui.Quote(path))
}
+6
View File
@@ -25,3 +25,9 @@ func TestScannerError(t *testing.T) {
test.Equals(t, printer.ScannerError("/path", errors.New("error \"message\"")), nil)
test.Equals(t, []string{"scan: error \"message\"\n"}, term.Errors)
}
func TestExcludedItem(t *testing.T) {
term, printer := createTextProgress()
printer.ExcludedItem("/p\nath")
test.Equals(t, []string{"excluded \"/p\\nath\""}, term.Output)
}
+3 -3
View File
@@ -41,7 +41,7 @@ func (t *textPrinter) Update(p State, duration time.Duration) {
}
func (t *textPrinter) Error(item string, err error) error {
t.E("ignoring error for %s: %s\n", item, err)
t.E("ignoring error for %s: %s\n", ui.Quote(item), err)
return nil
}
@@ -65,9 +65,9 @@ func (t *textPrinter) CompleteItem(messageType restorer.ItemAction, item string,
}
if messageType == restorer.ActionDirRestored || messageType == restorer.ActionOtherRestored || messageType == restorer.ActionDeleted {
t.VV("%-9v %v", action, item)
t.VV("%-9v %v", action, ui.Quote(item))
} else {
t.VV("%-9v %v with size %v", action, item, ui.FormatBytes(size))
t.VV("%-9v %v with size %v", action, ui.Quote(item), ui.FormatBytes(size))
}
}
+14 -7
View File
@@ -1,6 +1,7 @@
package restore
import (
"strconv"
"testing"
"time"
@@ -49,18 +50,20 @@ func TestPrintSummaryOnSuccessWithSkipped(t *testing.T) {
func TestPrintCompleteItem(t *testing.T) {
for _, data := range []struct {
action restorer.ItemAction
item string
size uint64
expected string
}{
{restorer.ActionDirRestored, 0, "restored test"},
{restorer.ActionFileRestored, 123, "restored test with size 123 B"},
{restorer.ActionOtherRestored, 0, "restored test"},
{restorer.ActionFileUpdated, 123, "updated test with size 123 B"},
{restorer.ActionFileUnchanged, 123, "unchanged test with size 123 B"},
{restorer.ActionDeleted, 0, "deleted test"},
{restorer.ActionDirRestored, "test", 0, "restored test"},
{restorer.ActionFileRestored, "test", 123, "restored test with size 123 B"},
{restorer.ActionOtherRestored, "test", 0, "restored test"},
{restorer.ActionFileUpdated, "test", 123, "updated test with size 123 B"},
{restorer.ActionFileUnchanged, "test", 123, "unchanged test with size 123 B"},
{restorer.ActionDeleted, "test", 0, "deleted test"},
{restorer.ActionFileRestored, "a\nb", 123, "restored " + strconv.Quote("a\nb") + " with size 123 B"},
} {
term, printer := createTextProgress()
printer.CompleteItem(data.action, "test", data.size)
printer.CompleteItem(data.action, data.item, data.size)
test.Equals(t, []string{data.expected}, term.Output)
}
}
@@ -69,4 +72,8 @@ func TestError(t *testing.T) {
term, printer := createTextProgress()
test.Equals(t, printer.Error("/path", errors.New("error \"message\"")), nil)
test.Equals(t, []string{"ignoring error for /path: error \"message\"\n"}, term.Errors)
term, printer = createTextProgress()
test.Equals(t, printer.Error("a\nb", errors.New("failed")), nil)
test.Equals(t, []string{"ignoring error for " + strconv.Quote("a\nb") + ": failed\n"}, term.Errors)
}