From db5b7303c254af467a6458d9025f825ab50b452e Mon Sep 17 00:00:00 2001 From: n-peugnet Date: Wed, 22 Sep 2021 21:06:18 +0200 Subject: export unprefix in utils and fix error msg --- repo.go | 10 ++++------ utils/string.go | 14 ++++++++++++++ utils/string_test.go | 24 ++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 6 deletions(-) create mode 100644 utils/string.go create mode 100644 utils/string_test.go diff --git a/repo.go b/repo.go index f36bb65..dc61d01 100644 --- a/repo.go +++ b/repo.go @@ -38,7 +38,6 @@ import ( "os" "path/filepath" "reflect" - "strings" "sync" "github.com/chmduquesne/rollinghash/rabinkarp64" @@ -215,15 +214,14 @@ func listFiles(path string) []File { } func unprefixFiles(files []File, prefix string) (ret []File) { + var err error ret = make([]File, len(files)) - preSize := len(prefix) for i, f := range files { - if !strings.HasPrefix(f.Path, prefix) { - logger.Warning(f.Path, "is not prefixed by", prefix) + if f.Path, err = utils.Unprefix(f.Path, prefix); err != nil { + logger.Warning(err) } else { - f.Path = f.Path[preSize:] + ret[i] = f } - ret[i] = f } return } diff --git a/utils/string.go b/utils/string.go new file mode 100644 index 0000000..b3cbb17 --- /dev/null +++ b/utils/string.go @@ -0,0 +1,14 @@ +package utils + +import ( + "fmt" + "strings" +) + +func Unprefix(path string, prefix string) (string, error) { + if !strings.HasPrefix(path, prefix) { + return path, fmt.Errorf("%q is not prefixed by %q", path, prefix) + } else { + return path[len(prefix):], nil + } +} diff --git a/utils/string_test.go b/utils/string_test.go new file mode 100644 index 0000000..5d42c24 --- /dev/null +++ b/utils/string_test.go @@ -0,0 +1,24 @@ +package utils_test + +import ( + "testing" + + "github.com/n-peugnet/dna-backup/utils" +) + +func TestUnprefix(t *testing.T) { + str, err := utils.Unprefix("foo/bar", "foo/") + if str != "bar" { + t.Errorf("expected: %q, actual: %q", "bar", str) + } + if err != nil { + t.Error(err) + } + str, err = utils.Unprefix("foo/bar", "baz") + if str != "foo/bar" { + t.Errorf("expected: %q, actual: %q", "foo/bar", str) + } + if err == nil { + t.Error("err should not be nil") + } +} -- cgit v1.2.3