mirror of
https://github.com/ipfs/kubo.git
synced 2025-09-10 05:52:20 +08:00
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>
This commit is contained in:
18
path/path.go
18
path/path.go
@ -50,6 +50,24 @@ func (p Path) IsJustAKey() bool {
|
||||
return (len(parts) == 2 && parts[0] == "ipfs")
|
||||
}
|
||||
|
||||
// PopLastSegment returns a new Path without its final segment, and the final
|
||||
// segment, separately. If there is no more to pop (the path is just a key),
|
||||
// the original path is returned.
|
||||
func (p Path) PopLastSegment() (Path, string, error) {
|
||||
|
||||
if p.IsJustAKey() {
|
||||
return p, "", nil
|
||||
}
|
||||
|
||||
segs := p.Segments()
|
||||
newPath, err := ParsePath("/" + strings.Join(segs[:len(segs)-1], "/"))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return newPath, segs[len(segs)-1], nil
|
||||
}
|
||||
|
||||
func FromSegments(prefix string, seg ...string) (Path, error) {
|
||||
return ParsePath(prefix + strings.Join(seg, "/"))
|
||||
}
|
||||
|
@ -49,3 +49,31 @@ func TestIsJustAKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPopLastSegment(t *testing.T) {
|
||||
cases := map[string][]string{
|
||||
"QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", ""},
|
||||
"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", ""},
|
||||
"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n", "a"},
|
||||
"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a/b": []string{"/ipfs/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/a", "b"},
|
||||
"/ipns/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/x/y/z": []string{"/ipns/QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n/x/y", "z"},
|
||||
}
|
||||
|
||||
for p, expected := range cases {
|
||||
path, err := ParsePath(p)
|
||||
if err != nil {
|
||||
t.Fatalf("ParsePath failed to parse \"%s\", but should have succeeded", p)
|
||||
}
|
||||
head, tail, err := path.PopLastSegment()
|
||||
if err != nil {
|
||||
t.Fatalf("PopLastSegment failed, but should have succeeded: %s", err)
|
||||
}
|
||||
headStr := head.String()
|
||||
if headStr != expected[0] {
|
||||
t.Fatalf("expected head of PopLastSegment(%s) to return %v, not %v", p, expected[0], headStr)
|
||||
}
|
||||
if tail != expected[1] {
|
||||
t.Fatalf("expected tail of PopLastSegment(%s) to return %v, not %v", p, expected[1], tail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user