geneartedModels folder being deleted in second Run and facing compilation error

i have following task to create models , its being created in build folder, while running server for first time but next time onwards when i bring up my server im getting compilation errors. when i see inside build folder those models being deleted not sure how its gets deleted. anypointers?

ext {
	generatedJavaSourceDir = "src/main/java"
clean {
	delete generatedJavaSourceDir
task buildAmberModels(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
	generatorName = "spring"
	inputSpec = "$projectDir/src/main/resources/schema/client.json"
	outputDir = "$projectDir/openapi"
	modelPackage = "amber.api.models"

tasks.buildAmberModels {
	doLast {
		copy {
			from "$projectDir/openapi/src/main/java/amber/models"
			into "$projectDir/src/main/java/amber/models"
	delete "$projectDir/openapi"

compileJava.dependsOn buildAmberModels

Probably because of your delete which is done always when the buildAmberModels task is configured, even if it is not going to be executed and as you also do not leverage task configuration avoidance, that means anytime you run any Gradle task.

Besides that, I would also recommend not to generate into the regular checked in source directory.

Also your buildAmberModels task will be up-to-date on the second run on, as you do not declare the additional output files you create.

And furthermore, practically any explicit dependsOn that does not have a lifecycle task on the left-hand side is a code smell.

This way for example any task needing sources like some code analyzer, or sourcesJar and so on will not see those sources, or use some stale state if it was run before and so on. Better throw away the delete and doLast from the buildAmberModels task, make it generate into layout.buildDirectory.dir("generated/openapi")or similar and properly wire the generation task with sourceSets { main { java.srcDir(buildAmberModels) } }, then all source needing tasks automatically have the necessary task dependency and see the proper source files.