目录
使用方式:" >使用方式:
1. 项目中已经存在这些内容" >1. 项目中已经存在这些内容
2. 新建项目这个怎么搞" >2. 新建项目这个怎么搞
首页 后端开发 Golang golangci-lint应用

golangci-lint应用

Aug 04, 2023 pm 05:03 PM
go golangci-lint

golangci-lint 是什么?

golangci-lint 是一个 Go linters 聚合器,而 linter 是使用工具来对代码提供一些检查,保证提交代码的质量。golangci-lint 是一个 Go linters 聚合器,而 linter 是使用工具来对代码提供一些检查,保证提交代码的质量。

为什么不直接使用 golangci-lint ?

需要手动执行,在之前使用的过程中,由于项目是多人活动,总是会忘记执行golangci-lint 进行代码检查,当前我自己也是。所以我们希望采用一种隐式的方式来自动执行。那么经过多番思考,采用 git 的 hooks 可以来自动执行一些脚本。

这期间还有一些其他的尝试,不过这个文章主要说 在git中的使用ci-lint,有兴趣的可以移步到为什么最终采用git 本地 hooks 的方式执行golangci-lint?

采用 git 的 hooks 来自动执行检查!

前提条件

请设置 goland 的默认终端为 bash,不然后面执行脚本的时候,可能会不支持。

golangci-lint应用

由于现在采用 git 作为我们的版本管理系统(VCS),而git

为什么不直接使用 golangci-lint ?🎜🎜需要手动执行,在之前使用的过程中,由于项目是多人活动,总是会忘记执行golangci-lint 进行代码检查,当前我自己也是。所以我们希望采用一种隐式的方式来自动执行。那么经过多番思考,采用 git 的 hooks 可以来自动执行一些脚本。🎜🎜这期间还有一些其他的尝试,不过这个文章主要说 在git中的使用ci-lint,有兴趣的可以移步到为什么最终采用git 本地 hooks 的方式执行golangci-lint?🎜🎜🎜🎜采用 git 的 hooks 来自动执行检查!🎜🎜前提条件:🎜🎜请设置 goland 的默认终端为 bash,不然后面执行脚本的时候,可能会不支持。🎜
golangci-lint应用
🎜由于现在采用 git 作为我们的版本管理系统(VCS),而git在执行一些操作之前,允许执行脚本,这就可以让我们来执行一些操作前的代码检查。🎜🎜项目代码目录:🎜
├── .githooks
│   ├── applypatch-msg.sample
│   ├── commit-msg.sample
│   ├── fsmonitor-watchman.sample
│   ├── post-update.sample
│   ├── pre-applypatch.sample
│   ├── pre-commit
│   ├── pre-merge-commit.sample
│   ├── pre-push
│   ├── pre-rebase.sample
│   ├── pre-receive.sample
│   ├── prepare-commit-msg.sample
│   ├── push-to-checkout.sample
│   └── update.sample
├── .golangci.yml
├── go.mod
├── golangci-lint.sh
└── init.sh
登录后复制
  1. 可以通过项目结构看到,需要在项目根目录增加一个 .githooks 文件夹,.githooks 文件夹,

  2. 然后增加 .golangci.yml golangci-lint 使用的配置文件,

  3. 增加一个 手动执行goalngci-lint的执行脚本golangci-lint.sh

  4. 最后就是项目应用 git hooks 的脚本init.sh,用于初始化这个项目的脚本。

说了这么多,还不知道这个到底是干啥的,先来看一下效果图

commit的时候会帮助我们进行文件的 fmt:

golangci-lint应用

push

🎜🎜然后增加 .golangci.yml golangci-lint 使用的配置文件,🎜🎜🎜🎜增加一个 手动执行goalngci-lint的执行脚本golangci-lint.sh,🎜🎜🎜🎜最后就是项目应用 git hooks 的脚本init.sh,用于初始化这个项目的脚本。🎜

说了这么多,还不知道这个到底是干啥的,先来看一下效果图🎜

commit的时候会帮助我们进行文件的 fmt:🎜

golangci-lint应用

push的时候会检查整个项目是否存在有问题的地方:🎜

golangci-lint应用

如果项目存在可能的问题,那么是不会让你 push 的。通过这种方式来保证服务器上的代码都是符合规则的。

使用方式:

1. 项目中已经存在这些内容

首次通过执行 init.sh 脚本进行项目初始化设置。

golangci-lint应用

这会检查你的环境,如果一些工具不存在,它会自动下载。并会修改默认 git 钩子指向当前项目的 .githooks 文件夹。

好了,就这样,就是这么简单。

2. 新建项目这个怎么搞

这都是小问题,复制内容过去吧。

但是在复制这些之前,你一定已经是在一个git 管理的根目录下。

那么下面就开始你的复制吧。

.githooks/pre-commit:

#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

# 获取所有变化的go文件
STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep .go$)

if [ "$STAGED_GO_FILES" = "" ]; then
    exit 0
