summaryrefslogtreecommitdiff
path: root/punycode.py
blob: c6abb37f960ab973bf20e6516f1429fb9ad0c393 (plain)
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
#!/usr/bin/env python
import argparse
import sys


class Domain(object):
    def __init__(self, domain):
        """Constructor"""
        if sys.version_info[0] < 3:
            domain = domain.decode('utf-8').encode('utf-8')
            idna = domain.decode('utf-8').encode('idna')
            self.ascii = idna
            self.utf_8 = idna.decode('idna').encode('utf-8')
        else:
            idna = bytes(domain, 'idna')
            self.ascii = idna.decode('ascii')
            self.utf_8 = idna.decode('idna')
        if self.ascii == self.utf_8:
            self.type = 'ascii'
            self.utf_8 = None
        else:
            if self.utf_8 == domain:
                self.type = 'unicode'
            else:
                self.type = 'punycode'

    def display(self):
        print('INPUT: \x1B[1m{}\x1B[0m\nASCII: \x1B[1m{}\x1B[0m'
              .format(self.type, self.ascii))
        if self.utf_8 is not None:
            print('UTF-8: \x1B[1m{}\x1B[0m'.format(self.utf_8))

def parse_arguments():
    """Parse and store arguments."""
    desc = 'A simple punycode to unicode and back converter.'
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument('domain', help='domain name to convert')

    # Store the supplied args
    return parser.parse_args()


def main(main_sysargs):
    args = parse_arguments()

    domain = Domain(args.domain)
    domain.display()


if __name__ == '__main__':
    main(sys.argv)