Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude files from aar with Gradle dynamically?

I'm having android library (aar) that contains (and builds while building module) native code:

apply plugin: 'com.android.library'

android {
  compileSdkVersion 16
  buildToolsVersion "25.0.0"

  defaultConfig {
    minSdkVersion 11
    targetSdkVersion 16
    versionCode 1
    versionName "1.0"

    ndk {
      abiFilters 'armeabi-v7a'
    }
  }

  externalNativeBuild {
    ndkBuild {
      path 'jni/Android.mk'
    }
  }

  sourceSets {
    main {
      manifest.srcFile 'AndroidManifest.xml'
      java.srcDirs = ['src']
      res.srcDirs = ['res']
      jni.srcDirs = ['jni']
    }
  }

  packagingOptions {
    exclude '/lib/armeabi-v7a/libv8.cr.so'
    exclude '/lib/armeabi-v7a/libv8_libbase.cr.so'
     // TODO : generate dynamically from `SHARED_V8_LIB_FILENAMES`
  }
}

I've modified Android.mk file to have different config dependent on SHARED_V8_LIB_FILENAMES environment variable:

...
# Report configuration
ifeq ($(SHARED_V8_LIB_FILENAMES),)
# static
$(info [Configuration] Linking statically with built-in v8)
else
# dynamic

define info_define
    $(info [Configuration] Linking dynamically with shared v8 library ./libfoo-binaries/android_$(TARGET_ARCH_ABI)/$1)
endef
$(foreach item,$(SHARED_V8_LIB_FILENAMES),$(eval $(call info_define,$(item))))
endif
...

How can i modify my build.gradle in order to generate packageOptions section dependent on environment variable SHARED_V8_LIB_FILENAMES? I need to check if the variable is set, parse it with space separator and add files list to be excluded from final aar file.

like image 402
4ntoine Avatar asked Oct 03 '17 11:10

4ntoine


1 Answers

Actually i was able to do it myself:

apply plugin: 'com.android.library'

android {
  compileSdkVersion 16
  buildToolsVersion "25.0.0"

  defaultConfig {
    minSdkVersion 11
    targetSdkVersion 16
    versionCode 1
    versionName "1.0"

    ndk {
      abiFilters 'armeabi-v7a'
    }
  }

  externalNativeBuild {
    ndkBuild {
      path 'jni/Android.mk'
    }
  }

  sourceSets {
    main {
      manifest.srcFile 'AndroidManifest.xml'
      java.srcDirs = ['src']
      res.srcDirs = ['res']
      jni.srcDirs = ['jni']
    }
  }

  def sharedV8LibFilesSet = []
  def sharedV8LibFiles = System.getenv('SHARED_V8_LIB_FILENAMES')
  if (sharedV8LibFiles != null) {
    def sharedV8LibFilesArray = sharedV8LibFiles.split(' ')
    sharedV8LibFilesArray.each { eachFileName ->
      sharedV8LibFilesSet.add("**/" + eachFileName)
      println "[Configuration] Excluding shared v8 library " + eachFileName + " from AAR"
    }
  } else {
    println "[Configuration] No shared v8 libraries excluded from AAR"
  }

  packagingOptions {
    excludes = sharedV8LibFilesSet
  }
}

Any code style changes/improvements appreciated.

like image 54
4ntoine Avatar answered Nov 09 '22 19:11

4ntoine