Merge pull request #4 from ipfs/feat/parse

Add Parse func accepting various types
This commit is contained in:
Jeromy Johnson
2016-11-17 09:35:58 -08:00
committed by GitHub
2 changed files with 73 additions and 0 deletions

19
cid.go
View File

@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/binary"
"fmt"
"strings"
mbase "github.com/multiformats/go-multibase"
mh "github.com/multiformats/go-multihash"
@@ -47,6 +48,24 @@ type Cid struct {
hash mh.Multihash
}
func Parse(v interface{}) (*Cid, error) {
switch v2 := v.(type) {
case string:
if strings.Contains(v2, "/ipfs/") {
return Decode(strings.Split(v2, "/ipfs/")[1])
}
return Decode(v2)
case []byte:
return Cast(v2)
case mh.Multihash:
return NewCidV0(v2), nil
case *Cid:
return v2, nil
default:
return nil, fmt.Errorf("can't parse %+v as Cid", v2)
}
}
func Decode(v string) (*Cid, error) {
if len(v) < 2 {
return nil, fmt.Errorf("cid too short")

View File

@@ -2,7 +2,9 @@ package cid
import (
"bytes"
"fmt"
"math/rand"
"strings"
"testing"
mh "github.com/multiformats/go-multihash"
@@ -125,3 +127,55 @@ func TestFuzzCid(t *testing.T) {
_, _ = Cast(buf[:s])
}
}
func TestParse(t *testing.T) {
cid, err := Parse(123)
if err == nil {
t.Fatalf("expected error from Parse()")
}
if !strings.Contains(err.Error(), "can't parse 123 as Cid") {
t.Fatalf("expected int error, got %s", err.Error())
}
theHash := "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n"
h, err := mh.FromB58String(theHash)
if err != nil {
t.Fatal(err)
}
assertions := [][]interface{}{
[]interface{}{NewCidV0(h), theHash},
[]interface{}{NewCidV0(h).Bytes(), theHash},
[]interface{}{h, theHash},
[]interface{}{theHash, theHash},
[]interface{}{"/ipfs/" + theHash, theHash},
[]interface{}{"https://ipfs.io/ipfs/" + theHash, theHash},
[]interface{}{"http://localhost:8080/ipfs/" + theHash, theHash},
}
assert := func(arg interface{}, expected string) error {
cid, err = Parse(arg)
if err != nil {
return err
}
if cid.version != 0 {
return fmt.Errorf("expected version 0, got %s", string(cid.version))
}
actual := cid.Hash().B58String()
if actual != expected {
return fmt.Errorf("expected hash %s, got %s", expected, actual)
}
actual = cid.String()
if actual != expected {
return fmt.Errorf("expected string %s, got %s", expected, actual)
}
return nil
}
for _, args := range assertions {
err := assert(args[0], args[1].(string))
if err != nil {
t.Fatal(err)
}
}
}