使用Fastlane为Kotlin DSL配置的Android项目递增特定变体版本号并提交Git
实现方案
1. 编写versionCode自增工具方法
在你的Fastfile中添加如下可复用方法,通过正则匹配指定变体的versionCode,完成自增后写回配置文件:
# 参数说明: # variant_name:变体对象名,示例传 "Dev" # config_file_path:变体配置Kotlin文件的本地路径 def increment_variant_version_code(variant_name, config_file_path) content = File.read(config_file_path) # 跨行匹配对应变体下的versionCode配置 match_result = content.match(/object\s+#{variant_name}\s*:\s*Variants\s*\{.*?override\s+val\s+versionCode\s*=\s*(\d+)/m) unless match_result UI.user_error!("未在目标文件中找到#{variant_name}变体的versionCode配置,请检查路径或匹配规则") end current_code = match_result[1].to_i new_code = current_code + 1 # 替换对应行的versionCode数值 updated_content = content.gsub(/(object\s+#{variant_name}\s*:\s*Variants\s*\{.*?override\s+val\s+versionCode\s*=\s*)\d+/m, "\\1#{new_code}") File.write(config_file_path, updated_content) UI.success("#{variant_name}变体versionCode已更新:#{current_code} -> #{new_code}") end
2. 编写完整执行Lane
将版本更新、Git提交推送逻辑整合为可调用的Lane:
lane :bump_variant_version do |options| # 读取传入参数,设置默认值 target_variant = options[:variant_name] || "Dev" config_path = options[:config_file] || "app/src/main/kotlin/你的配置目录/Dev.kt" commit_msg = options[:commit_msg] || "chore: 自增#{target_variant}变体versionCode" # 执行versionCode自增 increment_variant_version_code(target_variant, config_path) # 执行Git操作 git_add(path: config_path) git_commit(path: config_path, message: commit_msg) push_to_git_remote # 若需指定分支可添加参数:push_to_git_remote(branch: "你的分支名") end
3. 使用方法
在项目根目录终端执行对应命令即可触发流程:
- 默认更新Dev变体版本号:
fastlane bump_variant_version - 指定变体、配置文件与提交信息:
fastlane bump_variant_version variant_name:Prod config_file:app/src/main/kotlin/config/Prod.kt commit_msg:"chore: 提升生产环境版本号"
注意事项:
- 正则匹配规则适配你给出的Dev.kt代码格式,如果实际项目中配置文件的代码格式(比如缩进、变量名写法)有变动,对应调整正则匹配规则即可。
- 如果多个变体配置存放在同一个Kotlin文件中,只需要修改
config_file参数为对应文件路径即可,逻辑无需调整。- 执行命令前确保当前环境的git账号有对应仓库的推送权限,避免推送失败。
内容的提问来源于stack exchange,提问作者enjektor0
相关产品推荐
相关产品推荐

