|
1 | 1 | package cmdenv
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - cidenc "gx/ipfs/QmVjZoEZg2oxXGFGjbD28x3gGN6ALHAW6BN2LKRUcaJ21i/go-cidutil/cidenc" |
| 4 | + path "gx/ipfs/QmQtg7N4XjAk2ZYpBjjv8B6gQprsRekabHBCnF6i46JYKJ/go-path" |
5 | 5 | cmds "gx/ipfs/Qma6uuSyjkecGhMFFLfzyJDPyoDtNJSHJNweDccZhaWkgU/go-ipfs-cmds"
|
| 6 | + cidenc "gx/ipfs/QmckgkstbdXagMTQ4e1DW2SzxGcjjudbqEvA5H2Rb7uvAT/go-cidutil/cidenc" |
6 | 7 | cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
|
7 | 8 | mbase "gx/ipfs/QmekxXDhCxCJRNuzmHreuaT3BsuJcsjcXWNrtV9C8DRHtd/go-multibase"
|
8 | 9 | )
|
@@ -48,3 +49,38 @@ func EnableCidBaseGlobal(req *cmds.Request, env cmds.Environment) error {
|
48 | 49 | cidenc.Default = enc
|
49 | 50 | return nil
|
50 | 51 | }
|
| 52 | + |
| 53 | +// FromPath creates a new encoder that is influenced from the encoded |
| 54 | +// Cid in a Path. For CidV0 the multibase from the base encoder is |
| 55 | +// used and automatic upgrades are disabled. For CidV1 the multibase |
| 56 | +// from the CID is used and upgrades are eneabled. On error the base |
| 57 | +// encoder is returned. If you don't care about the error condiation |
| 58 | +// it is safe to ignore the error returned. |
| 59 | +func CidEncoderFromPath(enc cidenc.Encoder, p string) (cidenc.Encoder, error) { |
| 60 | + v := extractCidString(p) |
| 61 | + if cidVer(v) == 0 { |
| 62 | + return cidenc.Encoder{Base: enc.Base, Upgrade: false}, nil |
| 63 | + } |
| 64 | + e, err := mbase.NewEncoder(mbase.Encoding(v[0])) |
| 65 | + if err != nil { |
| 66 | + return enc, err |
| 67 | + } |
| 68 | + return cidenc.Encoder{Base: e, Upgrade: true}, nil |
| 69 | +} |
| 70 | + |
| 71 | +func extractCidString(p string) string { |
| 72 | + segs := path.FromString(p).Segments() |
| 73 | + v := segs[0] |
| 74 | + if v == "ipfs" || v == "ipld" && len(segs) > 0 { |
| 75 | + v = segs[1] |
| 76 | + } |
| 77 | + return v |
| 78 | +} |
| 79 | + |
| 80 | +func cidVer(v string) int { |
| 81 | + if len(v) == 46 && v[:2] == "Qm" { |
| 82 | + return 0 |
| 83 | + } else { |
| 84 | + return 1 |
| 85 | + } |
| 86 | +} |
0 commit comments