feat: 添加 session 以及 clone

main v1.2.4
NoahLan 11 months ago
parent e2d7f82c96
commit 8d2e458d61

@ -47,12 +47,13 @@ type Cmd struct {
*Options *Options
// Runtime // Runtime
Cmd *exec.Cmd // CMD Cmd *exec.Cmd // CMD
Name string // name of binary(command) to run Name string // name of binary(command) to run
Args []string // arguments Args []string // arguments
Env []string // *optional environment Env []string // *optional environment
Dir string // working dir Dir string // working dir
stdIn io.WriteCloser // 标准输入通道 Session *Session // 数据存储
stdIn io.WriteCloser // 标准输入通道
stdoutStream *OutputStream // 标准输出通道 stdoutStream *OutputStream // 标准输出通道
stderrStream *OutputStream // 标准错误输出通道 stderrStream *OutputStream // 标准错误输出通道
@ -96,6 +97,7 @@ func NewCmd(opts ...Option) *Cmd {
Buffered: true, Buffered: true,
DevMode: true, DevMode: true,
}, },
Session: NewSession(0),
// flags // flags
started: false, started: false,
stopped: false, stopped: false,
@ -244,6 +246,16 @@ func (c *Cmd) Stopped() bool {
return c.stopped 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() { func (c *Cmd) run() {
defer func() { defer func() {
c.statusChan <- c.Status() c.statusChan <- c.Status()

@ -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()
}
Loading…
Cancel
Save