Forked from HannahMitt/generatepublicresources.gradle
Created
October 17, 2019 09:35
-
-
Save kassadin/b993d68a9b64e877a9b5e312217331d6 to your computer and use it in GitHub Desktop.
This is a gradle task to generate the public.xml file in an Android library project. It assumes all public resources are kept in a res-public/ resource source directory. Providing this as a starting point, but there may be more efficient ways.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.xml.MarkupBuilder | |
// Task to generate our public.xml file | |
// See https://developer.android.com/studio/projects/android-library.html#PrivateResources | |
// We assume resources within res-public are public | |
task generatepublicxml { | |
def resDir = project.projectDir.absolutePath + "/src/main/res-public" | |
// Include the desired res types | |
// Note: we don't need the qualified resource directories, | |
// since those resources will already be defined in the unqualified directories | |
def tree = fileTree(dir: resDir, | |
includes: ['**/anim/*.xml', | |
'**/color/*.xml', | |
'**/drawable/*.xml', | |
'**/layout/*.xml', | |
'**/values/*.xml' | |
], | |
exclude: '**/public.xml' | |
); | |
// Create new public.xml with writer | |
new File(resDir + "/values/public.xml").withWriter { writer -> | |
// Create MarkupBuilder with 4 space indent | |
def destXml = new MarkupBuilder(new IndentPrinter(writer, " ", true)); | |
def destXmlMkp = destXml.getMkp(); | |
// GIST NOTE: our project needed the ResourceName suppression, but its not needed in general | |
destXml.resources( | |
'xmlns:tools': 'http://schemas.android.com/tools', | |
'tools:ignore': 'ResourceName' | |
) { | |
// Leave file comment | |
destXmlMkp.yield "\r\n" | |
destXmlMkp.comment("AUTO-GENERATED FILE. DO NOT MODIFY. public.xml is generated by the generatepublicxml gradle task") | |
tree.each { resFile -> | |
// use the directory name to get the type | |
def type = resFile.getParentFile().getName() | |
if (type == "values") { | |
// Resource files under values. Parse the file, and pull out the resource definitions | |
def parsePublicResources = new XmlParser().parse(resFile) | |
parsePublicResources.children().each { | |
// Type is usually the element, but sometimes a type attribute is present | |
// example: <item name="line_spacing_multiplier" format="float" type="dimen">1.4</item> | |
type = it.name() | |
if(it.@type){ | |
type = it.@type | |
} | |
// it.@name is value in name= | |
"public"("name": it.@name, "type": type) | |
} | |
} else { | |
// Drawable, layout, etc files | |
"public"("name": resFile.getName().tokenize('.')[0], "type": type) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment