hello , how could I inject Gradle project version...
# gradle
a
hello , how could I inject Gradle project version dynamically inside Kotlin header file or after @since tag to achieve something like that :
Copy code
/*
 * File: FileName.kt
 * Author: Author name
 * Created on:  time
 * Description: 
 * @since : [Project Version]
 */
t
in theory you could create a Gradle task that searches in the source code for
[Project version]
and replaces it with actual version
m
I think
since
is the version where the file was created, isnt? So I think automating it could be a bit misleading
v
- a bit + very
2
If it is done during build. If that task is just a script you call manually when you added things it would not be misleading. But where is the point then. Instead of
[Project Version]
you could also just put the actual version there. What is the use-case?
a
I think its best to create a pre-commit Git hook that automatically updates the project version in newly created or updated files by extracting the version number from the branch name, assuming it follows a specific versioning convention
if anyone interested, here is a pre-commit hook that inject project version from Gradle build file or branch name that follow a versioning convention ,for only staged files after a successful build
Copy code
# Extract the version number from build.gradle.kts
VERSION=$(grep -Eo 'version\s*=\s*"[^"]+"' build.gradle.kts | sed -E 's/version\s*=\s*"([^"]+)"/\1/')

#Or Extract the version number from the branch name assuming the format is like 'featurevX.Y'
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
VERSION=$(echo $BRANCH_NAME | grep -Eo '[vV][A-Z0-9][^ ]*')

# Find all modified .kt files
MODIFIED_FILES=$(git diff --cached --name-only | grep '\.kt$')

# Check if the version number was found
if [ -z "$VERSION" ]; then
  # If version number was not found, check if any modified file contains @version
  for file in $MODIFIED_FILES; do
    if grep -q "@version" "$file"; then
      echo "Error: @version found in $file but unable to extract version from build.gradle.kts."
      exit 1
    fi
  done
else
  # If version number was found, replace @version with the extracted version in all modified files
  for file in $MODIFIED_FILES; do
    sed -i "s/@version/${VERSION}/g" "$file"
    git add "$file"
  done
fi