From 504ad6328dc4d8ed2b543465a133ce2c5cc7ffa5 Mon Sep 17 00:00:00 2001 From: Rafid Bin Mostofa Date: Thu, 4 Jul 2024 15:15:05 +0600 Subject: [PATCH] fix: use TrimPrefix for relative paths (#145) Use strings.TrimPrefix for relative paths instead of strings.TrimLeft, as the latter takes in a cutset instead of a prefix substring. --- internal/slicer/slicer.go | 2 +- internal/slicer/slicer_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/internal/slicer/slicer.go b/internal/slicer/slicer.go index 1f59c6c8..f164efd8 100644 --- a/internal/slicer/slicer.go +++ b/internal/slicer/slicer.go @@ -180,7 +180,7 @@ func Run(options *RunOptions) (*Report, error) { return nil } - relPath := filepath.Clean("/" + strings.TrimLeft(o.Path, targetDir)) + relPath := filepath.Clean("/" + strings.TrimPrefix(o.Path, targetDir)) if o.Mode.IsDir() { relPath = relPath + "/" } diff --git a/internal/slicer/slicer_test.go b/internal/slicer/slicer_test.go index 7c76f8c2..4f9dee55 100644 --- a/internal/slicer/slicer_test.go +++ b/internal/slicer/slicer_test.go @@ -1021,6 +1021,36 @@ var slicerTests = []slicerTest{{ }, filesystem: map[string]string{}, report: map[string]string{}, +}, { + summary: "Relative paths are properly trimmed during extraction", + slices: []setup.SliceKey{{"test-package", "myslice"}}, + pkgs: map[string][]byte{ + "test-package": testutil.MustMakeDeb([]testutil.TarEntry{ + // This particular path starting with "/foo" is chosen to test for + // a particular bug; which appeared due to the usage of + // strings.TrimLeft() instead strings.TrimPrefix() to determine a + // relative path. Since TrimLeft takes in a cutset instead of a + // prefix, the desired relative path was not produced. + // See https://github.com/canonical/chisel/pull/145. + testutil.Dir(0755, "./foo-bar/"), + }), + }, + hackopt: func(c *C, opts *slicer.RunOptions) { + opts.TargetDir = filepath.Join(filepath.Clean(opts.TargetDir), "foo") + err := os.Mkdir(opts.TargetDir, 0755) + c.Assert(err, IsNil) + }, + release: map[string]string{ + "slices/mydir/test-package.yaml": ` + package: test-package + slices: + myslice: + contents: + /foo-bar/: + mutate: | + content.list("/foo-bar/") + `, + }, }} var defaultChiselYaml = `