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


##########
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:
   Fixed in 9d79f67d09. The suffix is now parsed by the resource-bundle 
convention `language(_COUNTRY(_variant))` instead of BCP 47: the language must 
be an ISO language and, when a second segment is present, it must be an ISO 
country — so `foo_en_prod.properties` is rejected outright rather than 
misparsed as `en-Prod`. Added a `report_en_prod.properties` fixture plus a 
country-parsing test (`messages_pt_BR` → country `BR`). The `db_it.properties` 
→ Italian case is inherent to the name-based heuristic; `includePlugins=false` 
remains the escape hatch when an app's classpath has ambiguous root-level 
bundles.



##########
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:
   1: Fixed in 9d79f67d09 — the `active` highlight now compares the language 
subtag (`availableLocale.language == currentLocale.language`), so it fires on 
first visit when the request locale carries a country (`en_US` vs `en`). 
Applied to both copies.
   
   2: Keeping `?lang=` replacing the query string as a conscious scaffold 
decision — the generated layout links from simple pages, and preserving 
arbitrary parameters via `g:link params:` in a layout misbehaves on error/404 
pages that have no resolvable controller. Apps with stateful query params can 
adapt the snippet.



##########
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:
   Fixed in 9d79f67d09 — reordered to intro → `g:each` example → 
plugin-discovery paragraph → YAML, and updated the validation sentence to 
mention the new ISO-country check.



-- 
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