├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── plugin ├── build.gradle └── src │ ├── main │ ├── groovy │ │ └── com │ │ │ └── jenzz │ │ │ └── buildconstants │ │ │ ├── BuildConstantsExtension.groovy │ │ │ ├── BuildConstantsPlugin.groovy │ │ │ ├── BuildConstantsTask.groovy │ │ │ ├── categories │ │ │ └── StringCategory.groovy │ │ │ ├── factories │ │ │ ├── FileFactory.groovy │ │ │ ├── JavaFileFactory.groovy │ │ │ └── XmlFileFactory.groovy │ │ │ ├── mappers │ │ │ ├── AppIdToPathMapper.groovy │ │ │ └── Mapper.groovy │ │ │ ├── sanitizers │ │ │ ├── FileNameSanitizer.groovy │ │ │ ├── JavaFileNameSanitizer.groovy │ │ │ └── XmlFileNameSanitizer.groovy │ │ │ └── writers │ │ │ ├── BaseConstantsWriter.groovy │ │ │ ├── ConstantsWriter.groovy │ │ │ ├── JavaConstantsWriter.groovy │ │ │ └── XmlConstantsWriter.groovy │ └── resources │ │ └── META-INF │ │ └── gradle-plugins │ │ └── com.jenzz.buildconstants.properties │ └── test │ └── groovy │ └── com │ └── jenzz │ └── buildconstants │ ├── categories │ └── StringCategoryTest.groovy │ ├── factories │ ├── JavaFileFactoryTest.groovy │ └── XmlFileFactoryTest.groovy │ ├── mappers │ └── AppIdToPathMapperTest.groovy │ └── sanitizers │ ├── JavaFileNameSanitizerTest.groovy │ └── XmlFileNameSanitizerTest.groovy ├── sample ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── jenzz │ │ └── buildconstants │ │ └── sample │ │ └── MainActivity.java │ └── res │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ └── strings.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | .gradle 3 | local.properties 4 | build 5 | 6 | # Android Studio 7 | .idea 8 | *.iml 9 | 10 | # Mac OSX 11 | .DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | android: 4 | components: 5 | - tools 6 | - platform-tools 7 | - build-tools-23.0.3 8 | - android-23 9 | - extra-android-m2repository 10 | 11 | jdk: 12 | - oraclejdk8 13 | 14 | before_cache: 15 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 16 | 17 | cache: 18 | directories: 19 | - $HOME/.gradle/caches/ 20 | - $HOME/.gradle/wrapper/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | Version 1.1.0 *(2016/05/04)* 5 | -------------------------- 6 | * Add support for product flavors (#1) 7 | 8 | Version 1.0.1 *(2016/02/20)* 9 | -------------------------- 10 | * Fix artifact name 11 | **--> Note:** classpath changed from `gradle.plugin.com.jenzz:plugin:1.0.0` to `gradle.plugin.com.jenzz:buildconstants:1.0.1` 12 | * Non-instantiable Java constants 13 | 14 | Version 1.0.0 *(2016/02/15)* 15 | -------------------------- 16 | * Initial release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Jens Driller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Android Build Constants Plugin [![Build Status](https://travis-ci.org/jenzz/gradle-android-buildconstants-plugin.svg?branch=master)](https://travis-ci.org/jenzz/gradle-android-buildconstants-plugin) 2 | ============================== 3 | A Gradle plugin for Android which generates both Java and XML constants as part of the build process. 4 | 5 | Why do I need this? 6 | =================== 7 | In short: To define constants that are accessible from everywhere in your Android app. 8 | 9 | In long: There are two ways to define constants in Android. Both have their limitations. 10 | * Creating constants using `buildConfigField` only adds entries to `BuildConfig.java` which means you cannot access them via XML. 11 | * Creating a custom `constants.xml` resource file with entries like `constant_value` 12 | lets you easily reference the constant via `@string/constant` in XML, but requires you to have a `Context` object on the Java side 13 | to get the value using `getResources().getString(R.string.constant)`. 14 | 15 | None of the above solutions is ideal. This plugin lets you specify constants in your `build.gradle` file 16 | that will be translated into both a Java and an XML-based version with the same constant value. 17 | 18 | How does it work? 19 | ================= 20 | The plugin creates a new task per build type, e.g. *generateDebugBuildConstants*. 21 | It hooks into the build process ahead of the *processDebugResources* task so it will be executed every time you assemble your project. 22 | It supports incremental builds, i.e. if none of the inputs or outputs have changed, Gradle can skip the task (up-to-date). 23 | 24 | Usage 25 | ----- 26 | The plugin currently supports **Integer**, **Boolean** and **String** data types. 27 | 28 | You can specify the constants using a closure in your `build.gradle` file like this: 29 | 30 | ```groovy 31 | buildConstants { 32 | constants { 33 | aBoolean = true 34 | aString = 'string' 35 | aNumber = 123 36 | } 37 | } 38 | ``` 39 | 40 | The plugin will then generate both a Java and an XML version of the constants like so: 41 | 42 | **Java:** 43 | ```java 44 | public final class BuildConstants { 45 | 46 | public static final boolean ABOOLEAN = true; 47 | public static final String ASTRING = "string"; 48 | public static final int ANUMBER = 123; 49 | 50 | private BuildConstants() { 51 | throw new AssertionError("No instances."); 52 | } 53 | } 54 | ``` 55 | 56 | **XML:** 57 | ```xml 58 | 59 | true 60 | string 61 | 123 62 | 63 | ``` 64 | 65 | Alternatively, you can define the constants using a map: 66 | 67 | ```groovy 68 | buildConstants { 69 | constants = [ 70 | aBoolean : true, 71 | aString : 'string', 72 | aNumber : 123 73 | ] 74 | } 75 | ``` 76 | 77 | Or specify just a single constant (similar to `buildConfigField`): 78 | 79 | ```groovy 80 | buildConstants { 81 | constant 'single_constant', 'single_string' 82 | } 83 | ``` 84 | 85 | The default generated file names are `BuildConstants.java` and `build_constants.xml`. 86 | You can change them like this: 87 | 88 | ```groovy 89 | buildConstants { 90 | javaFileName 'SampleBuildConstants' 91 | xmlFileName 'sample_build_constants' 92 | } 93 | ``` 94 | 95 | Example 96 | ------- 97 | Check out the [sample project](https://github.com/jenzz/gradle-android-buildconstants-plugin/tree/master/sample) for an example implementation. 98 | 99 | Download 100 | -------- 101 | Build script snippet for use in all Gradle versions: 102 | 103 | ```groovy 104 | buildscript { 105 | repositories { 106 | maven { 107 | url 'https://plugins.gradle.org/m2/' 108 | } 109 | } 110 | dependencies { 111 | classpath 'gradle.plugin.com.jenzz:buildconstants:1.1.0' 112 | } 113 | } 114 | 115 | apply plugin: 'com.jenzz.buildconstants' 116 | ``` 117 | 118 | Build script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1: 119 | 120 | ```groovy 121 | plugins { 122 | id 'com.jenzz.buildconstants' version '1.1.0' 123 | } 124 | ``` 125 | 126 | License 127 | ------- 128 | This project is licensed under the [MIT License](https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/master/LICENSE). -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | dependencies { 6 | classpath 'com.android.tools.build:gradle:2.1.0' 7 | } 8 | } 9 | 10 | allprojects { 11 | repositories { 12 | jcenter() 13 | } 14 | } 15 | 16 | ext { 17 | pluginVersion = '1.1.0' 18 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /plugin/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'groovy' 3 | id 'maven' 4 | id 'com.gradle.plugin-publish' version '0.9.4' 5 | } 6 | 7 | dependencies { 8 | compile gradleApi() 9 | compile 'com.android.tools.build:gradle:2.1.0' 10 | 11 | testCompile 'org.assertj:assertj-core:3.4.1' 12 | testCompile 'org.mockito:mockito-core:1.10.19' 13 | } 14 | 15 | //noinspection GroovyUnusedAssignment 16 | archivesBaseName = 'buildconstants' 17 | group = 'com.jenzz' 18 | version = rootProject.pluginVersion 19 | 20 | pluginBundle { 21 | website = 'https://github.com/jenzz/gradle-android-buildconstants-plugin' 22 | vcsUrl = 'https://github.com/jenzz/gradle-android-buildconstants-plugin' 23 | description = 'A Gradle plugin for Android which generates both Java and XML constants as part of the build process.' 24 | tags = ['java', 'groovy', 'gradle', 'buildconstants', 'buildconfig', 'constants', 'generated'] 25 | 26 | //noinspection GroovyAssignabilityCheck 27 | plugins { 28 | buildConstantsPlugin { 29 | id = 'com.jenzz.buildconstants' 30 | displayName = 'Android build constants generator' 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/BuildConstantsExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants 2 | 3 | import com.android.annotations.NonNull 4 | 5 | import static groovy.lang.Closure.DELEGATE_FIRST 6 | 7 | @SuppressWarnings("GroovyUnusedDeclaration") 8 | public class BuildConstantsExtension { 9 | 10 | String javaFileName = "BuildConstants" 11 | String xmlFileName = "build_constants" 12 | 13 | Map constants = new LinkedHashMap<>() 14 | 15 | public constants(@NonNull Closure closure) { 16 | Map tmpConstants = new LinkedHashMap<>() 17 | closure.delegate = tmpConstants 18 | closure.resolveStrategy = DELEGATE_FIRST 19 | closure() 20 | constants.clear() 21 | constants.putAll tmpConstants 22 | } 23 | 24 | public constant(@NonNull String key, @NonNull Object value) { 25 | constants.put(key, value) 26 | } 27 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/BuildConstantsPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants 2 | 3 | import com.android.build.gradle.AppPlugin 4 | import org.gradle.api.GradleException 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | 8 | class BuildConstantsPlugin implements Plugin { 9 | 10 | @Override 11 | void apply(Project project) { 12 | if (!project.plugins.findPlugin(AppPlugin)) { 13 | throw new GradleException( 14 | 'You must apply the Android plugin before using the \'com.jenzz.buildconstants\' plugin') 15 | } 16 | 17 | project.extensions.add 'buildConstants', BuildConstantsExtension 18 | 19 | project.afterEvaluate { 20 | 21 | project.android.applicationVariants.all { variant -> 22 | 23 | def variantName = variant.name.capitalize() 24 | def generateConstantsTask = project.tasks.create([name : "generate${variantName}BuildConstants", 25 | description: "Generates both Java and XML build constants", 26 | type : BuildConstantsTask], { 27 | appId = variant.applicationId 28 | variantDir = variant.dirName 29 | constants = project.buildConstants.constants 30 | }) 31 | 32 | def processResourcesTask = project.tasks.find { 33 | def pattern = ~/process${variantName}Resources$/ 34 | pattern.matcher(it.name).matches() 35 | } 36 | 37 | processResourcesTask.dependsOn generateConstantsTask 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/BuildConstantsTask.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants 2 | 3 | import com.android.annotations.NonNull 4 | import com.jenzz.buildconstants.factories.JavaFileFactory 5 | import com.jenzz.buildconstants.factories.XmlFileFactory 6 | import com.jenzz.buildconstants.mappers.AppIdToPathMapper 7 | import com.jenzz.buildconstants.sanitizers.JavaFileNameSanitizer 8 | import com.jenzz.buildconstants.sanitizers.XmlFileNameSanitizer 9 | import com.jenzz.buildconstants.writers.JavaConstantsWriter 10 | import com.jenzz.buildconstants.writers.XmlConstantsWriter 11 | import org.gradle.api.DefaultTask 12 | import org.gradle.api.Task 13 | import org.gradle.api.tasks.Input 14 | import org.gradle.api.tasks.OutputFile 15 | import org.gradle.api.tasks.TaskAction 16 | 17 | class BuildConstantsTask extends DefaultTask { 18 | 19 | @Input String appId 20 | @Input String variantDir 21 | @Input Map constants 22 | 23 | @OutputFile File javaFile 24 | @OutputFile File xmlFile 25 | 26 | private String javaFileName; 27 | 28 | @Override 29 | Task configure(Closure closure) { 30 | Task configure = super.configure(closure) 31 | javaFile = createJavaFile() 32 | xmlFile = createXmlFile() 33 | configure 34 | } 35 | 36 | @SuppressWarnings("GroovyUnusedDeclaration") 37 | @TaskAction 38 | void run() { 39 | brewJava(); 40 | brewXml(); 41 | } 42 | 43 | @NonNull 44 | private File createJavaFile() { 45 | String fileNameInput = project.buildConstants.javaFileName 46 | String fileName = javaFileName = new JavaFileNameSanitizer().sanitize fileNameInput 47 | new JavaFileFactory(appId, project.buildDir.path, variantDir, new AppIdToPathMapper()).create fileName 48 | } 49 | 50 | @NonNull 51 | private File createXmlFile() { 52 | String fileNameInput = project.buildConstants.xmlFileName 53 | String fileName = new XmlFileNameSanitizer().sanitize fileNameInput 54 | new XmlFileFactory(project.buildDir.path, variantDir).create fileName 55 | } 56 | 57 | private void brewJava() { 58 | new JavaConstantsWriter(javaFile, appId, javaFileName).write constants 59 | } 60 | 61 | private void brewXml() { 62 | new XmlConstantsWriter(xmlFile).write constants 63 | } 64 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/categories/StringCategory.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.categories 2 | 3 | import static java.lang.Character.isUpperCase 4 | 5 | @Category(String) 6 | class StringCategory { 7 | 8 | boolean isCapitalized() { 9 | isUpperCase charAt(0) 10 | } 11 | 12 | boolean isNotCapitalized() { 13 | !isCapitalized() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/factories/FileFactory.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.factories 2 | 3 | import com.android.annotations.NonNull 4 | 5 | public interface FileFactory { 6 | 7 | @NonNull 8 | File create(@NonNull String fileName) 9 | } 10 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/factories/JavaFileFactory.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.factories 2 | 3 | import com.android.annotations.NonNull 4 | import com.jenzz.buildconstants.mappers.Mapper 5 | 6 | public class JavaFileFactory implements FileFactory { 7 | 8 | @NonNull private final String appId 9 | @NonNull private final String buildDir 10 | @NonNull private final String variantDir 11 | @NonNull private final Mapper appIdToPathMapper 12 | 13 | JavaFileFactory(@NonNull String appId, 14 | @NonNull String buildDir, 15 | @NonNull String variantDir, 16 | @NonNull Mapper appIdToPathMapper) { 17 | this.appId = appId 18 | this.buildDir = buildDir 19 | this.variantDir = variantDir 20 | this.appIdToPathMapper = appIdToPathMapper 21 | } 22 | 23 | @NonNull 24 | @Override 25 | File create(@NonNull String fileName) { 26 | String appPath = appIdToPathMapper.map appId 27 | new File("${buildDir}/generated/source/buildConfig/${variantDir}/${appPath}/${fileName}.java") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/factories/XmlFileFactory.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.factories 2 | 3 | import com.android.annotations.NonNull 4 | 5 | public class XmlFileFactory implements FileFactory { 6 | 7 | @NonNull private final String buildDir 8 | @NonNull private final String variantDir 9 | 10 | XmlFileFactory(@NonNull String buildDir, 11 | @NonNull String variantDir) { 12 | this.buildDir = buildDir 13 | this.variantDir = variantDir 14 | } 15 | 16 | @NonNull 17 | @Override 18 | File create(@NonNull String fileName) { 19 | new File("${buildDir}/intermediates/res/merged/${variantDir}/values/${fileName}.xml") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/mappers/AppIdToPathMapper.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.mappers; 2 | 3 | import com.android.annotations.Nullable; 4 | 5 | public class AppIdToPathMapper implements Mapper { 6 | 7 | @Nullable 8 | @Override 9 | public String map(@Nullable String appId) { 10 | appId?.replaceAll '\\.', '/' 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/mappers/Mapper.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.mappers 2 | 3 | import com.android.annotations.Nullable 4 | 5 | public interface Mapper { 6 | 7 | @Nullable 8 | TO map(@Nullable FROM from); 9 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/sanitizers/FileNameSanitizer.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sanitizers 2 | 3 | import com.android.annotations.NonNull 4 | import com.android.annotations.Nullable 5 | 6 | public interface FileNameSanitizer { 7 | 8 | @NonNull 9 | String sanitize(@Nullable String fileName); 10 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/sanitizers/JavaFileNameSanitizer.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sanitizers 2 | 3 | import com.android.annotations.NonNull 4 | import com.android.annotations.Nullable 5 | import com.jenzz.buildconstants.categories.StringCategory 6 | import org.gradle.api.InvalidUserDataException 7 | import org.slf4j.Logger 8 | 9 | import static org.slf4j.LoggerFactory.getLogger 10 | 11 | public class JavaFileNameSanitizer implements FileNameSanitizer { 12 | 13 | private static final String SUFFIX = ".java" 14 | private static final Logger log = getLogger(JavaFileNameSanitizer.class) 15 | 16 | @NonNull 17 | @Override 18 | public String sanitize(@Nullable String fileName) { 19 | if (fileName == null) { 20 | throw new InvalidUserDataException("Java file name must not be null.") 21 | } 22 | 23 | if (fileName.isEmpty()) { 24 | throw new InvalidUserDataException("Java file name must not be empty.") 25 | } 26 | 27 | if (fileName.endsWith(SUFFIX)) { // remove potential suffix 28 | fileName = fileName.substring(0, fileName.length() - SUFFIX.length()) 29 | log.warn("Java file name extension not required. Ignoring " + SUFFIX + " suffix.") 30 | } 31 | 32 | use(StringCategory) { 33 | if (fileName.isNotCapitalized()) { 34 | fileName = fileName.capitalize() 35 | log.warn("Java file name must be capitalized. Renaming it to \"" + fileName + "\".") 36 | } 37 | } 38 | 39 | fileName 40 | } 41 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/sanitizers/XmlFileNameSanitizer.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sanitizers 2 | 3 | import com.android.annotations.NonNull 4 | import com.android.annotations.Nullable 5 | import org.gradle.api.InvalidUserDataException 6 | import org.slf4j.Logger 7 | 8 | import static org.slf4j.LoggerFactory.getLogger 9 | 10 | public class XmlFileNameSanitizer implements FileNameSanitizer { 11 | 12 | private static final String SUFFIX = ".xml" 13 | private static final Logger log = getLogger(XmlFileNameSanitizer.class) 14 | 15 | @NonNull 16 | @Override 17 | public String sanitize(@Nullable String fileName) { 18 | if (fileName == null) { 19 | throw new InvalidUserDataException("XML file name must not be null.") 20 | } 21 | 22 | if (fileName.isEmpty()) { 23 | throw new InvalidUserDataException("XML file name must not be empty.") 24 | } 25 | 26 | if (fileName.endsWith(SUFFIX)) { // remove potential suffix 27 | fileName = fileName.substring 0, fileName.length() - SUFFIX.length() 28 | log.warn("XML file name extension not required. Ignoring " + SUFFIX + " suffix.") 29 | } 30 | 31 | if (!fileName.matches("^[a-z0-9_]+\$")) { 32 | throw new InvalidUserDataException("XML file name must contain only lowercase a-z, 0-9, or _.") 33 | } 34 | 35 | fileName 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/writers/BaseConstantsWriter.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.writers 2 | 3 | import com.android.annotations.NonNull 4 | import org.gradle.api.InvalidUserDataException; 5 | 6 | public abstract class BaseConstantsWriter implements ConstantsWriter { 7 | 8 | @NonNull private final File file 9 | 10 | BaseConstantsWriter(@NonNull File file) { 11 | this.file = file 12 | } 13 | 14 | @Override 15 | void write(@NonNull Map constants) { 16 | file.withWriter { writer -> 17 | writer.append writeHeader() 18 | constants.each { 19 | String constant; 20 | switch (it.value.class) { 21 | case String: 22 | constant = writeString it 23 | break 24 | case Integer: 25 | constant = writeInteger it 26 | break 27 | case Boolean: 28 | constant = writeBoolean it 29 | break 30 | } 31 | if (constant == null) { 32 | throw new InvalidUserDataException( 33 | "Data type is not supported. Only String, Integer and Boolean are allowed."); 34 | } 35 | writer.append "\t" + constant + "\n" 36 | } 37 | writer.append writeFooter() 38 | } 39 | } 40 | 41 | @NonNull 42 | abstract String writeHeader() 43 | 44 | @NonNull 45 | abstract String writeString(@NonNull Map.Entry constant) 46 | 47 | @NonNull 48 | abstract String writeInteger(@NonNull Map.Entry constant) 49 | 50 | @NonNull 51 | abstract String writeBoolean(@NonNull Map.Entry constant) 52 | 53 | @NonNull 54 | abstract String writeFooter() 55 | } 56 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/writers/ConstantsWriter.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.writers 2 | 3 | import com.android.annotations.NonNull 4 | 5 | interface ConstantsWriter { 6 | 7 | void write(@NonNull Map constants) 8 | } -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/writers/JavaConstantsWriter.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.writers 2 | 3 | import com.android.annotations.NonNull 4 | 5 | import static java.util.Locale.ENGLISH 6 | 7 | public class JavaConstantsWriter extends BaseConstantsWriter { 8 | 9 | @NonNull private final String packageName 10 | @NonNull private final String className 11 | 12 | JavaConstantsWriter(@NonNull File file, 13 | @NonNull String packageName, 14 | @NonNull String className) { 15 | super(file) 16 | this.packageName = packageName 17 | this.className = className 18 | } 19 | 20 | @NonNull 21 | @Override 22 | String writeHeader() { 23 | //@formatter:off 24 | "/**" + "\n" + 25 | " * Automatically generated file. DO NOT MODIFY." + "\n" + 26 | " * Check your build.gradle for buildConstants to edit these values." + "\n" + 27 | "*/" + "\n" + 28 | "package $packageName;" + "\n" + 29 | "\n" + 30 | "public final class $className {" + "\n" + 31 | "\n" 32 | //@formatter:on 33 | } 34 | 35 | @NonNull 36 | @Override 37 | String writeString(@NonNull Map.Entry constant) { 38 | write "String", constant.key, "\"$constant.value\"" 39 | } 40 | 41 | @NonNull 42 | @Override 43 | String writeInteger(@NonNull Map.Entry constant) { 44 | write "int", constant.key, constant.value.toString() 45 | } 46 | 47 | @NonNull 48 | @Override 49 | String writeBoolean(@NonNull Map.Entry constant) { 50 | write "boolean", constant.key, constant.value.toString() 51 | } 52 | 53 | @NonNull 54 | @Override 55 | String writeFooter() { 56 | //@formatter:off 57 | "\n" + 58 | "\t" + "private $className() {" + "\n" + 59 | "\t" + "\t" + "throw new AssertionError(\"No instances.\");" + "\n" + 60 | "\t" + "}" + "\n" + 61 | "}" 62 | //@formatter:on 63 | } 64 | 65 | @NonNull 66 | private static String write(@NonNull String dataType, @NonNull String key, @NonNull String value) { 67 | "public static final $dataType ${key.toUpperCase(ENGLISH)} = $value;" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /plugin/src/main/groovy/com/jenzz/buildconstants/writers/XmlConstantsWriter.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.writers 2 | 3 | import com.android.annotations.NonNull 4 | 5 | import static java.util.Locale.ENGLISH 6 | 7 | public class XmlConstantsWriter extends BaseConstantsWriter { 8 | 9 | XmlConstantsWriter(@NonNull File file) { 10 | super(file) 11 | } 12 | 13 | @Override 14 | String writeHeader() { 15 | //@formatter:off 16 | "" + "\n" + 17 | "" + "\n" + 18 | "\n" + 19 | "\t" + "" + "\n" + 20 | "\t" + "" + "\n" + 21 | "\n" 22 | //@formatter:on 23 | } 24 | 25 | @NonNull 26 | @Override 27 | String writeString(@NonNull Map.Entry constant) { 28 | write "string", constant 29 | } 30 | 31 | @NonNull 32 | @Override 33 | String writeInteger(@NonNull Map.Entry constant) { 34 | write "integer", constant 35 | } 36 | 37 | @NonNull 38 | @Override 39 | String writeBoolean(@NonNull Map.Entry constant) { 40 | write "bool", constant 41 | } 42 | 43 | @NonNull 44 | @Override 45 | String writeFooter() { 46 | //@formatter:off 47 | "\n" + 48 | "" 49 | //@formatter:on 50 | } 51 | 52 | @NonNull 53 | private static String write(@NonNull String dataType, @NonNull Map.Entry constant) { 54 | "<$dataType name=\"${constant.key.toLowerCase(ENGLISH)}\">$constant.value" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /plugin/src/main/resources/META-INF/gradle-plugins/com.jenzz.buildconstants.properties: -------------------------------------------------------------------------------- 1 | # suppress inspection "UnusedProperty" 2 | implementation-class=com.jenzz.buildconstants.BuildConstantsPlugin -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/categories/StringCategoryTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.categories 2 | 3 | import org.junit.Test 4 | 5 | import static org.assertj.core.api.Assertions.assertThat 6 | 7 | class StringCategoryTest { 8 | 9 | @Test 10 | void isCapitalized() { 11 | use(StringCategory) { 12 | assertThat "Hello".isCapitalized() isTrue() 13 | assertThat "hello".isCapitalized() isFalse() 14 | } 15 | } 16 | 17 | @Test 18 | void isNotCapitalized() { 19 | use(StringCategory) { 20 | assertThat "Hello".isNotCapitalized() isFalse() 21 | assertThat "hello".isNotCapitalized() isTrue() 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/factories/JavaFileFactoryTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.factories 2 | 3 | import com.jenzz.buildconstants.mappers.Mapper 4 | import org.junit.Before 5 | import org.junit.Test 6 | import org.mockito.Mock 7 | 8 | import static org.assertj.core.api.Assertions.assertThat 9 | import static org.mockito.Matchers.anyString 10 | import static org.mockito.Mockito.verify 11 | import static org.mockito.Mockito.when 12 | import static org.mockito.MockitoAnnotations.initMocks 13 | 14 | class JavaFileFactoryTest { 15 | 16 | private final appId = "appId" 17 | private final buildDir = "buildDir" 18 | private final variantDir = "variantDir" 19 | private final fileName = "fileName" 20 | 21 | @Mock private Mapper mockAppIdToPathMapper 22 | 23 | private fileFactory 24 | 25 | @Before 26 | void setUp() { 27 | initMocks this 28 | 29 | fileFactory = new JavaFileFactory(appId, buildDir, variantDir, mockAppIdToPathMapper) 30 | } 31 | 32 | @Test 33 | void usesAppIdToPathMapper() { 34 | fileFactory.create fileName 35 | 36 | verify(mockAppIdToPathMapper).map appId 37 | } 38 | 39 | @Test 40 | void createsCorrectPath() { 41 | String appPath = "appPath" 42 | when(mockAppIdToPathMapper.map(anyString())).thenReturn appPath 43 | 44 | File actual = fileFactory.create fileName 45 | File expected = new File("${buildDir}/generated/source/buildConfig/${variantDir}/${appPath}/${fileName}.java") 46 | 47 | assertThat actual.path isEqualTo expected.path 48 | } 49 | } -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/factories/XmlFileFactoryTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.factories 2 | 3 | import org.junit.Test 4 | 5 | import static org.assertj.core.api.Assertions.assertThat 6 | 7 | class XmlFileFactoryTest { 8 | 9 | @Test 10 | void createsCorrectPath() { 11 | String buildDir = "buildDir" 12 | String variantDir = "variantDir" 13 | String fileName = "fileName" 14 | FileFactory fileFactory = new XmlFileFactory(buildDir, variantDir) 15 | 16 | File actual = fileFactory.create fileName 17 | File expected = new File("${buildDir}/intermediates/res/merged/${variantDir}/values/${fileName}.xml") 18 | 19 | assertThat actual.path isEqualTo expected.path 20 | } 21 | } -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/mappers/AppIdToPathMapperTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.mappers 2 | 3 | import org.junit.Test 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | class AppIdToPathMapperTest { 8 | 9 | private final Mapper mapper = new AppIdToPathMapper() 10 | 11 | @Test 12 | void handlesNull() { 13 | assertThat mapper.map(null) isNull() 14 | } 15 | 16 | @Test 17 | void replacesDotsWithSlashes() { 18 | assertThat mapper.map("com.jenzz.buildconstants") isEqualTo "com/jenzz/buildconstants" 19 | } 20 | } -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/sanitizers/JavaFileNameSanitizerTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sanitizers 2 | 3 | import org.gradle.api.InvalidUserDataException 4 | import org.junit.Test 5 | 6 | import static org.assertj.core.api.Assertions.assertThat 7 | 8 | class JavaFileNameSanitizerTest { 9 | 10 | private final FileNameSanitizer sanitizer = new JavaFileNameSanitizer() 11 | 12 | @Test(expected = InvalidUserDataException.class) 13 | void throwsIfNull() { 14 | sanitizer.sanitize null 15 | } 16 | 17 | @Test(expected = InvalidUserDataException.class) 18 | void throwsIfEmpty() { 19 | sanitizer.sanitize "" 20 | } 21 | 22 | @Test 23 | void capitalizes() { 24 | assertThat sanitizer.sanitize("fileName") isEqualTo "FileName" 25 | } 26 | 27 | @Test 28 | void removesSuffix() { 29 | assertThat sanitizer.sanitize("FileName.java") isEqualTo "FileName" 30 | } 31 | 32 | @Test 33 | void returnsCleanFileName() { 34 | String fileName = "BuildConstants" 35 | assertThat sanitizer.sanitize(fileName) isEqualTo fileName 36 | } 37 | } -------------------------------------------------------------------------------- /plugin/src/test/groovy/com/jenzz/buildconstants/sanitizers/XmlFileNameSanitizerTest.groovy: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sanitizers 2 | 3 | import org.gradle.api.InvalidUserDataException 4 | import org.junit.Test 5 | 6 | import static org.assertj.core.api.Assertions.assertThat 7 | 8 | class XmlFileNameSanitizerTest { 9 | 10 | private final FileNameSanitizer sanitizer = new XmlFileNameSanitizer() 11 | 12 | @Test(expected = InvalidUserDataException.class) 13 | void throwsIfNull() { 14 | sanitizer.sanitize(null) 15 | } 16 | 17 | @Test(expected = InvalidUserDataException.class) 18 | void throwsIfEmpty() { 19 | sanitizer.sanitize("") 20 | } 21 | 22 | @Test(expected = InvalidUserDataException.class) 23 | void throwsIfCapitalized() { 24 | sanitizer.sanitize("Hello") 25 | } 26 | 27 | @Test(expected = InvalidUserDataException.class) 28 | void throwsIfContainsUpperCase() { 29 | sanitizer.sanitize("hEllo") 30 | } 31 | 32 | @Test(expected = InvalidUserDataException.class) 33 | void throwsIfNotAlphanumeric() { 34 | sanitizer.sanitize("hello-") 35 | } 36 | 37 | @Test 38 | void removesSuffix() { 39 | assertThat sanitizer.sanitize("file_name.xml") isEqualTo "file_name" 40 | } 41 | 42 | @Test 43 | void returnsCleanFileName() { 44 | String fileName = "build_constants" 45 | assertThat sanitizer.sanitize(fileName) isEqualTo fileName 46 | } 47 | } -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | maven { 4 | url "https://plugins.gradle.org/m2/" 5 | } 6 | } 7 | dependencies { 8 | classpath "gradle.plugin.com.jenzz:buildconstants:$rootProject.pluginVersion" 9 | } 10 | } 11 | 12 | apply plugin: 'com.android.application' 13 | apply plugin: 'com.jenzz.buildconstants' 14 | 15 | android { 16 | compileSdkVersion 23 17 | buildToolsVersion '23.0.3' 18 | 19 | defaultConfig { 20 | applicationId 'com.jenzz.buildconstants.sample' 21 | minSdkVersion 16 22 | targetSdkVersion 23 23 | versionCode 1 24 | //noinspection GroovyAssignabilityCheck 25 | versionName rootProject.pluginVersion 26 | } 27 | 28 | buildTypes { 29 | debug { 30 | applicationIdSuffix '.debug' 31 | } 32 | } 33 | 34 | flavorDimensions 'abi', 'version' 35 | 36 | productFlavors { 37 | free { 38 | dimension 'version' 39 | } 40 | pro { 41 | dimension 'version' 42 | } 43 | arm { 44 | dimension "abi" 45 | } 46 | mips { 47 | dimension "abi" 48 | } 49 | x86 { 50 | dimension "abi" 51 | } 52 | } 53 | } 54 | 55 | dependencies { 56 | compile 'com.android.support:appcompat-v7:23.3.0' 57 | } 58 | 59 | buildConstants { 60 | javaFileName 'SampleBuildConstants' 61 | xmlFileName 'sample_build_constants' 62 | 63 | constants { 64 | aBoolean = true 65 | aString = 'string' 66 | aNumber = 123 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sample/src/main/java/com/jenzz/buildconstants/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.jenzz.buildconstants.sample; 2 | 3 | import android.content.res.Resources; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.app.AppCompatActivity; 7 | 8 | public class MainActivity extends AppCompatActivity { 9 | 10 | @SuppressWarnings("unused") 11 | @Override 12 | protected void onCreate(@Nullable Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | 15 | // Java constants 16 | String javaString = SampleBuildConstants.ASTRING; 17 | boolean javaBoolean = SampleBuildConstants.ABOOLEAN; 18 | int javaNumber = SampleBuildConstants.ANUMBER; 19 | 20 | // XML constants 21 | Resources res = getResources(); 22 | String xmlString = res.getString(R.string.astring); 23 | boolean xmlBoolean = res.getBoolean(R.bool.aboolean); 24 | int xmlNumber = res.getInteger(R.integer.anumber); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jenzz/gradle-android-buildconstants-plugin/e023542f5744ee84bd790922f5dc3bf353ea0fc5/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Sample 4 | 5 | 6 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':plugin', ':sample' 2 | 3 | project(':plugin').name = 'buildconstants' --------------------------------------------------------------------------------