- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/
94 lines
1.8 KiB
Go
94 lines
1.8 KiB
Go
// Package task 负责启动外部命令并流式输出,供运行面板使用。
|
|
package task
|
|
|
|
import (
|
|
"bufio"
|
|
"io"
|
|
"os/exec"
|
|
"sync"
|
|
)
|
|
|
|
// Task 是一次命令执行。
|
|
type Task struct {
|
|
// Name 是命令名,用于界面显示。
|
|
Name string
|
|
// Lines 按输出顺序流出标准输出与标准错误的每一行,结束时关闭。
|
|
Lines chan string
|
|
|
|
cmd *exec.Cmd
|
|
done chan struct{}
|
|
mu sync.Mutex
|
|
stopped bool
|
|
}
|
|
|
|
// Start 在 dir 下启动命令,标准输出与标准错误合并成有序的行。
|
|
func Start(dir, name string, args ...string) (*Task, error) {
|
|
cmd := exec.Command(name, args...)
|
|
cmd.Dir = dir
|
|
cmd.SysProcAttr = procAttr()
|
|
|
|
pr, pw := io.Pipe()
|
|
cmd.Stdout = pw
|
|
cmd.Stderr = pw
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
_ = pw.Close()
|
|
_ = pr.Close()
|
|
return nil, err
|
|
}
|
|
|
|
t := &Task{
|
|
Name: name,
|
|
Lines: make(chan string, 2048),
|
|
cmd: cmd,
|
|
done: make(chan struct{}),
|
|
}
|
|
|
|
go func() {
|
|
defer close(t.Lines)
|
|
sc := bufio.NewScanner(pr)
|
|
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
|
|
for sc.Scan() {
|
|
t.Lines <- sc.Text()
|
|
}
|
|
_ = pr.Close()
|
|
}()
|
|
|
|
go func() {
|
|
_ = cmd.Wait()
|
|
_ = pw.Close()
|
|
close(t.done)
|
|
}()
|
|
|
|
return t, nil
|
|
}
|
|
|
|
// Wait 阻塞到命令结束。
|
|
func (t *Task) Wait() { <-t.done }
|
|
|
|
// ExitCode 返回退出码,进程还没结束时为 -1。
|
|
func (t *Task) ExitCode() int {
|
|
if t == nil || t.cmd == nil || t.cmd.ProcessState == nil {
|
|
return -1
|
|
}
|
|
return t.cmd.ProcessState.ExitCode()
|
|
}
|
|
|
|
// Stopped 报告是否被主动停止。
|
|
func (t *Task) Stopped() bool {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
return t.stopped
|
|
}
|
|
|
|
// Stop 结束整个进程树,go run 派生的子进程也一并结束。
|
|
func (t *Task) Stop() {
|
|
if t == nil || t.cmd == nil || t.cmd.Process == nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
t.stopped = true
|
|
t.mu.Unlock()
|
|
killTree(t.cmd.Process.Pid)
|
|
}
|