Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BSVR-54] Spotless pre-commit hook 추가 #4

Merged
merged 10 commits into from
Jul 1, 2024
1,340 changes: 1,340 additions & 0 deletions .editorconfig

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/sh

PROJECT_ROOT=$(git rev-parse --show-toplevel)

# part1
stagedFiles=$(git diff --staged --name-only)

# part2
echo "Running spotlessApply. Formatting code..."
cd $PROJECT_ROOT && ./gradlew spotlessApply

if [ $? -ne 0 ]; then
echo "Spotless apply failed!"
exit 1
fi

# part3
for file in $stagedFiles; do
if test -f "$file"; then
git add $file
fi
done
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @EunjiShin @wjdwnsdnjs13 @pminsung12
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

루트 디렉토리의 모든 파일에 대해 특정 사용자 지정하는 방법이구나 👍🏻

Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package org.depromeet.spot.application;

import jakarta.annotation.PostConstruct;
import java.util.TimeZone;

import jakarta.annotation.PostConstruct;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

Expand All @@ -18,5 +20,4 @@ public static void main(String[] args) {
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone(DEFAULT_TIMEZONE_KST));
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan(
basePackages = {
"org.depromeet.spot.application"
}
)
@ComponentScan(basePackages = {"org.depromeet.spot.application"})
@Configuration
public class SpotApplicationConfig {

}

public class SpotApplicationConfig {}
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package org.depromeet.spot.application.sample.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.depromeet.spot.application.sample.controller.request.SampleRequest;
import org.depromeet.spot.application.sample.controller.response.SampleResponse;
import org.springframework.http.HttpStatus;
Expand All @@ -12,6 +9,10 @@
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

// FIXME: swagger 확인용 샘플 컨트롤러 입니다. 이후 실제 작업 시작할 때 삭제 예정이에요!
@RestController
@RequiredArgsConstructor
Expand All @@ -22,11 +23,8 @@ public class SampleController {
@PostMapping
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "swagger 테스트용 API :: 주어진 메세지를 반환한다.")
public SampleResponse testSwagger(
@RequestBody SampleRequest sampleRequest
) {
public SampleResponse testSwagger(@RequestBody SampleRequest sampleRequest) {
var message = sampleRequest.message();
return new SampleResponse(message);
}

}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package org.depromeet.spot.application.sample.controller.request;

import jakarta.validation.constraints.NotBlank;

import org.hibernate.validator.constraints.Length;

public record SampleRequest(
@NotBlank(message = "메세지는 공백일 수 없습니다.")
@Length(min = 1, max = 30, message = "메세지는 1~30글자 사이여야 합니다.")
String message
) {

}
@NotBlank(message = "메세지는 공백일 수 없습니다.")
@Length(min = 1, max = 30, message = "메세지는 1~30글자 사이여야 합니다.")
String message) {}
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
package org.depromeet.spot.application.sample.controller.response;

public record SampleResponse(
String message
) {

}
public record SampleResponse(String message) {}
34 changes: 34 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ plugins {
id("java")
id("org.springframework.boot") version "3.0.1"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
id("com.diffplug.spotless") version "6.21.0"
}

allprojects {
Expand All @@ -18,6 +19,7 @@ subprojects {
apply(plugin = "java")
apply(plugin = "org.springframework.boot")
apply(plugin = "io.spring.dependency-management")
apply(plugin = "com.diffplug.spotless")

java {
sourceCompatibility = JavaVersion.VERSION_17
Expand All @@ -36,6 +38,38 @@ subprojects {
testImplementation("org.junit.jupiter:junit-jupiter")
}

// 코드 포맷터 spotless
spotless {
java {
// Google Java 포맷 적용
googleJavaFormat().aosp()
// 아래 순서로 import문 정렬
importOrder("java", "javax", "jakarta", "org", "com")
// 사용하지 않는 import 제거
removeUnusedImports()
// 각 라인 끝에 있는 공백을 제거
trimTrailingWhitespace()
// 파일 끝에 새로운 라인 추가
endWithNewline()
Comment on lines +44 to +53
Copy link
Collaborator

@pminsung12 pminsung12 Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주석 👍🏻 이해완.

}
}
Comment on lines +42 to +55
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wjdwnsdnjs13 놉! 요기 build.gradle 보면 spotless에서 어떤 포맷을 사용할건지 설정해두었어~
그래서 별다른 설정 안해도 ./gradlew spotlessApply만 하면 알아서 적용될거야!

그런데 매번 spotlessApply를 하면 번거로우니까,

  • ./gradlew compileJava를 돌릴때 (build.gradle tasks.named compileJava 부분)
  • commit을 찍을 때 (.githooks의 pre-commit 부분)

내가 굳이 spotless을 돌리지 않아도 자동으로 동작하게 만들어둔게 pre-commit 설정~~


// git commit시 자동으로 spotless 적용되도록 설정
// 최초 적용시 && script 변경시 ./gradlew compileJava 한번 실행해주세요
tasks.register<Copy>("updateGitHooks") {
Copy link
Collaborator

@pminsung12 pminsung12 Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 .git/hooks에 파일을 바로 정의하지 않고, pre-commit에 정의해서 컴파일 하기 전에 복사하는 이유는 버전관리 떄문이야?

Copy link
Collaborator Author

@EunjiShin EunjiShin Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고것도 있는데, .git 폴더가 기본적으로 숨김폴더라서 직접 스크립트를 넣을 수가 없더라고!
.git은 로컬에서 관리되는 값이지 리모트 저장소로 올라가는 값이 아니라서, .git에 바로 정의하면 팀원끼리 해당 스크립트를 공유할 수가 없다고 하더라고??

저 스크립트가 각자의 로컬에 있어야 원하는대로 훅이 동작해서, 스크립트 공유 목적으로 빼둔거라고 생각하면 될 것 같아!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 그러네 .git은 당연히 공유가 안되겠다 .github랑 개념을 혼동했다. 확인~

from(file("${rootProject.rootDir}/.githooks/pre-commit"))
into(file("${rootProject.rootDir}/.git/hooks"))
}

tasks.register<Exec>("makeGitHooksExecutable") {
commandLine("chmod", "+x", "${rootProject.rootDir}/.git/hooks/pre-commit")
dependsOn("updateGitHooks")
}

tasks.named<JavaCompile>("compileJava") {
dependsOn("makeGitHooksExecutable")
}
Comment on lines +64 to +71
Copy link
Collaborator

@pminsung12 pminsung12 Jul 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compile 전에 githook이 무조건 걸리는구나 👍🏻


tasks.test {
useJUnitPlatform()
}
Expand Down