You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于GitLab CI/CD实现Android应用版本号自动递增方案问询

实现GitLab CI/CD中Flutter Android版本号自动递增方案

核心思路

以pubspec.yaml作为版本号单一数据源,通过GitLab CI脚本自动拆分、递增major.minor.patch格式的版本号,同步更新Android构建配置,可选将版本号变更提交至Git仓库便于追溯,最终衔接现有构建与部署流程。

步骤1:修改GitLab CI配置

新增版本号递增阶段,调整原有任务依赖,完整配置如下:

stages:
- version-bump  # 新增版本号递增阶段
- build-aab
- upload-playstore

# 版本号自动递增任务
bump-version:
  stage: version-bump
  tags:
  - mobile
  script:
    # 读取pubspec.yaml中的当前版本号(拆分版本名与构建号)
    - CURRENT_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //g' | cut -d '+' -f 1)
    # 拆分major/minor/patch字段
    - IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
    # 递增patch版本号
    - NEW_PATCH=$((PATCH + 1))
    - NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
    # 用Git提交数生成唯一构建号
    - BUILD_NUMBER=$(git rev-list --count HEAD)
    # 更新pubspec.yaml的版本号
    - sed -i "s/^version: .*/version: $NEW_VERSION+$BUILD_NUMBER/" pubspec.yaml
    # 同步版本号到Android build.gradle
    - sed -i "s/versionName \".*\"/versionName \"$NEW_VERSION\"/" android/app/build.gradle
    - sed -i "s/versionCode .*/versionCode $BUILD_NUMBER/" android/app/build.gradle
    # 提交版本号变更到Git仓库(可选,需CI有推送权限)
    - git config --global user.name "GitLab CI/CD"
    - git config --global user.email "ci@example.com"
    - git add pubspec.yaml android/app/build.gradle
    - git commit -m "Bump version to $NEW_VERSION+$BUILD_NUMBER [skip ci]"
    - git push https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_REPOSITORY_URL#*@} HEAD:${CI_COMMIT_BRANCH}
  only:
  - test

# 原构建任务,新增依赖确保版本号先更新
build-android:
  stage: build-aab
  tags:
  - mobile
  script:
  - flutter pub get
  - flutter build appbundle
  artifacts:
    paths:
    - build/app/outputs/bundle/release/app-release.aab
    expire_in: 30 day
  only:
  - test
  needs: ["bump-version"]

# 原上传任务,保持不变
upload-to-playstore:
  stage: upload-playstore
  tags:
  - mobile
  script:
  - ls -lart
  - export LC_ALL=en_US.UTF-8
  - export LANG=en_US.UTF-8
  - cd android
  - fastlane deploy_beta
  only:
  - test
  needs: ["build-android"]

步骤2:Fastlane配置适配(可选)

若Fastlane部署需要明确指定版本号,可在android/fastlane/Fastfile中直接读取更新后的配置:

lane :deploy_beta do
  # 从pubspec.yaml读取版本信息
  pubspec = YAML.load_file('../pubspec.yaml')
  version_name = pubspec['version'].split('+')[0]
  version_code = pubspec['version'].split('+')[1].to_i

  supply(
    track: 'beta',
    version_name: version_name,
    version_code: version_code,
    # 其他原有配置...
  )
end

关键注意事项

  • CI权限:若需提交版本号变更到Git,需在项目设置→CI/CD→权限中开启「允许CI作业访问Git仓库」,确保CI_JOB_TOKEN有推送权限。
  • 版本格式兼容:确保pubspec.yaml中版本号严格遵循x.y.z+build_number格式,避免非数字字符导致脚本解析错误。
  • 灵活调整递增规则:若需递增major或minor版本,可通过手动触发CI时传递自定义变量(如MAJOR_BUMP=true),在脚本中添加判断逻辑调整对应字段。

内容的提问来源于stack exchange,提问作者user25014605

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 07:53:26