├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle-plugin ├── build.gradle.kts └── src │ └── main │ └── java │ └── dev │ └── rikka │ └── tools │ └── autoresconfig │ ├── AutoResConfigExtension.java │ ├── AutoResConfigPlugin.java │ ├── GenerateJavaTask.java │ ├── GenerateLocaleConfigResTask.java │ ├── GenerateResTask.java │ ├── GenerateTask.java │ └── Util.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle.kts /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | 3 | *.bat text eol=crlf 4 | *.jar binary -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .idea/ 3 | .gradle/ 4 | local.properties 5 | *.iml 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 RikkaW 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AutoResConfig 2 | 3 | For Android application projects that accept user-submitted translations, the number of supported languages may be large and growing. When new languages are added, developers need to manually update `resConfig` (1) and language array xml/class (2). Manual means there could be human error. 4 | 5 | (1) `resConfig` limits the final packaged resources. Libraries may carry languages resources which the language is not supported by the application itself. Set `resConfig` could reduce apk size. 6 | 7 | (2) If the application has a "choose language" feature, there must be an array of supported languages (could be as an Android resource XML or a Java class). 8 | 9 | This plugin collect locales from `values-` folders, set `resConfig`, generate language array xml/class. 10 | 11 | ## Usage 12 | 13 | ![gradle-plugin](https://img.shields.io/maven-central/v/dev.rikka.tools.autoresconfig/dev.rikka.tools.autoresconfig.gradle.plugin?label=gradle-plugin) 14 | 15 | Replace all the `` below with the version shows here. 16 | 17 | 1. Add gradle plugin 18 | 19 | ```groovy 20 | // "old way" 21 | buildscript { 22 | repositories { 23 | mavenCentral() 24 | } 25 | dependencies { 26 | classpath 'dev.rikka.tools.autoresconfig:gradle-plugin:' 27 | } 28 | } 29 | ``` 30 | 31 | ```groovy 32 | // "new way" 33 | plugins { 34 | id 'dev.rikka.tools.autoresconfig' version '' 35 | } 36 | ``` 37 | 38 | 2. Use the plugin in Android application module 39 | 40 | ```groovy 41 | plugins { 42 | id('dev.rikka.tools.autoresconfig') 43 | } 44 | 45 | 3. Config in Android application module 46 | 47 | ```groovy 48 | autoResConfig { 49 | generateClass = true 50 | generatedClassFullName = "rikka.autoresconfig.Locales" 51 | generateRes = true 52 | generatedResPrefix = null 53 | generatedArrayFirstItem = "SYSTEM" 54 | 55 | // Generate Android 13 localeConfig xml 56 | // see https://developer.android.com/about/versions/13/features/app-languages#use-localeconfig 57 | generateLocaleConfig = true 58 | } 59 | ``` -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | task("clean", type = Delete::class) { 2 | delete(buildDir) 3 | } 4 | 5 | subprojects { 6 | group = "dev.rikka.tools.autoresconfig" 7 | version = "1.2.1" 8 | 9 | plugins.withId("java") { 10 | println("- Configuring `java`") 11 | 12 | extensions.configure { 13 | sourceCompatibility = JavaVersion.VERSION_11 14 | targetCompatibility = JavaVersion.VERSION_11 15 | } 16 | tasks.register("sourcesJar", type = Jar::class) { 17 | archiveClassifier.set("sources") 18 | from(project.extensions.getByType().getByName("main").allSource) 19 | } 20 | tasks.register("javadocJar", type = Jar::class) { 21 | archiveClassifier.set("javadoc") 22 | from(tasks["javadoc"]) 23 | } 24 | tasks.withType(Javadoc::class) { 25 | isFailOnError = false 26 | } 27 | } 28 | plugins.withId("maven-publish") { 29 | println("- Configuring `publishing`") 30 | 31 | afterEvaluate { 32 | extensions.configure { 33 | publications { 34 | withType(MavenPublication::class) { 35 | version = project.version.toString() 36 | group = project.group.toString() 37 | 38 | pom { 39 | name.set("AutoResConfig") 40 | description.set("AutoResConfig") 41 | url.set("https://github.com/RikkaApps/AutoResConfig") 42 | licenses { 43 | license { 44 | name.set("MIT License") 45 | url.set("https://github.com/RikkaApps/AutoResConfig/blob/main/LICENSE") 46 | } 47 | } 48 | developers { 49 | developer { 50 | name.set("RikkaW") 51 | } 52 | } 53 | scm { 54 | connection.set("scm:git:https://github.com/RikkaApps/AutoResConfig.git") 55 | url.set("https://github.com/RikkaApps/AutoResConfig") 56 | } 57 | } 58 | } 59 | } 60 | repositories { 61 | mavenLocal() 62 | maven { 63 | name = "ossrh" 64 | url = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2") 65 | credentials(PasswordCredentials::class.java) 66 | } 67 | } 68 | } 69 | } 70 | plugins.withId("signing") { 71 | println("- Configuring `signing`") 72 | 73 | afterEvaluate { 74 | extensions.configure { 75 | if (findProperty("signing.gnupg.keyName") != null) { 76 | useGpgCmd() 77 | 78 | val signingTasks = sign(extensions.getByType().publications) 79 | tasks.withType(AbstractPublishToMaven::class) { 80 | dependsOn(signingTasks) 81 | } 82 | } 83 | } 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | `java-gradle-plugin` 4 | `maven-publish` 5 | signing 6 | } 7 | 8 | repositories { 9 | mavenCentral() 10 | google() 11 | } 12 | 13 | dependencies { 14 | compileOnly(gradleApi()) 15 | compileOnly(libs.android.gradle) 16 | } 17 | 18 | gradlePlugin { 19 | plugins { 20 | create("AutoResConfig") { 21 | id = project.group.toString() 22 | displayName = "AutoResConfig" 23 | description = "A gradle plugin generates resConfig & languages array from project res folder." 24 | implementationClass = "$id.AutoResConfigPlugin" 25 | } 26 | } 27 | } 28 | 29 | afterEvaluate { 30 | publishing { 31 | publications { 32 | named("pluginMaven", MavenPublication::class) { 33 | artifactId = "gradle-plugin" 34 | 35 | artifact(tasks["sourcesJar"]) 36 | artifact(tasks["javadocJar"]) 37 | } 38 | } 39 | } 40 | 41 | tasks.withType(Jar::class) { 42 | manifest { 43 | attributes(mapOf("Implementation-Version" to project.version.toString())) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/AutoResConfigExtension.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import org.gradle.api.provider.Property; 4 | 5 | public abstract class AutoResConfigExtension { 6 | 7 | public abstract Property getGenerateClass(); 8 | 9 | public abstract Property getGeneratedClassFullName(); 10 | 11 | public abstract Property getGenerateRes(); 12 | 13 | public abstract Property getGenerateLocaleConfig(); 14 | 15 | public abstract Property getGeneratedResPrefix(); 16 | 17 | public abstract Property getGeneratedArrayFirstItem(); 18 | 19 | public AutoResConfigExtension() { 20 | getGenerateClass().set(true); 21 | getGeneratedClassFullName().set("rikka.autoresconfig.AutoResConfigLocales"); 22 | getGenerateRes().set(true); 23 | getGeneratedArrayFirstItem().set("SYSTEM"); 24 | getGenerateLocaleConfig().set(true); 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return "AutoResConfigExtension{" + 30 | "generateClass=" + getGenerateClass().get() + 31 | ", generatedClassFullName=" + getGeneratedClassFullName().get() + 32 | ", generateRes=" + getGenerateRes().get() + 33 | ", generatedResPrefix=" + getGeneratedResPrefix().getOrElse("(null)") + 34 | ", generatedArrayFirstItem=" + getGeneratedArrayFirstItem().get() + 35 | ", generateLocaleConfig=" + getGenerateLocaleConfig().get() + 36 | "}"; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/AutoResConfigPlugin.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import com.android.build.gradle.AppExtension; 4 | import com.android.build.gradle.api.ApplicationVariant; 5 | import com.android.builder.core.AbstractProductFlavor; 6 | import org.gradle.api.GradleException; 7 | import org.gradle.api.Plugin; 8 | import org.gradle.api.Project; 9 | import org.gradle.api.logging.Logger; 10 | import org.gradle.api.logging.Logging; 11 | import org.gradle.api.tasks.SourceTask; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.nio.file.Files; 16 | import java.util.*; 17 | import java.util.stream.Collectors; 18 | 19 | @SuppressWarnings("unused") 20 | public class AutoResConfigPlugin implements Plugin { 21 | 22 | private static final Map displayLocaleMap = new HashMap<>(); 23 | 24 | static { 25 | displayLocaleMap.put("zh-CN", "zh-Hans"); 26 | displayLocaleMap.put("zh-TW", "zh-Hant"); 27 | } 28 | 29 | private final Logger logger = Logging.getLogger(AutoResConfigPlugin.class); 30 | private final Map> modifierCache = new HashMap<>(); 31 | 32 | private void collectModifiers(File dir, Collection output) throws IOException { 33 | if (!dir.exists() || !dir.isDirectory()) { 34 | return; 35 | } 36 | 37 | logger.debug("AutoResConfig: Collect modifiers from " + dir); 38 | 39 | try (var stream = Files.list(dir.toPath())) { 40 | output.addAll(stream 41 | .filter(file -> { 42 | try { 43 | return Files.isDirectory(file) 44 | && file.toFile().getName().startsWith("values-") 45 | && Files.exists(file.resolve("strings.xml")) 46 | 47 | // not an empty xml 48 | // TODO replace with find ? 49 | && Files.size(file.resolve("strings.xml")) > 62; 50 | } catch (IOException e) { 51 | return false; 52 | } 53 | }) 54 | .map(java.nio.file.Path::getFileName) 55 | .map(path -> path.toFile().getName().substring("values-".length())) 56 | .filter(s -> s.split("-").length <= 3) 57 | .collect(Collectors.toList())); 58 | } 59 | } 60 | 61 | private Collection collectModifiers(@SuppressWarnings("deprecation") ApplicationVariant variant) { 62 | var set = new HashSet(); 63 | set.add("en"); 64 | 65 | Set resDirs = new HashSet<>(); 66 | variant.getSourceSets().forEach(sourceProvider -> resDirs.addAll(sourceProvider.getResDirectories())); 67 | 68 | for (File dir : resDirs) { 69 | Set modifiers = modifierCache.get(dir.getAbsolutePath()); 70 | if (modifiers != null) { 71 | set.addAll(modifiers); 72 | } 73 | } 74 | 75 | var list = new ArrayList<>(set); 76 | list.sort(String.CASE_INSENSITIVE_ORDER); 77 | return list; 78 | } 79 | 80 | private boolean updateResConfig(@SuppressWarnings("deprecation") ApplicationVariant variant, Collection modifiers) { 81 | var mergedFlavor = variant.getMergedFlavor(); 82 | 83 | //noinspection deprecation 84 | if (mergedFlavor instanceof AbstractProductFlavor) { 85 | //noinspection deprecation 86 | var flavor = (AbstractProductFlavor) mergedFlavor; 87 | flavor.addResourceConfigurations(modifiers); 88 | return true; 89 | } else { 90 | return false; 91 | } 92 | } 93 | 94 | private Collection convertModifiersToLocales(Collection modifiers) { 95 | var locales = new ArrayList(); 96 | 97 | String locale; 98 | for (String modifier : modifiers) { 99 | if (modifier.startsWith("b+")) { 100 | String[] names = modifier.substring("b+".length()).split("\\+", 2); 101 | if (names.length == 2) { 102 | locale = names[0] + "-" + names[1]; 103 | } else { 104 | locale = names[0]; 105 | } 106 | } else { 107 | String[] names = modifier.split("-", 2); 108 | if (names.length == 2) { 109 | locale = names[0] + "-" + names[1].substring("r".length()); 110 | } else { 111 | locale = names[0]; 112 | } 113 | } 114 | 115 | locales.add(locale); 116 | } 117 | 118 | locales.sort(String.CASE_INSENSITIVE_ORDER); 119 | return locales; 120 | } 121 | 122 | private Collection convertLocalesToDisplayLocales(Collection locales) { 123 | var displayLocales = new ArrayList(); 124 | 125 | for (String locale : locales) { 126 | String displayLocale = displayLocaleMap.get(locale); 127 | if (displayLocale == null) { 128 | displayLocale = locale; 129 | } 130 | displayLocales.add(displayLocale); 131 | } 132 | 133 | return displayLocales; 134 | } 135 | 136 | @Override 137 | public void apply(Project project) { 138 | var appExtension = project.getExtensions().findByType(AppExtension.class); 139 | if (appExtension == null) throw new GradleException("Android application extension not found"); 140 | 141 | var extension = project.getExtensions().create( 142 | "autoResConfig", AutoResConfigExtension.class); 143 | 144 | // Build a file path -> locale modifiers cache 145 | modifierCache.clear(); 146 | 147 | appExtension.getSourceSets().all(sourceSet -> { 148 | Set mainModifiers = null; 149 | 150 | logger.info("AutoResConfig: Collect locale modifiers for " + sourceSet.getName()); 151 | 152 | for (File dir : sourceSet.getRes().getSrcDirs()) { 153 | var absolutePath = dir.getAbsolutePath(); 154 | 155 | var set = modifierCache.get(absolutePath); 156 | if (set != null) continue; 157 | 158 | set = new HashSet<>(); 159 | set.add("en"); 160 | 161 | modifierCache.put(absolutePath, set); 162 | 163 | try { 164 | collectModifiers(dir, set); 165 | } catch (IOException e) { 166 | logger.error("AutoResConfig: Failed to collect modifiers from " + dir, e); 167 | } 168 | 169 | if (sourceSet.getName().equals("main")) { 170 | mainModifiers = set; 171 | } 172 | } 173 | 174 | if (sourceSet.getName().equals("main")) { 175 | if (mainModifiers != null) { 176 | var list = new ArrayList<>(mainModifiers); 177 | list.sort(String.CASE_INSENSITIVE_ORDER); 178 | 179 | appExtension.getDefaultConfig().resConfigs(list); 180 | logger.info("AutoResConfig: Update default resConfig " + mainModifiers); 181 | } else { 182 | logger.warn("AutoResConfig: mainModifiers is null"); 183 | } 184 | } 185 | }); 186 | 187 | appExtension.getApplicationVariants().all(variant -> { 188 | var variantName = variant.getName(); 189 | var variantNameCapitalized = Util.capitalize(variantName); 190 | 191 | logger.info("AutoResConfig: Variant " + variantName); 192 | logger.info("AutoResConfig: " + extension); 193 | 194 | var modifiers = collectModifiers(variant); 195 | 196 | if (updateResConfig(variant, modifiers)) { 197 | logger.info("AutoResConfig: Update resConfig " + modifiers); 198 | } else { 199 | logger.error("AutoResConfig: Failed to update resConfig"); 200 | } 201 | 202 | var locales = convertModifiersToLocales(modifiers); 203 | var displayLocales = convertLocalesToDisplayLocales(locales); 204 | logger.info("AutoResConfig: Locales " + locales); 205 | logger.info("AutoResConfig: Display locales " + displayLocales); 206 | 207 | if (extension.getGenerateClass().get()) { 208 | var javaSourceDir = new File(project.getBuildDir(), 209 | String.format("generated/auto_res_config/%s/java", variantName)); 210 | 211 | var taskName = String.format("generate%sAutoResConfigSource", variantNameCapitalized); 212 | 213 | var generateJavaTask = project.getTasks().register(taskName, 214 | GenerateJavaTask.class, extension, javaSourceDir, locales, displayLocales); 215 | 216 | variant.registerJavaGeneratingTask(generateJavaTask, javaSourceDir); 217 | 218 | logger.info("AutoResConfig: register " + taskName + " " + javaSourceDir); 219 | } 220 | 221 | if (extension.getGenerateRes().get()) { 222 | var resDir = new File(project.getBuildDir(), 223 | String.format("generated/auto_res_config/%s/res", variantName)); 224 | 225 | var taskName = String.format("generate%sAutoResConfigRes", variantNameCapitalized); 226 | 227 | var generateResTask = project.getTasks().register(taskName, 228 | GenerateResTask.class, extension, resDir, locales, displayLocales); 229 | 230 | variant.registerGeneratedResFolders( 231 | project.files(resDir).builtBy(generateResTask)); 232 | 233 | logger.info("AutoResConfig: register " + taskName + " " + resDir); 234 | } 235 | 236 | if (extension.getGenerateLocaleConfig().get()) { 237 | var resDir = new File(project.getBuildDir(), 238 | String.format("generated/auto_res_config/%s/res", variantName)); 239 | 240 | var taskName = String.format("generate%sAutoResConfigLocaleConfigRes", variantNameCapitalized); 241 | 242 | var generateResTask = project.getTasks().register(taskName, 243 | GenerateLocaleConfigResTask.class, resDir, locales, displayLocales); 244 | 245 | variant.registerGeneratedResFolders( 246 | project.files(resDir).builtBy(generateResTask)); 247 | 248 | logger.info("AutoResConfig: register " + taskName + " " + resDir); 249 | } 250 | }); 251 | 252 | } 253 | } 254 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/GenerateJavaTask.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import javax.inject.Inject; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.PrintStream; 7 | import java.util.Collection; 8 | import java.util.stream.Collectors; 9 | 10 | public class GenerateJavaTask extends GenerateTask { 11 | 12 | private final AutoResConfigExtension extension; 13 | private final File file; 14 | 15 | @Inject 16 | public GenerateJavaTask(AutoResConfigExtension extension, File dir, 17 | Collection locales, Collection displayLocales) { 18 | super(dir, locales, displayLocales); 19 | 20 | this.extension = extension; 21 | this.file = new File(dir, String.format("%s.java", 22 | String.join("/", extension.getGeneratedClassFullName().get().split("\\.")))); 23 | } 24 | 25 | @Override 26 | public void generate() throws IOException { 27 | super.generate(); 28 | 29 | createFile(file); 30 | 31 | var os = new PrintStream(file); 32 | write(os); 33 | os.flush(); 34 | os.close(); 35 | } 36 | 37 | public void write(PrintStream os) { 38 | String content = "package %s;\n" + 39 | "\n" + 40 | "public final class %s {\n" + 41 | " public static final String[] LOCALES = {%s%s};\n" + 42 | " public static final String[] DISPLAY_LOCALES = {%s%s};\n" + 43 | "}\n"; 44 | 45 | var generatedClassFullName = extension.getGeneratedClassFullName().get(); 46 | var index = generatedClassFullName.lastIndexOf('.'); 47 | var packageName = generatedClassFullName.substring(0, index); 48 | var className = generatedClassFullName.substring(index + 1); 49 | 50 | var localesString = locales.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(",")); 51 | var displayLocalesString = displayLocales.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(",")); 52 | var firstItem = extension.getGeneratedArrayFirstItem().getOrElse("").isEmpty() ? "" 53 | : ("\"" + extension.getGeneratedArrayFirstItem().get() + "\","); 54 | 55 | os.printf(content, 56 | packageName, 57 | className, 58 | firstItem, 59 | localesString, 60 | firstItem, 61 | displayLocalesString); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/GenerateLocaleConfigResTask.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import javax.inject.Inject; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.PrintStream; 7 | import java.util.Collection; 8 | import java.util.stream.Collectors; 9 | 10 | public class GenerateLocaleConfigResTask extends GenerateTask { 11 | 12 | private final File file; 13 | 14 | @Inject 15 | public GenerateLocaleConfigResTask(File dir, Collection locales, Collection displayLocales) { 16 | super(dir, locales, displayLocales); 17 | 18 | this.file = new File(dir, "xml/locales_config.xml"); 19 | } 20 | 21 | @Override 22 | public void generate() throws IOException { 23 | super.generate(); 24 | 25 | createFile(file); 26 | 27 | var os = new PrintStream(file); 28 | write(os); 29 | os.flush(); 30 | os.close(); 31 | } 32 | 33 | public void write(PrintStream os) { 34 | String content = "\n" + 35 | "\n" + 36 | "%s\n" + 37 | "\n"; 38 | 39 | var localesString = locales.stream().map(s -> "").collect(Collectors.joining("\n")); 40 | 41 | os.printf(content, localesString); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/GenerateResTask.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import javax.inject.Inject; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.PrintStream; 7 | import java.util.Collection; 8 | import java.util.stream.Collectors; 9 | 10 | public class GenerateResTask extends GenerateTask { 11 | 12 | private final AutoResConfigExtension extension; 13 | private final File file; 14 | 15 | @Inject 16 | public GenerateResTask(AutoResConfigExtension extension, File dir, Collection locales, Collection displayLocales) { 17 | super(dir, locales, displayLocales); 18 | 19 | this.extension = extension; 20 | this.file = new File(dir, "values/arrays.xml"); 21 | } 22 | 23 | @Override 24 | public void generate() throws IOException { 25 | super.generate(); 26 | 27 | createFile(file); 28 | 29 | var os = new PrintStream(file); 30 | write(os); 31 | os.flush(); 32 | os.close(); 33 | } 34 | 35 | public void write(PrintStream os) { 36 | String content = "\n" + 37 | "\n" + 38 | "\n" + 39 | "%s%s\n" + 40 | "\n" + 41 | "\n" + 42 | "%s%s\n" + 43 | "\n" + 44 | "\n"; 45 | 46 | var prefix = extension.getGeneratedResPrefix().getOrElse(""); 47 | var localesString = locales.stream().map(s -> "" + s + "").collect(Collectors.joining("\n")); 48 | var displayLocalesString = displayLocales.stream().map(s -> "" + s + "").collect(Collectors.joining("\n")); 49 | var localesResName = prefix.isEmpty() ? "locales" : prefix + "_locales"; 50 | var displayLocalesResName = prefix.isEmpty() ? "display_locales" : prefix + "_display_locales"; 51 | var firstItem = extension.getGeneratedArrayFirstItem().getOrElse("").isEmpty() ? "" 52 | : ("" + extension.getGeneratedArrayFirstItem().get() + "\n"); 53 | 54 | os.printf(content, 55 | localesResName, 56 | firstItem, 57 | localesString, 58 | displayLocalesResName, 59 | firstItem, 60 | displayLocalesString); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/GenerateTask.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | import org.gradle.api.DefaultTask; 4 | import org.gradle.api.tasks.TaskAction; 5 | 6 | import javax.inject.Inject; 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.nio.file.FileVisitResult; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.SimpleFileVisitor; 13 | import java.nio.file.attribute.BasicFileAttributes; 14 | import java.util.Collection; 15 | 16 | public abstract class GenerateTask extends DefaultTask { 17 | 18 | protected final Collection locales; 19 | protected final Collection displayLocales; 20 | private final File dir; 21 | 22 | @Inject 23 | public GenerateTask(File dir, Collection locales, Collection displayLocales) { 24 | this.locales = locales; 25 | this.displayLocales = displayLocales; 26 | this.dir = dir; 27 | } 28 | 29 | @TaskAction 30 | public void generate() throws IOException { 31 | try { 32 | Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<>() { 33 | @Override 34 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 35 | Files.delete(dir); 36 | return FileVisitResult.CONTINUE; 37 | } 38 | 39 | @Override 40 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 41 | Files.delete(file); 42 | return FileVisitResult.CONTINUE; 43 | } 44 | }); 45 | } catch (IOException ignored) { 46 | } 47 | } 48 | 49 | public final void createFile(File file) throws IOException { 50 | if (!file.exists()) { 51 | if (!file.getParentFile().exists()) { 52 | if (!file.getParentFile().mkdirs()) { 53 | throw new IOException("Failed to create " + file.getParentFile()); 54 | } 55 | } 56 | if (!file.createNewFile()) { 57 | throw new IOException("Failed to create " + file); 58 | } 59 | } 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /gradle-plugin/src/main/java/dev/rikka/tools/autoresconfig/Util.java: -------------------------------------------------------------------------------- 1 | package dev.rikka.tools.autoresconfig; 2 | 3 | public class Util { 4 | 5 | public static String capitalize(String val) { 6 | char[] arr = val.toCharArray(); 7 | arr[0] = Character.toUpperCase(arr[0]); 8 | return new String(arr); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RikkaApps/AutoResConfig/3415ad4e79e1f37c5ae8016ef791f8e960f1a3ba/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("UnstableApiUsage") 2 | 3 | include(":gradle-plugin") 4 | 5 | pluginManagement { 6 | repositories { 7 | mavenCentral() 8 | google() 9 | gradlePluginPortal() 10 | } 11 | } 12 | 13 | dependencyResolutionManagement { 14 | repositories { 15 | mavenCentral() 16 | google() 17 | } 18 | versionCatalogs { 19 | create("libs") { 20 | val agp = "7.0.4" 21 | 22 | library("android-gradle", "com.android.tools.build", "gradle").version(agp) 23 | } 24 | } 25 | } --------------------------------------------------------------------------------