master
go 87 lines 1.95 KB
Raw
1 package migrations
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10
11 "github.com/ipfs/kubo/config"
12 "github.com/ipfs/kubo/misc/fsutil"
13 )
14
15 const (
16 versionFile = "version"
17 )
18
19 // IpfsDir returns the path of the ipfs directory. If dir specified, then
20 // returns the expanded version dir. If dir is "", then return the directory
21 // set by IPFS_PATH, or if IPFS_PATH is not set, then return the default
22 // location in the home directory.
23 func IpfsDir(dir string) (string, error) {
24 var err error
25 if dir == "" {
26 dir, err = config.PathRoot()
27 if err != nil {
28 return "", err
29 }
30 }
31 dir, err = fsutil.ExpandHome(dir)
32 if err != nil {
33 return "", err
34 }
35 return dir, nil
36 }
37
38 // CheckIpfsDir gets the ipfs directory and checks that the directory exists.
39 func CheckIpfsDir(dir string) (string, error) {
40 var err error
41 dir, err = IpfsDir(dir)
42 if err != nil {
43 return "", err
44 }
45
46 _, err = os.Stat(dir)
47 if err != nil {
48 return "", err
49 }
50
51 return dir, nil
52 }
53
54 // RepoVersion returns the version of the repo in the ipfs directory. If the
55 // ipfs directory is not specified then the default location is used.
56 func RepoVersion(ipfsDir string) (int, error) {
57 ipfsDir, err := CheckIpfsDir(ipfsDir)
58 if err != nil {
59 return 0, err
60 }
61 return repoVersion(ipfsDir)
62 }
63
64 // WriteRepoVersion writes the specified repo version to the repo located in
65 // ipfsDir. If ipfsDir is not specified, then the default location is used.
66 func WriteRepoVersion(ipfsDir string, version int) error {
67 ipfsDir, err := IpfsDir(ipfsDir)
68 if err != nil {
69 return err
70 }
71
72 vFilePath := filepath.Join(ipfsDir, versionFile)
73 return os.WriteFile(vFilePath, fmt.Appendf(nil, "%d\n", version), 0o644)
74 }
75
76 func repoVersion(ipfsDir string) (int, error) {
77 c, err := os.ReadFile(filepath.Join(ipfsDir, versionFile))
78 if err != nil {
79 return 0, err
80 }
81
82 ver, err := strconv.Atoi(strings.TrimSpace(string(c)))
83 if err != nil {
84 return 0, errors.New("invalid data in repo version file")
85 }
86 return ver, nil
87 }