@cryptotaxi247 / kubo / commits / cf0a85b7a

Implements Path.PopLastSegment().

This allows a path (/ipfs/foo/bar) to be separated between its head (/ipfs/foo) and its tail (bar). License: MIT Signed-off-by: Stephen Whitmore <noffle@ipfs.io>

Stephen Whitmore committed Jan 24, 2016 at 23:29 UTC cf0a85b7a4a847b78c6ab04bdf634c9ed7659844
2 files changed +46
path/path.go
+18
@@ -50,6 +50,24 @@ func (p Path) IsJustAKey() bool {
50 return (len(parts) == 2 && parts[0] == "ipfs")
51 }
52
53 +// PopLastSegment returns a new Path without its final segment, and the final
54 +// segment, separately. If there is no more to pop (the path is just a key),
55 +// the original path is returned.
56 +func (p Path) PopLastSegment() (Path, string, error) {
57 +
58 + if p.IsJustAKey() {
59 + return p, "", nil
60 + }
61 +
62 + segs := p.Segments()
63 + newPath, err := ParsePath("/" + strings.Join(segs[:len(segs)-1], "/"))
64 + if err != nil {
65 + return "", "", err
66 + }
67 +
68 + return newPath, segs[len(segs)-1], nil
69 +}
70 +
71 func FromSegments(prefix string, seg ...string) (Path, error) {
72 return ParsePath(prefix + strings.Join(seg, "/"))
73 }
path/path_test.go
+28
@@ -49,3 +49,31 @@ func TestIsJustAKey(t *testing.T) {
49 }
50 }
51 }
52 +
53 +func TestPopLastSegment(t *testing.T) {
54 + cases := map[string][]string{
55 + "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", ""},
56 + "/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", ""},
57 + "/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", "a"},
58 + "/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a/b": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a", "b"},
59 + "/ipns/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/x/y/z": []string{"/ipns/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/x/y", "z"},
60 + }
61 +
62 + for p, expected := range cases {
63 + path, err := ParsePath(p)
64 + if err != nil {
65 + t.Fatalf("ParsePath failed to parse \"%s\", but should have succeeded", p)
66 + }
67 + head, tail, err := path.PopLastSegment()
68 + if err != nil {
69 + t.Fatalf("PopLastSegment failed, but should have succeeded: %s", err)
70 + }
71 + headStr := head.String()
72 + if headStr != expected[0] {
73 + t.Fatalf("expected head of PopLastSegment(%s) to return %v, not %v", p, expected[0], headStr)
74 + }
75 + if tail != expected[1] {
76 + t.Fatalf("expected tail of PopLastSegment(%s) to return %v, not %v", p, expected[1], tail)
77 + }
78 + }
79 +}