Tommi's Scribbles
Have Gradle Ignore Git-ignored Files

- Published on 2022-02-19
During some projects, I've encountered the need inside a Gradle project to ignore the same set of files ignored by git in .gitignore. This seems like a relatively simple task, and in fact it is. Yet, there doesn't seem to be many examples on how to do this online. So this article is here to rectify.
How to have gradle ignore files in .gitignore
As mentioned in the opening, making gradle ignore the same files git ignores through .gitignore is simple. Gradle has a built-in method for ignoring files. As of this writing, gradle uses Ant's defaults for ignoring files. Adding more filters is thus a breeze.
Inside your gradle project's settings.gradle.kts, you add the following after defining your plugin settings. The plugin settings need to be the first thing in the file per Gradle documentation.
try { val file = File(".gitignore") val fr = java.io.FileReader(file) val br = java.io.BufferedReader(fr) var line = br.readLine() while (line != null) { val sb = StringBuffer() sb.append(line) val lineString = sb.toString() if (!lineString.contains('#') && lineString.isNotEmpty()) { // Ignore comments and empty lines org.apache.tools.ant.DirectoryScanner.addDefaultExclude(lineString) } line = br.readLine() } fr.close() } catch(e: Exception) { // IOException is probs enough here, but whatever println("Error:$e") }
One thing to note is that Gradle by default ignores the .gitignore file. If you are doing something such as zipping your gradle build to submit to CodeCommit via CDK, or similar, you might want to include .gitignore as well. This is also easy:
org.apache.tools.ant.DirectoryScanner.removeDefaultExclude("**/.gitignore")
Gradle documentation has a link to the full list of default Ant excludes if there is something else you want to include.
Conclusion
And that's it. Now, if you do a gradle task such a zipping a directory, or making a build, or whatever you do, gradle will happily ignore the files and directories that are in your .gitignore file.