github.com/cs3org/reva/v2@v2.27.7/pkg/publicshare/manager/json/persistence/file/file.go (about) 1 // Copyright 2018-2021 CERN 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // In applying this license, CERN does not waive the privileges and immunities 16 // granted to it by virtue of its status as an Intergovernmental Organization 17 // or submit itself to any jurisdiction. 18 19 package file 20 21 import ( 22 "context" 23 "encoding/json" 24 "fmt" 25 "os" 26 "path/filepath" 27 "sync" 28 29 "github.com/cs3org/reva/v2/pkg/publicshare/manager/json/persistence" 30 ) 31 32 type file struct { 33 path string 34 initialized bool 35 lock *sync.RWMutex 36 } 37 38 // New returns a new Cache instance 39 func New(path string) persistence.Persistence { 40 return &file{ 41 path: path, 42 lock: &sync.RWMutex{}, 43 } 44 } 45 46 func (p *file) Init(_ context.Context) error { 47 if p.isInitialized() { 48 return nil 49 } 50 51 p.lock.Lock() 52 defer p.lock.Unlock() 53 if p.initialized { 54 return nil 55 } 56 57 // attempt to create the db file 58 var fi os.FileInfo 59 var err error 60 if fi, err = os.Stat(p.path); os.IsNotExist(err) { 61 folder := filepath.Dir(p.path) 62 if err := os.MkdirAll(folder, 0755); err != nil { 63 return err 64 } 65 if _, err := os.Create(p.path); err != nil { 66 return err 67 } 68 } 69 70 if fi == nil || fi.Size() == 0 { 71 err := os.WriteFile(p.path, []byte("{}"), 0644) 72 if err != nil { 73 return err 74 } 75 } 76 p.initialized = true 77 return nil 78 } 79 80 func (p *file) Read(_ context.Context) (persistence.PublicShares, error) { 81 if !p.isInitialized() { 82 return nil, fmt.Errorf("not initialized") 83 } 84 db := map[string]interface{}{} 85 readBytes, err := os.ReadFile(p.path) 86 if err != nil { 87 return nil, err 88 } 89 if err := json.Unmarshal(readBytes, &db); err != nil { 90 return nil, err 91 } 92 return db, nil 93 } 94 95 func (p *file) Write(_ context.Context, db persistence.PublicShares) error { 96 if !p.isInitialized() { 97 return fmt.Errorf("not initialized") 98 } 99 dbAsJSON, err := json.Marshal(db) 100 if err != nil { 101 return err 102 } 103 104 return os.WriteFile(p.path, dbAsJSON, 0644) 105 } 106 107 func (p *file) isInitialized() bool { 108 p.lock.RLock() 109 defer p.lock.RUnlock() 110 return p.initialized 111 }