-
Notifications
You must be signed in to change notification settings - Fork 34
/
locale.ex
2324 lines (1800 loc) · 70.1 KB
/
locale.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Cldr.Locale do
@moduledoc """
Functions to parse and normalize locale names into a structure
locale represented by a `Cldr.LanguageTag`.
CLDR represents localisation data organized into locales, with
each locale being identified by a locale name that is formatted
according to [RFC5646](https://tools.ietf.org/html/rfc5646).
In practise, the CLDR data utilizes a simple subset of locale name
formats being:
* a Language code such as `en` or `fr`
* a Language code and Tertitory code such as `en-GB`
* a Language code and Script such as `zh-Hant`
* and in only two cases a Language code, Territory code and Variant
such as `ca-ES-valencia` and `en-US-posix`.
The RFC defines a language tag as:
> A language tag is composed from a sequence of one or more "subtags",
each of which refines or narrows the range of language identified by
the overall tag. Subtags, in turn, are a sequence of alphanumeric
characters (letters and digits), distinguished and separated from
other subtags in a tag by a hyphen ("-", [Unicode] U+002D)
Therefore `Cldr` uses the hyphen ("-", [Unicode] U+002D) as the subtag
separator. On certain platforms, including POSIX platforms, the
subtag separator is a "_" (underscore) rather than a "-" (hyphen). Where
appropriate, `Cldr` will transliterate any underscore into a hyphen before
parsing or processing.
### Locale name validity
When validating a locale name, `Cldr` will attempt to match the requested
locale name to a configured locale. Therefore `Cldr.Locale.new/2` may
return an `{:ok, language_tag}` tuple even when the locale returned does
not exactly match the requested locale name. For example, the following
attempts to create a locale matching the non-existent "english as spoken
in Spain" local name. Here `Cldr` will match to the nearest configured
locale, which in this case will be "en".
iex> Cldr.Locale.new("en-ES", TestBackend.Cldr)
{:ok, %Cldr.LanguageTag{
backend: TestBackend.Cldr,
canonical_locale_name: "en-ES",
cldr_locale_name: :en,
extensions: %{},
gettext_locale_name: "en",
language: "en",
locale: %{},
private_use: [],
rbnf_locale_name: :en,
requested_locale_name: "en-ES",
script: :Latn,
territory: :ES,
transform: %{},
language_variants: []
}}
### Matching locales to requested locale names
When attempting to match the requested locale name to a configured
locale, `Cldr` attempt to match against a set of reductions in the
following order and will return the first match:
* language, script, territory, [variants]
* language, territory, [variants]
* language, script, [variants]
* language, [variants]
* language, script, territory
* language, territory
* language, script
* language
* requested locale name
* nil
Therefore matching is tolerant of a request for unknown scripts,
territories and variants. Only the requested language is a
requirement to be matched to a configured locale.
### Substitutions for Obsolete and Deprecated locale names
CLDR provides data to help manage the transition from obsolete
or deprecated locale names to current names. For example, the
following requests the locale name "mo" which is the deprecated
code for "Moldovian". The replacement code is "ro" (Romanian).
iex> Cldr.Locale.new("mo", TestBackend.Cldr)
{:ok, %Cldr.LanguageTag{
backend: TestBackend.Cldr,
extensions: %{},
gettext_locale_name: nil,
language: "ro",
language_subtags: [],
language_variants: [],
locale: %{}, private_use: [],
rbnf_locale_name: :ro,
requested_locale_name: "mo",
script: :Latn,
transform: %{},
canonical_locale_name: "ro",
cldr_locale_name: :ro,
territory: :RO
}}
### Likely subtags
CLDR also provides data to indetify the most likely subtags for a
requested locale name. This data is based on the default content data,
the population data, and the the suppress-script data in [BCP47]. It is
heuristically derived, and may change over time. For example, when
requesting the locale "en", the following is returned:
iex> Cldr.Locale.new("en", TestBackend.Cldr)
{:ok, %Cldr.LanguageTag{
backend: TestBackend.Cldr,
canonical_locale_name: "en",
cldr_locale_name: :en,
extensions: %{},
gettext_locale_name: "en",
language: "en",
locale: %{},
private_use: [],
rbnf_locale_name: :en,
requested_locale_name: "en",
script: :Latn,
territory: :US,
transform: %{},
language_variants: []
}}
Which shows that a the likely subtag for the script is :Latn and the likely
territory is "US".
Using the example for Substitutions above, we can see the
result of combining substitutions and likely subtags for locale name "mo"
returns the current language code of "ro" as well as the likely
territory code of "MD" (Moldova).
### Unknown territory codes
Whilst `Cldr` is tolerant of invalid territory codes. Therefore validity is
not checked by `Cldr.Locale.new/2` but it is checked by `Cldr.validate_locale/2`
which is the recommended api for forming language tags.
iex> Cldr.Locale.new("en-XX", TestBackend.Cldr)
{:ok, %Cldr.LanguageTag{
backend: TestBackend.Cldr,
canonical_locale_name: "en-XX",
cldr_locale_name: :en,
extensions: %{},
gettext_locale_name: "en",
language: "en",
locale: %{},
private_use: [],
rbnf_locale_name: :en,
requested_locale_name: "en-XX",
script: :Latn,
territory: :XX,
transform: %{},
language_variants: []
}}
### Locale extensions
Unicode defines the [U extension](https://unicode.org/reports/tr35/#Locale_Extension_Key_and_Type_Data)
which support defining the requested treatment of CLDR data formats. For example, a locale name
can configure the requested:
* calendar to be used for dates
* collation
* currency
* currency format
* number system
* first day of the week
* 12-hour or 24-hour time
* time zone
* and many other items
For example, the following locale name will request the use of the timezone `Australia/Sydney`,
and request the use of `accounting` format when formatting currencies:
iex> MyApp.Cldr.validate_locale "en-AU-u-tz-ausyd-cf-account"
{
:ok,
%Cldr.LanguageTag{
backend: MyApp.Cldr,
canonical_locale_name: "en-AU-u-cf-account-tz-ausyd",
cldr_locale_name: :"en-AU",
extensions: %{},
gettext_locale_name: "en",
language: "en",
language_subtags: [],
language_variants: [],
locale: %Cldr.LanguageTag.U{
calendar: nil,
cf: :account,
col_alternate: nil,
col_backwards: nil,
col_case_first: nil,
col_case_level: nil,
col_normalization: nil,
col_numeric: nil,
col_reorder: nil,
col_strength: nil,
collation: nil,
currency: nil,
dx: nil,
em: nil,
fw: nil,
hc: nil,
lb: nil,
lw: nil,
ms: nil,
numbers: nil,
rg: nil,
sd: nil,
ss: nil,
timezone: "Australia/Sydney",
va: nil,
vt: nil
},
private_use: '',
rbnf_locale_name: :en,
requested_locale_name: "en-AU",
script: :Latn,
territory: :AU,
transform: %{}
}
}
"""
alias Cldr.LanguageTag
alias Cldr.LanguageTag.{U, T}
import Cldr.Helpers, only: [empty?: 1]
@typedoc "The name of a locale"
@type locale_name() :: atom()
@typedoc "A reference to a locale"
@type locale_reference :: LanguageTag.t() | locale_name() | String.t()
@typedoc "The name of a language"
@type language :: String.t() | nil
@typedoc "The name of a script"
@type script :: atom() | String.t() | nil
@typedoc "The name of a territory"
@type territory_reference :: atom() | String.t() | nil
@typedoc "A territory code as an ISO3166 Alpha-2 in atom form"
@type territory_code :: atom()
@typedoc "The list of language variants as strings"
@type variants :: [String.t()] | []
@typedoc "The list of language subtags as strings"
@type subtags :: [String.t(), ...] | []
@root_locale Cldr.Config.root_locale_name()
@root_language Atom.to_string(@root_locale)
@root_rbnf_locale_name Cldr.Config.root_locale_name()
defdelegate new(locale_name, backend), to: __MODULE__, as: :canonical_language_tag
defdelegate new!(locale_name, backend), to: __MODULE__, as: :canonical_language_tag!
defdelegate locale_name_to_posix(locale_name), to: Cldr.Config
defdelegate locale_name_from_posix(locale_name), to: Cldr.Config
@doc """
Mapping of language data to known
scripts and territories
"""
@language_data Cldr.Config.language_data()
def language_data do
@language_data
end
@doc """
Returns mappings between a locale
and its parent.
The mappings exist only where normal
inheritance rules are not applied.
"""
@parent_locales Cldr.Config.parent_locales()
def parent_locale_map do
@parent_locales
end
@doc """
Returns a list of all the parent locales
for a given locale.
## Examples
Cldr.Locale.parents "fr-ca"
=> {:ok, [#Cldr.LanguageTag<fr [validated]>, #Cldr.LanguageTag<en [validated]>]}
"""
@spec parents(LanguageTag.t()) ::
{:ok, list(LanguageTag.t())} | {:error, {module(), String.t()}}
def parents(locale, acc \\ [])
def parents(%LanguageTag{} = locale, acc) do
case parent(locale) do
{:error, _} -> {:ok, Enum.reverse(acc)}
{:ok, locale} -> parents(locale, [locale | acc])
end
end
def parents(locale, []) do
with {:ok, locale} <- Cldr.validate_locale(locale, Cldr.default_backend!()) do
parents(locale)
end
end
def parents(locale, backend) when is_atom(backend) do
with {:ok, locale} <- Cldr.validate_locale(locale, backend) do
parents(locale)
end
end
@doc """
Returns the parent for a given locale.
The function implements locale inheritance
in accordance with [CLDR's inheritance rules](https://unicode.org/reports/tr35/#Locale_Inheritance).
Only locales that are configured are returned.
That is, there may be a different parent locale in CLDR
but unless those locales are configured they are not
candidates to be parents in this context. The contract
is to return either a known locale or an error.
### Inheritance
* Inheritance starts by looking for a parent locale via
`Cldr.Config.parent_locales/0`.
* If not found, strip in turn the variant, script and territory
while checking to see if a base locale for the given language
exists.
* If no parent language exists then move to the default
locale and its inheritance chain.
"""
@spec parent(LanguageTag.t()) ::
{:ok, LanguageTag.t()} | {:error, {module(), binary()}}
def parent(%LanguageTag{language: @root_locale}) do
{:error, no_parent_error(@root_locale)}
end
def parent(%LanguageTag{backend: backend} = child) do
if parent = Map.get(parent_locale_map(), child.cldr_locale_name) do
Cldr.validate_locale(parent, backend)
else
child
|> find_parent(backend)
|> return_parent_or_default(child, backend)
|> transfer_extensions(child)
end
end
@spec parent(locale_name(), Cldr.backend()) ::
{:ok, LanguageTag.t()} | {:error, {module(), binary()}}
def parent(locale_name, backend \\ Cldr.default_backend!()) do
with {:ok, locale} <- Cldr.validate_locale(locale_name, backend) do
parent(locale)
end
end
defp find_parent(%LanguageTag{language_variants: [_ | _] = variants} = locale, backend) do
%LanguageTag{language: language, script: script, territory: territory} = locale
first_match(language, script, territory, variants, &known_locale(&1, &2, backend))
end
defp find_parent(%LanguageTag{territory: territory} = locale, backend)
when not is_nil(territory) do
%LanguageTag{language: language, script: script} = locale
first_match(language, script, nil, [], &known_locale(&1, &2, backend))
end
defp find_parent(%LanguageTag{language: language}, backend) do
parent_locale_map()
|> Map.get(language)
|> known_locale(backend)
end
defp known_locale(locale_name, tags \\ [], backend)
defp known_locale(nil, _tags, _backend) do
nil
end
defp known_locale(locale_name, tags, backend) when is_binary(locale_name) do
locale_name = String.to_existing_atom(locale_name)
known_locale(locale_name, tags, backend)
rescue ArgumentError ->
nil
end
defp known_locale(locale_name, _tags, backend) when is_atom(locale_name) do
Enum.find(backend.known_locale_names(), &(locale_name == &1))
end
def known_rbnf_locale_name(locale_name, _tags \\ [], backend) do
locale_name = String.to_existing_atom(locale_name)
Cldr.known_rbnf_locale_name(locale_name, backend)
rescue ArgumentError ->
nil
end
defp return_parent_or_default(parent, %LanguageTag{cldr_locale_name: parent} = child, backend) do
default_locale = Cldr.default_locale(backend)
if child.language == default_locale.language do
{:error, no_parent_error(child.canonical_locale_name)}
else
{:ok, default_locale}
end
end
defp return_parent_or_default(parent, _child, backend) do
Cldr.validate_locale(parent, backend)
end
defp transfer_extensions({:error, _reason} = error, _child) do
error
end
defp transfer_extensions({:ok, parent}, child) do
{:ok, %{parent | locale: child.locale, transform: child.transform}}
end
defp no_parent_error(locale_name) do
{Cldr.NoParentError, "The locale #{inspect(locale_name)} has no parent locale"}
end
@doc """
Returns the list of fallback locales, starting the
the provided locale.
Fallbacks are a list of locate names which can
be used to resolve translation or other localization
data if such localised data does not exist for
this specific locale. After locale-specific fallbacks
are determined, the the default locale and its fallbacks
are added to the chain.
## Arguments
* `locale` is any `LanguageTag.t`
## Returns
* `{:ok, list_of_locales}` or
* `{:error, {exception, reason}}`
## Examples
In these examples the default locale is `:"en-001"`.
Cldr.Locale.fallback_locales(Cldr.Locale.new!("fr-CA", MyApp.Cldr))
=> {:ok,
[#Cldr.LanguageTag<fr-CA [validated]>, #Cldr.LanguageTag<fr [validated]>,
#Cldr.LanguageTag<en [validated]>]}
# Fallbacks are typically formed by progressively
# stripping variant, territory and script from the
# given locale name. But not always - there are
# certain fallbacks that take a different path.
Cldr.Locale.fallback_locales(Cldr.Locale.new!("nb", MyApp.Cldr))
=> {:ok,
[#Cldr.LanguageTag<nb [validated]>, #Cldr.LanguageTag<no [validated]>,
#Cldr.LanguageTag<en [validated]>]}
"""
@spec fallback_locales(LanguageTag.t()) ::
{:ok, [LanguageTag.t(), ...]} | {:error, {module(), binary()}}
@doc since: "2.26.0"
def fallback_locales(%LanguageTag{} = locale) do
with {:ok, parents} <- parents(locale) do
{:ok, [locale | parents]}
end
end
@doc """
Returns the list of fallback locales, starting the
the provided locale.
Fallbacks are a list of locate names which can
be used to resolve translation or other localization
data if such localised data does not exist for
this specific locale. After locale-specific fallbacks
are determined, the the default locale and its fallbacks
are added to the chain.
## Arguments
* `locale_name` is any locale name returned by
`Cldr.known_locale_names/1`
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module. The default is
`Cldr.default_locale/0`.
## Returns
* `{:ok, list_of_locales}` or
* `{:error, {exception, reason}}`
## Examples
In these examples the default locale is `:"en-001"`.
Cldr.Locale.fallback_locales(:"fr-CA")
=> {:ok,
[#Cldr.LanguageTag<fr-CA [validated]>, #Cldr.LanguageTag<fr [validated]>,
#Cldr.LanguageTag<en [validated]>]}
# Fallbacks are typically formed by progressively
# stripping variant, territory and script from the
# given locale name. But not always - there are
# certain fallbacks that take a different path.
Cldr.Locale.fallback_locales(:nb)
=> {:ok,
[#Cldr.LanguageTag<nb [validated]>, #Cldr.LanguageTag<no [validated]>,
#Cldr.LanguageTag<en [validated]>]}
"""
@spec fallback_locales(locale_reference, Cldr.backend) ::
{:ok, [LanguageTag.t(), ...]} | {:error, {module(), binary()}}
@doc since: "2.26.0"
def fallback_locales(locale_name, backend \\ Cldr.default_backend!()) do
with {:ok, locale} <- Cldr.validate_locale(locale_name, backend) do
fallback_locales(locale)
end
end
@doc """
Returns the list of fallback locale names, starting the
the provided locale.
Fallbacks are a list of locate names which can
be used to resolve translation or other localization
data if such localised data does not exist for
this specific locale. After locale-specific fallbacks
are determined, the the default locale and its fallbacks
are added to the chain.
## Arguments
* `locale` is any `LanguageTag.t`
## Returns
* `{:ok, list_of_locale_names}` or
* `{:error, {exception, reason}}`
## Examples
In these examples the default locale is `:"en-001"`.
iex> Cldr.Locale.fallback_locale_names(Cldr.Locale.new!("fr-CA", MyApp.Cldr))
{:ok, [:"fr-CA", :fr, :"en-001", :en]}
# Fallbacks are typically formed by progressively
# stripping variant, territory and script from the
# given locale name. But not always - there are
# certain fallbacks that take a different path.
iex> Cldr.Locale.fallback_locale_names(Cldr.Locale.new!("nb", MyApp.Cldr))
{:ok, [:nb, :no, :"en-001", :en]}
"""
@spec fallback_locale_names(LanguageTag.t()) ::
{:ok, [locale_name, ...]} | {:error, {module(), binary()}}
@doc since: "2.26.0"
def fallback_locale_names(%LanguageTag{} = locale) do
with {:ok, fallbacks} <- fallback_locales(locale) do
locale_names = Enum.map(fallbacks, &Map.get(&1, :cldr_locale_name))
{:ok, locale_names}
end
end
@doc """
Returns the list of fallback locale names, starting the
the provided locale name.
Fallbacks are a list of locate names which can
be used to resolve translation or other localization
data if such localised data does not exist for
this specific locale. After locale-specific fallbacks
are determined, the the default locale and its fallbacks
are added to the chain.
## Arguments
* `locale_name` is any locale name returned by
`Cldr.known_locale_names/1`
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module. The default is
`Cldr.default_locale/0`.
## Returns
* `{:ok, list_of_locale_names}` or
* `{:error, {exception, reason}}`
## Examples
In these examples the default locale is `:"en-001"`.
iex> Cldr.Locale.fallback_locale_names(:"fr-CA")
{:ok, [:"fr-CA", :fr, :"en-001", :en]}
# Fallbacks are typically formed by progressively
# stripping variant, territory and script from the
# given locale name. But not always - there are
# certain fallbacks that take a different path.
iex> Cldr.Locale.fallback_locale_names(:nb)
{:ok, [:nb, :no, :"en-001", :en]}
"""
@spec fallback_locale_names(locale_reference, Cldr.backend()) ::
{:ok, [locale_name, ...]} | {:error, {module(), binary()}}
@doc since: "2.26.0"
def fallback_locale_names(locale_name, backend \\ Cldr.default_backend!()) do
with {:ok, locale} <- Cldr.validate_locale(locale_name, backend) do
fallback_locale_names(locale)
end
end
@doc """
Returns a map of a territory code to its
most-spoken language.
## Example
Cldr.Locale.languages_for_territories()
=> %{
AQ: "und",
PE: "es",
SR: "nl",
NU: "en",
...
}
"""
@language_for_territory Cldr.Config.language_tag_for_territory()
@doc since: "2.26.0"
def languages_for_territories do
@language_for_territory
end
@doc """
Returns the "best fit" locale for a given territory.
Using the population percentage data from CLDR, the
language most commonly spoken in the given territory
is used to form a locale name which is then validated
against the given backend.
First a territory-specific locale is validated and if
that fails, the base language only is validate.
For example, if the territory is `AU` then then the
language most spoken is "en". First, the locale "en-AU"
is validated and if that fails, "en" is validated.
## Arguments
* `territory` is any ISO 3166 Alpha-2 territory
code that can be validated by `Cldr.validate_territory/1`
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module.
## Returns
* `{:ok, language_tag}` or
* `{:error, {exception, reason}}`
## Examples
iex> Cldr.Locale.locale_for_territory(:AU, TestBackend.Cldr)
Cldr.validate_locale(:"en-AU", TestBackend.Cldr)
iex> Cldr.Locale.locale_for_territory(:US, TestBackend.Cldr)
Cldr.validate_locale(:"en-US", TestBackend.Cldr)
iex> Cldr.Locale.locale_for_territory(:ZZ)
{:error, {Cldr.UnknownTerritoryError, "The territory :ZZ is unknown"}}
"""
@doc since: "2.26.0"
@spec locale_for_territory(territory_code(), Cldr.backend()) ::
{:ok, LanguageTag.t()} | {:error, {module(), String.t()}}
def locale_for_territory(territory, backend \\ Cldr.default_backend!()) do
with {:ok, territory} <- Cldr.validate_territory(territory) do
case Map.get(languages_for_territories(), territory) do
nil ->
{:error, no_locale_for_territory_error(territory)}
language ->
validate_locale(language, territory, backend)
end
end
end
# See first if there is a territory specific version of this
# language, otherwise the base language itself
defp validate_locale(language, nil, backend) do
Cldr.validate_locale(language, backend)
end
defp validate_locale(language, territory, backend) do
case Cldr.validate_locale("#{language}-#{to_string(territory)}", backend) do
{:ok, locale} -> {:ok, locale}
{:error, _} -> validate_locale(language, nil, backend)
end
end
@consider_as_tld [
:AD, :AS, :BZ, :CC, :CD, :CO, :DJ, :FM, :IO, :LA, :ME, :MS, :NU, :SC, :SR, :SU, :TV, :TK, :WS
]
@doc """
Returns a list of territory top-level domains that are
considered to be generic top level domains.
See https://developers.google.com/search/docs/advanced/crawling/managing-multi-regional-sites
for an explanation of why some valid territory suffixxes
are considered as TLDs.
## Example
iex> Cldr.Locale.consider_as_tlds
[:AD, :AS, :BZ, :CC, :CD, :CO, :DJ, :FM, :IO, :LA, :ME, :MS, :NU, :SC, :SR, :SU, :TV, :TK, :WS]
"""
def consider_as_tlds do
@consider_as_tld
end
@doc """
Returns a "best fit" locale for a host name.
## Arguments
* `host` is any valid host name
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module.
* `options` is a keyword list of options. The default
is `[]`.
## Options
* `:tlds` is a list of territory codes as upper-cased
atoms that are to be considered as top-level domains.
The default list is `consider_as_tlds/0`.
## Returns
* `{:ok, langauge_tag}` or
* `{:error, {exception, reason}}`
## Notes
Certain top-level domains have become associated with content
underlated to the territory for who the domain is registered.
Therefore Google (and perhaps others) do not associate these
TLDs as belonging to the territory but rather are considered
generic top-level domain names.
## Examples
iex> Cldr.Locale.locale_from_host "a.b.com.au", TestBackend.Cldr
Cldr.validate_locale(:"en-AU", TestBackend.Cldr)
iex> Cldr.Locale.locale_from_host "a.b.com.tv", TestBackend.Cldr
{:error,
{Cldr.UnknownLocaleError, "No locale was identified for territory \\"tv\\""}}
iex> Cldr.Locale.locale_from_host "a.b.com", TestBackend.Cldr
{:error,
{Cldr.UnknownLocaleError, "No locale was identified for territory \\"com\\""}}
"""
@doc since: "2.26.0"
@spec locale_from_host(String.t(), Cldr.backend(), Keyword.t()) ::
{:ok, LanguageTag.t()} | {:error, {module(), String.t()}}
def locale_from_host(host, backend, options \\ []) do
tld_list = Keyword.get(options, :tlds, consider_as_tlds())
with {:ok, territory} <- territory_from_host(host) do
if territory in tld_list do
{:error, no_locale_for_territory_error(territory)}
else
locale_for_territory(territory, backend)
end
end
end
@doc """
Returns the last segment of a host that might
be a territory.
## Arguments
* `host` is any valid host name
## Returns
* `{:ok, territory}` or
* `{:error, {exception, reason}}`
## Examples
iex> Cldr.Locale.territory_from_host("a.b.com.au")
{:ok, :AU}
iex> Cldr.Locale.territory_from_host("a.b.com")
{:error,
{Cldr.UnknownLocaleError, "No locale was identified for territory \\"com\\""}}
"""
@doc since: "2.26.0"
@spec territory_from_host(String.t()) ::
{:ok, territory_code()} | {:error, {module(), String.t()}}
def territory_from_host(host) do
territory =
host
|> String.split(".")
|> Enum.reverse()
|> hd()
try do
territory = String.upcase(territory) |> String.to_existing_atom()
Cldr.validate_territory(territory)
rescue ArgumentError ->
{:error, no_locale_for_territory_error(territory)}
end
end
@doc """
Returns the effective territory for a locale.
## Arguments
* `language_tag` is any language tag returned by `Cldr.Locale.new/2`
or any `locale_name` returned by `Cldr.known_locale_names/1`. If
the parameter is a `locale_name` then a default backend must be
configured in `config.exs` or an exception will be raised.
## Returns
* The territory to be used for localization purposes.
## Examples
iex> Cldr.Locale.territory_from_locale "en-US"
:US
iex> Cldr.Locale.territory_from_locale "en-US-u-rg-cazzzz"
:CA
iex> Cldr.Locale.territory_from_locale "en-US-u-rg-xxxxx"
{:error, {Cldr.LanguageTag.ParseError, "The value \\"xxxxx\\" is not valid for the key \\"rg\\""}}
## Notes
A locale can reflect the desired territory to be used
when determining region-specific defaults for items such
as:
* default currency,
* default calendar and week data,
* default time cycle, and
* default measurement system and unit preferences
Territory information is stored in the locale in up to three
different places:
1. The `:territory` extracted from the locale name or
defined by default for a given language. This is the typical
use case when locale names such as `en-US` or `es-AR` are
used.
2. In some cases it might be desirable to override the territory
derived from the locale name. For example, the default
territory for the language "en" is "US" but it may be desired
to apply the defaults for the territory "AU" instead, without
otherwise changing the localization intent. In this case
the [U extension](https://unicode.org/reports/tr35/#u_Extension) is
used to define a
[regional override](https://unicode.org/reports/tr35/#RegionOverride).
3. Similarly, the [regional subdivision identifier]
(https://unicode.org/reports/tr35/#UnicodeSubdivisionIdentifier)
can be used to influence localization decisions. This identifier
is not currently used in `ex_cldr` and dependent libraries
however it is correctly parsed to support future use.
"""
@spec territory_from_locale(LanguageTag.t() | locale_name() | String.t()) :: territory_code()
@doc since: "2.18.2"
def territory_from_locale(%LanguageTag{locale: %{rg: _rg}} = language_tag) do
language_tag.locale.rg || language_tag.territory || Cldr.default_territory()
end
def territory_from_locale(%LanguageTag{} = language_tag) do
language_tag.territory || Cldr.default_territory()
end
def territory_from_locale(locale_name) do
territory_from_locale(locale_name, Cldr.default_backend!())
end
@doc """
Returns the effective territory for a locale.
## Arguments
* `locale_name` is any locale name returned by
`Cldr.known_locale_names/1`.
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module.
## Returns
* The territory to be used for localization purposes or
`{:error, {exception, reason}}`.
## Examples
iex> Cldr.Locale.territory_from_locale "en-US", TestBackend.Cldr
:US
iex> Cldr.Locale.territory_from_locale "en-US-u-rg-cazzzz", TestBackend.Cldr
:CA
iex> Cldr.Locale.territory_from_locale "en-US-u-rg-xxxxx", TestBackend.Cldr
{:error, {Cldr.LanguageTag.ParseError, "The value \\"xxxxx\\" is not valid for the key \\"rg\\""}}
## Notes
A locale can reflect the desired territory to be used
when determining region-specific defaults for items such
as:
* default currency,
* default calendar and week data,
* default time cycle, and
* default measurement system and unit preferences
Territory information is stored in the locale in up to three
different places:
1. The `:territory` extracted from the locale name or
defined by default for a given language. This is the typical
use case when locale names such as `en-US` or `es-AR` are