From dd1d46fac59b35180ca048f4fc923a54ecb3cc79 Mon Sep 17 00:00:00 2001 From: "Shane F. Carr" Date: Fri, 4 Dec 2026 01:23:33 -0800 Subject: [PATCH] =?UTF-8?q?CLDR-19944=20Materialize=20root=20intervalForma?= =?UTF-8?q?tItem=20=E2=86=91=E2=86=91=E2=86=91=20in=20production=20data=20?= =?UTF-8?q?and=20exclude=20root=20fallback=20in=20JSON?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per UTS #35 Part 4 Step 1, intervalFormatItem entries do not inherit from root for non-root locales. Previously: - GenerateProductionData stripped explicitly vetted ↑↑↑ (INHERITANCE_MARKER) intervalFormatItem entries whose Bailey value came from root, making them indistinguishable from absent (unvetted) paths in production XML and ICU. - Ldml2JsonConverter (resolved mode) inherited absent intervalFormatItem entries from root into non-root CLDR JSON bundles. Changes: - GenerateProductionData: materialize explicit ↑↑↑ intervalFormatItem entries whose Bailey value comes from root (preserving original non-distinguishing attributes such as draft), with parent-locale and lateral-calendar-alias deduplication, draft-precedence checks, and descendant anti-shadowing. - LdmlConvertRules / Ldml2JsonConverter / VerifyJson: exclude root-sourced intervalFormatItem paths for non-root locales in resolved mode using getSourceLocaleIdExtended(path, null, false) so resolved JSON matches what vetters approved and is identical on raw and production XML. - Add unit tests in GenerateProductionDataTest and Ldml2JsonConverterTest. Co-authored-by: Gemini <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../unicode/cldr/json/Ldml2JsonConverter.java | 21 + .../unicode/cldr/json/LdmlConvertRules.java | 5 + .../org/unicode/cldr/json/VerifyJson.java | 1 + .../cldr/tool/GenerateProductionData.java | 328 +++++++++- .../cldr/json/Ldml2JsonConverterTest.java | 475 ++++++++++++++ .../cldr/tool/GenerateProductionDataTest.java | 608 ++++++++++++++++++ 6 files changed, 1434 insertions(+), 4 deletions(-) create mode 100644 tools/cldr-code/src/test/java/org/unicode/cldr/json/Ldml2JsonConverterTest.java create mode 100644 tools/cldr-code/src/test/java/org/unicode/cldr/tool/GenerateProductionDataTest.java diff --git a/tools/cldr-code/src/main/java/org/unicode/cldr/json/Ldml2JsonConverter.java b/tools/cldr-code/src/main/java/org/unicode/cldr/json/Ldml2JsonConverter.java index fbb4c175abe..72b6d56c92f 100644 --- a/tools/cldr-code/src/main/java/org/unicode/cldr/json/Ldml2JsonConverter.java +++ b/tools/cldr-code/src/main/java/org/unicode/cldr/json/Ldml2JsonConverter.java @@ -584,6 +584,24 @@ public static boolean isFallbackValue(CLDRFile file, String path) { status.pathWhereFound.equals(GlossonymConstructor.PSEUDO_PATH); } + /** + * Per UTS #35 Part 4, {@code intervalFormatItem} elements do not inherit from {@code root} for + * non-root locales. Uses {@code skipInheritanceMarker = false} so that an explicit {@code ↑↑↑} + * vetted in a non-root locale is treated as sourced from that locale rather than {@code root}. + */ + public static boolean isExcludedRootInheritance(CLDRFile file, String path) { + if (!file.isResolved() + || XMLSource.ROOT_ID.equals(file.getLocaleID()) + || !path.contains("/intervalFormatItem[")) { + return false; + } + if (!LdmlConvertRules.INTERVAL_FORMAT_ITEM_PATTERN.matcher(path).matches()) { + return false; + } + return XMLSource.ROOT_ID.equals( + file.getSourceLocaleIdExtended(path, null, false /* skipInheritanceMarker */)); + } + /** Read all paths in the file, and assign each to a JSONSection. Return the map. */ private Map> mapPathsToSections( AtomicInteger readCount, @@ -615,6 +633,9 @@ private Map> mapPathsToSections( if (!includeRedundant && isFallbackValue(file, path)) { continue; } + if (isExcludedRootInheritance(file, path)) { + continue; + } // now get the fullpath and value String fullPath = file.getFullXPath(path); diff --git a/tools/cldr-code/src/main/java/org/unicode/cldr/json/LdmlConvertRules.java b/tools/cldr-code/src/main/java/org/unicode/cldr/json/LdmlConvertRules.java index 233fc9d30b0..0ba9552c478 100644 --- a/tools/cldr-code/src/main/java/org/unicode/cldr/json/LdmlConvertRules.java +++ b/tools/cldr-code/src/main/java/org/unicode/cldr/json/LdmlConvertRules.java @@ -446,6 +446,11 @@ public static boolean attrValueAsArraySet(final String nodeName, final String ke */ public static final Pattern VERSION_PATTERN = Pattern.compile("//ldml/identity/version.*"); + /** Interval format items do not inherit from root for non-root locales (UTS #35 Part 4). */ + public static final Pattern INTERVAL_FORMAT_ITEM_PATTERN = + Pattern.compile( + "//ldml/dates/calendars/calendar\\[@type=\"[^\"]+\"\\](?:\\[[^\\]]+\\])*/dateTimeFormats/intervalFormats(?:\\[[^\\]]+\\])*/intervalFormatItem\\[[^\\]]+\\](?:\\[[^\\]]+\\])*/greatestDifference(?:\\[[^\\]]+\\])+"); + /** A simple class to hold the specification of a path transformation. */ public static class PathTransformSpec { diff --git a/tools/cldr-code/src/main/java/org/unicode/cldr/json/VerifyJson.java b/tools/cldr-code/src/main/java/org/unicode/cldr/json/VerifyJson.java index d985705cdd5..ec04321df85 100644 --- a/tools/cldr-code/src/main/java/org/unicode/cldr/json/VerifyJson.java +++ b/tools/cldr-code/src/main/java/org/unicode/cldr/json/VerifyJson.java @@ -316,6 +316,7 @@ private void processMainLocale(CLDRLocale l) throws Throwable { if (xpath.endsWith("/alias")) continue; if (Ldml2JsonConverter.isFallbackValue(f, xpath)) continue; + if (Ldml2JsonConverter.isExcludedRootInheritance(f, xpath)) continue; final String v = f.getStringValue(xpath); // Handle the no inheritance marker. diff --git a/tools/cldr-code/src/main/java/org/unicode/cldr/tool/GenerateProductionData.java b/tools/cldr-code/src/main/java/org/unicode/cldr/tool/GenerateProductionData.java index d145a1a9d62..476effdc1fd 100644 --- a/tools/cldr-code/src/main/java/org/unicode/cldr/tool/GenerateProductionData.java +++ b/tools/cldr-code/src/main/java/org/unicode/cldr/tool/GenerateProductionData.java @@ -51,6 +51,7 @@ import org.unicode.cldr.util.InternalCldrException; import org.unicode.cldr.util.Level; import org.unicode.cldr.util.LocaleIDParser; +import org.unicode.cldr.util.LocaleInheritanceInfo; import org.unicode.cldr.util.LocaleNames; import org.unicode.cldr.util.LogicalGrouping; import org.unicode.cldr.util.ProgressTracker; @@ -168,9 +169,8 @@ public static void main(String[] args) throws IOException { VERBOSE = MyOptions.verbose.option.doesOccur(); DEBUG = MyOptions.Debug.option.doesOccur(); String fileMatch = MyOptions.fileMatch.option.getValue(); - if (fileMatch != null) { - FILE_MATCH = Pattern.compile(fileMatch).matcher(""); - } + FILE_MATCH = (fileMatch != null) ? Pattern.compile(fileMatch).matcher("") : null; + skippedPreBasicLocales.clear(); // controls for minimization ADD_LOGICAL_GROUPS = MyOptions.logicalGroups.option.getBooleanValue(); @@ -509,6 +509,7 @@ private static boolean copyOneFileAndReturnIsEmpty( Set toRemove = new TreeSet<>(); // TreeSet just makes debugging easier Set toRetain = new TreeSet<>(); Set toRetainSpecial = new TreeSet<>(); + Map toMaterialize = new TreeMap<>(); Output pathWhereFound = new Output<>(); Output localeWhereFound = new Output<>(); RedundantPluralChecker redundantPlurals = @@ -521,15 +522,21 @@ private static boolean copyOneFileAndReturnIsEmpty( ImmutableSortedSet.copyOf(cldrFileUnresolved); // sort for debugging boolean gotOne = false; + boolean hasIntervalFormatItem = false; for (String xpath : sortedPaths) { + if (isIntervalFormatItemPath(xpath)) { + hasIntervalFormatItem = true; + } if (!pathShouldBeSkipped( localeId, xpath, + factory, cldrFileUnresolved, cldrFileResolved, toRemove, toRetain, toRetainSpecial, + toMaterialize, specialPathsAreRequired, pathWhereFound, localeWhereFound, @@ -537,6 +544,16 @@ private static boolean copyOneFileAndReturnIsEmpty( gotOne = true; // past the gauntlet } } + if (hasIntervalFormatItem + && addAntiShadowingAliasOverrides( + localeId, + factory, + cldrFileUnresolved, + cldrFileResolved, + toRemove, + toMaterialize)) { + gotOne = true; + } if (specialPathsAreRequired) { addSpecialPathsIfMissing(toRetainSpecial); } @@ -550,6 +567,7 @@ private static boolean copyOneFileAndReturnIsEmpty( toRemove, toRetain, toRetainSpecial, + toMaterialize, cldrFileResolved, redundantPlurals, pw); @@ -572,11 +590,13 @@ private static boolean copyOneFileAndReturnIsEmpty( private static boolean pathShouldBeSkipped( String localeId, String xpath, + Factory factory, CLDRFile cldrFileUnresolved, CLDRFile cldrFileResolved, Set toRemove, Set toRetain, Set toRetainSpecial, + Map toMaterialize, boolean specialPathsAreRequired, Output pathWhereFound, Output localeWhereFound, @@ -585,7 +605,22 @@ private static boolean pathShouldBeSkipped( return true; } String value = cldrFileUnresolved.getStringValue(xpath); - if (value == null || CldrUtility.INHERITANCE_MARKER.equals(value)) { + if (value == null) { + toRemove.add(xpath); + return true; + } + if (CldrUtility.INHERITANCE_MARKER.equals(value)) { + if (shouldMaterializeRootIntervalFormat( + localeId, + xpath, + factory, + cldrFileUnresolved, + cldrFileResolved, + pathWhereFound, + localeWhereFound, + toMaterialize)) { + return false; + } toRemove.add(xpath); return true; } @@ -666,6 +701,7 @@ private static int writeFileCountPaths( Set toRemove, Set toRetain, Set toRetainSpecial, + Map toMaterialize, CLDRFile cldrFileResolved, RedundantPluralChecker redundantPlurals, PrintWriter pw) { @@ -680,6 +716,7 @@ private static int writeFileCountPaths( showIfNonZero(localeId, "removing", toRemove); showIfNonZero(localeId, "retaining", toRetain); showIfNonZero(localeId, "retaining for special paths", toRetainSpecial); + showIfNonZero(localeId, "materializing", toMaterialize.keySet()); } if (CONSTRAINED_RESTORATION) { toRetain.retainAll(toRemove); // only add paths that were there already @@ -733,6 +770,19 @@ private static int writeFileCountPaths( } } + // Materialize explicitly vetted ↑↑↑ intervalFormatItem paths whose Bailey value comes + // from root (and any descendant anti-shadowing overrides), preserving full XPath attributes + // such as draft. + for (Entry entry : toMaterialize.entrySet()) { + String fullPath = entry.getKey(); + String value = entry.getValue(); + if (DEBUG) { + System.out.println( + "Materializing root intervalFormatItem: ⇒ «" + value + "»\t" + fullPath); + } + outCldrFile.add(fullPath, value); + } + // double-check results int count = 0; for (String xpath : outCldrFile) { @@ -1069,6 +1119,276 @@ private static boolean isDateTimePath(String xpath) { && xpath.contains("FormatLength[@type="); } + private static final Pattern INTERVAL_FORMAT_ITEM_PATTERN = + Pattern.compile( + "//ldml/dates/calendars/calendar\\[@type=\"[^\"]+\"\\](?:\\[[^\\]]+\\])*/dateTimeFormats/intervalFormats(?:\\[[^\\]]+\\])*/intervalFormatItem\\[[^\\]]+\\](?:\\[[^\\]]+\\])*/greatestDifference(?:\\[[^\\]]+\\])+"); + + private static boolean isIntervalFormatItemPath(String xpath) { + return xpath.contains("/intervalFormatItem[") + && INTERVAL_FORMAT_ITEM_PATTERN.matcher(xpath).matches(); + } + + /** + * Checks whether an explicit {@code ↑↑↑} ({@link CldrUtility#INHERITANCE_MARKER}) on an {@code + * intervalFormatItem} path should be materialized to its root Bailey value in production XML. + * + *