fi

echo "check gofmt ..."
CHECK_FMT=$(gofmt -s -w -l $STAGED_GO_FILES)
if [ -n "${CHECK_FMT##* }" ]; then
    echo
    echo -e "these files will be\033[32m gofmt\033[0m formatted:"
    for file in ${CHECK_FMT[*]}; do
        echo -e "\033[36m\t$file\033[0m"
    done
    git add ${CHECK_FMT//\/n/ }
    echo
fi

echo "check goimports ..."
CHECK_GOPLS=$(goimports -l -w $STAGED_GO_FILES)
if [ -n "${CHECK_GOPLS##* }" ]; then
    echo
    echo -e "these files will be\033[32m goimports\033[0m formatted:"
    for file in ${CHECK_GOPLS[*]}; do
        echo -e "\033[36m\t$file\033[0m"
    done
    git add ${CHECK_GOPLS//\/n/ }
    echo
fi

printf "\033[32m COMMIT SUCCEEDED \033[0m\n"
echo

exit 0
登录后复制

.githooks/pre-push:

#!/bin/sh

# An example hook script to verify what is about to be pushed.  Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed.  If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
#   <local ref> <local oid> <remote ref> <remote oid>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).

#remote="$1"
#url="$2"
printf "\033[32m 推送前需要检查当前项目可以 go build 通过 \033[0m\n"

echo "run golangci-lint..."
echo

# 运行 golangci-lint 检查工具
golangci-lint run ./...
if [ $? -ne 0 ]; then
    printf "\033[31m PUSH FAILED \033[0m\n"
    exit 1
fi

printf "\033[32m PUSH SUCCEEDED \033[0m\n"
echo

exit 0
登录后复制

golangci-lint.sh

#!/bin/sh

if ! command -v golangci-lint &>/dev/null; then
    echo "golangci-lint not installed or available in the PATH" >&2
    echo "install golangci-lint ..." >&2
    go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1
fi

#goland 可直接定位文件
golangci-lint run ./... |sed &#39;s/\\/\//g&#39;
登录后复制

init.sh

#!/bin/sh

# 检查 go 是否安装
checkGoEnv() {
    # go是否安装
    if ! command -v go &>/dev/null; then
        echo "go not installed or available in the PATH" >&2
        echo "please check https://golang.google.cn" >&2
        exit 1
    fi

    # go proxy 是否设置
    if [ -z $GOPROXY ]; then
        echo "go proxy not set in the PATH" >&2
        echo "please set GOPROXY, https://goproxy.cn,direct || https://goproxy.io,direct" >&2
        exit 1
    fi

    echo "go env installed ..."
}

# 检查 go 相关工具包是否安装
checkGoLintEnv() {
    if ! command -v goimports &>/dev/null; then
        echo "goimports not installed or available in the PATH" >&2
        echo "install goimports ..." >&2
        go install golang.org/x/tools/cmd/goimports@latest
        checkGoLintEnv
        return
    fi

    echo "goimports installed ..."
}

# 检查 golangci-lint 是否安装
checkCiLintEnv() {
    if ! command -v golangci-lint &>/dev/null; then
        echo "golangci-lint not installed or available in the PATH" >&2
        echo "install golangci-lint ..." >&2
        go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1
        checkCiLintEnv
    fi

    echo "golangci-lint installed ..."
}

# 初始化钩子配置
initHooks() {
    # 如果当前目录不存在 .githooks 目录,说明位置不对
    if [ ! -d ".githooks" ]; then
        echo "exec incorrect position"
        exit 1
    fi

    # 检查是否已经设置了
    exist=$(git config core.hooksPath)
    if [ -z $exist ]; then
        # 设置 hooks 默认位置
        git config core.hooksPath .githooks
        echo "init git hooks ..." >&2
    fi
}

main() {
    checkGoEnv
    checkGoLintEnv
    checkCiLintEnv
    initHooks
}

main
登录后复制

.golangci.yml

run:
  timeout: 2m
  tests: false

linters:
  disable-all: true
  enable:
    - typecheck
    - staticcheck
    - govet
    - gocritic

linters-settings:
  govet:
    check-shadowing: true
    disable-all: true
    enable:
      - asmdecl
      - assign
      - atomic
      - atomicalign
      - bools
      - buildtag
      - cgocall
      - composites
      - copylocks
      - httpresponse
      - loopclosure
      - lostcancel
      - nilfunc
      - nilness
      - printf
      - shadow
      - shift
      - stdmethods
      - structtag
      - tests
      - unmarshal
      - unreachable
      - unsafeptr
      - unusedresult

  staticcheck:
    go: "1.17"
    checks: [ "all", "-SA3*", "-SA6000", "-SA6001", "-SA6003", "-ST*", "ST1006", "ST1008", "ST1016", "-QF1" ]

  gocritic:
    enabled-tags:
      - diagnostic
      - experimental
      - opinionated
      - style
    enabled-checks:
      - sliceClear
    disabled-tags:
      - performance
    disabled-checks:
      - assignOp
      - badLock
      - badRegexp
      - codegenComment
      - commentFormatting
      - commentedOutCode
      - docStub
      - dupArg
      - dupBranchBody
      - dupCase
      - dupImport
      - exitAfterDefer
      - externalErrorReassign
      - flagDeref
      - hexLiteral
      - ifElseChain
      - importShadow
      - initClause
      - mapKey
      - nestingReduce
      - newDeref
      - redundantSprint
      - regexpMust
      - regexpPattern
      - regexpSimplify
      - ruleguard
      - sloppyLen
      - sloppyTypeAssert
      - sortSlice
      - sprintfQuotedString
      - sqlQuery
      - stringConcatSimplify
      - syncMapLoadAndDelete
      - tooManyResultsChecker
      - typeDefFirst
      - typeUnparen
      - underef
      - unlabelStmt
      - unlambda
      - unnecessaryBlock
      - unnecessaryDefer
      - yodaStyleExpr
      - whyNoLint
      - paramTypeCombine
      - emptyStringTest
登录后复制

好了,现在你应该是这样的结构了吧

项目代码目录:

├── .githooks
│   ├── pre-commit
│   └── pre-push
├── .golangci.yml
├── golangci-lint.sh
└── init.sh
登录后复制

如果不是,请返回到上面在看一下步骤。

这个时候可以执行 init.sh 脚本来初始化了。

最后可以在 https://github.com/ywanbing/golangci仓库中获取代码。

以上是golangci-lint应用的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

深入理解 Golang 函数生命周期与变量作用域 深入理解 Golang 函数生命周期与变量作用域 Apr 19, 2024 am 11:42 AM

在Go中,函数生命周期包括定义、加载、链接、初始化、调用和返回;变量作用域分为函数级和块级,函数内的变量在内部可见,而块内的变量仅在块内可见。

Go WebSocket 消息如何发送? Go WebSocket 消息如何发送? Jun 03, 2024 pm 04:53 PM

在Go中,可以使用gorilla/websocket包发送WebSocket消息。具体步骤:建立WebSocket连接。发送文本消息:调用WriteMessage(websocket.TextMessage,[]byte("消息"))。发送二进制消息:调用WriteMessage(websocket.BinaryMessage,[]byte{1,2,3})。

如何在 Go 中使用正则表达式匹配时间戳? 如何在 Go 中使用正则表达式匹配时间戳? Jun 02, 2024 am 09:00 AM

在Go中,可以使用正则表达式匹配时间戳:编译正则表达式字符串,例如用于匹配ISO8601时间戳的表达式:^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$。使用regexp.MatchString函数检查字符串是否与正则表达式匹配。

Golang 与 Go 语言的区别 Golang 与 Go 语言的区别 May 31, 2024 pm 08:10 PM

Go和Go语言是不同的实体,具有不同的特性。Go(又称Golang)以其并发性、编译速度快、内存管理和跨平台优点而闻名。Go语言的缺点包括生态系统不如其他语言丰富、语法更严格以及缺乏动态类型。

Golang 技术性能优化中如何避免内存泄漏? Golang 技术性能优化中如何避免内存泄漏? Jun 04, 2024 pm 12:27 PM

内存泄漏会导致Go程序内存不断增加,可通过:关闭不再使用的资源,如文件、网络连接和数据库连接。使用弱引用防止内存泄漏,当对象不再被强引用时将其作为垃圾回收目标。利用go协程,协程栈内存会在退出时自动释放,避免内存泄漏。

如何在 IDE 中查看 Golang 函数文档? 如何在 IDE 中查看 Golang 函数文档? Apr 18, 2024 pm 03:06 PM

使用IDE查看Go函数文档:将光标悬停在函数名称上。按下热键(GoLand:Ctrl+Q;VSCode:安装GoExtensionPack后,F1并选择"Go:ShowDocumentation")。

Go 并发函数的单元测试指南 Go 并发函数的单元测试指南 May 03, 2024 am 10:54 AM

对并发函数进行单元测试至关重要,因为这有助于确保其在并发环境中的正确行为。测试并发函数时必须考虑互斥、同步和隔离等基本原理。可以通过模拟、测试竞争条件和验证结果等方法对并发函数进行单元测试。

如何使用 Golang 的错误包装器? 如何使用 Golang 的错误包装器? Jun 03, 2024 pm 04:08 PM

在Golang中,错误包装器允许你在原始错误上追加上下文信息,从而创建新错误。这可用于统一不同库或组件抛出的错误类型,简化调试和错误处理。步骤如下:使用errors.Wrap函数将原有错误包装成新错误。新错误包含原始错误的上下文信息。使用fmt.Printf输出包装后的错误,提供更多上下文和可操作性。在处理不同类型的错误时,使用errors.Wrap函数统一错误类型。

See all articles