jdaugherty commented on code in PR #15940:
URL: https://github.com/apache/grails-core/pull/15940#discussion_r3555740708


##########
grails-i18n/src/main/groovy/org/grails/plugins/i18n/I18nAutoConfiguration.java:
##########
@@ -130,4 +130,30 @@ public MessageSource messageSource(GrailsApplication 
grailsApplication, GrailsPl
         }
         return messageSource;
     }
+
+    /**
+     * Discovers the locales the application is translated into (from {@code 
<basename>_<locale>.properties}
+     * bundles on the classpath) so that a language selector can list only 
real translations rather
+     * than every JVM locale. Published to the servlet context by {@link 
I18nGrailsPlugin} and
+     * consumed by the {@code g:localeSelect available="true"} tag.
+     *
+     * <p>By default every {@code *.properties} bundle on the classpath is 
considered, so locales
+     * contributed by plugins &mdash; whose bundles are namespaced (e.g.
+     * {@code spring-security-core_*.properties}) &mdash; are included 
alongside the application's own.
+     * Set {@code grails.i18n.availableLocales.includePlugins=false} to 
restrict discovery to the
+     * application's own {@code messages_*.properties} bundles.
+     *
+     * @param defaultLocale the base {@code messages.properties} locale, 
always included
+     * ({@code grails.i18n.default.locale}, defaults to {@code en})
+     * @param includePlugins whether to also scan plugin-contributed message 
bundles
+     * ({@code grails.i18n.availableLocales.includePlugins}, defaults to 
{@code true})
+     */
+    @Bean
+    @ConditionalOnMissingBean(AvailableLocaleResolver.class)
+    public AvailableLocaleResolver availableLocaleResolver(GrailsApplication 
grailsApplication,
+            @Value("${grails.i18n.default.locale:en}") String defaultLocale,

Review Comment:
   `grails.i18n.default.locale` now has two different defaults within the same 
class: the `defaultLocale` field above defaults to *empty* (falling back to 
`Locale.getDefault()` via `fixedLocale()`), while this parameter defaults to 
`en`. For an app whose base `messages.properties` is not English, the selector 
will always advertise English even though no English translation exists.
   
   The parsing also diverges (`Locale.forLanguageTag(...replace('_','-'))` here 
vs `StringUtils.parseLocale` in `fixedLocale()`). Suggest injecting the same 
empty-default property and reusing the existing field/`StringUtils.parseLocale` 
so the one config key behaves consistently across the class.



##########
grails-i18n/src/main/groovy/org/grails/plugins/i18n/I18nGrailsPlugin.groovy:
##########
@@ -42,6 +43,30 @@ class I18nGrailsPlugin extends Plugin {
     String version = GrailsUtil.getGrailsVersion()
     String watchedResources = "file:./${baseDir}/**/*.properties".toString()
 
+    /**
+     * Publishes the discovered available locales to the servlet context so 
that views and the
+     * {@code g:localeSelect available="true"} tag can render a language 
selector. Reading a servlet
+     * context attribute keeps consumers decoupled from this module.
+     */
+    static final String AVAILABLE_LOCALES_ATTRIBUTE = 'availableLocales'
+
+    @Override
+    void doWithApplicationContext() {
+        publishAvailableLocales()
+    }
+
+    private void publishAvailableLocales() {
+        def ctx = applicationContext
+        if (!(ctx instanceof WebApplicationContext)) {
+            return
+        }
+        def servletContext = ((WebApplicationContext) ctx).servletContext
+        if (servletContext != null && 
ctx.containsBean('availableLocaleResolver')) {

Review Comment:
   The resolver is looked up by bean **name** here (and again in `onChange`), 
but the auto-configuration backs off by **type** 
(`@ConditionalOnMissingBean(AvailableLocaleResolver.class)`). If a user 
registers their own `AvailableLocaleResolver` under any other bean name, the 
auto-configured bean backs off, `containsBean('availableLocaleResolver')` is 
false, and nothing is ever published to the servlet context — the selector 
silently disappears even though a resolver exists.
   
   Consider resolving by type instead, e.g. 
`ctx.getBeanProvider(AvailableLocaleResolver).ifAvailable { ... }`, so the 
customization path promised by `@ConditionalOnMissingBean` actually works 
end-to-end.



##########
grails-forge/grails-forge-core/src/main/resources/gsp/main.gsp:
##########
@@ -18,6 +18,22 @@
             <asset:image class="w-75" src="grails.svg" alt="Grails Logo"/>
         </a>
         <ul class="navbar-nav ms-auto">
+            <g:set var="availableLocales" 
value="${application.getAttribute('availableLocales')}"/>
+            <g:if test="${availableLocales && availableLocales.size() > 1}">
+                <g:set var="currentLocale" 
value="${org.springframework.web.servlet.support.RequestContextUtils.getLocale(request)}"/>
+                <li class="nav-item dropdown">
+                    <a class="nav-link dropdown-toggle" href="#" 
id="localeDropdown" role="button" data-bs-toggle="dropdown" 
aria-expanded="false">
+                        <i class="bi bi-globe 
me-1"></i>${currentLocale.getDisplayName(currentLocale)}
+                    </a>
+                    <ul class="dropdown-menu dropdown-menu-end" 
aria-labelledby="localeDropdown">
+                        <g:each in="${availableLocales}" var="availableLocale">
+                            <li>
+                                <a class="dropdown-item${availableLocale == 
currentLocale ? ' active' : ''}" 
href="?lang=${availableLocale.toLanguageTag()}">${availableLocale.getDisplayName(availableLocale)}</a>

Review Comment:
   Two behavioural nits (both also apply to the identical copy in 
`grails-profiles/web/skeleton/grails-app/views/layouts/main.gsp`):
   
   1. `availableLocale == currentLocale` compares full locales, but 
`currentLocale` usually carries a country on first visit (e.g. `en_US` from 
`Accept-Language`) while the discovered list holds language-only locales — so 
the `active` highlight never fires until the user explicitly picks an entry. A 
language-level fallback comparison would behave better out of the box.
   2. `href="?lang=..."` replaces the entire query string, so switching 
language drops any existing request parameters (pagination, filters, etc.). 
Probably acceptable for the scaffold, but worth a conscious decision.



##########
grails-doc/src/en/guide/i18n/changingLocales.adoc:
##########
@@ -26,6 +26,29 @@ By default, the user locale is detected from the incoming 
`Accept-Language` head
 
 Grails will automatically switch the user's locale and subsequent requests 
will use the switched locale.
 
+To offer a language selector, the i18n plugin discovers the locales your 
application is actually translated into by scanning the classpath for 
`messages_&#42;.properties` bundles (plus the default locale, configurable via 
`grails.i18n.default.locale`). This list is exposed as the 
`AvailableLocaleResolver` bean and published to the servlet context under the 
`availableLocales` attribute. The `<g:localeSelect available="true"/>` tag 
renders a `<select>` limited to those locales, and you can iterate the list 
directly in a view to build your own switcher:

Review Comment:
   This paragraph ends with "build your own switcher:" but the `g:each` example 
it introduces is pushed below the plugin-discovery paragraph and the YAML 
block. Reordering to intro → example → plugin-discovery paragraph → YAML would 
read better.



##########
grails-i18n/src/main/groovy/org/grails/plugins/i18n/AvailableLocaleResolver.java:
##########
@@ -0,0 +1,173 @@
+/*
+ *  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 
&mdash; whose
+ * bundles are namespaced (e.g. {@code spring-security-core_fr.properties}) 
&mdash; are
+ * included too. Candidate suffixes are validated against {@link 
Locale#getISOLanguages()}
+ * so non-i18n properties files (e.g. {@code application.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 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), and the suffix must 
be a recognised language.
+     */
+    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 code = base.substring(underscore + 1);
+        if (code.isEmpty()) {
+            return null;
+        }
+        Locale locale = Locale.forLanguageTag(code.replace('_', '-'));
+        return ISO_LANGUAGES.contains(locale.getLanguage()) ? locale : null;

Review Comment:
   Only the language subtag is validated, so with `includePlugins=true` (the 
default) any root-level properties file whose suffix happens to parse to a 
known language leaks into the selector:
   
   - `db_it.properties` → contributes Italian
   - `foo_en_prod.properties` → `forLanguageTag("en-prod")` treats `prod` as a 
*script* subtag, producing an `en-Prod` locale that passes the ISO-language 
check and shows up as a second English-looking entry
   
   Since `.properties` bundles follow the 
`basename_language(_COUNTRY(_variant))` convention rather than BCP 47, 
validating the whole suffix (ISO language, and ISO country when present) before 
accepting it would cut these false positives down considerably.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to