mystic-agit 개발 블로그

[Jenkins][Groovy] 파일 읽기, 쓰기 본문

CI-CD/Jenkins

[Jenkins][Groovy] 파일 읽기, 쓰기

mystic-agit 2024. 3. 26. 11:36

Jenkins를 통한 Android 빌드 전

gradle.properties에 있는 특정 값을 읽어와 바꿔주고 덮어쓰기 한 뒤

빌드를 진행하고 싶었다.

 

Shell 혹은 Python 스크립트로도 제어할 수 있지만

스크립트 파일을 생성할 경우

- 관리할 파일이 추가로 발생

- 해당 파일이 없는 Git hash 기준에선 사용 불가 (파일 관리 프로젝트 형태에 따른)

이런 비효율적인 부분이 있어 Jenkinsfile인 Groovy 코드에서 직접 구현을 해보았다.

 

//..이전 코드 생략..
stage ("check gradle.properties") {

	// 생략된 코드에서 shouldStart 변수로 실행 여부 확인
    when { expression { return shouldStart == "true"}}
    
    steps {
        dir ("myPath") {
            script {
            	// (1)
                // Git의 main 브랜치에 포함되었던 파일이 아닌 경우 File 클래스를 통해 search 되지 않음.
                // 만약 gradle.properties를 File 클래스를 통해 찾으려면
                // Git의 main(혹은 master)에 한번 포함되어야함.
                // def gradlePropFile = new File("${env.WORKSPACE}/myPath/gradle.properties")  // 해당 코드 FileNotFound 발생
                
                // (2)
                // gradle.properties 파일 읽기
                def gradlePropFile = readFile("${env.WORKSPACE}/myPath/gradle.properties")

                def contents = ""
                def lines = gradlePropFile.readLines()

                lines.each { line ->
                	// default : publish.mode.test=false
                    // default 구문이 있는지 확인
                    if(line.contains("publish.mode.test")) {
                        contents = contents + "publish.mode.test=true" + "\n"
                    }
                    else {
                        contents = contents + line + "\n"
                    }
                }            

                // 위 (1)코드에서 File 클래스를 사용했다면 delete() 호출 가능
                // gradlePropFile.delete()
                
                // 기존 gradpe.properties 파일 삭제
                sh 'rm gradle.properties'

				// 새 gradle.properties 생성
                writeFile(file: "${env.WORKSPACE}/myPath/gradle.properties", text: contents, encoding: "UTF-8")
            }
        }
    }
}
//.. 이후 코드 생략..

 

(1)에 작성된 주석 내용처럼

나의 프로젝트에서 gradle.properties 파일은 Git의 main 혹은 master 브랜치에 있는 파일은 아니였다.

현재 작업중인 파일은 병합되지 않은 별도의 브랜치(feature/myWork)였고, 이런 경우 File 클래스로 해당 파일을 못찾는 이슈가 있었다.

대신, readFile 함수를 통해 가져올 수 있었다.

 

관련 정보

https://stackoverflow.com/questions/7729302/how-to-read-a-file-in-groovy-into-a-string

Comments