-
-
Notifications
You must be signed in to change notification settings - Fork 974
Add available-locale discovery and a language selector to i18n #15940
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jdaugherty
merged 6 commits into
apache:8.0.x
from
codeconsole:feat/i18n-available-locale-selector
Jul 10, 2026
+790
−2
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d62ae0a
Add available-locale discovery and a language selector to i18n
codeconsole b756b53
Include plugin-contributed locales in available-locale discovery
codeconsole 081acf9
Merge remote-tracking branch 'upstream/8.0.x' into feat/i18n-availabl…
codeconsole 8f9d7aa
Merge branch '8.0.x' into feat/i18n-available-locale-selector
codeconsole 170ae02
Cover available-locale wiring, plugin lifecycle and taglib branches
codeconsole 9d79f67
Address review: type-based resolver lookup, consistent default locale…
codeconsole File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
97 changes: 97 additions & 0 deletions
97
grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/LocaleSelectAvailableSpec.groovy
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
| package org.grails.web.taglib | ||
|
|
||
| import grails.testing.web.taglib.TagLibUnitTest | ||
| import org.grails.plugins.web.taglib.FormTagLib | ||
| import spock.lang.Specification | ||
|
|
||
| /** | ||
| * Tests the {@code available="true"} mode of {@code g:localeSelect}, which restricts the options to | ||
| * the locales the i18n plugin publishes to the servlet context (the app's real translations) instead | ||
| * of every locale the JVM knows about. | ||
| */ | ||
| class LocaleSelectAvailableSpec extends Specification implements TagLibUnitTest<FormTagLib> { | ||
|
|
||
| void 'available="true" lists only the locales published to the servlet context'() { | ||
| given: | ||
| request.servletContext.setAttribute('availableLocales', | ||
| [Locale.forLanguageTag('en'), Locale.forLanguageTag('es')]) | ||
|
|
||
| when: | ||
| String output = applyTemplate('<g:localeSelect name="lang" available="true"/>') | ||
|
|
||
| then: 'the two published locales are options' | ||
| output.contains('name="lang"') | ||
| output.contains('value="en"') | ||
| output.contains('value="es"') | ||
|
|
||
| and: 'a locale that has no bundle is not offered' | ||
| !output.contains('value="fr"') | ||
| } | ||
|
|
||
| void 'without available="true" the tag still lists every JVM locale'() { | ||
| when: | ||
| String output = applyTemplate('<g:localeSelect name="lang"/>') | ||
|
|
||
| then: | ||
| output.contains('value="fr"') | ||
| } | ||
|
|
||
| void 'an explicit available="false" keeps the full JVM locale list even when locales are published'() { | ||
| given: | ||
| request.servletContext.setAttribute('availableLocales', | ||
| [Locale.forLanguageTag('en'), Locale.forLanguageTag('es')]) | ||
|
|
||
| when: | ||
| String output = applyTemplate('<g:localeSelect name="lang" available="false"/>') | ||
|
|
||
| then: 'a locale outside the published list is still offered' | ||
| output.contains('value="fr"') | ||
| } | ||
|
|
||
| void 'available="true" falls back to the current locale when nothing is published'() { | ||
| when: | ||
| String output = applyTemplate('<g:localeSelect name="lang" available="true"/>') | ||
|
|
||
| then: 'no servlet-context attribute is present, so the select is not empty and not the full JVM list' | ||
| output.contains('<select') | ||
| !output.contains('value="fr"') | ||
| } | ||
|
|
||
| void 'the published list can drive a custom link dropdown like the create-app layout does'() { | ||
| given: 'the same servlet-context attribute the i18n plugin publishes and the create-app main.gsp reads' | ||
| request.servletContext.setAttribute('availableLocales', | ||
| [Locale.forLanguageTag('en'), Locale.forLanguageTag('es')]) | ||
|
|
||
| when: 'the navbar snippet from the generated layout is rendered' | ||
| String output = applyTemplate(''' | ||
| <g:set var="availableLocales" value="${application.getAttribute('availableLocales')}"/> | ||
| <g:if test="${availableLocales && availableLocales.size() > 1}"> | ||
| <g:each in="${availableLocales}" var="availableLocale"> | ||
| <a href="?lang=${availableLocale.toLanguageTag()}">${availableLocale.getDisplayName(availableLocale)}</a> | ||
| </g:each> | ||
| </g:if> | ||
| '''.stripIndent()) | ||
|
|
||
| then: 'one ?lang= link per published locale is produced' | ||
| output.contains('href="?lang=en"') | ||
| output.contains('href="?lang=es"') | ||
| } | ||
| } |
186 changes: 186 additions & 0 deletions
186
grails-i18n/src/main/groovy/org/grails/plugins/i18n/AvailableLocaleResolver.java
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
| package org.grails.plugins.i18n; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.Collections; | ||
| import java.util.Comparator; | ||
| import java.util.HashSet; | ||
| import java.util.LinkedHashSet; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Set; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import org.springframework.core.io.Resource; | ||
| import org.springframework.core.io.support.PathMatchingResourcePatternResolver; | ||
| import org.springframework.core.io.support.ResourcePatternResolver; | ||
|
|
||
| /** | ||
| * Discovers the locales an application is actually translated into by scanning the | ||
| * classpath for {@code <basename>_<locale>.properties} resource bundles. | ||
| * | ||
| * <p>Unlike {@link java.util.Locale#getAvailableLocales()} (which returns every locale | ||
| * the JVM knows about), this returns only the locales that have a matching message | ||
| * bundle plus the configured default locale, making it suitable for driving a language | ||
| * selector. The result is sorted by each locale's display name in its own language and | ||
| * cached; {@link #clearCache()} forces a re-scan (used when bundles change in development). | ||
| * | ||
| * <p>By default only the application's own {@code messages_*.properties} bundles are | ||
| * scanned. When {@code includePluginBundles} is enabled, every {@code *.properties} | ||
| * bundle on the classpath is considered, so locales contributed by plugins — whose | ||
| * bundles are namespaced (e.g. {@code spring-security-core_fr.properties}) — are | ||
| * included too. Candidate suffixes are validated against the ISO language codes (and the ISO | ||
| * country codes when a country is present), so non-i18n properties files (e.g. | ||
| * {@code application.properties} or {@code foo_en_prod.properties}) are ignored. See | ||
| * {@code grails.i18n.availableLocales.includePlugins}. | ||
| * | ||
| * @since 8.0.0 | ||
| */ | ||
| public class AvailableLocaleResolver { | ||
|
|
||
| private static final Logger log = LoggerFactory.getLogger(AvailableLocaleResolver.class); | ||
|
|
||
| /** The base name of an application's own message bundles ({@code messages.properties}). */ | ||
| public static final String DEFAULT_BASE_NAME = "messages"; | ||
|
|
||
| private static final String PROPERTIES_SUFFIX = ".properties"; | ||
|
|
||
| private static final Set<String> ISO_LANGUAGES = new HashSet<>(Arrays.asList(Locale.getISOLanguages())); | ||
|
|
||
| private static final Set<String> ISO_COUNTRIES = new HashSet<>(Arrays.asList(Locale.getISOCountries())); | ||
|
|
||
| private final ResourcePatternResolver resourcePatternResolver; | ||
|
|
||
| private final Locale defaultLocale; | ||
|
|
||
| private final boolean includePluginBundles; | ||
|
|
||
| private volatile List<Locale> cachedLocales; | ||
|
|
||
| /** | ||
| * Scans only the application's own {@code messages_*.properties} bundles. | ||
| * | ||
| * @param classLoader the class loader whose classpath is scanned for message bundles | ||
| * @param defaultLocale the locale of the base {@code messages.properties} bundle, | ||
| * always included in the result (may be {@code null} to include none) | ||
| */ | ||
| public AvailableLocaleResolver(ClassLoader classLoader, Locale defaultLocale) { | ||
| this(classLoader, defaultLocale, false); | ||
| } | ||
|
|
||
| /** | ||
| * @param classLoader the class loader whose classpath is scanned for message bundles | ||
| * @param defaultLocale the locale of the base bundle, always included (may be {@code null}) | ||
| * @param includePluginBundles whether to also consider plugin-contributed bundles (every | ||
| * {@code *.properties} on the classpath) rather than only the application's {@code messages} | ||
| */ | ||
| public AvailableLocaleResolver(ClassLoader classLoader, Locale defaultLocale, boolean includePluginBundles) { | ||
| this.resourcePatternResolver = new PathMatchingResourcePatternResolver(classLoader); | ||
| this.defaultLocale = defaultLocale; | ||
| this.includePluginBundles = includePluginBundles; | ||
| } | ||
|
|
||
| /** | ||
| * @return an unmodifiable, display-name-sorted list of the locales the application is | ||
| * translated into. Computed once and cached until {@link #clearCache()} is called. | ||
| */ | ||
| public List<Locale> getAvailableLocales() { | ||
| List<Locale> locales = this.cachedLocales; | ||
| if (locales == null) { | ||
| synchronized (this) { | ||
| locales = this.cachedLocales; | ||
| if (locales == null) { | ||
| locales = computeAvailableLocales(); | ||
| this.cachedLocales = locales; | ||
| } | ||
| } | ||
| } | ||
| return locales; | ||
| } | ||
|
|
||
| /** | ||
| * Discards the cached list so the next {@link #getAvailableLocales()} re-scans the classpath. | ||
| */ | ||
| public void clearCache() { | ||
| this.cachedLocales = null; | ||
| } | ||
|
|
||
| private List<Locale> computeAvailableLocales() { | ||
| Set<Locale> locales = new LinkedHashSet<>(); | ||
| if (this.defaultLocale != null && !this.defaultLocale.getLanguage().isEmpty()) { | ||
| locales.add(this.defaultLocale); | ||
| } | ||
| String pattern = "classpath*:" + DEFAULT_BASE_NAME + "_*" + PROPERTIES_SUFFIX; | ||
| if (this.includePluginBundles) { | ||
| pattern = "classpath*:*" + PROPERTIES_SUFFIX; | ||
| } | ||
| try { | ||
| for (Resource resource : this.resourcePatternResolver.getResources(pattern)) { | ||
| Locale locale = localeFromBundleFilename(resource.getFilename()); | ||
| if (locale != null) { | ||
| locales.add(locale); | ||
| } | ||
| } | ||
| } | ||
| catch (IOException ex) { | ||
| log.warn("Unable to resolve available locales from message bundles: {}", ex.getMessage()); | ||
| } | ||
| List<Locale> sorted = new ArrayList<>(locales); | ||
| sorted.sort(Comparator.comparing((Locale locale) -> locale.getDisplayName(locale))); | ||
| return Collections.unmodifiableList(sorted); | ||
| } | ||
|
|
||
| /** | ||
| * Extracts the locale a bundle filename encodes, or {@code null} if it is not a locale-specific | ||
| * message bundle. The base name ends at the first underscore (matching Grails' own message-source | ||
| * convention, where plugin base names use hyphens). The suffix follows the resource-bundle | ||
| * convention {@code language(_COUNTRY(_variant))} — not BCP 47 — so the language must | ||
| * be an ISO language and, when present, the country an ISO country; anything else (e.g. | ||
| * {@code foo_en_prod.properties}) is rejected rather than misparsed as a script or region. | ||
| */ | ||
| private static Locale localeFromBundleFilename(String filename) { | ||
| if (filename == null || !filename.endsWith(PROPERTIES_SUFFIX)) { | ||
| return null; | ||
| } | ||
| String base = filename.substring(0, filename.length() - PROPERTIES_SUFFIX.length()); | ||
| int underscore = base.indexOf('_'); | ||
| if (underscore < 0) { | ||
| return null; | ||
| } | ||
| String[] parts = base.substring(underscore + 1).split("_", 3); | ||
| String language = parts[0]; | ||
| if (!ISO_LANGUAGES.contains(language)) { | ||
| return null; | ||
| } | ||
| if (parts.length == 1) { | ||
| return Locale.of(language); | ||
| } | ||
| String country = parts[1]; | ||
| if (!ISO_COUNTRIES.contains(country)) { | ||
| return null; | ||
| } | ||
| return (parts.length == 2) ? Locale.of(language, country) : Locale.of(language, country, parts[2]); | ||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.