build: 添加代码格式化配置

This commit is contained in:
AiKrai 2025-04-29 11:12:00 +08:00
parent 29f5e1b75f
commit db9be40c16
18 changed files with 55 additions and 38 deletions

2
.gitignore vendored
View File

@ -7,6 +7,8 @@ build/
!**/src/test/**/build/ !**/src/test/**/build/
/logs /logs
/config /config
/gradlew
/gradlew.bat
### STS ### ### STS ###
.apt_generated .apt_generated

View File

@ -1,6 +1,7 @@
plugins { plugins {
kotlin("jvm") version "1.9.25" kotlin("jvm") version "1.9.25"
kotlin("plugin.spring") version "1.9.25" kotlin("plugin.spring") version "1.9.25"
id("com.diffplug.spotless") version "6.25.0"
id("org.springframework.boot") version "3.4.4" id("org.springframework.boot") version "3.4.4"
id("io.spring.dependency-management") version "1.1.7" id("io.spring.dependency-management") version "1.1.7"
id("com.google.devtools.ksp") version "1.9.25-1.0.20" id("com.google.devtools.ksp") version "1.9.25-1.0.20"
@ -29,6 +30,21 @@ kotlin {
} }
} }
spotless {
kotlin {
ktlint()
.editorConfigOverride(
mapOf(
"ktlint_standard_no-wildcard-imports" to "disabled",
"ktlint_standard_trailing-comma-on-call-site" to "disabled",
"ktlint_standard_trailing-comma-on-declaration-site" to "disabled",
"indent_size" to "2"
)
)
target("src/**/*.kt")
}
}
tasks.withType<Test> { tasks.withType<Test> {
useJUnitPlatform() useJUnitPlatform()
} }

View File

@ -12,4 +12,4 @@ class HuToolConfig {
fun snowflake(): Snowflake { fun snowflake(): Snowflake {
return IdUtil.getSnowflake() return IdUtil.getSnowflake()
} }
} }

View File

@ -44,7 +44,7 @@ class ResponseAdvisor(
response.headers.contentType = MediaType.APPLICATION_JSON response.headers.contentType = MediaType.APPLICATION_JSON
return objectMapper.writeValueAsString(RespBean.success(body)) return objectMapper.writeValueAsString(RespBean.success(body))
} }
if (body == null) { if (body == null) {
return RespBean.success<Any>(null) return RespBean.success<Any>(null)
} }

View File

