21

I am using Android Studio with Google Drive, which makes hidden system files visible (such as Icon and desktop.ini), causing errors, as described here. Rather than run scripts to delete these files, I'd like to instruct gradle 2.14 to ignore them.

In an attempt to figure out how to exclude files, I created files named "excludeme.txt" in the directories \app\src\main\res\values and in \app\src\main\java\com\hfad\stopwatch\. I unsuccessfully tried various modifications to the two build.gradle files in my project. None successfully excluded the file.

Specifically, I made the following modification to the build.gradle file for Module: app, per this question:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'], excludes: ['**/excludeme.txt'])
                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12' 
}

I also added this to the android section of the same build.gradle file, per this question:

aaptOptions {
    ignoreAssetsPattern "!excludeme.txt"
}

I also added:

sourceSets {
    main {
        java {
            srcDir "src"                [I also tried w/o this line]
            exclude "**/excludeme.txt"
        }
    }
}

When I selected Build > Clean Project, which triggered a build, I got this output, which shows that the file in the resources folder was not ignored:

Information:Gradle tasks [clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
C:\Users\Ellen\GoogleDrive\Ellen-CS115\AndroidStudioProjects\Stopwatch\app\src\main\res\values\excludeme.txt
Error:(1, 1) Error: Premature end of file.
Error:Execution failed for task ':app:mergeDebugResources'.
> C:\Users\Ellen\GoogleDrive\Ellen-CS115\AndroidStudioProjects\Stopwatch\app\src\main\res\values\excludeme.txt:1:1: Error: Premature end of file.

The results were the same if I removed the exclamation point:

aaptOptions {
    ignoreAssetsPattern "!excludeme.txt"
}

How do I properly instruct gradle to ignore files containing a certain pattern when building Android projects?

Update 1

Per Stefan's suggestion below, I added the following to the build.gradle file for Module: app:

android {
    [omitted]
    sourceSets.main.res.exclude '**/whatever.txt'
}

I added a file named whatever.txt in the res/layout directory, and the build failed with:

Error:Execution failed for task ':app:mergeDebugResources'.
> C:\Users\Ellen\GoogleDrive\Ellen-CS115\AndroidStudioProjects\Starbuzz\app\src\main\res\layout\whatever.txt: Error: The file name must end with .xml

Update 2

Per Nathan's suggestion, I added:

packagingOptions {
    exclude '**/whatever.txt'
    exclude 'src/main/res/layout/whatever.txt'
}

to build.gradle (Module: app) in the android section. No improvement:

Information:Gradle tasks [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]
/Users/spertus/GoogleDrive/Ellen-CS115/AndroidStudioProjects/MacTest/app/src/main/res/layout/whatever.txt
Error:Error: The file name must end with .xml
Error:Execution failed for task ':app:mergeDebugResources'.
> /Users/spertus/GoogleDrive/Ellen-CS115/AndroidStudioProjects/MacTest/app/src/main/res/layout/whatever.txt: Error: The file name must end with .xml
Information:BUILD FAILED

(This last build was on a Mac, unlike the others, which were on Windows.)

Community
  • 1
  • 1
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
  • The Gradle documentation on [file trees](https://docs.gradle.org/current/userguide/working_with_files.html#sec:file_trees) may be helpful. Is there a reason to compile the fileTree in the dependency section of the build? If you will be excluding files from your build resources, use the [`sourceSet`](https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSet.html) block. – Nathan Jan 27 '17 at 20:24
  • Thank you. I didn't see a `sourceSet` block in any of the `build.gradle` files. I'll take a look at the documentation you cite. – Ellen Spertus Jan 27 '17 at 20:26
  • If after trying a few things with `sourceSet` you run into issues, update your answer and I will see if I can help :) – Nathan Jan 27 '17 at 20:28
  • I tried adding `sourceSets`, as described above. The errors all seem to be about the resource file. I'm not sure I need to exclude non *.java files from src directories; they might be ignored automatically. – Ellen Spertus Jan 27 '17 at 20:40
  • @Nathan Could you take another look? I tried using `sourceSets` and added a bounty. – Ellen Spertus Feb 01 '17 at 23:04
  • I have added an answer that uses the `PackagingOptions` DSL object that is Android Gradle specific. – Nathan Feb 07 '17 at 19:51
  • Any luck on this? I simply cannot get exclude/excludes to work no matter what I do. Even the simplest cases fail to exclude anything. – Diarrhio Apr 14 '17 at 16:28
  • @Diarrhio Still no solution. – Ellen Spertus Apr 14 '17 at 21:39
  • 1
    @EllenSpertus I figured it out. See my answer below – Diarrhio Apr 19 '17 at 18:20
  • This Q already existed... https://stackoverflow.com/questions/16701256/android-studio-exclude-class-from-build – Tom Oct 10 '17 at 16:00
  • @Tom That question asked about excluding certain class files. – Ellen Spertus Oct 11 '17 at 21:40
  • Really good investigation! It seems aapt supports a *--ignore-assets* option, it simply excludes some asset files from final artifact. Sadly aapt doesn't support exclude any resource file, android gradle plugin can do nothing about it. I'm considering copy files out of the project before build, then copy back afterwards. – Henry.T Sep 13 '18 at 07:02

4 Answers4

6

Looks like a recent change in gradle changed the DSL for sourceSets, so you now need to specify the exclude on the filter field:

android {
    sourceSets.main.res.filter.exclude '**/whatever.txt'
}
Diarrhio
  • 190
  • 3
  • 6
  • 2
    Thank you. This isn't working for me using Gradle 3.3 in Android Studio. I don't get an error, but it does not exclude the files. What version of Gradle are you using? – Ellen Spertus Apr 22 '17 at 17:19
  • Gradle 3.3, with Android plugin 2.3.0. One thing I forgot to mention is that Android Studio will *still* show the files in the Project View. However, when it comes time to compile, the files will be excluded/ignored. That didn't make solving this problem any easier ;) – Diarrhio Apr 23 '17 at 00:52
  • I tried this in Update 1. It still doesn't work. I get the same error at `app:mergeDebugResources`. – Ellen Spertus Apr 23 '17 at 01:38
  • 1
    Might be a bug. If you look at the docs (http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.api.AndroidSourceSet.html) that should definitely be supported. – Diarrhio Apr 23 '17 at 21:21
1

The Android plugin has its own concept of SourceSets: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure

So you'll probably want to do something like

android {
    sourceSets.main.res.exclude '**/whatever.txt'
}
Stefan Oehme
  • 449
  • 2
  • 7
1

In the child project, in your case I believe it is :APP, add the following to the build.gradle file.

packagingOptions {
    //Exclude the file(s) in this method. Provide the path and file name.    
    exclude 'src\main\res\layout\whatever.txt' 
}

The PackagingOptions DSL object allows you to control what files are included in the APK. exclude takes a string or pattern as an argument which will allow you to ignore files or directories by name or pattern.

EDIT Customizing which resources to keep from the Android Studio docs.

  1. Create XML file in your project with a <resources> tag.
  2. Add tools:keep="[list resources]"
  3. Add `tools:discard="[list resources]"
  4. Save the file in project resources at res/raw/keep.xml The build will not include this file.

The end file should look similar to the one in the Android Studio Docs

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@layout/l_used*_c,@layout/l_used_a,@layout/l_used_b*"
    tools:discard="@layout/unused2" />
Nathan
  • 3,082
  • 1
  • 27
  • 42
  • 1
    Thanks. deferring lunch to test before bounty expires. :-) – Ellen Spertus Feb 07 '17 at 20:42
  • Change `whatever.txt` to `whatever.xml`. Since it is in the layouts folder, Android may be expecting a .xml file. The build process for multi project builds can be a little confusing to track down what task is being executed first without explicitly ordering each one. Once you change the extension see what error message you receive. – Nathan Feb 07 '17 at 21:00
  • 1
    Thanks. I made the suggested change. I now get errors parsing XML of whatever.xml, so it's still not being excluded. – Ellen Spertus Feb 07 '17 at 21:09
  • Every file in the layout directory must follow be an: "XML files that define a user interface layout." Try to exclude the actual problem file and get rid of the introduced file. – Nathan Feb 07 '17 at 21:29
1

After much banging of head against keyboard, this worked for me:

apply plugin: 'com.android.library'

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern;

    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)

    if (matcher.find())
        return matcher.group(1).toLowerCase()
    else {
        println "NO MATCH FOUND"
        return "";
    }
}

android {
.
.
.
    sourceSets {
            main {
                if (getCurrentFlavor() == 'stripped') {
                    java.exclude('**/excluded1.java',
                    .
                    .)
            }
            java {
              srcDir 'main'
            }
          }
        } 
     }         

N.B. Credit to: How to get current flavor in gradle for writing the getCurrentFlavor method,

user330844
  • 872
  • 1
  • 12
  • 12