MyGoland 首次提交:Go 轻量 IDE
- 编辑器:多标签、语法高亮、gopls 全套(补全/诊断/跳转/重命名/代码动作/内联提示/签名大纲) - 调试:Delve DAP(断点/条件断点/变量树/表达式求值/goroutine 列表) - 测试:结果树、覆盖率行着色、失败跳源码、-run 精确运行、行号可跑标记 - Git:状态着色、选择性暂存提交、pull/push、历史并排对比 - 本地历史 + 自动快照 + 崩溃恢复、会话/光标恢复 - 全局搜索替换(预览+确认,GBK 安全)、多终端、gopls 崩溃自愈 - 设计文档与验证记录见 docs/plans/
This commit is contained in:
commit
a80c0f886a
220 files changed
+20784
No files matched your search
@@ -0,0 +1,492 @@
|
||||
// Package dap 实现一个最小可用的 Debug Adapter Protocol 客户端,用于驱动 dlv dap。
|
||||
package dap
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// request 是发往调试适配器的请求。
|
||||
type request struct {
|
||||
Seq int `json:"seq"`
|
||||
Type string `json:"type"`
|
||||
Command string `json:"command"`
|
||||
Arguments any `json:"arguments,omitempty"`
|
||||
}
|
||||
|
||||
// response 是适配器的应答。
|
||||
type response struct {
|
||||
Seq int `json:"seq"`
|
||||
Type string `json:"type"`
|
||||
RequestSeq int `json:"request_seq"`
|
||||
Success bool `json:"success"`
|
||||
Command string `json:"command"`
|
||||
Message string `json:"message"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
|
||||
// message 用来区分应答与事件。
|
||||
type message struct {
|
||||
Type string `json:"type"`
|
||||
Event string `json:"event"`
|
||||
Seq int `json:"seq"`
|
||||
}
|
||||
|
||||
// Client 是一个 DAP 连接。
|
||||
type Client struct {
|
||||
cmd *exec.Cmd
|
||||
conn net.Conn
|
||||
bw *bufio.Writer
|
||||
r *bufio.Reader
|
||||
|
||||
mu sync.Mutex
|
||||
seq int
|
||||
pending map[int]chan response
|
||||
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
onEvent func(event string, body json.RawMessage)
|
||||
logf func(string, ...any)
|
||||
}
|
||||
|
||||
// Start 启动 dlv dap 并连接它监听的端口。
|
||||
//
|
||||
// dlv dap 不接受 stdio 传输:它会监听一个随机端口并把地址打到标准输出,
|
||||
// 所以先解析 "DAP server listening at: host:port" 再拨号。
|
||||
func Start(dir string, onEvent func(string, json.RawMessage), logf func(string, ...any)) (*Client, error) {
|
||||
if logf == nil {
|
||||
logf = func(string, ...any) {}
|
||||
}
|
||||
path, err := exec.LookPath("dlv")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("找不到 dlv,请先执行:go install github.com/go-delve/delve/cmd/dlv@latest")
|
||||
}
|
||||
cmd := exec.Command(path, "dap", "--listen=127.0.0.1:0")
|
||||
cmd.Dir = dir
|
||||
cmd.SysProcAttr = procAttr()
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("启动 dlv 失败:%w", err)
|
||||
}
|
||||
|
||||
addrCh := make(chan string, 1)
|
||||
go func() {
|
||||
sc := bufio.NewScanner(stdout)
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
logf("dlv: %s", line)
|
||||
if i := strings.Index(line, "listening at:"); i >= 0 {
|
||||
addr := strings.TrimSpace(line[i+len("listening at:"):])
|
||||
select {
|
||||
case addrCh <- addr:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
sc := bufio.NewScanner(stderr)
|
||||
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for sc.Scan() {
|
||||
logf("dlv: %s", sc.Text())
|
||||
}
|
||||
}()
|
||||
|
||||
var addr string
|
||||
select {
|
||||
case addr = <-addrCh:
|
||||
case <-time.After(20 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
return nil, fmt.Errorf("dlv dap 没有在 20 秒内就绪")
|
||||
}
|
||||
|
||||
var conn net.Conn
|
||||
for i := 0; i < 20; i++ {
|
||||
conn, err = net.DialTimeout("tcp", addr, 2*time.Second)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
return nil, fmt.Errorf("连接 %s 失败:%w", addr, err)
|
||||
}
|
||||
|
||||
c := &Client{
|
||||
cmd: cmd,
|
||||
conn: conn,
|
||||
bw: bufio.NewWriter(conn),
|
||||
r: bufio.NewReader(conn),
|
||||
pending: map[int]chan response{},
|
||||
done: make(chan struct{}),
|
||||
onEvent: onEvent,
|
||||
logf: logf,
|
||||
}
|
||||
go c.readLoop()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// readFrame 读出一条 DAP 报文。
|
||||
func readFrame(r *bufio.Reader) ([]byte, error) {
|
||||
length := -1
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
if k, v, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(v))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dap: 非法的 Content-Length %q", v)
|
||||
}
|
||||
length = n
|
||||
}
|
||||
}
|
||||
if length < 0 {
|
||||
return nil, errors.New("dap: 缺少 Content-Length")
|
||||
}
|
||||
buf := make([]byte, length)
|
||||
if _, err := io.ReadFull(r, buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func (c *Client) readLoop() {
|
||||
defer c.close()
|
||||
for {
|
||||
body, err := readFrame(c.r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var m message
|
||||
if err := json.Unmarshal(body, &m); err != nil {
|
||||
continue
|
||||
}
|
||||
switch m.Type {
|
||||
case "response":
|
||||
var resp response
|
||||
if err := json.Unmarshal(body, &resp); err != nil {
|
||||
continue
|
||||
}
|
||||
c.mu.Lock()
|
||||
ch := c.pending[resp.RequestSeq]
|
||||
c.mu.Unlock()
|
||||
if ch != nil {
|
||||
select {
|
||||
case ch <- resp:
|
||||
default:
|
||||
}
|
||||
}
|
||||
case "event":
|
||||
var ev struct {
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &ev)
|
||||
if c.onEvent != nil {
|
||||
go c.onEvent(m.Event, ev.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Do 发送请求并等待应答。
|
||||
func (c *Client) Do(command string, args any, timeout time.Duration) (json.RawMessage, error) {
|
||||
c.mu.Lock()
|
||||
c.seq++
|
||||
seq := c.seq
|
||||
ch := make(chan response, 1)
|
||||
c.pending[seq] = ch
|
||||
c.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
delete(c.pending, seq)
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
|
||||
body, err := json.Marshal(request{Seq: seq, Type: "request", Command: command, Arguments: args})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.Lock()
|
||||
_, werr := fmt.Fprintf(c.bw, "Content-Length: %d\r\n\r\n", len(body))
|
||||
if werr == nil {
|
||||
_, werr = c.bw.Write(body)
|
||||
}
|
||||
if werr == nil {
|
||||
werr = c.bw.Flush()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if werr != nil {
|
||||
return nil, werr
|
||||
}
|
||||
|
||||
select {
|
||||
case resp := <-ch:
|
||||
if !resp.Success {
|
||||
if resp.Message != "" {
|
||||
return nil, errors.New("dap: " + resp.Message)
|
||||
}
|
||||
return nil, fmt.Errorf("dap: %s 失败", command)
|
||||
}
|
||||
return resp.Body, nil
|
||||
case <-time.After(timeout):
|
||||
return nil, fmt.Errorf("dap: %s 超时", command)
|
||||
case <-c.done:
|
||||
return nil, errors.New("dap: 连接已关闭")
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize 完成 DAP 握手。
|
||||
func (c *Client) Initialize() error {
|
||||
_, err := c.Do("initialize", map[string]any{
|
||||
"clientID": "mygoland",
|
||||
"clientName": "MyGoland",
|
||||
"adapterID": "go",
|
||||
"linesStartAt1": true,
|
||||
"columnsStartAt1": true,
|
||||
"pathFormat": "path",
|
||||
"supportsVariableType": true,
|
||||
"supportsVariablePaging": false,
|
||||
"supportsRunInTerminalRequest": false,
|
||||
}, 30*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// Launch 启动被调试程序,args 是传给程序的参数。
|
||||
func (c *Client) Launch(program string, args []string, stopOnEntry bool, timeout time.Duration) error {
|
||||
_, err := c.Do("launch", map[string]any{
|
||||
"mode": "debug",
|
||||
"program": program,
|
||||
"args": args,
|
||||
"stopOnEntry": stopOnEntry,
|
||||
}, timeout)
|
||||
return err
|
||||
}
|
||||
|
||||
// Evaluate 在某个栈帧上求值。
|
||||
func (c *Client) Evaluate(expr string, frameID int) (string, error) {
|
||||
body, err := c.Do("evaluate", map[string]any{
|
||||
"expression": expr,
|
||||
"frameId": frameID,
|
||||
"context": "watch",
|
||||
}, 15*time.Second)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out struct {
|
||||
Result string `json:"result"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if out.Type != "" {
|
||||
return out.Result + " (" + out.Type + ")", nil
|
||||
}
|
||||
return out.Result, nil
|
||||
}
|
||||
|
||||
// ConfigurationDone 告诉适配器配置阶段结束,程序可以跑起来。
|
||||
func (c *Client) ConfigurationDone() error {
|
||||
_, err := c.Do("configurationDone", nil, 10*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// BreakpointSpec 是设置断点时的入参:行号 + 可选条件。
|
||||
type BreakpointSpec struct {
|
||||
Line int `json:"line"`
|
||||
Condition string `json:"condition,omitempty"`
|
||||
}
|
||||
|
||||
// Breakpoint 是一个断点。
|
||||
type Breakpoint struct {
|
||||
Line int `json:"line"`
|
||||
Verified bool `json:"verified"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// SetBreakpoints 为某个文件设置断点,行号从 1 开始。
|
||||
func (c *Client) SetBreakpoints(path string, specs []BreakpointSpec) ([]Breakpoint, error) {
|
||||
bps := make([]map[string]any, 0, len(specs))
|
||||
lines := make([]int, 0, len(specs))
|
||||
for _, s := range specs {
|
||||
entry := map[string]any{"line": s.Line}
|
||||
if s.Condition != "" {
|
||||
entry["condition"] = s.Condition
|
||||
}
|
||||
bps = append(bps, entry)
|
||||
lines = append(lines, s.Line)
|
||||
}
|
||||
body, err := c.Do("setBreakpoints", map[string]any{
|
||||
"source": map[string]any{"path": path},
|
||||
"breakpoints": bps,
|
||||
"lines": lines,
|
||||
}, 15*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out struct {
|
||||
Breakpoints []Breakpoint `json:"breakpoints"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return out.Breakpoints, nil
|
||||
}
|
||||
|
||||
// Frame 是一个调用栈帧。
|
||||
type Frame struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Line int `json:"line"`
|
||||
Column int `json:"column"`
|
||||
Source struct {
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
} `json:"source"`
|
||||
}
|
||||
|
||||
// Thread 是一个线程。dlv dap 把 goroutine 当线程列出来,
|
||||
// name 通常是 goroutine 正停住的函数名。
|
||||
type Thread struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Threads 列出当前的线程(goroutine)。
|
||||
func (c *Client) Threads() ([]Thread, error) {
|
||||
body, err := c.Do("threads", nil, 15*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out struct {
|
||||
Threads []Thread `json:"threads"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return out.Threads, nil
|
||||
}
|
||||
|
||||
// StackTrace 取某个线程的调用栈。
|
||||
func (c *Client) StackTrace(threadID, levels int) ([]Frame, error) {
|
||||
body, err := c.Do("stackTrace", map[string]any{
|
||||
"threadId": threadID,
|
||||
"startFrame": 0,
|
||||
"levels": levels,
|
||||
}, 15*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out struct {
|
||||
StackFrames []Frame `json:"stackFrames"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return out.StackFrames, nil
|
||||
}
|
||||
|
||||
// Scope 是一个作用域。
|
||||
type Scope struct {
|
||||
Name string `json:"name"`
|
||||
VariablesReference int `json:"variablesReference"`
|
||||
Expensive bool `json:"expensive"`
|
||||
}
|
||||
|
||||
// Scopes 取栈帧的作用域。
|
||||
func (c *Client) Scopes(frameID int) ([]Scope, error) {
|
||||
body, err := c.Do("scopes", map[string]any{"frameId": frameID}, 15*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out struct {
|
||||
Scopes []Scope `json:"scopes"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return out.Scopes, nil
|
||||
}
|
||||
|
||||
// Variable 是一个变量。
|
||||
type Variable struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Type string `json:"type"`
|
||||
VariablesReference int `json:"variablesReference"`
|
||||
}
|
||||
|
||||
// Variables 取某个引用下的变量。
|
||||
func (c *Client) Variables(ref int) ([]Variable, error) {
|
||||
body, err := c.Do("variables", map[string]any{"variablesReference": ref}, 15*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out struct {
|
||||
Variables []Variable `json:"variables"`
|
||||
}
|
||||
_ = json.Unmarshal(body, &out)
|
||||
return out.Variables, nil
|
||||
}
|
||||
|
||||
// Continue 继续执行。
|
||||
func (c *Client) Continue(threadID int) error {
|
||||
_, err := c.Do("continue", map[string]any{"threadId": threadID}, 15*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// Next 步过。
|
||||
func (c *Client) Next(threadID int) error {
|
||||
_, err := c.Do("next", map[string]any{"threadId": threadID}, 15*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// StepIn 单步进入。
|
||||
func (c *Client) StepIn(threadID int) error {
|
||||
_, err := c.Do("stepIn", map[string]any{"threadId": threadID}, 15*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// StepOut 跳出。
|
||||
func (c *Client) StepOut(threadID int) error {
|
||||
_, err := c.Do("stepOut", map[string]any{"threadId": threadID}, 15*time.Second)
|
||||
return err
|
||||
}
|
||||
|
||||
// Close 断开并结束调试会话。
|
||||
func (c *Client) Close() {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
_, _ = c.Do("disconnect", map[string]any{"terminateDebuggee": true}, 3*time.Second)
|
||||
c.close()
|
||||
if c.cmd != nil && c.cmd.Process != nil {
|
||||
_ = c.cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) close() {
|
||||
c.once.Do(func() {
|
||||
close(c.done)
|
||||
if c.conn != nil {
|
||||
_ = c.conn.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package dap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// eventLog 收集适配器事件。
|
||||
type eventLog struct {
|
||||
mu sync.Mutex
|
||||
events map[string]chan json.RawMessage
|
||||
}
|
||||
|
||||
func newEventLog() *eventLog {
|
||||
return &eventLog{events: map[string]chan json.RawMessage{}}
|
||||
}
|
||||
|
||||
func (l *eventLog) push(name string, body json.RawMessage) {
|
||||
l.mu.Lock()
|
||||
ch, ok := l.events[name]
|
||||
if !ok {
|
||||
ch = make(chan json.RawMessage, 8)
|
||||
l.events[name] = ch
|
||||
}
|
||||
l.mu.Unlock()
|
||||
select {
|
||||
case ch <- body:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (l *eventLog) wait(name string, d time.Duration) (json.RawMessage, bool) {
|
||||
l.mu.Lock()
|
||||
ch, ok := l.events[name]
|
||||
if !ok {
|
||||
ch = make(chan json.RawMessage, 8)
|
||||
l.events[name] = ch
|
||||
}
|
||||
l.mu.Unlock()
|
||||
select {
|
||||
case body := <-ch:
|
||||
return body, true
|
||||
case <-time.After(d):
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
const prog = `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func add(a, b int) int {
|
||||
sum := a + b
|
||||
return sum
|
||||
}
|
||||
|
||||
func main() {
|
||||
x := 1
|
||||
y := 2
|
||||
fmt.Println(add(x, y))
|
||||
}
|
||||
`
|
||||
|
||||
// goroutineProg 三个 worker 并发跑,用来验证 threads 列 goroutine。
|
||||
const goroutineProg = `package main
|
||||
|
||||
import "sync"
|
||||
|
||||
func worker(wg *sync.WaitGroup, n int) {
|
||||
defer wg.Done()
|
||||
x := n * 2
|
||||
_ = x
|
||||
}
|
||||
|
||||
func main() {
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 3; i++ {
|
||||
wg.Add(1)
|
||||
go worker(&wg, i)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
`
|
||||
|
||||
// TestThreadsGoroutines 停在并发程序的断点上时,threads 应列出
|
||||
// goroutine,且当前停住的那个在列表里——这是调试面板 goroutine 列表的数据源。
|
||||
func TestThreadsGoroutines(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("集成测试需要 dlv")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := filepath.Join(dir, "main.go")
|
||||
if err := os.WriteFile(main, []byte(goroutineProg), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
log := newEventLog()
|
||||
c, err := Start(dir, log.push, t.Logf)
|
||||
if err != nil {
|
||||
t.Skipf("dlv 不可用: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if err := c.Initialize(); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
launched := make(chan error, 1)
|
||||
go func() { launched <- c.Launch("./", nil, false, 120*time.Second) }()
|
||||
|
||||
if _, ok := log.wait("initialized", 90*time.Second); !ok {
|
||||
t.Fatal("没有收到 initialized 事件")
|
||||
}
|
||||
// 第 7 行 `x := n * 2`:三个 worker 都会经过。
|
||||
if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 7}}); err != nil {
|
||||
t.Fatalf("setBreakpoints: %v", err)
|
||||
}
|
||||
if err := c.ConfigurationDone(); err != nil {
|
||||
t.Fatalf("configurationDone: %v", err)
|
||||
}
|
||||
body, ok := log.wait("stopped", 90*time.Second)
|
||||
if !ok {
|
||||
t.Fatal("没有停在断点上")
|
||||
}
|
||||
var stopped struct {
|
||||
ThreadID int `json:"threadId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
threads, err := c.Threads()
|
||||
if err != nil {
|
||||
t.Fatalf("threads: %v", err)
|
||||
}
|
||||
if len(threads) == 0 {
|
||||
t.Fatal("应至少列出一个 goroutine")
|
||||
}
|
||||
ids := map[int]bool{}
|
||||
current := false
|
||||
for _, th := range threads {
|
||||
if th.ID == 0 {
|
||||
t.Fatalf("goroutine 编号不应为 0: %+v", th)
|
||||
}
|
||||
if ids[th.ID] {
|
||||
t.Fatalf("goroutine 编号重复: %d", th.ID)
|
||||
}
|
||||
ids[th.ID] = true
|
||||
if th.ID == stopped.ThreadID {
|
||||
current = true
|
||||
}
|
||||
}
|
||||
if !current {
|
||||
t.Fatalf("当前停住的 goroutine %d 不在列表里: %+v", stopped.ThreadID, threads)
|
||||
}
|
||||
<-launched
|
||||
}
|
||||
|
||||
func TestDebugSession(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("集成测试需要 dlv")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := filepath.Join(dir, "main.go")
|
||||
if err := os.WriteFile(main, []byte(prog), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
log := newEventLog()
|
||||
c, err := Start(dir, log.push, t.Logf)
|
||||
if err != nil {
|
||||
t.Skipf("dlv 不可用: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if err := c.Initialize(); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
|
||||
launched := make(chan error, 1)
|
||||
go func() { launched <- c.Launch("./", nil, false, 120*time.Second) }()
|
||||
|
||||
// 等适配器准备好接收断点。
|
||||
if _, ok := log.wait("initialized", 90*time.Second); !ok {
|
||||
t.Fatal("没有收到 initialized 事件")
|
||||
}
|
||||
if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 6}}); err != nil {
|
||||
t.Fatalf("setBreakpoints: %v", err)
|
||||
}
|
||||
if err := c.ConfigurationDone(); err != nil {
|
||||
t.Fatalf("configurationDone: %v", err)
|
||||
}
|
||||
|
||||
body, ok := log.wait("stopped", 90*time.Second)
|
||||
if !ok {
|
||||
t.Fatal("没有停在断点上")
|
||||
}
|
||||
var stopped struct {
|
||||
Reason string `json:"reason"`
|
||||
ThreadID int `json:"threadId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stopped.ThreadID == 0 {
|
||||
t.Fatalf("stopped 事件没有线程号: %s", body)
|
||||
}
|
||||
|
||||
frames, err := c.StackTrace(stopped.ThreadID, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("stackTrace: %v", err)
|
||||
}
|
||||
if len(frames) == 0 {
|
||||
t.Fatal("调用栈为空")
|
||||
}
|
||||
top := frames[0]
|
||||
if top.Line != 6 {
|
||||
t.Fatalf("断点行号: got %d want 6(栈顶 %s)", top.Line, top.Name)
|
||||
}
|
||||
if !strings.HasSuffix(strings.ToLower(top.Source.Path), "main.go") {
|
||||
t.Fatalf("栈顶文件不对: %s", top.Source.Path)
|
||||
}
|
||||
|
||||
// 变量里应当有 a 和 b。
|
||||
scopes, err := c.Scopes(top.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("scopes: %v", err)
|
||||
}
|
||||
names := map[string]string{}
|
||||
for _, sc := range scopes {
|
||||
if sc.Expensive || sc.VariablesReference == 0 {
|
||||
continue
|
||||
}
|
||||
vs, err := c.Variables(sc.VariablesReference)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, v := range vs {
|
||||
names[v.Name] = v.Value
|
||||
}
|
||||
}
|
||||
if _, ok := names["a"]; !ok {
|
||||
t.Fatalf("变量里没有 a:%v", names)
|
||||
}
|
||||
if names["a"] != "1" {
|
||||
t.Fatalf("a 的值: got %q want \"1\"", names["a"])
|
||||
}
|
||||
|
||||
// 表达式求值。
|
||||
res, err := c.Evaluate("a+b", top.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("evaluate: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(res, "3") {
|
||||
t.Fatalf("a+b 求值结果: %q", res)
|
||||
}
|
||||
|
||||
// 单步一次,应当移动到 return 行。
|
||||
if err := c.Next(stopped.ThreadID); err != nil {
|
||||
t.Fatalf("next: %v", err)
|
||||
}
|
||||
body, ok = log.wait("stopped", 60*time.Second)
|
||||
if !ok {
|
||||
t.Fatal("单步后没有再次停下")
|
||||
}
|
||||
if err := json.Unmarshal(body, &stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames, err = c.StackTrace(stopped.ThreadID, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("stackTrace: %v", err)
|
||||
}
|
||||
if frames[0].Line != 7 {
|
||||
t.Fatalf("单步后行号: got %d want 7", frames[0].Line)
|
||||
}
|
||||
|
||||
// 继续执行,程序应当跑完。
|
||||
if err := c.Continue(stopped.ThreadID); err != nil {
|
||||
t.Fatalf("continue: %v", err)
|
||||
}
|
||||
if _, ok := log.wait("terminated", 60*time.Second); !ok {
|
||||
t.Fatal("程序没有结束")
|
||||
}
|
||||
if err := <-launched; err != nil {
|
||||
t.Fatalf("launch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConditionalBreakpoint 验证条件断点:循环里只有 i == 3 那次才停。
|
||||
func TestConditionalBreakpoint(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("集成测试需要 dlv")
|
||||
}
|
||||
prog := `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
total := 0
|
||||
for i := 0; i < 5; i++ {
|
||||
total += i
|
||||
}
|
||||
fmt.Println(total)
|
||||
}
|
||||
`
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := filepath.Join(dir, "main.go")
|
||||
if err := os.WriteFile(main, []byte(prog), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
log := newEventLog()
|
||||
c, err := Start(dir, log.push, t.Logf)
|
||||
if err != nil {
|
||||
t.Skipf("dlv 不可用: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if err := c.Initialize(); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
go func() { _ = c.Launch("./", nil, false, 120*time.Second) }()
|
||||
|
||||
if _, ok := log.wait("initialized", 90*time.Second); !ok {
|
||||
t.Fatal("没有收到 initialized 事件")
|
||||
}
|
||||
// 第 8 行是 total += i,条件 i == 3
|
||||
if _, err := c.SetBreakpoints(main, []BreakpointSpec{{Line: 8, Condition: "i == 3"}}); err != nil {
|
||||
t.Fatalf("setBreakpoints: %v", err)
|
||||
}
|
||||
if err := c.ConfigurationDone(); err != nil {
|
||||
t.Fatalf("configurationDone: %v", err)
|
||||
}
|
||||
|
||||
body, ok := log.wait("stopped", 90*time.Second)
|
||||
if !ok {
|
||||
t.Fatal("条件断点没有停下")
|
||||
}
|
||||
var stopped struct {
|
||||
ThreadID int `json:"threadId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames, err := c.StackTrace(stopped.ThreadID, 10)
|
||||
if err != nil || len(frames) == 0 {
|
||||
t.Fatalf("stackTrace: %v", err)
|
||||
}
|
||||
if got := frames[0].Line; got != 8 {
|
||||
t.Fatalf("应停在第 8 行,实际 %d", got)
|
||||
}
|
||||
|
||||
// 停在 i == 3 时,变量 i 的值必须是 3
|
||||
scopes, err := c.Scopes(frames[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("scopes: %v", err)
|
||||
}
|
||||
found := ""
|
||||
for _, sc := range scopes {
|
||||
if sc.Expensive || sc.VariablesReference == 0 {
|
||||
continue
|
||||
}
|
||||
vs, err := c.Variables(sc.VariablesReference)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, v := range vs {
|
||||
if v.Name == "i" {
|
||||
found = v.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
if found != "3" {
|
||||
t.Fatalf("条件断点应在 i == 3 时停下,实际 i = %q", found)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !windows
|
||||
|
||||
package dap
|
||||
|
||||
import "syscall"
|
||||
|
||||
// procAttr 在非 Windows 平台不需要额外属性。
|
||||
func procAttr() *syscall.SysProcAttr {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build windows
|
||||
|
||||
package dap
|
||||
|
||||
import "syscall"
|
||||
|
||||
// procAttr 隐藏 dlv 子进程的控制台窗口。
|
||||
func procAttr() *syscall.SysProcAttr {
|
||||
return &syscall.SysProcAttr{HideWindow: true}
|
||||
}
|
||||
Reference in new issue
Block a user