import codecs
import encodings.idna
import re
import sys
def getEffectiveTLDs(path):
file = codecs.open(path, "r", "UTF-8")
domains = set()
while True:
line = file.readline()
if len(line) == 0:
raise StopIteration
line = line.rstrip()
if line.startswith("//") or "." not in line:
continue
line = re.split(r"[ \t\n]", line, 1)[0]
entry = EffectiveTLDEntry(line)
domain = entry.domain()
assert domain not in domains, \
"repeating domain %s makes no sense" % domain
domains.add(domain)
yield entry
def _normalizeHostname(domain):
def convertLabel(label):
if _isASCII(label):
return label.lower()
return encodings.idna.ToASCII(label)
return ".".join(map(convertLabel, domain.split(".")))
def _isASCII(s):
"True if s consists entirely of ASCII characters, false otherwise."
for c in s:
if ord(c) > 127:
return False
return True
class EffectiveTLDEntry:
_exception = False
_wild = False
def __init__(self, line):
if line.startswith("!"):
self._exception = True
domain = line[1:]
elif line.startswith("*."):
self._wild = True
domain = line[2:]
else:
domain = line
self._domain = _normalizeHostname(domain)
def domain(self):
"The domain this represents."
return self._domain
def exception(self):
"True if this entry's domain denotes does not denote an effective TLD."
return self._exception
def wild(self):
"True if this entry represents a class of effective TLDs."
return self._wild
def main(output, effective_tld_filename):
def boolStr(b):
if b:
return "true"
return "false"
for etld in getEffectiveTLDs(effective_tld_filename):
exception = boolStr(etld.exception())
wild = boolStr(etld.wild())
output.write('ETLD_ENTRY("%s", %s, %s)\n' % (etld.domain(), exception, wild))
if __name__ == '__main__':
main(sys.stdout, sys.argv[1])