2

I have a custom function for wrapping Service api call

I want to add some warning while some api call forget adding safeApiCall{}

suspend fun <T:Any> safeApiCall(
  apiCall: suspend () -> T
) {
  //do something
}

interface Service {
  @Get
  suspend fun getUser() : User
  @Put
  suspend fun updateUser(name:String) : User
}

val service:Service
service.getUser() //warning "should use safeApiCall"
SafeApiCall { service.getUser() } //ok

This is my attempt , but not working

interface $Interface$ {
    suspend fun $Method$ ($Parameter$ : $ParameterType$): $ReturnType$
}
$Interface$.$MethodCall$
        
Ewei
  • 31
  • 5

1 Answers1

4

That was tricky, but here it is:

enter image description here

You need to use script constraints. The idea is to filter the parent of your whole match. There are many ways to do that, e.g. to distinguish them by their type.

Here is my search:

Template:

$Service$.$method$($args$)

$Service$ variable filter:

Type = you.package.Service

$args$ (optional, though):

Count = [0: +Inf]

And the most important part, the whole template script filter:

__context__.parent.parent.class.name == "org.jetbrains.kotlin.psi.KtNamedFunction"

It's dirty, I know. For some reason I was not able to make it work with instanceof, but you may tune it.

If you do, you may ask: How do I debug that script?

Here is my advice. Open the IDEA's logs (Help -> Show Log in Explorer). Then use println() in the script, it will print it's argument to the STDOUT:

enter image description here

You see, here there were two matches, but the parent of the second one (which os ok as per your request) was of a different type. So, a quick guess and dirty fix here was to compare them. A more cunning way would be to get the name of the wrapping construct and check if it's safeApiCall or not. I'll leave that to you as an exercise.

Good luck!

madhead
  • 31,729
  • 16
  • 153
  • 201
  • @МихаилНафталь, indeed. My answer is just a starter. It passes the "tests", the original OPs request. As I've noted, OP could improve it to handle any kind of logic. Don't blame me for being to lazy polishing this query. – madhead Jan 19 '22 at 13:19