Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: make ishell context values safe to use concurrently #152

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 25 additions & 11 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package ishell

import "sync"

// Context is an ishell context. It embeds ishell.Actions.
type Context struct {
contextValues
*contextValues
progressBar ProgressBar
err error

Expand Down Expand Up @@ -30,32 +32,44 @@ func (c *Context) ProgressBar() ProgressBar {
}

// contextValues is the map for values in the context.
type contextValues map[string]interface{}
type contextValues struct {
vals map[string]interface{}
*sync.RWMutex
}

// Get returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Get with
// the same key returns the same result.
func (c contextValues) Get(key string) interface{} {
return c[key]
func (c *contextValues) Get(key string) interface{} {
c.RLock()
defer c.RUnlock()
return c.vals[key]
}

// Set sets the key in this context to value.
func (c *contextValues) Set(key string, value interface{}) {
if *c == nil {
*c = make(map[string]interface{})
if c.vals == nil {
c.vals = make(map[string]interface{})
c.RWMutex = &sync.RWMutex{}
}
(*c)[key] = value
c.Lock()
c.vals[key] = value
c.Unlock()
}

// Del deletes key and its value in this context.
func (c contextValues) Del(key string) {
delete(c, key)
func (c *contextValues) Del(key string) {
c.Lock()
delete(c.vals, key)
c.Unlock()
}

// Keys returns all keys in the context.
func (c contextValues) Keys() (keys []string) {
for key := range c {
func (c *contextValues) Keys() (keys []string) {
c.RLock()
for key := range c.vals {
keys = append(keys, key)
}
c.RUnlock()
return
}
8 changes: 4 additions & 4 deletions ishell.go
Original file line number Diff line number Diff line change
Expand Up @@ -669,10 +669,10 @@ func newContext(s *Shell, cmd *Cmd, args []string) *Context {
Args: args,
RawArgs: s.rawArgs,
Cmd: *cmd,
contextValues: func() contextValues {
values := contextValues{}
for k := range s.contextValues {
values[k] = s.contextValues[k]
contextValues: func() *contextValues {
values := &contextValues{}
for k := range s.contextValues.vals {
values.Set(k, s.contextValues.vals[k])
}
return values
}(),
Expand Down