From d0e0822854f14b5066c3d694878bb00b32479379 Mon Sep 17 00:00:00 2001 From: Lars Gierth Date: Thu, 17 Nov 2016 14:40:43 +0100 Subject: [PATCH] Add Parse func accepting various types --- cid.go | 19 +++++++++++++++++++ cid_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/cid.go b/cid.go index 88243d3..68f1c01 100644 --- a/cid.go +++ b/cid.go @@ -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") diff --git a/cid_test.go b/cid_test.go index 48bb1e4..0c51bdb 100644 --- a/cid_test.go +++ b/cid_test.go @@ -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) + } + } +}