Could not import third-party class in gradle file other than build.gradle

I want to import a third-party class org.ajoberstar.grgit.Grgit in a gradle file version.gradle . However it is giving me the error that it is unable to resolve class org.ajoberstar.grgit.Grgit(I am using apply from: "version.gradle" in build.gradle). But if I import it in build.gradle , it works fine. Here is what I am doing:

build.gradle:

plugins {
  id "org.ajoberstar.grgit" version "1.5.0"
}
apply from: "version.gradle"

// Version of jar file.
version = 1.0

jar
 {
  destinationDir = file(JAR_DIR)
  from {
    (configurations.runtime).collect {
      it.isDirectory() ? it : zipTree(it)
    }
  }
  manifest {
    attributes 'Main-Class': 'com.awesomeness.Main'
  }
}

jar.dependsOn versionTxt

// Artifact dependecies.
    dependencies {
      compile files("$TOOLS/lib/grgit-1.5.0.jar")
      compile files("$TOOLS/lib/groovy-all-2.4.7.jar")
      compile files("$TOOLS/lib/org.eclipse.jgit-4.2.0.201601211800-r.jar")
    }

Here is the version.gradle file:

import org.ajoberstar.grgit.Grgit
//
import java.text.DateFormat

task versionTxt()  {
    doLast {
        Grgit grgit = Grgit.open()
        File file = new File("$buildDir/version.txt")
        file.write("")
        file.append("Version: $version")
        file.append("Branch: "+grgit.branch.current.trackingBranch.name)
        file.append("Build-Type: ")
        file.append("Build-Date: " + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date((long)grgit.head().time*1000l)))
        file.append("Commit-Id: "+ grgit.head().abbreviatedId)
    }
}

I tried a few SO links like:

But I could not resolve this. Any help?

Your version.gradle has its own buildscript classpath which is not the same as build.gradle

The solution is something like

plugins {
  id "org.ajoberstar.grgit" version "1.5.0"
}
ext {
   Grgit = org.ajoberstar.grgit.Grgit
} 
apply from: "version.gradle"

version.gradle

task versionTxt {
    doLast {
        Grgit grgit = Grgit.open()
        ... 
     } 
} 

I’m guessing (haven’t tested) another solution might be to copy the buildscript classpath from the other project.

Eg: version.gradle

buildscript {
    dependencies {
        classpath files(project(':some-project').buildscript.configurations.classpath) 
    } 
} 
import org.ajoberstar.grgit.Grgit
...