-
Notifications
You must be signed in to change notification settings - Fork 110
/
shell.go
82 lines (63 loc) · 1.44 KB
/
shell.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package gxutil
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
sh "github.com/ipfs/go-ipfs-api"
homedir "github.com/mitchellh/go-homedir"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
log "github.com/whyrusleeping/stump"
)
var UsingGateway bool
func NewShell() *sh.Shell {
if apivar := os.Getenv("IPFS_API"); apivar != "" {
log.VLog("using '%s' from IPFS_API env as api endpoint.", apivar)
return sh.NewShell(apivar)
}
ash, err := getLocalAPIShell()
if err == nil {
return ash
}
UsingGateway = true
log.VLog("using global ipfs gateways as api endpoint")
return sh.NewShell("https://ipfs.io")
}
func getLocalAPIShell() (*sh.Shell, error) {
ipath := os.Getenv("IPFS_PATH")
if ipath == "" {
home, err := homedir.Dir()
if err != nil {
return nil, err
}
ipath = filepath.Join(home, ".ipfs")
}
apifile := filepath.Join(ipath, "api")
data, err := ioutil.ReadFile(apifile)
if err != nil {
return nil, err
}
addr := strings.Trim(string(data), "\n\t ")
host, err := multiaddrToNormal(addr)
if err != nil {
return nil, err
}
local := sh.NewShell(host)
_, _, err = local.Version()
if err != nil {
return nil, err
}
return local, nil
}
func multiaddrToNormal(addr string) (string, error) {
maddr, err := ma.NewMultiaddr(addr)
if err != nil {
return "", err
}
_, host, err := manet.DialArgs(maddr)
if err != nil {
return "", err
}
return host, nil
}