如何调试视觉工作室代码中的泡泡茶应用
#terminal #go #commandline #bubbletea

问题

我已经使用Bubble Tea framework进行了几周的新TUI。

我当前使用VS代码作为我的主要IDE,并与GO extension相结合。除其他功能外,此扩展名使您能够通过dlv进行调试golang扩展。

但是,如果您尝试使用默认配置调试泡泡茶应用程序,则您的TUI将永远不会启动,并且您会在调试控制台中看到以下错误:Error: open /dev/tty: device not configured

// The default config is not useful for debugging TUIs
{
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${fileDirname}"
        }
    ]
}

解决问题

Bubble Tea README提到,要解决问题,您需要以无头模式运行调试器。

# Start the debugger
$ dlv debug --headless .
API server listening at: 127.0.0.1:34241

# Connect to it from another terminal
$ dlv connect 127.0.0.1:34241

因此,要将VS代码调试器附加到泡泡茶应用程序,您将需要:

  1. 以无头模式启动调试器:

    dlv debug --headless --listen=:2345 .
    
  2. 从vscode连接到它

    // .vscode/tasks.json
    {
        "configurations": [
            {
                "name": "Attach to Sunbeam",
                "type": "go",
                "debugAdapter": "dlv-dap",
                "request": "attach",
                "mode": "remote",
                "remotePath": "${workspaceFolder}",
                "port": 2345,
                "host": "127.0.0.1"
            }
        ]
    }
    

可选:自动启动调试器

上面的方法仍然需要每次要调试应用程序时都需要两次操作。幸运的是,您可以设置每次开始调试应用程序时都将运行的preLaunchTask

我们将创建一个背景任务,该任务将负责启动dlv无头服务器。为了允许VS代码成功启动服务器或返回错误,我们需要定义problemMatcher

// .vscode/tasks.json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run headless dlv",
            "type": "process",
            "command": [
                "dlv",
            ],
            "args": [
                "debug",
                "--headless",
                "--listen=:2345",
                "--api-version=2",
                "${workspaceFolder}/main.go"
            ],
            "isBackground": true,
            "problemMatcher": {
                "owner": "go",
                "fileLocation": "relative",
                "pattern": {
                    "regexp": "^couldn't start listener:", // error if matched
                },
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "^API server listening at:",
                    "endsPattern": "^Got a connection, launched process" // success if matched
                }
            }
        }
    ]
}

然后,我们将在调试器配置中引用此preLaunchTask

{
    "configurations": [
        {
            "name": "Attach to Sunbeam",
            "type": "go",
            "debugAdapter": "dlv-dap",
            "request": "attach",
            "mode": "remote",
            "remotePath": "${workspaceFolder}",
            "port": 2345,
            "host": "127.0.0.1",
            "preLaunchTask": "Run headless dlv" // Here !
        }
    ]
}

恭喜,您现在应该能够设置断点并从VS代码调试BubbleTea应用程序!

感谢您的阅读!如果您想结帐我的工作,请看一下sunbeam repository