52 lines
2.3 KiB
Java
52 lines
2.3 KiB
Java
import java.io.IOException;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Locale;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
/** Regenerates localized country names while preserving the maintained dialing codes. */
|
|
public final class GenerateCountryCallingCodeLocales {
|
|
private static final Pattern ITEM = Pattern.compile(
|
|
"\\{\\\"code\\\":\\\"([^\\\"]+)\\\",\\\"name\\\":\\\"[^\\\"]*\\\",\\\"dial_code\\\":\\\"([^\\\"]+)\\\"}");
|
|
|
|
private record Country(String code, String dialCode) {}
|
|
|
|
public static void main(String[] args) throws IOException {
|
|
Path assets = Path.of("app", "src", "main", "assets");
|
|
String source = Files.readString(assets.resolve("country_calling_codes.json"), StandardCharsets.UTF_8);
|
|
Matcher matcher = ITEM.matcher(source);
|
|
List<Country> countries = new ArrayList<>();
|
|
while (matcher.find()) {
|
|
countries.add(new Country(matcher.group(1), matcher.group(2)));
|
|
}
|
|
if (countries.isEmpty()) {
|
|
throw new IllegalStateException("No country records found in the source JSON");
|
|
}
|
|
|
|
write(assets.resolve("country_calling_codes_en.json"), countries, Locale.ENGLISH);
|
|
write(assets.resolve("country_calling_codes_ar.json"), countries, Locale.forLanguageTag("ar"));
|
|
}
|
|
|
|
private static void write(Path output, List<Country> countries, Locale locale) throws IOException {
|
|
StringBuilder json = new StringBuilder("[\n");
|
|
for (int index = 0; index < countries.size(); index++) {
|
|
Country country = countries.get(index);
|
|
String name = new Locale.Builder().setRegion(country.code()).build().getDisplayCountry(locale);
|
|
json.append(" {\"code\":\"").append(country.code())
|
|
.append("\",\"name\":\"").append(escape(name))
|
|
.append("\",\"dial_code\":\"").append(country.dialCode()).append("\"}");
|
|
json.append(index + 1 == countries.size() ? "\n" : ",\n");
|
|
}
|
|
json.append("]\n");
|
|
Files.writeString(output, json, StandardCharsets.UTF_8);
|
|
}
|
|
|
|
private static String escape(String value) {
|
|
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
|
}
|
|
}
|