GenerateChangelogTask.kt 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import org.gradle.api.DefaultTask
  2. import org.gradle.api.tasks.Input
  3. import org.gradle.api.tasks.TaskAction
  4. import java.io.ByteArrayOutputStream
  5. open class GenerateChangelogTask : DefaultTask() {
  6. @Input
  7. var appName: String = ""
  8. @Input
  9. var versionName: String = ""
  10. @Input
  11. var tagPrefix: String = ""
  12. get() = field.lowercase()
  13. private val buildType: String
  14. get() = if (tagPrefix == "development") "debug" else "release"
  15. @TaskAction
  16. fun generate() {
  17. // Retrieve all tags sorted by date, latest first
  18. val tagsCommand = listOf("git", "tag", "--sort=-committerdate")
  19. val tagsOutput = execAndGetOutput(tagsCommand)
  20. val tags = tagsOutput.split("\n")
  21. // Extracting the two most recent tags
  22. val currentVersion = tags.first()
  23. val previousVersion = tags.last()
  24. // Getting changes between the latest and previous version tags
  25. val changes = execAndGetOutput(listOf(
  26. "git",
  27. "log",
  28. "--pretty=format:%s <%an>",
  29. "$previousVersion..$currentVersion"
  30. ))
  31. println("Changes between $previousVersion and $currentVersion:\n$changes")
  32. var features = "Features:\n"
  33. var fixes = "Fixes:\n"
  34. var improvements = "Improvements:\n"
  35. changes.lineSequence().forEach { line ->
  36. val parts = line.split(":", limit = 2)
  37. val prefix = parts.getOrNull(0) ?: ""
  38. val rest = parts.getOrNull(1) ?: ""
  39. when {
  40. prefix.startsWith("ft") -> features += "$rest\n"
  41. prefix.startsWith("fi") -> fixes += "$rest\n"
  42. prefix.startsWith("im") -> improvements += "$rest\n"
  43. }
  44. }
  45. val header = "Changelog from $previousVersion to $currentVersion\n\n"
  46. val changelog = header + features + "\n" + fixes + "\n" + improvements
  47. val fileName = "${appName}-${versionName}-$tagPrefix"
  48. val changelogDir = project.file("./build/outputs/apk/$buildType")
  49. val changelogFilePath = "$changelogDir/CHANGELOG-$fileName.md"
  50. println("Changelog file path: $changelogFilePath")
  51. // Ensure the directory exists
  52. changelogDir.mkdirs()
  53. // Create and write to the changelog file
  54. val changelogFile = project.file(changelogFilePath)
  55. changelogFile.createNewFile()
  56. changelogFile.writeText(changelog)
  57. println(changelog)
  58. }
  59. private fun execAndGetOutput(command: List<String>): String {
  60. val outputStream = ByteArrayOutputStream()
  61. project.providers.exec {
  62. commandLine(command)
  63. standardOutput = outputStream
  64. }
  65. return String(outputStream.toByteArray(), Charsets.UTF_8).trim()
  66. }
  67. }