Spotless 형식 검사에서 Room DAO 클래스 제외

소개



Android 프로젝트의 Kotlin 코드가 기본 형식인지 확인하기 위해 CI에서 수행하기 위해 DroidKaigi/conference-app-2021을 흉내내고, Spotless plugin for Gradle을 도입했습니다.

도입 방법은 DroidKaigi/conference-app App Owner의 takahirom씨가 해설하고 있습니다.
KtLint + Spotless + GitHub Actions로 PR에 sugggested change

Room의 DAO 클래스는 포맷 체크의 대상에서 제외하고 싶다



예를 들어 Room의 DAO 클래스에 긴 SQL 문이 있다고 가정합니다.
Android Studio는 Room의 SQL 문을 강조 표시하기 때문에 읽기 쉽습니다.


(이미지는 안드로이드 스튜디오. 수중에 긴 SQL문이 없었기 때문에, 무의미한 ORDER BY구로 길게 하고 있습니다.)
./gradlew spotlessCheck 명령으로 포맷 체크를 실시하면, 1행이 길면 ktlint에 화나게 됩니다.
> Task :spotlessKotlin FAILED
Step 'ktlint' found problem in 'data/local/src/main/java/com/tfandkusu/videobookmark/data/local/dao/BookmarkDao.kt':
Error on line: 17, column: 1
Exceeded max line length (100)
java.lang.AssertionError: Error on line: 17, column: 1
Exceeded max line length (100)

따라서 SQL문을 1행 100문자 넘지 않도록 문자열을 +로 연결하여 2행으로 나누어 씁니다.
그러면 ktlint에게 화가 나지 않습니다.
그러나 SQL 문의 하이라이트 표시가 없어져 버립니다.
이것은 읽기가 어렵습니다.



따라서, Room의 DAO 클래스만 포맷 체크의 대상외로 하는 설정을 실시합니다.

전제



Room의 DAO 클래스의 파일명은 Dao.kt로 끝나는 것으로 합니다.

Spotless 설정 변경



targetExclude 파라미터로 Dao.kt 로 끝나는 파일을 체크의 대상외로 할 수 있습니다.

build.gradle
allprojects {
    repositories {
        google()
        mavenCentral()
    }
    apply plugin: "com.diffplug.spotless"
    spotless {
        ratchetFrom 'origin/main'
        kotlin {
            target '**/*.kt'
            // Dao.ktで終わるファイルを除外
            targetExclude('**/*Dao.kt')
            ktlint("0.41.0")
                    .userData([android: "true", experimental: "true"])
        }
    }
}

targetExclude 파라미터의 유효성



targetExclude 매개변수는 마지막 하나만 유효한 것 같습니다.
(1차 자료는 발견되지 않음)
따라서 다른 targetExclude 매개 변수가 targetExclude('**/*Dao.kt') 아래에 있으면 Dao.kt로 끝나는 파일을 제외 할 수 없습니다.

build.gradle

allprojects {
    repositories {
        google()
        mavenCentral()
    }
    apply plugin: "com.diffplug.spotless"
    spotless {
        ratchetFrom 'origin/main'
        kotlin {
            target '**/*.kt'
            targetExclude('**/*Dao.kt')
            targetExclude("$buildDir/**/*.kt")
            targetExclude('bin/**/*.kt')
            targetExclude("**/generated/**/*.kt")
            ktlint("0.41.0")
                    .userData([android: "true", experimental: "true"])
        }
    }
}

그러나 targetExclude 매개 변수에 여러 경로를 설정할 수 있습니다.
allprojects {
    repositories {
        google()
        mavenCentral()
    }
    apply plugin: "com.diffplug.spotless"
    spotless {
        ratchetFrom 'origin/main'
        kotlin {
            target '**/*.kt'
            targetExclude('**/*Dao.kt',"$buildDir/**/*.kt", 'bin/**/*.kt', "**/generated/**/*.kt")
            ktlint("0.41.0")
                    .userData([android: "true", experimental: "true"])
        }
    }
}

좋은 웹페이지 즐겨찾기