Skip to content
This repository has been archived by the owner on Jun 20, 2023. It is now read-only.

path: add ToCid API #61

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions path.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ func FromCid(c cid.Cid) Path {
return Path("/ipfs/" + c.String())
}

// ToCid attempts to convert the Path to a CID. This should always work if
// the path was created from ParsePath.
func (p Path) ToCid() (cid.Cid, error) {
parts := strings.Split(p.String(), "/")
if len(parts) < 3 || parts[2] == "" {
return cid.Undef, &pathError{fmt.Errorf("not enough path components"), p.String()}
}

switch parts[1] {
// TODO: Silently allowing IPNS though ParsePath doesn't validate the CID
// in that case.
Comment on lines +42 to +43
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note this. I'm not sure what's the expected IPNS format; we might need to validate its CID either way.

case "ipfs", "ipld", "ipns":
return decodeCid(parts[2])
default:
return cid.Undef, &pathError{fmt.Errorf("invalid namespace %s to extract CID (/ipfs/<CID> or /ipld/<CID> expected)", parts[1]), p.String()}
}
}

// Segments returns the different elements of a path
// (elements are delimited by a /).
func (p Path) Segments() []string {
Expand Down
8 changes: 7 additions & 1 deletion path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,17 @@ func TestPathParsing(t *testing.T) {
}

for p, expected := range cases {
_, err := ParsePath(p)
p, err := ParsePath(p)
valid := err == nil
if valid != expected {
t.Fatalf("expected %s to have valid == %t", p, expected)
}
if valid {
_, err := p.ToCid()
if err != nil {
t.Fatalf("ToCid(): failed to extract CID from valid path: %s", err)
}
}
}
}

Expand Down