Search code examples
gradlebuild.gradlegradlew

How to refer a method from a different file in gradle


The only thing I know we can do is have build.gradle and have the following defined at the top for example to reference from other .gradle files

apply from: 'common-methods.gradle'

But I want to do the same thing inside a different gradle file.

Example:

output.gradle

apply from: 'gradle/common.gradle'

task output{
    doLast{
        outputResults()
    }
}

def outputResults()
{
   def output = ResultGrabber()
   logger.quiet("I have the output saved")
}

common-method.gradle

def ResultGrabber()
{
   return 1
}

When I did something similar I got an error that it doesn't know the method. I am not an expert at gradle but I have a feeling build.gradle is special compared to other .gradle type files. If thats the case then is there an alternative solution?


Solution

  • For some weird reason I got it working when I placed the definition of my method inside build.gradle. So this is what my file structure looks like which works now

    build.gradle

    apply from: 'gradle/output-method.gradle'
    
    def outputResults()
    {
       logger.quiet("I have the output saved")
       return 1
    }
    

    output-method.gradle

    doLast{
    logger.quiet("Starting method")
    outputResults()
    logger.quiet("Ending method")
    }
    

    To be honest I am a bit shocked this worked because its build.gradle that's referencing output-method.gradle and not the otherway around. I made sure there was no pathing issue but in any case this solution allows me to avoid using duplicate code. I had mentioned in my post earlier that I already knew we could do something similar with build.gradle but I can't find any other working way. Someone had posted about defining my method inside ./buildSrc/src/groovy/ - but I haven't tested that out yet