diff --git a/ipns/name.go b/ipns/name.go index 2a6bbdbf4..5f8be3299 100644 --- a/ipns/name.go +++ b/ipns/name.go @@ -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" @@ -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 +} diff --git a/ipns/name_test.go b/ipns/name_test.go index 4b8ccd414..c3c31878c 100644 --- a/ipns/name_test.go +++ b/ipns/name_test.go @@ -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() @@ -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]) diff --git a/path/path.go b/path/path.go index 4230e298a..172f9dce5 100644 --- a/path/path.go +++ b/path/path.go @@ -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 {