github.com/argoproj/argo-cd/v3@v3.2.1/util/io/paths.go (about) 1 package io 2 3 import ( 4 "path/filepath" 5 "sync" 6 7 "github.com/google/uuid" 8 ) 9 10 type TempPaths interface { 11 Add(key string, value string) 12 GetPath(key string) (string, error) 13 GetPathIfExists(key string) string 14 GetPaths() map[string]string 15 } 16 17 // RandomizedTempPaths allows generating and memoizing random paths, each path being mapped to a specific key. 18 type RandomizedTempPaths struct { 19 root string 20 paths map[string]string 21 lock sync.RWMutex 22 } 23 24 func NewRandomizedTempPaths(root string) *RandomizedTempPaths { 25 return &RandomizedTempPaths{ 26 root: root, 27 paths: map[string]string{}, 28 } 29 } 30 31 func (p *RandomizedTempPaths) Add(key string, value string) { 32 p.lock.Lock() 33 defer p.lock.Unlock() 34 p.paths[key] = value 35 } 36 37 // GetPath generates a path for the given key or returns previously generated one. 38 func (p *RandomizedTempPaths) GetPath(key string) (string, error) { 39 p.lock.Lock() 40 defer p.lock.Unlock() 41 if val, ok := p.paths[key]; ok { 42 return val, nil 43 } 44 uniqueId, err := uuid.NewRandom() 45 if err != nil { 46 return "", err 47 } 48 repoPath := filepath.Join(p.root, uniqueId.String()) 49 p.paths[key] = repoPath 50 return repoPath, nil 51 } 52 53 // GetPathIfExists gets a path for the given key if it exists. Otherwise, returns an empty string. 54 func (p *RandomizedTempPaths) GetPathIfExists(key string) string { 55 p.lock.RLock() 56 defer p.lock.RUnlock() 57 if val, ok := p.paths[key]; ok { 58 return val 59 } 60 return "" 61 } 62 63 // GetPaths gets a copy of the map of paths. 64 func (p *RandomizedTempPaths) GetPaths() map[string]string { 65 p.lock.RLock() 66 defer p.lock.RUnlock() 67 paths := map[string]string{} 68 for k, v := range p.paths { 69 paths[k] = v 70 } 71 return paths 72 }