-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ipfsdir.go
102 lines (87 loc) · 2.22 KB
/
ipfsdir.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package migrations
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mitchellh/go-homedir"
)
const (
envIpfsPath = "IPFS_PATH"
defIpfsDir = ".ipfs"
versionFile = "version"
)
func init() {
homedir.DisableCache = true
}
// IpfsDir returns the path of the ipfs directory. If dir specified, then
// returns the expanded version dir. If dir is "", then return the directory
// set by IPFS_PATH, or if IPFS_PATH is not set, then return the default
// location in the home directory.
func IpfsDir(dir string) (string, error) {
var err error
if dir == "" {
dir = os.Getenv(envIpfsPath)
}
if dir != "" {
dir, err = homedir.Expand(dir)
if err != nil {
return "", err
}
return dir, nil
}
home, err := homedir.Dir()
if err != nil {
return "", err
}
if home == "" {
return "", errors.New("could not determine IPFS_PATH, home dir not set")
}
return filepath.Join(home, defIpfsDir), nil
}
// CheckIpfsDir gets the ipfs directory and checks that the directory exists.
func CheckIpfsDir(dir string) (string, error) {
var err error
dir, err = IpfsDir(dir)
if err != nil {
return "", err
}
_, err = os.Stat(dir)
if err != nil {
return "", err
}
return dir, nil
}
// RepoVersion returns the version of the repo in the ipfs directory. If the
// ipfs directory is not specified then the default location is used.
func RepoVersion(ipfsDir string) (int, error) {
ipfsDir, err := CheckIpfsDir(ipfsDir)
if err != nil {
return 0, err
}
return repoVersion(ipfsDir)
}
// WriteRepoVersion writes the specified repo version to the repo located in
// ipfsDir. If ipfsDir is not specified, then the default location is used.
func WriteRepoVersion(ipfsDir string, version int) error {
ipfsDir, err := IpfsDir(ipfsDir)
if err != nil {
return err
}
vFilePath := filepath.Join(ipfsDir, versionFile)
return ioutil.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0644)
}
func repoVersion(ipfsDir string) (int, error) {
c, err := ioutil.ReadFile(filepath.Join(ipfsDir, versionFile))
if err != nil {
return 0, err
}
ver, err := strconv.Atoi(strings.TrimSpace(string(c)))
if err != nil {
return 0, errors.New("invalid data in repo version file")
}
return ver, nil
}