Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/markdown_it/_punycode.py: 86%
29 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:07 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:07 +0000
1# Copyright 2014 Mathias Bynens <https://mathiasbynens.be/>
2# Copyright 2021 Taneli Hukkinen
3#
4# Permission is hereby granted, free of charge, to any person obtaining
5# a copy of this software and associated documentation files (the
6# "Software"), to deal in the Software without restriction, including
7# without limitation the rights to use, copy, modify, merge, publish,
8# distribute, sublicense, and/or sell copies of the Software, and to
9# permit persons to whom the Software is furnished to do so, subject to
10# the following conditions:
11#
12# The above copyright notice and this permission notice shall be
13# included in all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23import codecs
24import re
26REGEX_SEPARATORS = re.compile(r"[\x2E\u3002\uFF0E\uFF61]")
27REGEX_NON_ASCII = re.compile(r"[^\0-\x7E]")
30def encode(uni: str) -> str:
31 return codecs.encode(uni, encoding="punycode").decode()
34def decode(ascii: str) -> str:
35 return codecs.decode(ascii, encoding="punycode") # type: ignore[call-overload]
38def map_domain(string, fn):
39 parts = string.split("@")
40 result = ""
41 if len(parts) > 1:
42 # In email addresses, only the domain name should be punycoded. Leave
43 # the local part (i.e. everything up to `@`) intact.
44 result = parts[0] + "@"
45 string = parts[1]
46 labels = REGEX_SEPARATORS.split(string)
47 encoded = ".".join(fn(label) for label in labels)
48 return result + encoded
51def to_unicode(obj: str) -> str:
52 def mapping(obj: str) -> str:
53 if obj.startswith("xn--"):
54 return decode(obj[4:].lower())
55 return obj
57 return map_domain(obj, mapping)
60def to_ascii(obj: str) -> str:
61 def mapping(obj: str) -> str:
62 if REGEX_NON_ASCII.search(obj):
63 return "xn--" + encode(obj)
64 return obj
66 return map_domain(obj, mapping)