github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/repository/manager.go (about) 1 package repository 2 3 import ( 4 "errors" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 ) 9 10 // Manager keeps track of indivudal repositories. 11 type Manager struct { 12 basePath string 13 } 14 15 // NewManager returns a new manager instance. 16 func NewManager(basePath string) (*Manager, error) { 17 stat, err := os.Stat(basePath) 18 if err != nil { 19 return nil, err 20 } 21 if !stat.IsDir() { 22 return nil, errors.New("not a directory") 23 } 24 return &Manager{basePath: basePath}, nil 25 } 26 27 // ListNames returns the names of all registered repositories. 28 func (m *Manager) ListNames() ([]string, error) { 29 entries, err := ioutil.ReadDir(m.basePath) 30 if err != nil { 31 return nil, err 32 } 33 res := []string{} 34 for _, e := range entries { 35 if !e.IsDir() { 36 continue 37 } 38 res = append(res, e.Name()) 39 } 40 return res, nil 41 } 42 43 // Create registers a new repository. 44 func (m *Manager) Create(name string, pubKey []byte) error { 45 r := New(filepath.Join(m.basePath, name)) 46 err := r.Create() 47 if err != nil { 48 return err 49 } 50 return r.keys.SetSigningPublicKey(pubKey) 51 } 52 53 // Open returns a handle for the given existing repository. 54 func (m *Manager) Open(name string) (*Repository, error) { 55 absPath := filepath.Join(m.basePath, name) 56 r := New(absPath) 57 s, err := os.Stat(absPath) 58 if err != nil { 59 return nil, err 60 } 61 if !s.IsDir() { 62 return nil, errors.New("not a directory") 63 } 64 return r, nil 65 } 66 67 // Exists returns true if the repository with the given name exists. 68 func (m *Manager) Exists(name string) bool { 69 r, _ := m.Open(name) 70 return r != nil 71 }