Per UTS #35 Part 4, {@code intervalFormatItem} entries do not inherit from {@code root} + * for non-root locales, so stripping an explicitly vetted {@code ↑↑↑} whose Bailey value comes + * from {@code root} would make it indistinguishable from an absent (unvetted) path. To avoid + * redundant copies across child locales and aliased calendars, materialization is skipped when + * a non-root ancestor or lateral alias target in the inheritance chain already provides a + * surviving value (explicit or {@code ↑↑↑}) with at least the same draft status and coverage + * inclusion. + */ + private static boolean shouldMaterializeRootIntervalFormat( + String localeId, + String xpath, + Factory factory, + CLDRFile cldrFileUnresolved, + CLDRFile cldrFileResolved, + Output pathWhereFound, + Output localeWhereFound, + Map toMaterialize) { + String bailey = + getMaterializedRootIntervalFormatValue( + localeId, + xpath, + factory, + cldrFileUnresolved, + cldrFileResolved, + pathWhereFound, + localeWhereFound); + if (bailey == null) { + return false; + } + toMaterialize.put(cldrFileUnresolved.getFullXPath(xpath), bailey); + return true; + } + + private static String getMaterializedRootIntervalFormatValue( + String localeId, + String xpath, + Factory factory, + CLDRFile cldrFileUnresolved, + CLDRFile cldrFileResolved, + Output pathWhereFound, + Output localeWhereFound) { + if (!ADD_ROOT || localeId.equals(LocaleNames.ROOT) || !isIntervalFormatItemPath(xpath)) { + return null; + } + if (!INCLUDE_COMPREHENSIVE + && SDI.getCoverageLevel(xpath, localeId) == Level.COMPREHENSIVE) { + return null; + } + String bailey = cldrFileResolved.getBaileyValue(xpath, pathWhereFound, localeWhereFound); + if (bailey == null + || CldrUtility.INHERITANCE_MARKER.equals(bailey) + || CldrUtility.NO_INHERITANCE_MARKER.equals(bailey)) { + return null; + } + CLDRFile.DraftStatus currentDraft = + CLDRFile.DraftStatus.forXpath(cldrFileUnresolved.getFullXPath(xpath)); + if (Objects.equals(XMLSource.ROOT_ID, localeWhereFound.value)) { + if (isCoveredByNonRootInheritanceMarker( + localeId, xpath, currentDraft, factory, cldrFileUnresolved, cldrFileResolved)) { + return null; + } + return bailey; + } + // Bailey came from a non-root explicit value: if that cover survives production filtering + // at >= currentDraft, no materialization is needed. + String coverLocale = localeWhereFound.value; + String coverPath = pathWhereFound.value; + if (coverLocale == null + || coverPath == null + || XMLSource.CODE_FALLBACK_ID.equals(coverLocale) + || isSurvivingCover( + coverLocale, coverPath, currentDraft, factory, cldrFileUnresolved)) { + return null; + } + // The explicit cover is weaker-draft (or dropped by pre-basic/comprehensive filtering). + // Resolve at currentDraft to check whether the entry falls back to root at that draft + // threshold without altering unconfirmed resolution. + CLDRFile atCurrentDraft = factory.make(localeId, true, currentDraft); + Output draftPathWhereFound = new Output<>(); + Output draftLocaleWhereFound = new Output<>(); + String draftBailey = + atCurrentDraft.getBaileyValue(xpath, draftPathWhereFound, draftLocaleWhereFound); + if (draftBailey == null + || CldrUtility.INHERITANCE_MARKER.equals(draftBailey) + || CldrUtility.NO_INHERITANCE_MARKER.equals(draftBailey) + || !Objects.equals(XMLSource.ROOT_ID, draftLocaleWhereFound.value) + || !bailey.equals(draftBailey)) { + return null; + } + if (isCoveredByNonRootInheritanceMarker( + localeId, xpath, currentDraft, factory, cldrFileUnresolved, atCurrentDraft)) { + return null; + } + pathWhereFound.value = draftPathWhereFound.value; + localeWhereFound.value = draftLocaleWhereFound.value; + return draftBailey; + } + + private static boolean isSurvivingCover( + String coverLocale, + String coverPath, + CLDRFile.DraftStatus currentDraft, + Factory factory, + CLDRFile cldrFileUnresolved) { + if (!KEEP_PRE_BASIC && localeIsPreBasicNonIcu(coverLocale)) { + return false; + } + if (!INCLUDE_COMPREHENSIVE + && SDI.getCoverageLevel(coverPath, coverLocale) == Level.COMPREHENSIVE) { + return false; + } + CLDRFile coverUnresolved = + cldrFileUnresolved.getLocaleID().equals(coverLocale) + ? cldrFileUnresolved + : factory.make(coverLocale, false); + if (coverUnresolved.getStringValue(coverPath) == null) { + return false; + } + CLDRFile.DraftStatus coverDraft = + CLDRFile.DraftStatus.forXpath(coverUnresolved.getFullXPath(coverPath)); + return coverDraft.compareTo(currentDraft) >= 0; + } + + private static boolean isCoveredByNonRootInheritanceMarker( + String localeId, + String xpath, + CLDRFile.DraftStatus currentDraft, + Factory factory, + CLDRFile cldrFileUnresolved, + CLDRFile cldrFileResolved) { + List inheritanceChain = new ArrayList<>(); + cldrFileResolved.getSourceLocaleIdExtended( + xpath, null, true /* skipInheritanceMarker */, inheritanceChain); + for (LocaleInheritanceInfo info : inheritanceChain) { + LocaleInheritanceInfo.Reason reason = info.getReason(); + if (reason == LocaleInheritanceInfo.Reason.none + || reason == LocaleInheritanceInfo.Reason.alias) { + continue; + } + if (reason != LocaleInheritanceInfo.Reason.inheritanceMarker) { + break; + } + String coverLocale = info.getLocale(); + String coverPath = info.getPath(); + if (coverLocale == null + || coverPath == null + || XMLSource.ROOT_ID.equals(coverLocale) + || !isIntervalFormatItemPath(coverPath) + || (localeId.equals(coverLocale) && xpath.equals(coverPath))) { + continue; + } + CLDRFile coverUnresolved = + localeId.equals(coverLocale) + ? cldrFileUnresolved + : factory.make(coverLocale, false); + if (!CldrUtility.INHERITANCE_MARKER.equals(coverUnresolved.getStringValue(coverPath))) { + continue; + } + if (isSurvivingCover( + coverLocale, coverPath, currentDraft, factory, cldrFileUnresolved)) { + return true; + } + } + return false; + } + + /** + * Prevents a materialized {@code intervalFormatItem} on an aliased calendar in an ancestor + * locale (e.g., {@code buddhist} in {@code nl}) from shadowing a child locale's override on the + * alias target (e.g., {@code generic} in {@code nl_BE}). Because vertical locale inheritance + * precedes lateral alias resolution, materializing the aliased path in the parent would block + * the child from reaching its own alias target unless the child's resolved override is also + * emitted on the aliased path. + */ + private static boolean addAntiShadowingAliasOverrides( + String localeId, + Factory factory, + CLDRFile cldrFileUnresolved, + CLDRFile cldrFileResolved, + Set toRemove, + Map toMaterialize) { + if (!ADD_ROOT || localeId.equals(LocaleNames.ROOT)) { + return false; + } + boolean addedAny = false; + Set available = factory.getAvailable(); + Output ancPathWhereFound = new Output<>(); + Output ancLocaleWhereFound = new Output<>(); + CLDRFile.Status status = new CLDRFile.Status(); + for (String ancestor = LocaleIDParser.getParent(localeId); + ancestor != null && !XMLSource.ROOT_ID.equals(ancestor); + ancestor = LocaleIDParser.getParent(ancestor)) { + if (!available.contains(ancestor) + || (!KEEP_PRE_BASIC && localeIsPreBasicNonIcu(ancestor))) { + continue; + } + CLDRFile ancUnresolved = factory.make(ancestor, false); + CLDRFile ancResolved = factory.make(ancestor, true); + for (String ancPath : ancUnresolved) { + if (!isIntervalFormatItemPath(ancPath) + || !CldrUtility.INHERITANCE_MARKER.equals( + ancUnresolved.getStringValue(ancPath))) { + continue; + } + if (!INCLUDE_COMPREHENSIVE + && SDI.getCoverageLevel(ancPath, localeId) == Level.COMPREHENSIVE) { + continue; + } + String ancMaterialized = + getMaterializedRootIntervalFormatValue( + ancestor, + ancPath, + factory, + ancUnresolved, + ancResolved, + ancPathWhereFound, + ancLocaleWhereFound); + if (ancMaterialized == null || ancPath.equals(ancPathWhereFound.value)) { + continue; + } + // Ancestor materializes an aliased intervalFormatItem path. Check whether this + // child resolves ancPath to a different value via its own alias target. + String existing = cldrFileUnresolved.getStringValue(ancPath); + if (existing != null + && !CldrUtility.INHERITANCE_MARKER.equals(existing) + && !toRemove.contains(ancPath)) { + continue; + } + String srcLocale = cldrFileResolved.getSourceLocaleID(ancPath, status); + if (!localeId.equals(srcLocale) + || status.pathWhereFound == null + || ancPath.equals(status.pathWhereFound) + || toRemove.contains(status.pathWhereFound)) { + continue; + } + String resolvedVal = cldrFileResolved.getStringValue(ancPath); + if (resolvedVal == null + || CldrUtility.INHERITANCE_MARKER.equals(resolvedVal) + || CldrUtility.NO_INHERITANCE_MARKER.equals(resolvedVal) + || resolvedVal.equals(ancMaterialized)) { + continue; + } + CLDRFile.DraftStatus overrideDraft = + CLDRFile.DraftStatus.forXpath( + cldrFileUnresolved.getFullXPath(status.pathWhereFound)); + if (existing != null) { + // Ensure any pre-existing ↑↑↑ entry (and its stale fullPath/draft) is removed + // before toMaterialize writes the clean override path. + toRemove.add(ancPath); + } + toMaterialize.put(ancPath + overrideDraft.asXpath(), resolvedVal); + addedAny = true; + } + } + return addedAny; + } + /** * generate full dateTimePaths from any element * //ldml/dates/calendars/calendar[@type="gregorian"]/dateFormats/dateFormatLength[@type=".*"]/dateFormat[@type="standard"]/pattern[@type="standard"] diff --git a/tools/cldr-code/src/test/java/org/unicode/cldr/json/Ldml2JsonConverterTest.java b/tools/cldr-code/src/test/java/org/unicode/cldr/json/Ldml2JsonConverterTest.java new file mode 100644 index 00000000000..b689bb7343f --- /dev/null +++ b/tools/cldr-code/src/test/java/org/unicode/cldr/json/Ldml2JsonConverterTest.java @@ -0,0 +1,475 @@ +package org.unicode.cldr.json; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.unicode.cldr.tool.GenerateProductionData; +import org.unicode.cldr.util.CLDRFile; +import org.unicode.cldr.util.CLDRFile.DraftStatus; +import org.unicode.cldr.util.CLDRPaths; +import org.unicode.cldr.util.DtdType; +import org.unicode.cldr.util.Factory; + +class Ldml2JsonConverterTest { + + private static final String GREGORIAN_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + private static final String GREGORIAN_Y_Y_VARIANT = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"][@alt=\"variant\"]"; + private static final String GREGORIAN_FALLBACK = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatFallback"; + private static final String CHINESE_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + private static final String CHINESE_BH_H = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"Bh\"]/greatestDifference[@id=\"h\"]"; + private static final String CHINESE_FALLBACK = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatFallback"; + private static final String CHINESE_RANGE_MIXED = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatRanges/intervalFormatRange[@type=\"mixed\"]"; + private static final String DANGI_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"dangi\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + private static final String BUDDHIST_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"buddhist\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + private static final String BUDDHIST_H_H = + "//ldml/dates/calendars/calendar[@type=\"buddhist\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"H\"]/greatestDifference[@id=\"H\"]"; + private static final String ISLAMIC_CIVIL_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"islamic-civil\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + + private static Path createSkeletonCommonDir(Path rootDir) throws IOException { + Path commonDir = rootDir.resolve("common"); + for (DtdType type : DtdType.values()) { + for (String dir : type.directories) { + Files.createDirectories(commonDir.resolve(dir)); + } + } + for (String dir : List.of("dtd", "pathCoverage", "properties", "testData", "uca")) { + Files.createDirectories(commonDir.resolve(dir)); + } + copyDirFiles(Path.of(CLDRPaths.COMMON_DIRECTORY, "dtd"), commonDir.resolve("dtd")); + return commonDir; + } + + private static void copyDirFiles(Path srcDir, Path dstDir) throws IOException { + Files.createDirectories(dstDir); + try (var stream = Files.walk(srcDir)) { + for (Path src : stream.toList()) { + Path target = dstDir.resolve(srcDir.relativize(src)); + if (Files.isDirectory(src)) { + Files.createDirectories(target); + } else if (Files.isRegularFile(src)) { + Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING); + } + } + } + } + + private static void copySupportDirsForJson(Path commonDir) throws IOException { + for (String subDir : List.of("validity", "supplemental", "bcp47")) { + copyDirFiles(Path.of(CLDRPaths.COMMON_DIRECTORY, subDir), commonDir.resolve(subDir)); + } + } + + private static void writeLdml( + Path mainDir, String localeId, String identityXml, String calendarsXml) + throws IOException { + String xml = + """ + + + + + + %s + + + + %s + + + + """ + .formatted(identityXml, calendarsXml); + Files.writeString(mainDir.resolve(localeId + ".xml"), xml, StandardCharsets.UTF_8); + } + + @Test + void testIsExcludedRootInheritanceSynthetic(@TempDir Path tempDir) throws IOException { + Path commonDir = createSkeletonCommonDir(tempDir); + Path mainDir = commonDir.resolve("main"); + Files.copy(Path.of(CLDRPaths.MAIN_DIRECTORY, "root.xml"), mainDir.resolve("root.xml")); + + writeLdml( + mainDir, + "fr", + "", + """ + + + + + ↑↑↑ + + + + + + + + + y – y G + + + + + + + + + ↑↑↑ + ↑↑↑ + + + + + """); + writeLdml(mainDir, "fr_CA", "", ""); + writeLdml(mainDir, "agq", "", ""); + writeLdml( + mainDir, + "zh", + "", + """ + + + + + U年–U年 + + + + + """); + + Factory factory = Factory.make(mainDir.toString(), ".*"); + + // root keeps its own intervalFormatItem entries. + CLDRFile root = factory.make("root", true, DraftStatus.contributed); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(root, GREGORIAN_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(root, CHINESE_Y_Y)); + + // Unresolved CLDRFile never excludes paths. + CLDRFile frUnresolved = factory.make("fr", false, DraftStatus.contributed); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(frUnresolved, CHINESE_Y_Y)); + + // fr: absent chinese/dangi items and unconfirmed-only chinese Bh/h are excluded; + // intervalFormatFallback, intervalFormatRanges, explicit ↑↑↑ gregorian y/y (and alt), + // and aliased buddhist/islamic-civil items from fr generic are kept. + CLDRFile fr = factory.make("fr", true, DraftStatus.contributed); + assertTrue(Ldml2JsonConverter.isExcludedRootInheritance(fr, CHINESE_Y_Y)); + assertTrue(Ldml2JsonConverter.isExcludedRootInheritance(fr, CHINESE_BH_H)); + assertTrue(Ldml2JsonConverter.isExcludedRootInheritance(fr, DANGI_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, CHINESE_FALLBACK)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, CHINESE_RANGE_MIXED)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, GREGORIAN_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, GREGORIAN_Y_Y_VARIANT)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, BUDDHIST_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(fr, ISLAMIC_CIVIL_Y_Y)); + + // fr_CA: inherits gregorian y/y from non-root parent fr. + CLDRFile frCa = factory.make("fr_CA", true, DraftStatus.contributed); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(frCa, GREGORIAN_Y_Y)); + assertTrue(Ldml2JsonConverter.isExcludedRootInheritance(frCa, CHINESE_Y_Y)); + + // agq: unvetted gregorian y/y is excluded; intervalFormatFallback is kept. + CLDRFile agq = factory.make("agq", true, DraftStatus.contributed); + assertTrue(Ldml2JsonConverter.isExcludedRootInheritance(agq, GREGORIAN_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(agq, GREGORIAN_FALLBACK)); + + // zh: has chinese intervalFormatItems, and dangi aliases to zh chinese. + CLDRFile zh = factory.make("zh", true, DraftStatus.contributed); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(zh, CHINESE_Y_Y)); + assertFalse(Ldml2JsonConverter.isExcludedRootInheritance(zh, DANGI_Y_Y)); + } + + @Test + void testJsonOutputSyntheticRawAndProductionParity(@TempDir Path tempDir) throws Exception { + Path rawCommon = createSkeletonCommonDir(tempDir.resolve("raw")); + Path rawMain = rawCommon.resolve("main"); + Files.copy(Path.of(CLDRPaths.MAIN_DIRECTORY, "root.xml"), rawMain.resolve("root.xml")); + + // Synthetic locales exercising approved ↑↑↑, child dedup, unconfirmed ↑↑↑, absent items, + // lateral alias, and descendant anti-shadowing (nl buddhist vs nl_BE generic). + writeLdml( + rawMain, + "de", + "", + """ + + + + + ↑↑↑ + + + + + """); + writeLdml( + rawMain, + "de_AT", + "", + """ + + + + + ↑↑↑ + + + + + """); + writeLdml( + rawMain, + "fr", + "", + """ + + + + + ↑↑↑ + + + + + + + + + y – y G + + + + + """); + writeLdml( + rawMain, + "nl", + "", + """ + + + + + ↑↑↑ + + + + + + + + + ↑↑↑ + + + + + """); + writeLdml( + rawMain, + "nl_BE", + "", + """ + + + + + H–H + + + + + """); + writeLdml(rawMain, "agq", "", ""); + + Path prodCommon = tempDir.resolve("prod").resolve("common"); + GenerateProductionData.main( + new String[] {"-s", rawCommon.toString(), "-d", prodCommon.toString()}); + + copySupportDirsForJson(rawCommon); + copySupportDirsForJson(prodCommon); + + Path rawJsonDir = tempDir.resolve("json-raw"); + Path prodJsonDir = tempDir.resolve("json-prod"); + runJsonConverter(rawCommon, rawJsonDir); + runJsonConverter(prodCommon, prodJsonDir); + + for (String bcp47Tag : List.of("und", "de", "de-AT", "fr", "nl", "nl-BE", "agq")) { + for (String cal : + List.of( + "gregorian", + "generic", + "buddhist", + "chinese", + "dangi", + "islamic-civil")) { + assertEquals( + readIntervalFormats(rawJsonDir, bcp47Tag, cal), + readIntervalFormats(prodJsonDir, bcp47Tag, cal), + "JSON intervalFormats differ between raw and production for " + + bcp47Tag + + " / " + + cal); + } + } + + // Exact assertions on synthetic fixtures. + assertNotNull(readIntervalFormats(prodJsonDir, "und", "chinese").get("y")); + + JsonObject frChinese = readIntervalFormats(prodJsonDir, "fr", "chinese"); + assertNotNull(frChinese.get("intervalFormatFallback")); + assertNull(frChinese.get("y")); + assertNull(frChinese.get("Bh")); + + assertNull(readIntervalFormats(prodJsonDir, "fr", "dangi").get("y")); + assertNotNull(readIntervalFormats(prodJsonDir, "fr", "buddhist").get("y")); + assertNotNull(readIntervalFormats(prodJsonDir, "fr", "islamic-civil").get("y")); + + assertEquals( + "y–y", + readIntervalFormats(prodJsonDir, "de", "gregorian") + .getAsJsonObject("y") + .get("y") + .getAsString()); + assertEquals( + "y–y", + readIntervalFormats(prodJsonDir, "de-AT", "gregorian") + .getAsJsonObject("y") + .get("y") + .getAsString()); + + // nl buddhist keeps approved root generic H/H, while nl generic (unconfirmed) omits it; + // nl-BE buddhist keeps its generic override "H–H" (not shadowed by nl). + assertNull(readIntervalFormats(prodJsonDir, "nl", "generic").get("H")); + assertNotNull(readIntervalFormats(prodJsonDir, "nl", "buddhist").get("H")); + assertEquals( + "H–H", + readIntervalFormats(prodJsonDir, "nl-BE", "buddhist") + .getAsJsonObject("H") + .get("H") + .getAsString()); + + JsonObject agqGregorian = readIntervalFormats(prodJsonDir, "agq", "gregorian"); + assertNotNull(agqGregorian.get("intervalFormatFallback")); + assertNull(agqGregorian.get("y")); + } + + @Test + void testJsonOutputMatchesBetweenRawAndProductionRealLocales(@TempDir Path tempDir) + throws Exception { + Path rawCommon = createSkeletonCommonDir(tempDir.resolve("raw")); + String[] locales = {"root", "de", "es", "es_419", "fr", "nl", "agq"}; + Path realMainDir = Path.of(CLDRPaths.MAIN_DIRECTORY); + for (String locale : locales) { + Files.copy( + realMainDir.resolve(locale + ".xml"), + rawCommon.resolve("main").resolve(locale + ".xml")); + } + + Path prodCommon = tempDir.resolve("prod").resolve("common"); + GenerateProductionData.main( + new String[] {"-s", rawCommon.toString(), "-d", prodCommon.toString()}); + + copySupportDirsForJson(rawCommon); + copySupportDirsForJson(prodCommon); + + Path rawJsonDir = tempDir.resolve("json-raw"); + Path prodJsonDir = tempDir.resolve("json-prod"); + runJsonConverter(rawCommon, rawJsonDir); + runJsonConverter(prodCommon, prodJsonDir); + + // Data-independent invariant: raw and production XML produce identical intervalFormats JSON + // across all locales and calendars. + for (String bcp47Tag : List.of("und", "de", "es", "es-419", "fr", "nl", "agq")) { + for (String cal : + List.of( + "gregorian", + "generic", + "buddhist", + "chinese", + "dangi", + "islamic-civil")) { + assertEquals( + readIntervalFormats(rawJsonDir, bcp47Tag, cal), + readIntervalFormats(prodJsonDir, bcp47Tag, cal), + "JSON intervalFormats differ between raw and production for " + + bcp47Tag + + " / " + + cal); + } + } + } + + private static void runJsonConverter(Path commonDir, Path outDir) throws Exception { + Ldml2JsonConverter converter = + new Ldml2JsonConverter( + commonDir + "/", + outDir.toString(), + "main", + false, + true, + "optional", + ".*", + true, + null, + "0.0.0", + true, + true, + false, + false, + true, + Optional.empty()); + converter.processDirectory("main", DraftStatus.contributed); + } + + private static JsonObject readIntervalFormats(Path jsonRoot, String localeTag, String cal) + throws IOException { + String pkg = + switch (cal) { + case "gregorian", "generic" -> "cldr-dates-full"; + case "islamic-civil" -> "cldr-cal-islamic-full"; + default -> "cldr-cal-" + cal + "-full"; + }; + Path file = + jsonRoot.resolve(pkg) + .resolve("main") + .resolve(localeTag) + .resolve("ca-" + cal + ".json"); + JsonElement parsed = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + return parsed.getAsJsonObject() + .getAsJsonObject("main") + .getAsJsonObject(localeTag) + .getAsJsonObject("dates") + .getAsJsonObject("calendars") + .getAsJsonObject(cal) + .getAsJsonObject("dateTimeFormats") + .getAsJsonObject("intervalFormats"); + } +} diff --git a/tools/cldr-code/src/test/java/org/unicode/cldr/tool/GenerateProductionDataTest.java b/tools/cldr-code/src/test/java/org/unicode/cldr/tool/GenerateProductionDataTest.java new file mode 100644 index 00000000000..8d08dfcf71a --- /dev/null +++ b/tools/cldr-code/src/test/java/org/unicode/cldr/tool/GenerateProductionDataTest.java @@ -0,0 +1,608 @@ +package org.unicode.cldr.tool; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.unicode.cldr.util.CLDRFile; +import org.unicode.cldr.util.CLDRFile.DraftStatus; +import org.unicode.cldr.util.CLDRPaths; +import org.unicode.cldr.util.CldrUtility; +import org.unicode.cldr.util.DtdType; +import org.unicode.cldr.util.Factory; +import org.unicode.cldr.util.XMLSource; + +class GenerateProductionDataTest { + + private static final String GREGORIAN_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + private static final String GREGORIAN_Y_Y_VARIANT = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"][@alt=\"variant\"]"; + private static final String GREGORIAN_D_D = + "//ldml/dates/calendars/calendar[@type=\"gregorian\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"d\"]/greatestDifference[@id=\"d\"]"; + private static final String GENERIC_H_H = + "//ldml/dates/calendars/calendar[@type=\"generic\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"H\"]/greatestDifference[@id=\"H\"]"; + private static final String GENERIC_D_D = + "//ldml/dates/calendars/calendar[@type=\"generic\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"d\"]/greatestDifference[@id=\"d\"]"; + private static final String BUDDHIST_H_H = + "//ldml/dates/calendars/calendar[@type=\"buddhist\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"H\"]/greatestDifference[@id=\"H\"]"; + private static final String BUDDHIST_D_D = + "//ldml/dates/calendars/calendar[@type=\"buddhist\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"d\"]/greatestDifference[@id=\"d\"]"; + private static final String ISLAMIC_H_H = + "//ldml/dates/calendars/calendar[@type=\"islamic\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"H\"]/greatestDifference[@id=\"H\"]"; + private static final String ISLAMIC_CIVIL_H_H = + "//ldml/dates/calendars/calendar[@type=\"islamic-civil\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"H\"]/greatestDifference[@id=\"H\"]"; + private static final String CHINESE_BH_H = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"Bh\"]/greatestDifference[@id=\"h\"]"; + private static final String CHINESE_Y_Y = + "//ldml/dates/calendars/calendar[@type=\"chinese\"]/dateTimeFormats/intervalFormats/intervalFormatItem[@id=\"y\"]/greatestDifference[@id=\"y\"]"; + + private static Path createSkeletonCommonDir(Path rootDir) throws IOException { + Path commonDir = rootDir.resolve("common"); + for (DtdType type : DtdType.values()) { + for (String dir : type.directories) { + Files.createDirectories(commonDir.resolve(dir)); + } + } + for (String dir : List.of("dtd", "pathCoverage", "properties", "testData", "uca")) { + Files.createDirectories(commonDir.resolve(dir)); + } + Path realDtdDir = Path.of(CLDRPaths.COMMON_DIRECTORY, "dtd"); + try (var stream = Files.list(realDtdDir)) { + for (Path dtdFile : stream.toList()) { + if (Files.isRegularFile(dtdFile)) { + Files.copy(dtdFile, commonDir.resolve("dtd").resolve(dtdFile.getFileName())); + } + } + } + return commonDir; + } + + private static void copyRealMainLocales(Path destMainDir, String... locales) + throws IOException { + Path realMainDir = Path.of(CLDRPaths.MAIN_DIRECTORY); + for (String locale : locales) { + Files.copy(realMainDir.resolve(locale + ".xml"), destMainDir.resolve(locale + ".xml")); + } + } + + private static void writeLdml( + Path mainDir, String localeId, String identityXml, String calendarsXml) + throws IOException { + String xml = + """ + + + + + + %s + + + + %s + + + + """ + .formatted(identityXml, calendarsXml); + Files.writeString(mainDir.resolve(localeId + ".xml"), xml, StandardCharsets.UTF_8); + } + + @Test + void testMaterializationAndDeduplicationSynthetic(@TempDir Path tempDir) throws IOException { + Path srcCommon = createSkeletonCommonDir(tempDir.resolve("src")); + Path dstCommon = tempDir.resolve("dst").resolve("common"); + Path srcMain = srcCommon.resolve("main"); + copyRealMainLocales(srcMain, "root"); + + // es & es_419: both have approved ↑↑↑ on gregorian y/y -> es materializes, es_419 + // deduplicates. + writeLdml( + srcMain, + "es", + "", + """ + + + + + ↑↑↑ + + + + + """); + writeLdml( + srcMain, + "es_419", + "", + """ + + + + + ↑↑↑ + + + + + """); + + // nl: generic H/H (contributed) & d/d (approved) materialize with original draft; + // buddhist, islamic, and multi-hop islamic-civil H/H (contributed) deduplicate to generic. + writeLdml( + srcMain, + "nl", + "", + """ + + + + + ↑↑↑ + + + ↑↑↑ + + + + + + + + + ↑↑↑ + + + ↑↑↑ + + + + + + + + + ↑↑↑ + + + + + + + + + ↑↑↑ + + + + + """); + + // fr: chinese Bh/h has draft="unconfirmed" ↑↑↑ -> materialized with draft="unconfirmed"; + // chinese y/y is absent -> remains absent. + // Also tests parent ∅∅∅ (NO_INHERITANCE_MARKER) on gregorian d/d with child ↑↑↑. + writeLdml( + srcMain, + "fr", + "", + """ + + + + + ↑↑↑ + + + + + + + + + ∅∅∅ + + + y – y + + + + + """); + // fr_CA: gregorian d/d is ↑↑↑ over parent ∅∅∅ -> NOT materialized; + // gregorian y/y is approved ↑↑↑ over weaker-draft DIFFERENT parent "y – y" -> NOT + // materialized to root's "y–y" (would break unconfirmed resolution). + writeLdml( + srcMain, + "fr_CA", + "", + """ + + + + + ↑↑↑ + + + ↑↑↑ + + + + + """); + + // 3-level chain: en (approved ↑↑↑) -> en_001 (unconfirmed ↑↑↑) -> en_GB (approved ↑↑↑). + // en materializes; both en_001 and en_GB deduplicate against en! + writeLdml( + srcMain, + "en", + "", + """ + + + + + ↑↑↑ + + + + + """); + writeLdml( + srcMain, + "en_001", + "", + """ + + + + + ↑↑↑ + + + + + """); + writeLdml( + srcMain, + "en_GB", + "", + """ + + + + + ↑↑↑ + + + + + """); + // en_CA: alt="variant" with ↑↑↑ must NOT deduplicate across Reason.removedAttribute! + writeLdml( + srcMain, + "en_CA", + "", + """ + + + + + ↑↑↑ + + + + + """); + + // agq: no intervalFormatItem entries -> remains absent. + writeLdml(srcMain, "agq", "", ""); + + GenerateProductionData.main( + new String[] {"-s", srcCommon.toString(), "-d", dstCommon.toString()}); + + Factory dstFactory = Factory.make(dstCommon.resolve("main").toString(), ".*"); + CLDRFile rootFile = dstFactory.make("root", false); + String rootGregorianY = rootFile.getStringValue(GREGORIAN_Y_Y); + String rootGenericH = rootFile.getStringValue(GENERIC_H_H); + String rootGenericD = rootFile.getStringValue(GENERIC_D_D); + String rootChineseBhH = rootFile.getStringValue(CHINESE_BH_H); + + // es / es_419 + assertEquals(rootGregorianY, dstFactory.make("es", false).getStringValue(GREGORIAN_Y_Y)); + assertEquals( + DraftStatus.approved, + DraftStatus.forXpath(dstFactory.make("es", false).getFullXPath(GREGORIAN_Y_Y))); + assertNull(dstFactory.make("es_419", false).getStringValue(GREGORIAN_Y_Y)); + assertEquals("es", dstFactory.make("es_419", true).getSourceLocaleID(GREGORIAN_Y_Y, null)); + + // nl: generic materialized with draft preserved; buddhist/islamic/islamic-civil + // deduplicated. + CLDRFile nlUnresolved = dstFactory.make("nl", false); + CLDRFile nlResolved = dstFactory.make("nl", true); + assertEquals(rootGenericH, nlUnresolved.getStringValue(GENERIC_H_H)); + assertEquals( + DraftStatus.contributed, + DraftStatus.forXpath(nlUnresolved.getFullXPath(GENERIC_H_H))); + assertEquals(rootGenericD, nlUnresolved.getStringValue(GENERIC_D_D)); + assertEquals( + DraftStatus.approved, DraftStatus.forXpath(nlUnresolved.getFullXPath(GENERIC_D_D))); + assertNull(nlUnresolved.getStringValue(BUDDHIST_H_H)); + assertNull(nlUnresolved.getStringValue(BUDDHIST_D_D)); + assertNull(nlUnresolved.getStringValue(ISLAMIC_H_H)); + assertNull(nlUnresolved.getStringValue(ISLAMIC_CIVIL_H_H)); + assertEquals("nl", nlResolved.getSourceLocaleID(BUDDHIST_H_H, null)); + assertEquals("nl", nlResolved.getSourceLocaleID(ISLAMIC_CIVIL_H_H, null)); + + // fr & fr_CA + CLDRFile frUnresolved = dstFactory.make("fr", false); + assertEquals(rootChineseBhH, frUnresolved.getStringValue(CHINESE_BH_H)); + assertEquals( + DraftStatus.unconfirmed, + DraftStatus.forXpath(frUnresolved.getFullXPath(CHINESE_BH_H))); + assertNull(frUnresolved.getStringValue(CHINESE_Y_Y)); + assertNull(dstFactory.make("fr_CA", false).getStringValue(GREGORIAN_D_D)); + assertNull(dstFactory.make("fr_CA", false).getStringValue(GREGORIAN_Y_Y)); + assertEquals("y – y", dstFactory.make("fr_CA", true).getStringValue(GREGORIAN_Y_Y)); + + // 3-level chain: en -> en_001 -> en_GB + assertEquals(rootGregorianY, dstFactory.make("en", false).getStringValue(GREGORIAN_Y_Y)); + assertNull(dstFactory.make("en_001", false).getStringValue(GREGORIAN_Y_Y)); + assertNull(dstFactory.make("en_GB", false).getStringValue(GREGORIAN_Y_Y)); + assertEquals( + "en", + dstFactory + .make("en_GB", true, DraftStatus.approved) + .getSourceLocaleID(GREGORIAN_Y_Y, null)); + + // en_CA alt="variant": preserved, NOT stripped across Reason.removedAttribute. + CLDRFile enCaUnresolved = dstFactory.make("en_CA", false); + assertEquals(rootGregorianY, enCaUnresolved.getStringValue(GREGORIAN_Y_Y_VARIANT)); + + // agq: absent stays absent. + assertNull(dstFactory.make("agq", false).getStringValue(GREGORIAN_Y_Y)); + } + + @Test + void testDraftPrecedenceAndAntiShadowingEdgeCases(@TempDir Path tempDir) throws IOException { + Path srcCommon = createSkeletonCommonDir(tempDir.resolve("src")); + Path dstCommon = tempDir.resolve("dst").resolve("common"); + Path srcMain = srcCommon.resolve("main"); + copyRealMainLocales(srcMain, "root"); + + CLDRFile srcRoot = Factory.make(srcMain.toString(), ".*").make("root", false); + String rootGregorianY = srcRoot.getStringValue(GREGORIAN_Y_Y); + String rootGregorianD = srcRoot.getStringValue(GREGORIAN_D_D); + String rootGenericH = srcRoot.getStringValue(GENERIC_H_H); + + // 1. Parent de has draft="unconfirmed" ↑↑↑; child de_AT has approved ↑↑↑. + // 2. Parent de also has explicit draft="unconfirmed" equal to root on d/d; de_AT has + // approved ↑↑↑ on d/d. In both cases de_AT must materialize its approved copy. + writeLdml( + srcMain, + "de", + "", + """ + + + + + %s + + + ↑↑↑ + + + + + """ + .formatted(rootGregorianD)); + writeLdml( + srcMain, + "de_AT", + "", + """ + + + + + ↑↑↑ + + + ↑↑↑ + + + + + """); + + // 3. Parent nl has approved ↑↑↑ on buddhist H/H and unconfirmed ↑↑↑ on generic H/H, + // so nl materializes buddhist H/H as approved. Child nl_BE overrides generic H/H = + // "H–H" (approved) while also carrying a weaker draft="unconfirmed" ↑↑↑ on buddhist + // H/H. Anti-shadowing must emit buddhist H/H = "H–H" with approved status (clearing the + // stale draft="unconfirmed") so nl's materialized buddhist entry does not shadow nl_BE's + // generic override even under contributed filtering! + writeLdml( + srcMain, + "nl", + "", + """ + + + + + ↑↑↑ + + + + + + + + + ↑↑↑ + + + + + """); + writeLdml( + srcMain, + "nl_BE", + "", + """ + + + + + ↑↑↑ + + + + + + + + + H–H + + + + + """); + + GenerateProductionData.main( + new String[] {"-s", srcCommon.toString(), "-d", dstCommon.toString()}); + + Factory dstFactory = Factory.make(dstCommon.resolve("main").toString(), ".*"); + + // de & de_AT (both ↑↑↑ and explicit weaker-draft parent) + CLDRFile deAtUnresolved = dstFactory.make("de_AT", false); + assertEquals(rootGregorianY, deAtUnresolved.getStringValue(GREGORIAN_Y_Y)); + assertEquals( + DraftStatus.approved, + DraftStatus.forXpath(deAtUnresolved.getFullXPath(GREGORIAN_Y_Y))); + assertEquals(rootGregorianD, deAtUnresolved.getStringValue(GREGORIAN_D_D)); + assertEquals( + DraftStatus.approved, + DraftStatus.forXpath(deAtUnresolved.getFullXPath(GREGORIAN_D_D))); + CLDRFile deAtContributed = dstFactory.make("de_AT", true, DraftStatus.contributed); + assertEquals("de_AT", deAtContributed.getSourceLocaleID(GREGORIAN_Y_Y, null)); + assertEquals("de_AT", deAtContributed.getSourceLocaleID(GREGORIAN_D_D, null)); + + // nl: buddhist keeps its approved copy; generic stays unconfirmed. + CLDRFile nlUnresolved = dstFactory.make("nl", false); + assertEquals(rootGenericH, nlUnresolved.getStringValue(GENERIC_H_H)); + assertEquals( + DraftStatus.unconfirmed, + DraftStatus.forXpath(nlUnresolved.getFullXPath(GENERIC_H_H))); + assertEquals(rootGenericH, nlUnresolved.getStringValue(BUDDHIST_H_H)); + assertEquals( + DraftStatus.approved, + DraftStatus.forXpath(nlUnresolved.getFullXPath(BUDDHIST_H_H))); + CLDRFile nlContributed = dstFactory.make("nl", true, DraftStatus.contributed); + assertEquals("nl", nlContributed.getSourceLocaleID(BUDDHIST_H_H, null)); + assertEquals(XMLSource.ROOT_ID, nlContributed.getSourceLocaleID(GENERIC_H_H, null)); + + // nl_BE: anti-shadowing preserves "H–H" on buddhist H/H with approved status (not stale + // draft="unconfirmed") instead of inheriting nl's materialized rootGenericH. + CLDRFile nlBeUnresolved = dstFactory.make("nl_BE", false); + assertEquals("H–H", nlBeUnresolved.getStringValue(BUDDHIST_H_H)); + assertEquals( + DraftStatus.approved, + DraftStatus.forXpath(nlBeUnresolved.getFullXPath(BUDDHIST_H_H))); + CLDRFile nlBeResolved = dstFactory.make("nl_BE", true); + assertEquals("H–H", nlBeResolved.getStringValue(BUDDHIST_H_H)); + assertEquals("nl_BE", nlBeResolved.getSourceLocaleID(BUDDHIST_H_H, null)); + CLDRFile nlBeContributed = dstFactory.make("nl_BE", true, DraftStatus.contributed); + assertEquals("H–H", nlBeContributed.getStringValue(BUDDHIST_H_H)); + assertEquals("nl_BE", nlBeContributed.getSourceLocaleID(BUDDHIST_H_H, null)); + } + + @Test + void testAddRootFalseDoesNotMaterialize(@TempDir Path tempDir) throws IOException { + Path srcCommon = createSkeletonCommonDir(tempDir.resolve("src")); + Path dstCommon = tempDir.resolve("dst").resolve("common"); + Path srcMain = srcCommon.resolve("main"); + copyRealMainLocales(srcMain, "root"); + writeLdml( + srcMain, + "de", + "", + """ + + + + + ↑↑↑ + + + + + """); + + GenerateProductionData.main( + new String[] { + "-s", srcCommon.toString(), "-d", dstCommon.toString(), "-r", "false" + }); + + Factory dstFactory = Factory.make(dstCommon.resolve("main").toString(), ".*"); + assertNull(dstFactory.make("de", false).getStringValue(GREGORIAN_Y_Y)); + } + + @Test + void testRealLocalesResolvedEquivalence(@TempDir Path tempDir) throws IOException { + Path srcCommon = createSkeletonCommonDir(tempDir.resolve("src")); + Path dstCommon = tempDir.resolve("dst").resolve("common"); + String[] locales = {"root", "de", "es", "es_419", "fr", "nl", "agq"}; + copyRealMainLocales(srcCommon.resolve("main"), locales); + + GenerateProductionData.main( + new String[] {"-s", srcCommon.toString(), "-d", dstCommon.toString()}); + + Factory srcFactory = Factory.make(srcCommon.resolve("main").toString(), ".*"); + Factory dstFactory = Factory.make(dstCommon.resolve("main").toString(), ".*"); + + for (String locale : locales) { + CLDRFile dstUnresolved = dstFactory.make(locale, false); + for (String xpath : dstUnresolved) { + if (xpath.contains("/intervalFormatItem[")) { + String val = dstUnresolved.getStringValue(xpath); + assertNotNull(val, "Null value in " + locale + " for " + xpath); + assertNotEquals( + CldrUtility.INHERITANCE_MARKER, + val, + "Unresolved ↑↑↑ remaining in " + locale + " for " + xpath); + } + } + CLDRFile srcResolved = srcFactory.make(locale, true); + CLDRFile dstResolved = dstFactory.make(locale, true); + Set allPaths = new TreeSet<>(); + srcResolved.forEach( + p -> { + if (p.contains("/intervalFormatItem[")) allPaths.add(p); + }); + dstResolved.forEach( + p -> { + if (p.contains("/intervalFormatItem[")) allPaths.add(p); + }); + for (String xpath : allPaths) { + assertEquals( + srcResolved.getStringValue(xpath), + dstResolved.getStringValue(xpath), + "Resolved mismatch in " + locale + " for " + xpath); + } + } + } +}