2017-04-23 25 views
0

搖籃配置我想申請配置搖籃腳本,只有當條件滿足:應用條件

useRepo = System.getenv()["IGNORE_REPO_CFG"] == null 

buildscript { 
    useRepo && repositories { // <== HERE 
     maven.url 'http://localhost:8081/artifactory/release' 
    } 
} 

subprojects { 
    configurations { 
     all { 
      useRepo && resolutionStrategy { // <== HERE 
       cacheChangingModulesFor 0, 'seconds' 
       cacheDynamicVersionsFor 0, 'seconds' 
      } 
     } 
    } 
} 

由於Groovy中/搖籃範圍魔法我不能通過useRepobuildscriptsubprojects.configurations.all範圍。

我讀到類包裝:

class Cfg { 
    static final useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null 
} 

Cfg.useRepo我:

java.lang.ClassNotFoundException: Cfg 

UPDATE在:

project.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null 
buildscript { 
    project.ext.useRepo && repositories { 
     maven.url 'http://localhost:8081/artifactory/lognet-release' 
    } 
} 

我:

Caused by: groovy.lang.MissingPropertyException: Cannot get property 'useRepo' on extra properties extension as it does not exist 

回答

1

就像你試過,你應該使用project.ext

project.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null 

但是當你現在嘗試使用project.extsubprojects它是空的,因爲它沒有在這個項目定義。所以你需要用``rootProject.ext`訪問它,因爲你定義它有

subprojects { 
    configurations { 
     all { 
      rootProject.ext.useRepo && resolutionStrategy { // <== HERE 
       cacheChangingModulesFor 0, 'seconds' 
       cacheDynamicVersionsFor 0, 'seconds' 
      } 
     } 
    } 
} 

您嘗試使用extbuildscript內,但是,這並不工作,因爲buildscript -closure被執行首先,然後是另一個腳本。請參閱this Gradle Discussion

如果您想這樣做,您可以在settings.gradle內的gradle.ext上指定此變量。

gradle.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null 

然後使用它。

buildscript { 
    gradle.ext.useRepo && repositories { 
     maven.url 'http://localhost:8081/artifactory/lognet-release' 
    } 
} 
+0

謝謝。通過'settings.gradle'中的'gradle.ext.useRepo',我實現了我的目標。你能否說爲什麼在'build.gradle'中定義的'class'不能在'buildscript'內被訪問?它看起來像Gradle對'buildscript'閉包參數的類加載器做了一些魔術...... – gavenkoa

+1

@gavenkoa導致buildscript先於其他build.gradle執行,因爲您可以使用添加到構建腳本的類路徑中的類 – jmattheis