Hi :wave: I’m looking for a way to generate a clas...
# ksp
c
Hi 👋 I’m looking for a way to generate a class from a json file before/as part of my build. Would KSP be a viable way to do that?
e
No, but you could that with Gradle (or some other build system you use)
c
ok, thanks
d
Why shouldn't that be possible? Couldn't you just add a simple annotation; create a processor for that annotation; fetch the JSON file; create the source with maybe something like KotlinPoet? Ofcourse, changing the content of the json wouldn't trigger a new processor run with incremental builds. Or am I missing something?
e
How would you "fetch the JSON" with KSP 🤔
d
Copy code
error(URL("<https://reqres.in/api/users?page=2>").readText())
Works fine for me
@Chris C Did you mean something like that?
e
I believe he meant that there is a json file somewhere in the project. Not on some remote server. But will let @Chris C confirm
c
Yes, so I want the json file to be a local resource
e
Yeah KSP doe not (yet) support reading non source files https://github.com/google/ksp/issues/431
Sounds like a gradle plugin is better suited to your use case 🤔
d
Copy code
error(File("file.json").readText(Charsets.UTF_8))
? I'm guessing I'm probably missing something here. Sorry for the confusion.
c
I wanted to do something like this to read the json:
MyClass::class.java.getResourceAsStream("file.json")
j
theoretically you can add relative path as annotation argument and parse file path there. But since you are not really working at symbol level, KSP might not be a best suit for your use.
😈 1
c
Yes I was starting to wonder if that was the case. I'll take a look at adding an extra build step and maybe use kotlinpoet to generate the code. Thanks everyone for all the help and pointers.
m
I need something that mixes annotations with external files (yaml files). This doesn't seem to be officially supported in KSP at this point, but providing it via annotation argument would probably work. Or maybe a plugin argument (via build.gradle). @Jiaxiang if the path is provided that way, how can one access the file? Would you be so kind and provide a bit more insight on that?
j
you may try use relative path in annotation argument and open/read file with system API, that’s what I can think of, but they are not supported by KSP, which means incremental won’t work.
m
Sorry for maybe asking for something obvious, but what do you mean by system API? I'm not sure which API I can use to access the files from the context of the processor
j
APIs like
java.io.File
m
OK, I didn't imagine that would work, thank you for advice. Also, any plans to support it for ksp? I've seen the issue but it seems that it hasn't been touched for quite a while, even though it has P1 label