Skip to content

Commit

Permalink
Use mutex on cached git config
Browse files Browse the repository at this point in the history
This fixes a race condition caused by a concurrent map read and write
  • Loading branch information
jesseduffield committed Jul 9, 2023
1 parent 94800a5 commit b451ca5
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/commands/git_config/cached_git_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package git_config
import (
"os/exec"
"strings"
"sync"

"github.com/sirupsen/logrus"
)
Expand All @@ -20,6 +21,7 @@ type CachedGitConfig struct {
cache map[string]string
runGitConfigCmd func(*exec.Cmd) (string, error)
log *logrus.Entry
mutex sync.Mutex
}

func NewStdCachedGitConfig(log *logrus.Entry) *CachedGitConfig {
Expand All @@ -31,10 +33,14 @@ func NewCachedGitConfig(runGitConfigCmd func(*exec.Cmd) (string, error), log *lo
cache: make(map[string]string),
runGitConfigCmd: runGitConfigCmd,
log: log,
mutex: sync.Mutex{},
}
}

func (self *CachedGitConfig) Get(key string) string {
self.mutex.Lock()
defer self.mutex.Unlock()

if value, ok := self.cache[key]; ok {
self.log.Debugf("using cache for key " + key)
return value
Expand All @@ -46,6 +52,9 @@ func (self *CachedGitConfig) Get(key string) string {
}

func (self *CachedGitConfig) GetGeneral(args string) string {
self.mutex.Lock()
defer self.mutex.Unlock()

if value, ok := self.cache[args]; ok {
self.log.Debugf("using cache for args " + args)
return value
Expand Down

0 comments on commit b451ca5

Please sign in to comment.