在Ubuntu上对Golang项目进行版本控制时,通常会结合使用Git进行代码版本控制,以及Go Modules进行依赖管理。以下是详细的步骤和策略:
安装Git:
sudo apt update
sudo apt install git
初始化Git仓库:
cd /path/to/your/golang/project
git init
git add .
git commit -m "Initial commit"
关联远程仓库(如GitHub/GitLab):
git remote add origin https://github.com/yourname/repo.git
git push -u origin main
初始化Go Modules(Go 1.11及以上版本支持):
go mod init github.com/yourname/repo
这会生成go.mod
文件,记录模块信息和依赖版本。
添加/更新依赖: 在代码中import依赖后,运行以下命令自动下载并记录版本:
go mod tidy
或者手动指定依赖版本:
go get github.com/pkg/errors@v0.9.1
依赖版本锁定:
go.mod
和go.sum
文件会精确记录依赖版本,需提交到Git:
git add go.mod go.sum
git commit -m "Update dependencies"
分支策略:
main/master
:稳定生产代码develop
:开发分支feature/xxx
:功能分支fix/xxx
:修复分支.gitignore
配置:
忽略不必要的文件(例如编译产物):
# Go
/bin/
/vendor/
*.exe
*.test
*.prof
# IDE
.vscode/
.idea/
Tag发布版本: 对稳定版本打Tag(语义化版本vX.Y.Z):
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0
如果需要切换不同Go版本,可以使用goenv
或gvm
:
安装goenv:
git clone https://github.com/syndbg/goenv.git ~/.goenv
echo 'export PATH="$HOME/.goenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(goenv init -)"' >> ~/.bashrc
source ~/.bashrc
安装指定Go版本:
goenv install 1.20.5
goenv global 1.20.5
验证版本:
go version
在.github/workflows/go.yml
中配置:
name: Go Build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: '1.20'
- run: go mod tidy
- run: go build -v ./...
- run: go test ./...
通过以上步骤,你可以在Ubuntu环境中高效管理Golang项目的版本和依赖。