From 60c1c14b7faf7138a7072d18d061cf11149fd375 Mon Sep 17 00:00:00 2001 From: Matthias Diester Date: Fri, 21 May 2021 17:32:49 +0200 Subject: [PATCH] Add convenience path parse function Add function to parse a given path unsafe. --- path.go | 11 +++++++++++ path_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/path.go b/path.go index c4d2b74..f043762 100644 --- a/path.go +++ b/path.go @@ -499,6 +499,17 @@ func ParsePathString(pathString string, node *yamlv3.Node) (Path, error) { return ParseDotStylePathString(pathString, node) } +// ParsePathStringUnsafe returns a path by parsing a string representation of a +// path, which can either be GoPatch or DotStyle, but will not check the path +// elements against a given YAML document to verify the types (unsafe) +func ParsePathStringUnsafe(pathString string) (Path, error) { + if strings.HasPrefix(pathString, "/") { + return ParseGoPatchStylePathString(pathString) + } + + return ParseDotStylePathStringUnsafe(pathString) +} + func (element PathElement) isMapElement() bool { return len(element.Key) == 0 && len(element.Name) > 0 diff --git a/path_test.go b/path_test.go index 507bea3..100c318 100644 --- a/path_test.go +++ b/path_test.go @@ -101,6 +101,32 @@ var _ = Describe("path tests", func() { {Idx: -1, Key: "", Name: "newkey"}, }})) }) + + It("should parse an unspecified path type without checking against a YAML document (unsafe)", func() { + Expect(ParsePathStringUnsafe("list.one.newkey")).To(BeEquivalentTo(Path{DocumentIdx: 0, PathElements: []PathElement{ + {Idx: -1, Key: "", Name: "list"}, + {Idx: -1, Key: "", Name: "one"}, + {Idx: -1, Key: "", Name: "newkey"}, + }})) + + Expect(ParsePathStringUnsafe("list.0.newkey")).To(BeEquivalentTo(Path{DocumentIdx: 0, PathElements: []PathElement{ + {Idx: -1, Key: "", Name: "list"}, + {Idx: 0, Key: "", Name: ""}, + {Idx: -1, Key: "", Name: "newkey"}, + }})) + + Expect(ParsePathStringUnsafe("/list/one/newkey")).To(BeEquivalentTo(Path{DocumentIdx: 0, PathElements: []PathElement{ + {Idx: -1, Key: "", Name: "list"}, + {Idx: -1, Key: "", Name: "one"}, + {Idx: -1, Key: "", Name: "newkey"}, + }})) + + Expect(ParsePathStringUnsafe("/list/0/newkey")).To(BeEquivalentTo(Path{DocumentIdx: 0, PathElements: []PathElement{ + {Idx: -1, Key: "", Name: "list"}, + {Idx: 0, Key: "", Name: ""}, + {Idx: -1, Key: "", Name: "newkey"}, + }})) + }) }) Context("parse go-patch style path strings into paths", func() {