fsrepo.go 2 KB
Newer Older
1 2 3
package fsrepo

import (
4
	"io"
5 6
	"os"
	"path/filepath"
7

8 9
	config "github.com/jbenet/go-ipfs/repo/config"
	util "github.com/jbenet/go-ipfs/util"
10
	"github.com/jbenet/go-ipfs/util/debugerror"
11 12
)

13 14 15 16 17 18 19 20 21 22 23 24
type FSRepo struct {
	path   string
	config config.Config
}

func At(path string) *FSRepo {
	return &FSRepo{
		path: path,
	}
}

func (r *FSRepo) Open() error {
25
	// check repo path, then check all constituent parts.
26
	// TODO acquire repo lock
27 28 29 30 31 32 33 34 35 36 37 38 39 40
	// TODO if err := initCheckDir(logpath); err != nil { // }
	if err := initCheckDir(r.path); err != nil {
		return err
	}

	// datastore
	dspath, err := config.DataStorePath("")
	if err != nil {
		return err
	}
	if err := initCheckDir(dspath); err != nil {
		return debugerror.Errorf("datastore: %s", err)
	}

41 42 43 44 45 46 47 48
	logpath, err := config.LogsPath("")
	if err != nil {
		return debugerror.Wrap(err)
	}
	if err := initCheckDir(logpath); err != nil {
		return debugerror.Errorf("logs: %s", err)
	}

49 50 51 52 53 54 55 56
	return nil
}

func (r *FSRepo) SetConfig(conf *config.Config) error {
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
57
	if err := WriteConfigFile(configFilename, conf); err != nil {
58 59 60 61 62 63 64 65 66 67 68 69
		return err
	}
	r.config = *conf // copy so caller cannot modify the private config
	return nil
}

func (r *FSRepo) Close() error {
	return nil // TODO release repo lock
}

var _ io.Closer = &FSRepo{}

70 71 72 73 74 75 76 77 78 79 80
// ConfigIsInitialized returns true if the config exists in provided |path|.
func ConfigIsInitialized(path string) bool {
	configFilename, err := config.Filename(path)
	if err != nil {
		return false
	}
	if !util.FileExists(configFilename) {
		return false
	}
	return true
}
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

// initCheckDir ensures the directory exists and is writable
func initCheckDir(path string) error {
	// Construct the path if missing
	if err := os.MkdirAll(path, os.ModePerm); err != nil {
		return err
	}
	// Check the directory is writeable
	if f, err := os.Create(filepath.Join(path, "._check_writeable")); err == nil {
		os.Remove(f.Name())
	} else {
		return debugerror.New("'" + path + "' is not writeable")
	}
	return nil
}