~anitanayak/charms/trusty/ibm-mq/ibm-mq-trusty

« back to all changes in this revision

Viewing changes to .tox/py35/lib/python3.5/site-packages/wheel/util.py

  • Committer: Anita Nayak
  • Date: 2016-10-24 07:10:08 UTC
  • Revision ID: anitanayak@in.ibm.com-20161024071008-tqk3cefak6nc1c69
checking in after fixing lint errors

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""Utility functions."""
 
2
 
 
3
import sys
 
4
import os
 
5
import base64
 
6
import json
 
7
import hashlib
 
8
try:
 
9
    from collections import OrderedDict
 
10
except ImportError:
 
11
    OrderedDict = dict
 
12
 
 
13
__all__ = ['urlsafe_b64encode', 'urlsafe_b64decode', 'utf8',
 
14
           'to_json', 'from_json', 'matches_requirement']
 
15
 
 
16
def urlsafe_b64encode(data):
 
17
    """urlsafe_b64encode without padding"""
 
18
    return base64.urlsafe_b64encode(data).rstrip(binary('='))
 
19
 
 
20
 
 
21
def urlsafe_b64decode(data):
 
22
    """urlsafe_b64decode without padding"""
 
23
    pad = b'=' * (4 - (len(data) & 3))
 
24
    return base64.urlsafe_b64decode(data + pad)
 
25
 
 
26
 
 
27
def to_json(o):
 
28
    '''Convert given data to JSON.'''
 
29
    return json.dumps(o, sort_keys=True)
 
30
 
 
31
 
 
32
def from_json(j):
 
33
    '''Decode a JSON payload.'''
 
34
    return json.loads(j)
 
35
 
 
36
def open_for_csv(name, mode):
 
37
    if sys.version_info[0] < 3:
 
38
        nl = {}
 
39
        bin = 'b'
 
40
    else:
 
41
        nl = { 'newline': '' }
 
42
        bin = ''
 
43
    return open(name, mode + bin, **nl)
 
44
 
 
45
try:
 
46
    unicode
 
47
 
 
48
    def utf8(data):
 
49
        '''Utf-8 encode data.'''
 
50
        if isinstance(data, unicode):
 
51
            return data.encode('utf-8')
 
52
        return data
 
53
except NameError:
 
54
    def utf8(data):
 
55
        '''Utf-8 encode data.'''
 
56
        if isinstance(data, str):
 
57
            return data.encode('utf-8')
 
58
        return data
 
59
 
 
60
 
 
61
try:
 
62
    # For encoding ascii back and forth between bytestrings, as is repeatedly
 
63
    # necessary in JSON-based crypto under Python 3
 
64
    unicode
 
65
    def native(s):
 
66
        return s
 
67
    def binary(s):
 
68
        if isinstance(s, unicode):
 
69
            return s.encode('ascii')
 
70
        return s
 
71
except NameError:
 
72
    def native(s):
 
73
        if isinstance(s, bytes):
 
74
            return s.decode('ascii')
 
75
        return s
 
76
    def binary(s):
 
77
        if isinstance(s, str):
 
78
            return s.encode('ascii')
 
79
 
 
80
class HashingFile(object):
 
81
    def __init__(self, fd, hashtype='sha256'):
 
82
        self.fd = fd
 
83
        self.hashtype = hashtype
 
84
        self.hash = hashlib.new(hashtype)
 
85
        self.length = 0
 
86
    def write(self, data):
 
87
        self.hash.update(data)
 
88
        self.length += len(data)
 
89
        self.fd.write(data)
 
90
    def close(self):
 
91
        self.fd.close()
 
92
    def digest(self):
 
93
        if self.hashtype == 'md5':
 
94
            return self.hash.hexdigest()
 
95
        digest = self.hash.digest()
 
96
        return self.hashtype + '=' + native(urlsafe_b64encode(digest))
 
97
 
 
98
class OrderedDefaultDict(OrderedDict):
 
99
    def __init__(self, *args, **kwargs):
 
100
        if not args:
 
101
            self.default_factory = None
 
102
        else:
 
103
            if not (args[0] is None or callable(args[0])):
 
104
                raise TypeError('first argument must be callable or None')
 
105
            self.default_factory = args[0]
 
106
            args = args[1:]
 
107
        super(OrderedDefaultDict, self).__init__(*args, **kwargs)
 
108
 
 
109
    def __missing__ (self, key):
 
110
        if self.default_factory is None:
 
111
            raise KeyError(key)
 
112
        self[key] = default = self.default_factory()
 
113
        return default
 
114
 
 
115
if sys.platform == 'win32':
 
116
    import ctypes.wintypes
 
117
    # CSIDL_APPDATA for reference - not used here for compatibility with
 
118
    # dirspec, which uses LOCAL_APPDATA and COMMON_APPDATA in that order
 
119
    csidl = dict(CSIDL_APPDATA=26, CSIDL_LOCAL_APPDATA=28,
 
120
            CSIDL_COMMON_APPDATA=35)
 
121
    def get_path(name):
 
122
        SHGFP_TYPE_CURRENT = 0
 
123
        buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
 
124
        ctypes.windll.shell32.SHGetFolderPathW(0, csidl[name], 0, SHGFP_TYPE_CURRENT, buf)
 
125
        return buf.value
 
126
 
 
127
    def save_config_path(*resource):
 
128
        appdata = get_path("CSIDL_LOCAL_APPDATA")
 
129
        path = os.path.join(appdata, *resource)
 
130
        if not os.path.isdir(path):
 
131
            os.makedirs(path)
 
132
        return path
 
133
    def load_config_paths(*resource):
 
134
        ids = ["CSIDL_LOCAL_APPDATA", "CSIDL_COMMON_APPDATA"]
 
135
        for id in ids:
 
136
            base = get_path(id)
 
137
            path = os.path.join(base, *resource)
 
138
            if os.path.exists(path):
 
139
                yield path
 
140
else:
 
141
    def save_config_path(*resource):
 
142
        import xdg.BaseDirectory
 
143
        return xdg.BaseDirectory.save_config_path(*resource)
 
144
    def load_config_paths(*resource):
 
145
        import xdg.BaseDirectory
 
146
        return xdg.BaseDirectory.load_config_paths(*resource)
 
147
 
 
148
def matches_requirement(req, wheels):
 
149
    """List of wheels matching a requirement.
 
150
 
 
151
    :param req: The requirement to satisfy
 
152
    :param wheels: List of wheels to search.
 
153
    """
 
154
    try:
 
155
        from pkg_resources import Distribution, Requirement
 
156
    except ImportError:
 
157
        raise RuntimeError("Cannot use requirements without pkg_resources")
 
158
 
 
159
    req = Requirement.parse(req)
 
160
 
 
161
    selected = []
 
162
    for wf in wheels:
 
163
        f = wf.parsed_filename
 
164
        dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
 
165
        if dist in req:
 
166
            selected.append(wf)
 
167
    return selected