使用Sonar分析Golang代码

为了保证项目代码质量,需要控制每个Pull Request的代码单元测试覆盖率。翻看了Sonar文档,发现Sonar是一款保证代码质量的工具,可以满足此类需求。

下面就用一个Demo来体验一下Sonar的功能。

安装SonarQube

  1. 以Docker容器运行:
docker run -d --name sonarqube -p 9000:9000 sonarqube
  1. 访问http://localhost:9000
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-knBRUCVB-1583920707527)(https://upload-images.jianshu.io/upload_images/4269060-d8fdc548396b6d6e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)]
    使用默认的用户名密码admin/admin登陆。

注意:为了简化建立 SonarQube 的步骤,所有的内容我都使用了默认值。比如,我直接使用了 SonarQube 内建的数据库,端口也采用了默认的 9000。但是,在实际工程项目中,为了 Sonar 数据的长期可维护和升级,我们通常会使用自己的数据库。

安装Sonar Scanner

SonarQube平台搭建完成后,需要安装Sonar Scanner以及创建项目。可以从以下官方提供的Scanner中挑选满足需要的进行安装。

  1. 点击下载MacOS安装包
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mW4FxfJW-1583920707528)(https://upload-images.jianshu.io/upload_images/4269060-b6dda64bb1a64cd3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)]

  2. 下载完成之后解压,修改配置文件conf/sonar-scanner.properties,将sonar.host.url指向我们刚刚搭建的本地SonarQube平台http://localhost:9000
    使用Sonar分析Golang代码

  3. 将sonar-scanner/bin加入$PATH
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ASw03eEA-1583920707529)(https://upload-images.jianshu.io/upload_images/4269060-e31485909376994e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/600)]

  4. 执行sonar-scanner -h可以验证我们已经成功安装了Sonar Scanner
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QYkfAsBW-1583920707530)(https://upload-images.jianshu.io/upload_images/4269060-0cee02b019304c83.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)]

静态代码扫描

在进行静态代码扫描之前需要对项目进行配置,在项目目录下创建sonar-project.properties文件,以我这里分析的Golang项目为例

# must be unique in a given SonarQube instance
sonar.projectKey=play-golang

# --- optional properties ---

# defaults to project key
sonar.projectName=play-golang
# defaults to 'not provided'
sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Defaults to .
sonar.sources=.

# Encoding of the source code. Default is default system encoding
sonar.sourceEncoding=UTF-8

完成之后在项目根目录下执行sonar-scanner进行静态代码分析,扫描结束后可以在SonarQube查看扫描结果。
使用Sonar分析Golang代码

参考:

https://docs.sonarqube.org/latest/setup/get-started-2-minutes/
https://docs.sonarqube.org/latest/analysis/overview/
https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/

上一篇:SoanrQube7.4安装(Window)


下一篇:【环境搭建】SonarQube 8.0 部署到CentOS 6.8下