Hello, having an issue with `CodeGenerator#createN...
# ksp
r
Hello, having an issue with
CodeGenerator#createNewFileByPath
where it will sometimes just throw a
FileAlreadyExistsException
:
Copy code
public class AxiProcessor(
    env: SymbolProcessorEnvironment,
) : SymbolProcessor {
    private companion object Identifiers {
        const val COMMAND: String = "net.radstevee.axi.core.command.Command"
    }

    private val gen: CodeGenerator = env.codeGenerator

    override fun process(resolver: Resolver): List<KSAnnotated> {
        val services = mutableListOf<String>()

        // ...

        gen.createNewFileByPath(
            Dependencies(false),
            "META-INF/services/$COMMAND",
            ""
        ).use { out ->
            OutputStreamWriter(out, StandardCharsets.UTF_8).use { writer ->
                services.forEach { svc ->
                    writer.write(svc)
                    writer.write("\n")
                }
            }
        }

        return emptyList()
    }
}
Copy code
[ksp] kotlin.io.FileAlreadyExistsException: /home/radsteve/dev/axi/example/build/generated/ksp/main/resources/META-INF/services/net.radstevee.axi.core.command.Command
	at com.google.devtools.ksp.common.impl.CodeGeneratorImpl.createNewFile(CodeGeneratorImpl.kt:154)
	at com.google.devtools.ksp.common.impl.CodeGeneratorImpl.createNewFileByPath(CodeGeneratorImpl.kt:78)
	at net.radstevee.axi.ksp.AxiProcessor.process(AxiProcessor.kt:63)
How can I prevent this? Because I am not creating the file multiple times. The whole processing logic is also only checking for annotated declarations and adding onto the
services
list. If I just wrap the
createNewFileByPath
call in a try/catch, the file does get created but is just empty. I can't directly remove it since I don't know where it will be located. This doesn't happen if I clean build of course
d
You need to write your processor in a way that accounts for it being called but with no symbols of interest being found. In other words, do not write the file in the case where
resolver.getSymbols(
returns an empty sequence. If you search the chat for
FileAlreadyExistsException
you can see there are some other edge cases that lead to this exception