@ -1,6 +1,5 @@
package com.app.config.exception package com.app.config.exception
import com.app.data.RespBean import com.app.data.RespBean
import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletRequest
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
@ -35,23 +34,23 @@ class ExceptionAdviceHandel {
*/ */
private fun throwableAdvice(error: Throwable): RespBean<Void> { private fun throwableAdvice(error: Throwable): RespBean<Void> {
logger.error("系统发生未处理异常", error) logger.error("系统发生未处理异常", error)
// 获取详细错误信息 // 获取详细错误信息
val printStackTrace = ByteArrayOutputStream() val printStackTrace = ByteArrayOutputStream()
error.printStackTrace(PrintStream(printStackTrace)) error.printStackTrace(PrintStream(printStackTrace))
// 查找第一个应用包下的堆栈信息,用于定位错误 // 查找第一个应用包下的堆栈信息,用于定位错误
val stackElement = error.stackTrace.firstOrNull { val stackElement = error.stackTrace.firstOrNull {
it.className.startsWith("com.app") it.className.startsWith("com.app")
} }
// 格式化错误信息 // 格式化错误信息
val errorMsg = if (stackElement != null) { val errorMsg = if (stackElement != null) {
"系统异常: ${error.message ?: "Unknown error"} (位置: ${stackElement.className}:${stackElement.lineNumber})" "系统异常: ${error.message ?: "Unknown error"} (位置: ${stackElement.className}:${stackElement.lineNumber})"
} else { } else {
"系统异常: ${error.message ?: "Unknown error"}" "系统异常: ${error.message ?: "Unknown error"}"
} }
return RespBean.failure(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMsg) return RespBean.failure(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMsg)
} }

View File

@ -20,7 +20,7 @@ import org.springframework.web.bind.annotation.ResponseBody
class GlobalException( class GlobalException(
private val exceptionAdviceHandel: ExceptionAdviceHandel private val exceptionAdviceHandel: ExceptionAdviceHandel
) { ) {
// 所有未明确处理的异常将通过exceptionAdviceHandel统一处理 // 所有未明确处理的异常将通过exceptionAdviceHandel统一处理
@ExceptionHandler(Throwable::class) @ExceptionHandler(Throwable::class)
fun handleAllExceptions(req: HttpServletRequest, error: Throwable): RespBean<*> { fun handleAllExceptions(req: HttpServletRequest, error: Throwable): RespBean<*> {

View File

@ -1,6 +1,5 @@
package com.app.config.satoken package com.app.config.satoken
import cn.dev33.satoken.context.SaHolder import cn.dev33.satoken.context.SaHolder
import cn.dev33.satoken.filter.SaServletFilter import cn.dev33.satoken.filter.SaServletFilter
import cn.dev33.satoken.interceptor.SaInterceptor import cn.dev33.satoken.interceptor.SaInterceptor

View File

@ -26,6 +26,7 @@ class SwaggerConfig {
} }
} }
} }
@Bean @Bean
fun customOpenAPI(): OpenAPI { fun customOpenAPI(): OpenAPI {
return OpenAPI() return OpenAPI()
@ -57,5 +58,4 @@ class SwaggerConfig {
// .packagesToScan("com.csrs.web.controller.ai") // .packagesToScan("com.csrs.web.controller.ai")
// .build() // .build()
// } // }
}
}

View File

@ -1,4 +1,4 @@
package com.app.controller; package com.app.controller
import cn.dev33.satoken.stp.StpUtil import cn.dev33.satoken.stp.StpUtil
import com.app.data.dto.SignInRequest import com.app.data.dto.SignInRequest

View File

@ -1,6 +1,5 @@
package com.app.controller package com.app.controller
import cn.dev33.satoken.annotation.SaIgnore import cn.dev33.satoken.annotation.SaIgnore
import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMapping
@ -15,4 +14,4 @@ class HelloController {
fun hello(): String { fun hello(): String {
return "Hello, World!" return "Hello, World!"
} }
} }

View File

@ -26,4 +26,4 @@ class UserController(
): Page<User> { ): Page<User> {
return userService.list(pageNum!!, pageSize!!) return userService.list(pageNum!!, pageSize!!)
} }
} }

View File

@ -2,9 +2,9 @@ package com.app.data.dto
import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.media.Schema
data class SignInRequest ( data class SignInRequest(
@Schema(title = "username", description = "账号名称", defaultValue = "") @Schema(title = "username", description = "账号名称", defaultValue = "")
var username: String, var username: String,
@Schema(title = "password", description = "账号密码", defaultValue = "") @Schema(title = "password", description = "账号密码", defaultValue = "")
var password: String var password: String
) )

View File

@ -33,4 +33,4 @@ interface User {
val updateBy: String? val updateBy: String?
val updateTime: Timestamp? val updateTime: Timestamp?
val remark: String? val remark: String?
} }

View File

