How to read output from a task?

Hello,

I created a task to compute a version name from the latest git tag. I am basically writing a computed tag into a file in the build directory. However, when I try to read this text from file gives me below error:

/path/to/project/build/intermediates/versioning/versionName.txt (No such file or directory)

VersionNameTask.kt

abstract class VersionNameTask : DefaultTask() {

      @get:OutputFile
      abstract val outputFile: RegularFileProperty

      @TaskAction
      fun action() {
        outputFile.get().asFile.writeText(project.computeGitTag)
      }
    }

This is how I try to read the content of the generated file.

private fun BaseAppModuleExtension.configureVersioning(project: Project) {
  onVariantProperties.withBuildType("release") {
    val versionNameTask = project.tasks.register<VersionNameTask>(
      "computeVersionNameFor${name.capitalize(Locale.US)}"
    ) {
      group = "versioning"
      outputFile.set(project.layout.buildDirectory.file("intermediates/versioning/versionName.txt"))
    }
    val mappedVersionNameTask = versionNameTask.map { it.outputFile.get().asFile.readText() }

    outputs.forEach { variantOutput ->
      variantOutput.versionName.set(mappedVersionNameTask)
    }
  }
}

Can you please tell me what I am doing wrong? I assume I am reading the file content before the task generates it but why is this happening? I am using map transformation and shouldn’t it wait for the file to be created first? I couldn’t find anything useful. Thanks!