xref: /aosp_15_r20/external/ktfmt/online_formatter/src/main/kotlin/main.kt (revision 5be3f65c8cf0e6db0a7e312df5006e8e93cdf9ec)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.facebook.ktfmt.onlineformatter
18 
19 import com.amazonaws.services.lambda.runtime.Context
20 import com.amazonaws.services.lambda.runtime.RequestHandler
21 import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent
22 import com.facebook.ktfmt.cli.ParseResult
23 import com.facebook.ktfmt.cli.ParsedArgs
24 import com.facebook.ktfmt.format.Formatter
25 import com.google.gson.Gson
26 
27 class Handler : RequestHandler<APIGatewayProxyRequestEvent, String> {
28   init {
29     // Warm up.
30     gson.toJson(Formatter.format(Formatter.KOTLINLANG_FORMAT, "/* foo */ fun foo() {}"))
31   }
32 
handleRequestnull33   override fun handleRequest(event: APIGatewayProxyRequestEvent, context: Context?): String {
34     return gson.toJson(
35         try {
36           val request = gson.fromJson(event.body, Request::class.java)
37           val style = request?.style ?: return "{}"
38           when (val parseResult = ParsedArgs.parseOptions(listOfNotNull(style).toTypedArray())) {
39             is ParseResult.Ok -> {
40               val parsedArgs = parseResult.parsedValue
41               Response(
42                   source =
43                       Formatter.format(
44                           parsedArgs.formattingOptions.copy(maxWidth = request.maxWidth ?: 100),
45                           request.source.orEmpty(),
46                       ),
47                   err = null,
48               )
49             }
50             is ParseResult.Error -> {
51               Response(null, parseResult.errorMessage)
52             }
53             is ParseResult.ShowMessage -> {
54               Response(null, parseResult.message)
55             }
56           }
57         } catch (e: Exception) {
58           Response(null, e.message)
59         })
60   }
61 
62   companion object {
63     val gson = Gson()
64   }
65 }
66 
67 class Request {
68   var source: String? = ""
69   var style: String? = ""
70   var maxWidth: Int? = 100
71 }
72 
73 data class Response(val source: String?, val err: String?)
74