@ -56,8 +56,11 @@ class RequestLogFilter(
fun logRequestEnd(wrapper: ContentCachingResponseWrapper, startTime: Long) { fun logRequestEnd(wrapper: ContentCachingResponseWrapper, startTime: Long) {
val time = System.currentTimeMillis() - startTime val time = System.currentTimeMillis() - startTime
val status = wrapper.status val status = wrapper.status
val content = if (status != 200) "$status 错误" val content = if (status != 200) {
else String(wrapper.contentAsByteArray) "$status 错误"
} else {
String(wrapper.contentAsByteArray)
}
log.info("\n>>>>>请求处理耗时:[{}ms] 响应结果:{}", time, content) log.info("\n>>>>>请求处理耗时:[{}ms] 响应结果:{}", time, content)
} }
@ -79,25 +82,29 @@ class RequestLogFilter(
if (StpUtil.isLogin()) { if (StpUtil.isLogin()) {
val id = StpUtil.getLoginId() val id = StpUtil.getLoginId()
log.info(""" log.info(
"""
>>>>>请求ID:[${reqId}] >>>>>请求ID:[$reqId]
>>>>>请求URL:["${request.servletPath}"](${request.method}) >>>>>请求URL:["${request.servletPath}"](${request.method})
>>>>>远程IP:[${request.remoteAddr}] >>>>>远程IP:[${request.remoteAddr}]
>>>>>用户名:[username] >>>>>用户名:[username]
>>>>>用户ID:$id >>>>>用户ID:$id
>>>>>角色:${StpUtil.getRoleList()} >>>>>角色:${StpUtil.getRoleList()}
>>>>>请求参数列表: [$params] >>>>>请求参数列表: [$params]
""".trimIndent()) """.trimIndent()
)
} else { } else {
log.info(""" log.info(
"""
>>>>>请求ID:[${reqId}] >>>>>请求ID:[$reqId]
>>>>>请求URL:["${request.servletPath}"](${request.method}) >>>>>请求URL:["${request.servletPath}"](${request.method})
>>>>>远程IP地址:[${request.remoteAddr}] >>>>>远程IP地址:[${request.remoteAddr}]
>>>>>身份:未验证 >>>>>身份:未验证
>>>>>请求参数列表: [$params] >>>>>请求参数列表: [$params]
""".trimIndent()) """.trimIndent()
)
} }
} }

View File

@ -8,7 +8,6 @@ import org.babyfish.jimmer.spring.repository.KRepository
import org.babyfish.jimmer.sql.kt.ast.expression.eq import org.babyfish.jimmer.sql.kt.ast.expression.eq
import org.babyfish.jimmer.sql.kt.ast.expression.`eq?` import org.babyfish.jimmer.sql.kt.ast.expression.`eq?`
interface UserRepository : KRepository<User, Long> { interface UserRepository : KRepository<User, Long> {
fun findUser( fun findUser(
pageIndex: Int = 0, pageIndex: Int = 0,
@ -27,4 +26,4 @@ interface UserRepository : KRepository<User, Long> {
where(table.userName eq username) where(table.userName eq username)
select(table) select(table)
}.fetchOne() }.fetchOne()
} }

View File

@ -10,4 +10,4 @@ interface UserService {
pageNum: Int = 0, pageNum: Int = 0,
pageSize: Int = 10 pageSize: Int = 10
): Page<User> ): Page<User>
} }

View File

@ -12,11 +12,8 @@ import org.springframework.stereotype.Service
@Service @Service
class UserServiceImpl( class UserServiceImpl(
private val userRepository: UserRepository private val userRepository: UserRepository
): UserService { ) : UserService {
override fun signIn(username: String, password: String): String { override fun signIn(username: String, password: String): String {
// withContext(Dispatchers.IO) {
//
// }
val user = userRepository.findByUserName(username) ?: throw Exception("User not found") val user = userRepository.findByUserName(username) ?: throw Exception("User not found")
if (user.password != SecureUtil.sha1(password)) { if (user.password != SecureUtil.sha1(password)) {
throw Exception("Invalid password") throw Exception("Invalid password")
@ -25,7 +22,7 @@ class UserServiceImpl(
.setExtraData(mapOf("deptId" to user.deptId)) .setExtraData(mapOf("deptId" to user.deptId))
StpUtil.login(user.userId.toString(), parameter) StpUtil.login(user.userId.toString(), parameter)
val token = StpUtil.getTokenInfo() val token = StpUtil.getTokenInfo()
return token.tokenValue; return token.tokenValue
} }
override fun list( override fun list(
@ -34,4 +31,4 @@ class UserServiceImpl(
): Page<User> { ): Page<User> {
return userRepository.findUser(pageNum, pageSize) return userRepository.findUser(pageNum, pageSize)
} }
} }

View File

@ -9,5 +9,4 @@ class ApplicationTests {
@Test @Test
fun contextLoads() { fun contextLoads() {
} }
} }