Gradle configuration cache failed: Could not find method fileTree() on second run

Hi, i am working to enable configuration cache on my app. However i have issue with my own script that using file tree:

def vmSelectionAction = {
    fileTree(libDir).matching {
    }.visit { details ->
    }
}
def task = tasks.findByName("package${targetName}")
task.doFirst(vmSelectionAction)

So i applied that script on my android application module.
The first run it works fine, and seems configuration cache is saved.
Then i tried to modify my code and rebuild. It is used the previous configuration cache and return this error:

Execution failed for task ':app:packageDebug'.
> Could not find method fileTree() for arguments [/Users/doni.winata/gradlecc/app/build/intermediates/merged_native_libs/] on task ':app:packageDebug' of type com.android.build.gradle.tasks.PackageApplication.

I still confuse why it failed on second run and anyone know how to solve this issue ?
Thanks

I think you should open an issue about not getting a configuration cache problem reported in the first place if there is none yet, and if you share the link, I’ll also give my thumbs up.

The actual problem you have is, the call of fileTree at execution time which is a method on the Project instance which is forbidden to be used at execution time. As can be found on the configuration cache documentation page, the proper replacement is ObjectFactory#fileTree().from(dir).
So fileTree(libDir) needs to be replaced by objects.fileTree().from(libDir).

Now you still have the same problem actually as you still call objects which actually is a call to Project#getObjects() which you cannot do at execution time for the same reason. But to solve this, you just have to capture the ObjectFactory at configuration time and then just use it at execution time.

So the fixed snippet that is configuration cache compliant looks like this:

def objects = objects
def vmSelectionAction = {
    objects.fileTree().from(libDir).matching {
    }.visit { details ->
    }
}
def task = tasks.findByName("package${targetName}")
task.doFirst(vmSelectionAction)

Thank you for the explanation and sharing the snippet, it is working fine on my project.
I just posted the issue here as your suggestion:

I really appreciate your help.