[안드로이드] kakao sample gradle 분석 2.루트의 build.gradle

프로그래밍/Android 관련2017. 12. 5. 15:42

안녕하세요. 개발자 드리머즈입니다.


다음으로 알아볼 파일은.. 루트에 위치한 build.gradle 파일입니다.


안드로이드 디벨로퍼 사이트의 아래 설명에 해당하는 파일입니다.

(https://developer.android.com/studio/build/index.html?hl=ko)%3E)

최상위 빌드 파일

루트 프로젝트 디렉토리에 있는 최상위 build.gradle 파일은 프로젝트의 모든 모듈에 적용되는 빌드 구성을 정의합니다. 기본적으로, 최상위 빌드 파일은 프로젝트의 모든 모듈에 공통되는 Gradle 리포지토리 종속성을 정의하기 위해 buildscript {} 블록을 사용합니다. 다음 코드 샘플에서는 새 프로젝트가 만들어진 후 최상위 build.gradle에서 찾을 수 있는 기본 설정과 DSL 요소에 대해 설명합니다. 




이 파일에는 코드가 꽤 많기 때문에 조금씩 떼어서 보겠습니다.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
maven { url 'https://raw.github.com/xujiaao/mvn-repository/master/releases' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}


buildscript{}의 사용 이유는

기본적으로, 최상위 빌드 파일은 프로젝트의 모든 모듈에 공통되는 Gradle 리포지토리 종속성을 정의하기 위해 buildscript {} 블록을 사용합니다.

라고 합니다.


좀 더 자세한 설명은.. 아래처럼 영어로 되어있습니다.

/**
 * The buildscript {} block is where you configure the repositories and
 * dependencies for Gradle itself--meaning, you should not include dependencies
 * for your modules here. For example, this block includes the Android plugin for
 * Gradle as a dependency because it provides the additional instructions Gradle
 * needs to build Android app modules.
 */


buildscript
{

   
/**
     * The repositories {} block configures the repositories Gradle uses to
     * search or download the dependencies. Gradle pre-configures support for remote
     * repositories such as JCenter, Maven Central, and Ivy. You can also use local
     * repositories or define your own remote repositories. The code below defines
     * JCenter as the repository Gradle should use to look for its dependencies.
     */


    repositories
{
        jcenter
()
   
}

   
/**
     * The dependencies {} block configures the dependencies Gradle needs to use
     * to build your project. The following line adds Android Plugin for Gradle
     * version 3.0.1 as a classpath dependency.
     */


    dependencies
{
        classpath
'com.android.tools.build:gradle:3.0.1'
   
}
}

/**
 * The allprojects {} block is where you configure the repositories and
 * dependencies used by all modules in your project, such as third-party plugins
 * or libraries. Dependencies that are not required by all the modules in the
 * project should be configured in module-level build.gradle files. For new
 * projects, Android Studio configures JCenter as the default repository, but it
 * does not configure any dependencies.
 */


allprojects
{
   repositories
{
       jcenter
()
   
}
}
부족하지만 번역을 해보면..

/**
buildscript {} 블럭에서 Gradle 자신을 위한(모듈에 대한 의존성dependencies은 여기에 적으면 안됨)

저장소repositories와 의존성dependencies을 설정할 수 있습니다.예를 들어, 이 블럭은 Gradle을 위한

의존성으로 안드로이드 플러그인을 포함합니다. 왜냐하면 이는 Gradle이 안드로이드 앱 모듈을 빌드하는데

필요한 부가적인 설명을 제공하기 때문입니다.
 */


buildscript
{

   
/**
     
The repositories {} 블럭은 Gradle이 의존성dependencies을 검색, 다운로드할 때

     사용할 저장소repositories를 설정할 수 있습니다. Gradle은 JCenter, Maven Central

     그리고 Ivy 같은 외부 저장소에 대한 지원을 미리 설정합니다. 또한 당신은 로컬 저장소나

     당신 소유의 외부 저장소를 사용할 수 있습니다. 아래의 코드는 Gradle이 의존성dependencies

     을 찾아야 하는 저장소로 JCenter를 정의합니다.
     */


    repositories
{
        jcenter
()
   
}

   
/**
     dependencies {} 블럭은 Gradle이 당신의 프로젝트를 빌드하기 위해 필요한 의존성을 설정합니다.

     아래의 라인은 classpath 의존성으로 Gradle 버전 3.0.1을 위한 안드로이드 플러그인을 추가합니다.
     */


    dependencies
{
        classpath
'com.android.tools.build:gradle:3.0.1'
   
}
}

/**
 allprojects {} 블럭에서 써드 파티 플러그인이나 라이브러리 처럼 모든 모듈에서 사용되는

저장소repositories와 의존성dependencies를 설정합니다. 프로젝트의 모든 모듈에서 필요한 것은

아닌 의존성dependencies은 module 레벨의 build.gradle 파일에서 설정되어야 합니다.

새로운 프로젝트에서, 안드로이드 스튜디오는 기본 저장소로 JCenter를 설정하지만 이는 아무런 의존성

을 설정하지 않습니다.

allprojects
{
   repositories
{
       jcenter
()
   
}
}

와 같습니다.


대충 이해가 가네요. 필요한 특정.. 라이브러리의 이름을 dependencies{}블럭에 적고, 이 라이브러리를 찾기 위해 검색해야 하는 저장소는 repositories{}블럭에 명시한다는 말입니다.

다시 kakao sample쪽 코드를 해석해보면..

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
maven { url 'https://raw.github.com/xujiaao/mvn-repository/master/releases' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

Gradle을 위해 필요한 라이브러리는 'com.android.tools.build:gradle:3.0.1''com.google.gms:google-services:3.1.0'

인데, 이 것들은.. jcenter(), google() 그리고.. maven{}블럭의 경로?에서.. 찾으라고 하는 것 같습니다.

그런데 maven{}은 왜 필요한지 모르겠네요(remote Maven repository). 해당 주소로 가봐도.. 잘 모르겠고.. dependencies{}에.. 대응하는 게 없는 것 같네요.


그 다음 보이는 코드는 아래와 같습니다.

plugins {
id 'org.ajoberstar.grgit' version '1.7.1'
}

import org.ajoberstar.grgit.Grgit;

plugins {} 블럭이 등장했습니다.

https://docs.gradle.org/current/userguide/plugins.html 에.. 설명이 있긴한데 어렵네요. dependencies{}블럭과 비슷하게 필요한 것을 가져오는 것 같습니다. dependencies{}과 다른 점은 gradle 파일에서 특정 동작을 할 수 있게 도와주는 것 같습니다.

plugins의 대상이 되는.. 'org.ajoberstar.grgit'의 공식 사이트는 아래에 있습니다.

http://ajoberstar.org/grgit/grgit-gradle.html

간단히 살펴보니.. gradle 파일 내에서 git에 접근할 수 있도록 도와주는 plugin(library같은..)인 것 같습니다.


import org.ajoberstar.grgit.Grgit;

이 코드는 없어도 되는 것 같습니다. 바로 위의 plugins{} 블럭을 사용하면 자동으로 import되는 것 같습니다.

만약

plugins { id 'org.ajoberstar.grgit' version '<version>' apply false }

위의 코드처럼 plugins을 사용하면, git에 접근하기 전에 import를 해야 합니다.


계속해서 다음 코드를

ext {
git = null;
try {
git = Grgit.open()
versionCode = git.tag.list().size()
version = git.describe().split('-')[0]
branchName = project.hasProperty("branch") ? project.property("branch") : git.branch.current.name;
println "current branch: ${branchName}"

if (branchName.startsWith('master')) {
// do not bump version for master branch because release version is already tagged.
project.versionCode = versionCode;
project.version = version;
} else if (branchName.startsWith('hotfix')) {
bumpVersion(rootProject, 'revision')
} else {
bumpVersion(rootProject, 'minor')
}
} catch (Exception e) {
versionCode = project.VERSION_CODE.toInteger()
version = project.KAKAO_SDK_VERSION
version += "-SNAPSHOT"
}

defaultDeployPhase = project.hasProperty("deploy_phase") ? project.property("deploy_phase") : project.DEFAULT_PHASE

println "version: ${project.version}"
println "versionCode: ${project.versionCode}"
}

ext {} 블럭이 등장했습니다. 다행히 스택오버플로우에 도움이 될만한 내용이 있습니다.

https://stackoverflow.com/questions/21696534/ext-and-code-blocks-meaning-in-the-gradle-file

 ext is shorthand for project.ext, and is used to define extra properties for the project object. (It's also possible to define extra properties for many other objects.) When reading an extra property, the ext. is omitted (e.g. println project.springVersion or println springVersion). The same works from within methods. It does not make sense to declare a method named ext.

번역해보면 아래와 같습니다.

ext 는project.ext의 줄임말이고, project 오브젝트의 추가 프로퍼티extra properties를 정의하기 위해 사용됩니다. (많은 다른 오브젝트의 추가 프로퍼티 또한 정의할 수 있습니다) 추가 프로퍼티를 읽을 때, ext. 는 생략됩니다. (예: println project.springVersion 는 println springVersion와 같음). 함수에서도 같은 방식으로 동작합니다. ext라고 함수를 선언하면 안됩니다.


프로퍼티는 일반적인 프로그래밍 언어의 변수와 비슷한 것 같습니다.

http://kwonnam.pe.kr/wiki/gradle

여기에 gradle 변수에 대한 좋은 설명이 있습니다.

변수 선언

  • 로컬 변수 : def 변수명으로 선언. 해당 스크립트 로컬에서만 접근 가능하다.
  • ext 변수 : 프로젝트 전체와 서브 프로젝트에서도 접근 가능하다.
  • ext 변수 선언과 사용
    ext.javaVersion = '1.7' // 한개씩 선언
    ext {
        // 여러개 한꺼번에 선언
        springVersion = '3.1.0.RELEASE'
        emailNotification = 'build@master.org'
    }
     
    // 가변 Key, 가변 값 형태로 코드를 통해 프라퍼티를 추가할 때는 아래 방식을 사용한다.
    project.ext['keyname'] = 'value'
     
    task hello << {
        println "javaVersion : ${javaVersion}"
        println "springVersion : ${springVersion}"
        println "emailNotification : ${emailNotification}"
    } 


결국 프로젝트 전체와 서브 프로젝트에서도 접근 가능한 변수인 git을 만드는 것 같습니다.


다음은 코드는 아래와 같습니다.

apply plugin: 'java'

다행히 스택오버플로우에 힌트가 좀 있습니다.

https://stackoverflow.com/questions/26366653/what-is-apply-plugin-java

It imports the Java plugin for gradle, including a lot of predefined commands/tasks. This might be useful: gradle.org/plugins – Joffrey Oct 14 '14 at 17:27

이 코드는 gradle을 위한 자바 플러그인(미리 정의된 많은 커맨드/테스크를 포함)을 불러들입니다.


그렇다고 합니다. gradle에서 사용되는 자바 플러그인을 import하는 것인데.. kakaso sdk sample에서는 주석처리해도 문제가 없네요? 음..


내용이 길어져서 다음 포스트에 계속 합니다..



*참고

안드로이드 디벨로퍼 사이트 글 : https://developer.android.com/studio/build/index.html?hl=ko)%3E

gradle 공식 사이트 - 유저가이드 : https://docs.gradle.org/current/userguide/userguide.html

스택오버플로우 질문글 - DSL : https://stackoverflow.com/questions/38336576/what-does-dsl-mean-in-gradle

스팩오버플로우 질문글 - plugin : https://stackoverflow.com/questions/32352816/what-the-difference-in-applying-gradle-plugin

작성자

Posted by 드리머즈

관련 글

댓글 영역