github.com/xaverkapeller/go-gitignore@v0.0.0-20201129201858-74ef740b8b77/cache.go (about) 1 package gitignore 2 3 import ( 4 "sync" 5 ) 6 7 // Cache is the interface for the GitIgnore cache 8 type Cache interface { 9 // Set stores the GitIgnore ignore against its path. 10 Set(path string, ig GitIgnore) 11 12 // Get attempts to retrieve an GitIgnore instance associated with the given 13 // path. If the path is not known nil is returned. 14 Get(path string) GitIgnore 15 } 16 17 // cache is the default thread-safe cache implementation 18 type cache struct { 19 _i map[string]GitIgnore 20 _lock sync.Mutex 21 } 22 23 // NewCache returns a Cache instance. This is a thread-safe, in-memory cache 24 // for GitIgnore instances. 25 func NewCache() Cache { 26 return &cache{} 27 } // Cache() 28 29 // Set stores the GitIgnore ignore against its path. 30 func (c *cache) Set(path string, ignore GitIgnore) { 31 if ignore == nil { 32 return 33 } 34 35 // ensure the map is defined 36 if c._i == nil { 37 c._i = make(map[string]GitIgnore) 38 } 39 40 // set the cache item 41 c._lock.Lock() 42 c._i[path] = ignore 43 c._lock.Unlock() 44 } // Set() 45 46 // Get attempts to retrieve an GitIgnore instance associated with the given 47 // path. If the path is not known nil is returned. 48 func (c *cache) Get(path string) GitIgnore { 49 c._lock.Lock() 50 _ignore, _ok := c._i[path] 51 c._lock.Unlock() 52 if _ok { 53 return _ignore 54 } else { 55 return nil 56 } 57 } // Get() 58 59 // ensure cache supports the Cache interface 60 var _ Cache = &cache{}