使用Sonar分析Golang代码

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

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

安装SonarQube

  1. 以Docker容器运行:
docker run -d --name sonarqube -p 9000:9000 sonarqube
  1. 访问http://localhost:9000
    image.png

    使用默认的用户名密码admin/admin登陆。

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

安装Sonar Scanner

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

  1. 点击下载MacOS安装包


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

    image.png

  3. 将sonar-scanner/bin加入$PATH


    image.png
  4. 执行sonar-scanner -h可以验证我们已经成功安装了Sonar Scanner

    image.png

静态代码扫描

在进行静态代码扫描之前需要对项目进行配置,在项目目录下创建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查看扫描结果。

image.png

参考:

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/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、sonar 基础概念? a. 是一个代码质量分析平台。b. 通过插件机制,集成不同的测试工具。 (和jenki...
    凯天阅读 10,484评论 0 2
  • Sonar简介 Sonar是一个用于代码质量管理的开源平台,用于管理源代码的质量,可以从七个维度检测代码质量 通过...
    真的有神阅读 3,928评论 0 0
  • 一. Linux服务器搭建sonar https://www.digitalocean.com/community...
    hehetc阅读 2,094评论 4 3
  • 本文重点说明sonarqube的使用和搭建,以及集成到Jenkins,从因到果进行详细的说明。gitLab+Jen...
    GeekSpring阅读 25,692评论 1 7
  • 背景 随着区块链的这2年的快速发展,Go语言和针对GO语言测试工具也越来越完善,特别是Go语言的静态代码扫描工具完...
    老余2017阅读 11,399评论 1 17