Skip to content

Commit a8c5c91

Browse files
committed
Fix panic in extractCidString.
License: MIT Signed-off-by: Kevin Atkinson <[email protected]>
1 parent a4eb133 commit a8c5c91

File tree

2 files changed

+46
-7
lines changed

2 files changed

+46
-7
lines changed

core/commands/cmdenv/cidbase.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package cmdenv
22

33
import (
4+
"errors"
5+
46
path "gx/ipfs/QmZErC2Ay6WuGi96CPg316PwitdwgLo6RxZRqVjJjRj2MR/go-path"
57
cmds "gx/ipfs/QmaAP56JAwdjwisPTu4yx17whcjTr6y5JCSCF77Y1rahWV/go-ipfs-cmds"
68
cidenc "gx/ipfs/QmdPQx9fvN5ExVwMhRmh7YpCQJzJrFhd1AjVBwJmRMFJeX/go-cidutil/cidenc"
@@ -62,7 +64,10 @@ func CidBaseDefined(req *cmds.Request) bool {
6264
// the base encoder is returned. If you don't care about the error
6365
// condiation it is safe to ignore the error returned.
6466
func CidEncoderFromPath(enc cidenc.Encoder, p string) (cidenc.Encoder, error) {
65-
v := extractCidString(p)
67+
v, err := extractCidString(p)
68+
if err != nil {
69+
return enc, err
70+
}
6671
if cidVer(v) == 0 {
6772
return cidenc.Encoder{Base: enc.Base, Upgrade: false}, nil
6873
}
@@ -73,13 +78,16 @@ func CidEncoderFromPath(enc cidenc.Encoder, p string) (cidenc.Encoder, error) {
7378
return cidenc.Encoder{Base: e, Upgrade: true}, nil
7479
}
7580

76-
func extractCidString(p string) string {
77-
segs := path.FromString(p).Segments()
78-
v := segs[0]
79-
if v == "ipfs" || v == "ipld" && len(segs) > 0 {
80-
v = segs[1]
81+
func extractCidString(str string) (string, error) {
82+
p, err := path.ParsePath(str)
83+
if err != nil {
84+
return "", err
85+
}
86+
segs := p.Segments()
87+
if segs[0] == "ipfs" || segs[0] == "ipld" {
88+
return segs[1], nil
8189
}
82-
return v
90+
return "", errors.New("no CID found")
8391
}
8492

8593
func cidVer(v string) int {

core/commands/cmdenv/cidbase_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package cmdenv
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestExtractCidString(t *testing.T) {
8+
test := func(path string, cid string) {
9+
res, err := extractCidString(path)
10+
if err != nil || res != cid {
11+
t.Errorf("extractCidString(%s) failed", path)
12+
}
13+
}
14+
testFailure := func(path string) {
15+
_, err := extractCidString(path)
16+
if err == nil {
17+
t.Errorf("extractCidString(%s) should of failed", path)
18+
}
19+
}
20+
p := "QmRqVG8VGdKZ7KARqR96MV7VNHgWvEQifk94br5HpURpfu"
21+
test(p, p)
22+
test("/ipfs/"+p, p)
23+
testFailure("/ipns/" + p)
24+
25+
p = "zb2rhfkM4FjkMLaUnygwhuqkETzbYXnUDf1P9MSmdNjW1w1Lk"
26+
test(p, p)
27+
test("/ipfs/"+p, p)
28+
test("/ipld/"+p, p)
29+
30+
testFailure("/ipfs")
31+
}

0 commit comments

Comments
 (0)