Golang中go tool cover -html在Ubuntu系统失效问题排查

Golang中go tool cover -html在Ubuntu系统失效问题排查 go tool cover -html=xxx 在 Ubuntu 22.04 上不再有效,因为它使用了 /tmp 目录下的文件,但 Firefox 现在运行在沙盒环境中,无法访问系统的 /tmp 目录(或根目录)。

最近几个月,Firefox 从 apt 包改为了 snap 包。由于 snap 的工作方式,Firefox 现在运行在一个无法访问系统根目录的沙盒中,Firefox 看到的 /tmp 目录与系统的 /tmp/ 目录并不相同。

我为此开了一个 issue:cmd/cover: cover uses /tmp but ubuntu 22.04 Firefox now won’t access /tmp · Issue #68343 · golang/go · GitHub。他们显然不认为一个 go 工具在 Ubuntu 上无法按描述工作是 go 的问题。

如果你认为这个问题应该被修复,请去点赞。

同时,这里有一些变通方法:

  1. 使用 TMPDIR 环境变量覆盖:TMPDIR=/x/y/z go tool cover -html=x.out
  2. 卸载 Firefox 并使用 PPA(个人软件包存档)重新安装,但请注意,您还必须配置优先级,否则它只会使用 snap 重新安装。参见 software installation - How to install Firefox as a traditional deb package (without snap) in Ubuntu 22.04 or later versions? - Ask Ubuntu
  3. 使用 out= 选项将文件输出到用户目录中,然后在 Firefox 中打开该文件(但这需要每次运行 go tool cover 时都手动操作,或者将其包装在脚本中并使用 xdg-open 来打开 URL。)

更多关于Golang中go tool cover -html在Ubuntu系统失效问题排查的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

更多关于Golang中go tool cover -html在Ubuntu系统失效问题排查的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这是一个由Ubuntu Firefox snap包沙盒限制导致的兼容性问题。go tool cover默认使用系统临时目录生成HTML文件,而snap版本的Firefox无法访问真实的系统/tmp目录。

以下是几种可行的解决方案:

方案1:设置TMPDIR环境变量(推荐)

# 将临时目录设置为用户目录下的位置
TMPDIR=$HOME/tmp go tool cover -html=coverage.out

或者永久设置环境变量:

# 添加到 ~/.bashrc 或 ~/.zshrc
export TMPDIR=$HOME/.cache/go-tmp

# 创建目录
mkdir -p $HOME/.cache/go-tmp

方案2:使用自定义输出路径

# 指定输出到用户目录
go tool cover -html=coverage.out -o $HOME/coverage.html
# 然后用Firefox打开
firefox $HOME/coverage.html

方案3:创建包装脚本

// cover_wrapper.go
package main

import (
    "os"
    "os/exec"
    "path/filepath"
)

func main() {
    // 在用户目录创建临时文件
    tmpDir := filepath.Join(os.Getenv("HOME"), ".go-cover-html")
    os.MkdirAll(tmpDir, 0755)
    
    // 设置环境变量
    os.Setenv("TMPDIR", tmpDir)
    
    // 执行原命令
    cmd := exec.Command("go", os.Args[1:]...)
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Run()
}

编译并使用:

go build -o go-cover cover_wrapper.go
./go-cover tool cover -html=coverage.out

方案4:直接生成并打开

#!/bin/bash
# cover.sh
OUTPUT="$HOME/coverage-$$.html"
go tool cover -html="$1" -o "$OUTPUT"
firefox "file://$OUTPUT"

使用:

chmod +x cover.sh
./cover.sh coverage.out

方案5:使用其他浏览器

# 安装chromium或chrome
TMPDIR=$HOME/tmp go tool cover -html=coverage.out

这些解决方案都能绕过snap沙盒的限制,确保覆盖率报告能在Ubuntu 22.04+上正常显示。

回到顶部