基于Git提交生成版本号时Gradle报错:String.div()无匹配签名
Hey there, let's figure out why your Gradle script is throwing that error and fix it up!
What's Causing the Errors?
You've got two main issues here:
- String vs. Integer Mismatch: The
gitNumvariable is a string (sinceexecute().text.trim()returns text from the git command), and you're trying to use the/division operator on it. Strings don't have adiv()method in Groovy, which is exactly what the error message is complaining about. - Typo: You wrote
toIntergerinstead of the correcttoInteger—that missing "e" would have caused another error once you fixed the first issue.
Fixed Code Snippet
Here's the corrected version of your ext block, with clear explanations:
ext { // 获取版本号和构建号 def gitNumStr = "git rev-list --count master".execute().text.trim() // Convert the string result to an integer, and fix the typo def gitNum = gitNumStr.toInteger() // Use integer division to get the version (avoids floating point results) def version = gitNum.intdiv(10) // Modulo operation to get the build number def build = gitNum % 10 }
Key Fixes Breakdown
- Convert to Integer: First we take the string output from git and turn it into an actual integer so we can perform math operations on it.
- Integer Division: Using
intdiv(10)instead of/10ensures we get a whole number (e.g., 12 → 1 instead of 1.2). If you used/10directly, Groovy would return a float, which is probably not what you want for a version number. - Fixed Typo:
toIntegeris the correct method name for converting a string to an integer in Groovy.
Bonus: Add Fallback Logic
If there's a chance the git command might fail (e.g., not on the master branch, git not installed), you can add a fallback to avoid crashes:
ext { def gitNumStr = "git rev-list --count master".execute().text.trim() // Use 0 as a default if the git output isn't a valid integer def gitNum = gitNumStr.isInteger() ? gitNumStr.toInteger() : 0 def version = gitNum.intdiv(10) def build = gitNum % 10 }
内容的提问来源于stack exchange,提问作者Chris Young
相关产品推荐
相关产品推荐

