Skip to content

Commit

Permalink
feat: add ipns.Name.AsPath
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Sep 25, 2023
1 parent 68cc6ff commit ded21a4
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
10 changes: 10 additions & 0 deletions ipns/name.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"strings"

"github.com/ipfs/boxo/path"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/peer"
mb "github.com/multiformats/go-multibase"
Expand Down Expand Up @@ -133,3 +134,12 @@ func (n Name) MarshalJSON() ([]byte, error) {
func (n Name) Equal(other Name) bool {
return bytes.Equal(n.src, other.src)
}

// AsPath returns the IPNS Name as a [path.Path] prefixed by [path.IPNSNamespace].
func (n Name) AsPath() path.Path {
p, err := path.NewPathFromSegments(path.IPNSNamespace.String(), n.String())
if err != nil {
panic(fmt.Errorf("path.NewPathFromSegments was called with invalid parameters: %w", err))
}
return p
}
11 changes: 11 additions & 0 deletions ipns/name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ func TestName(t *testing.T) {
})
}

testPath := func(t *testing.T, name, input, expected string) {
t.Run("AsPath method: "+name, func(t *testing.T) {
t.Parallel()

name, err := NameFromString(input)
require.NoError(t, err)
require.Equal(t, expected, name.AsPath().String())
})
}

testMarshalJSON := func(t *testing.T, name, input, expected string) {
t.Run("Marshal JSON: "+name, func(t *testing.T) {
t.Parallel()
Expand Down Expand Up @@ -66,6 +76,7 @@ func TestName(t *testing.T) {
testFromCid(t, v[0], v[2], v[2])
testString(t, v[0], v[1], v[2])
testString(t, v[0], NamespacePrefix+v[1], v[2])
testPath(t, v[0], v[1], NamespacePrefix+v[2])
testMarshalJSON(t, v[0], v[1], `"`+v[2]+`"`)
testMarshalJSON(t, v[0], NamespacePrefix+v[1], `"`+v[2]+`"`)
testUnmarshalJSON(t, v[0], []byte(`"`+v[2]+`"`), v[2])
Expand Down
2 changes: 1 addition & 1 deletion path/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const (
//
// 1. Namespace is "ipfs", "ipld", or "ipns".
// 2. If namespace is "ipfs" or "ipld", "root" must be a valid [cid.Cid].
// 3. If namespace is "ipns", "root" may be a [ipns.Name] or a DNSLink FQDN.
// 3. If namespace is "ipns", "root" may be a [ipns.Name] or a [DNSLink] FQDN.
//
// [DNSLink]: https://dnslink.dev/
type Path interface {
Expand Down

0 comments on commit ded21a4

Please sign in to comment.