Skip to content

Instantly share code, notes, and snippets.

@warting
Last active May 23, 2023 11:32
Show Gist options
  • Save warting/8027eb45cfc15078d8c07fa9d3d34018 to your computer and use it in GitHub Desktop.
Save warting/8027eb45cfc15078d8c07fa9d3d34018 to your computer and use it in GitHub Desktop.
Generates a versions.properties files to be used by gradle in android project to set versions on android apps
import java.util.Properties
val versionFile = File("versions.properties")
val versions = Properties().apply {
if (versionFile.exists()) {
FileInputStream(versionFile).use {
load(it)
}
}
}
android {
defaultConfig {
versionName = versions.getProperty("V_VERSION", "1.0.0")
versionCode = versions.getProperty("V_VERSION_CODE", "1000000").toInt()
}
}
#!/bin/bash
# Generates a versions.properties files to be used by gradle in android project to set versions on android apps
# Overwrite versions.properties at the beginning
: > versions.properties
# Define the prefixes
prefixes=("v" "a")
# Get the latest commit hash
hash=$(git rev-parse --short HEAD)
# Check if the working directory is dirty
git diff --quiet || dirty=true
dirty=${dirty:-false}
# Loop over the prefixes
for prefix in "${prefixes[@]}"; do
# Get the latest git tag from current branch that matches the current prefix
tag=$(git describe --tags --match "${prefix}[0-9]*" --abbrev=0)
# Trim the prefix from the start of the tag name
version="${tag:1}"
# Split the version into major, minor, and patch parts
IFS='.' read -r -a version_parts <<< "$version"
major="${version_parts[0]}"
minor="${version_parts[1]}"
patch="${version_parts[2]}"
# Calculate the version code using arithmetic expansion
version_code=$((major * 10000 + minor * 100 + patch))
# Get the number of commits since the tag
commit_count=$(git rev-list --count "${tag}"..HEAD)
# Create the debug version string and append -dirty if necessary
debug_version="${version}-${commit_count}-g${hash}"
[[ $dirty == true ]] && debug_version+="-dirty"
# Convert prefix to uppercase for property names
prefix_upper="${prefix^^}"
# Print the result
printf "%s_VERSION=%s\n" "$prefix_upper" "$version"
printf "%s_DEBUG_VERSION=%s\n" "$prefix_upper" "$debug_version"
printf "%s_VERSION_CODE=%d\n" "$prefix_upper" "$version_code"
# Write to versions.properties
{
printf "%s_VERSION=%s\n" "$prefix_upper" "$version"
printf "%s_VERSION_CODE=%d\n" "$prefix_upper" "$version_code"
printf "%s_DEBUG_VERSION=%s\n" "$prefix_upper" "$debug_version"
} >> versions.properties
done
# Print more result
printf "HASH=%s\n" "$hash"
printf "DIRTY=%s\n" "$dirty"
# Write the hash to versions.properties after the loop
printf "HASH=%s\n" "$hash" >> versions.properties
printf "DIRTY=%s\n" "$dirty" >> versions.properties
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment