From 1f0226f7e01822a2a5b37d8626b59b7b6f4d0144 Mon Sep 17 00:00:00 2001 From: Ophestra Date: Tue, 7 Oct 2025 23:56:19 +0900 Subject: container/check: relocate overlay escape This is used in hst to format strings. Signed-off-by: Ophestra --- container/check/overlay.go | 29 +++++++++++++++++++++++++++++ container/check/overlay_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 container/check/overlay.go create mode 100644 container/check/overlay_test.go (limited to 'container/check') diff --git a/container/check/overlay.go b/container/check/overlay.go new file mode 100644 index 00000000..ab907fbd --- /dev/null +++ b/container/check/overlay.go @@ -0,0 +1,29 @@ +package check + +import "strings" + +const ( + // SpecialOverlayEscape is the escape string for overlay mount options. + SpecialOverlayEscape = `\` + // SpecialOverlayOption is the separator string between overlay mount options. + SpecialOverlayOption = "," + // SpecialOverlayPath is the separator string between overlay paths. + SpecialOverlayPath = ":" +) + +// EscapeOverlayDataSegment escapes a string for formatting into the data argument of an overlay mount call. +func EscapeOverlayDataSegment(s string) string { + if s == "" { + return "" + } + + if f := strings.SplitN(s, "\x00", 2); len(f) > 0 { + s = f[0] + } + + return strings.NewReplacer( + SpecialOverlayEscape, SpecialOverlayEscape+SpecialOverlayEscape, + SpecialOverlayOption, SpecialOverlayEscape+SpecialOverlayOption, + SpecialOverlayPath, SpecialOverlayEscape+SpecialOverlayPath, + ).Replace(s) +} diff --git a/container/check/overlay_test.go b/container/check/overlay_test.go new file mode 100644 index 00000000..bd90236d --- /dev/null +++ b/container/check/overlay_test.go @@ -0,0 +1,27 @@ +package check_test + +import ( + "testing" + + "hakurei.app/container/check" +) + +func TestEscapeOverlayDataSegment(t *testing.T) { + testCases := []struct { + name string + s string + want string + }{ + {"zero", "", ""}, + {"multi", `\\\:,:,\\\`, `\\\\\\\:\,\:\,\\\\\\`}, + {"bwrap", `/path :,\`, `/path \:\,\\`}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := check.EscapeOverlayDataSegment(tc.s); got != tc.want { + t.Errorf("escapeOverlayDataSegment: %s, want %s", got, tc.want) + } + }) + } +} -- cgit v1.3.1