diff --git a/ncmd/cmd.go b/ncmd/cmd.go index e87702b..f1820a0 100644 --- a/ncmd/cmd.go +++ b/ncmd/cmd.go @@ -47,12 +47,13 @@ type Cmd struct { *Options // Runtime - Cmd *exec.Cmd // CMD - Name string // name of binary(command) to run - Args []string // arguments - Env []string // *optional environment - Dir string // working dir - stdIn io.WriteCloser // 标准输入通道 + Cmd *exec.Cmd // CMD + Name string // name of binary(command) to run + Args []string // arguments + Env []string // *optional environment + Dir string // working dir + Session *Session // 数据存储 + stdIn io.WriteCloser // 标准输入通道 stdoutStream *OutputStream // 标准输出通道 stderrStream *OutputStream // 标准错误输出通道 @@ -96,6 +97,7 @@ func NewCmd(opts ...Option) *Cmd { Buffered: true, DevMode: true, }, + Session: NewSession(0), // flags started: false, stopped: false, @@ -244,6 +246,16 @@ func (c *Cmd) Stopped() bool { return c.stopped } +// Clone 克隆一个 Cmd 示例,所有配置转置 +// Cmd 是一个一次性用途的实例,要重启首先需要克隆 +func (c *Cmd) Clone() *Cmd { + clone := NewCmd(WithOptions(c.Options)) + clone.Dir = c.Dir + clone.Env = c.Env + + return clone +} + func (c *Cmd) run() { defer func() { c.statusChan <- c.Status() diff --git a/ncmd/session.go b/ncmd/session.go new file mode 100644 index 0000000..a30a040 --- /dev/null +++ b/ncmd/session.go @@ -0,0 +1,93 @@ +package ncmd + +import "sync" + +type Session struct { + id int64 // 唯一ID + data map[string]any // 数据存储 + + *sync.RWMutex +} + +func NewSession(id int64) *Session { + return &Session{ + id: id, + data: make(map[string]any), + RWMutex: &sync.RWMutex{}, + } +} + +func (s *Session) Id() int64 { + return s.id +} + +func (s *Session) SetId(id int64) { + s.id = id +} + +// Attribute 获取指定key对应参数 +func (s *Session) Attribute(key string) any { + s.RLock() + defer s.RUnlock() + + return s.data[key] +} + +// Keys 获取所有参数key +func (s *Session) Keys() []string { + s.RLock() + defer s.RUnlock() + + keys := make([]string, 0, len(s.data)) + for k := range s.data { + keys = append(keys, k) + } + return keys +} + +// Exists 指定key是否存在 +func (s *Session) Exists(key string) bool { + s.RLock() + defer s.RUnlock() + + _, has := s.data[key] + return has +} + +// Attributes 获取所有参数 +func (s *Session) Attributes() map[string]any { + s.RLock() + defer s.RUnlock() + + return s.data +} + +// RemoveAttribute 移除指定key对应参数 +func (s *Session) RemoveAttribute(key string) { + s.Lock() + defer s.Unlock() + + delete(s.data, key) +} + +// SetAttribute 设置参数 +func (s *Session) SetAttribute(key string, value any) { + s.Lock() + defer s.Unlock() + + s.data[key] = value +} + +// Invalidate 清理 +func (s *Session) Invalidate() { + s.Lock() + defer s.Unlock() + + s.id = 0 + s.data = make(map[string]any) +} + +// Close 关闭 +func (s *Session) Close() { + s.Invalidate() +}