github.com/uber/kraken@v0.1.4/lib/store/utils.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 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 package store 15 16 import ( 17 "bytes" 18 "io/ioutil" 19 "os" 20 "path" 21 22 "github.com/uber/kraken/utils/osutil" 23 ) 24 25 func createOrUpdateSymlink(sourcePath, targetPath string) error { 26 if _, err := os.Stat(targetPath); err == nil { 27 if existingSource, err := os.Readlink(targetPath); err != nil { 28 return err 29 } else if existingSource != sourcePath { 30 // If the symlink already exists and points to another valid location, recreate the symlink. 31 if err := os.Remove(targetPath); err != nil { 32 return err 33 } 34 if err := os.Symlink(sourcePath, targetPath); err != nil { 35 return err 36 } 37 } 38 } else if os.IsNotExist(err) { 39 if err := os.Symlink(sourcePath, targetPath); err != nil { 40 return err 41 } 42 } else { 43 return err 44 } 45 46 return nil 47 } 48 49 // walkDirectory is a helper function which scans the given dir and perform 50 // specified functions at given depth. 51 // This function doesn't wrap errors. 52 // 53 // Note: This could be an expensive operation and will potentially return stale 54 // data. 55 func walkDirectory(rootDir string, depth int, f func(string) error) error { 56 if depth == 0 { 57 empty, err := osutil.IsEmpty(rootDir) 58 if err != nil { 59 return err 60 } 61 if !empty { 62 if err = f(rootDir); err != nil { 63 return err 64 } 65 } 66 } else { 67 infos, err := ioutil.ReadDir(rootDir) 68 if err != nil { 69 return err 70 } 71 for _, info := range infos { 72 if info.IsDir() { 73 if err := walkDirectory(path.Join(rootDir, info.Name()), depth-1, f); err != nil { 74 return err 75 } 76 } 77 } 78 } 79 return nil 80 } 81 82 type bufferFileReader struct { 83 *bytes.Reader 84 } 85 86 func (b *bufferFileReader) Close() error { 87 return nil 88 } 89 90 // NewBufferFileReader returns an in-memory FileReader backed by b. 91 func NewBufferFileReader(b []byte) FileReader { 92 return &bufferFileReader{bytes.NewReader(b)} 93 }