utils.py 6.38 KB
Newer Older
Marc Betoule's avatar
Marc Betoule committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
## Copyright (C) 2008, 2009, 2010 APC LPNHE CNRS Universite Paris Diderot <lejeune@apc.univ-paris7.fr>  <betoule@apc.univ-paris7.fr>
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see http://www.gnu.org/licenses/gpl.html

""" Define various tools used by the pipe engine.
"""

import os.path as path
import re
import subprocess
22

Marc Betoule's avatar
Marc Betoule committed
23
import tempfile
24 25
import base64
import zlib
26
import datetime
Marc Betoule's avatar
Marc Betoule committed
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

def flatten(seq):
    """
    this generator flattens nested containers such as

    >>> l=( ('John', 'Hunter'), (1,23), [[[[42,(5,23)]]]])

    so that

    >>> for i in flatten(l): print i,
    John Hunter 1 23 42 5 23

    By: Composite of Holger Krekel and Luther Blissett
    From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294
    and Recipe 1.12 in cookbook
    """
    for item in seq:
        if isinstance(item,str): yield item
        else:
            try:
                iter(item)
                for subitem in flatten(item):
                    yield subitem
            except:
                yield item

53 54
_sup = re.compile(r"""[\(\)\{\}\[\]"']""")
_rep = re.compile(r"""\W+""")
55
def str_file(obj):
56 57
    """ String representation with all special caracters supressed or replaced by underscores.
    
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
58 59 60 61 62 63 64 65 66
    Parameters
    ----------
    obj: a python object.

    Returns
    -------
    string

    Examples
67
    --------
68
    >>> str_file((1,))
69 70
    '1_'
    """
71
    s = ''
72 73 74 75 76 77 78 79
    if isinstance(obj, str):
        s = _sup.sub('',obj)
        s = _rep.sub('_',s)
    else:
        try:
            s = '_'.join([str_file(o) for o in obj])
        except TypeError:
            s = str_file(str(obj))
80 81 82
    return s

def str_web(a):
Marc Betoule's avatar
Marc Betoule committed
83 84 85
    """String representation without the quotes and spaces that
    disturbs the web interface.

Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
86 87 88 89 90 91 92 93 94 95
    Parameters
    ----------
    a: a python object.

    Returns
    -------
    string

    Examples
    --------
96
    >>> print(str_web(['a', ' b']))
Marc Betoule's avatar
Marc Betoule committed
97 98 99 100 101 102 103 104 105
    [a,b]
    """
    s = str(a)
    s = s.replace('"','')
    s = s.replace("'",'')
    s = s.replace(' ','')
    return s


106 107 108 109 110 111 112 113 114 115 116 117
def str_date():
    """ Return a string representation of the date time now. 
    
    Returns:
    --------
    string %y/%m/%d %H:%M:%s

    """
    d = datetime.datetime.now()
    return (d.strftime("%Y-%m-%d %H:%M:%S"))


118 119 120
def is_code_file(s):
    """Check wether the file is a python code file based an the file
    extension.
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
121 122 123 124 125 126 127 128

    Parameters
    ----------
    s: string, file name.

    Returns
    -------
    boolean
129 130 131 132 133 134
    """
    return path.splitext(s)[1] in ['.py']
class crc32:
    """ Hash object using the crc32 algorithm.
    """
    def __init__(self, s=""):
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
135 136 137 138 139 140 141 142 143
        """ Initialize the hash object. 
        
        Parameters
        ----------
        s: string.
        """
        
        ## string, checksum given by the crc32 algorithm
        self.checksum = 0
144 145 146 147 148 149 150
        if s:
            self.checksum = zlib.crc32(s)

    def base32_digest(self):
        """Return a base32 digest of the checksum
        
        Checksum is computed using the crc32 algorithm.
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
151 152
 
        Returns
153
        -------
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
154 155 156 157
        string
       
        Examples
        --------
158 159 160
        >>> print crc32('test').base32_digest()
        3B7X4DA
        """
161
        return base64.b32encode(base64.b16decode("%08X"%(self.checksum & 0xffffffff))).replace('=','')
162 163
    
    def update(self, s):
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
164 165 166 167 168 169
        """Update this hash object's state with the provided string.
        
        Parameters
        ----------
        s: string.
        """
170 171 172 173 174 175 176 177 178 179 180 181 182
        self.checksum = zlib.crc32(s, self.checksum)

_rm_comment = re.compile(r'^[ \t]*#.*')
_rm_endline_comments = re.compile(r'#.*')
_rm_blank_lines = re.compile(r'^\s*$')
_rm_double_space= re.compile(r'(\S+)\s+')
_rm_endline_space = re.compile(r'\s+$')
_rm_useless_space = re.compile(r'\s*([^A-Za-z0-9 \t\n\r\f\v])\s*')

def reduced_code_formatting(s, unsafe=False):
    """ Return a code string with some part of the non syntactic
    information removed.

Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
183 184 185 186 187 188 189 190 191 192 193
    Parameters
    ----------
    s: string
    unsafe: boolean (optional), if True remove some syntactic information like spaces in string literals.

    Returns
    -------
    string

    Examples
    --------
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    >>> reduced_code_formatting(r'def pouet():\n    #lets try it\n    a,  b = foo ( bar )  \n')
    """
    min_code=""
    for l in s.splitlines():
        if _rm_comment.match(l):
            continue
        if _rm_blank_lines.match(l):
            continue
        l = _rm_endline_comments.sub('',l)
        l = _rm_endline_space.sub(r'',l)
        if unsafe:
            l = _rm_double_space.sub(r'\1 ',l)
            l = _rm_useless_space.sub(r'\1',l)
        min_code += l+'\n'
    return min_code

Marc Betoule's avatar
Marc Betoule committed
210
def hash_file(codefile):
Marc Betoule's avatar
Marc Betoule committed
211
    """Use cheksum algorithm to return a unique key for file.
212 213
    
    DEPRECATED: use crc32
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
214 215 216 217 218 219

    Parameters
    ----------
    codefile: string. 

    Returns
220
    -------
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
221 222 223 224
    string

    Examples
    --------
Marc Betoule's avatar
Marc Betoule committed
225
    >>> print(hash_file('../test/codesample.py'))
Marc Betoule's avatar
Marc Betoule committed
226 227 228
    3DDAAEC1
    """
    if not path.exists(codefile):
229
        print('Try to compute checksum of non existing file %s.'%codefile)
Marc Betoule's avatar
Marc Betoule committed
230 231 232 233 234 235 236 237
        return None
    
    sum_binary = "cksum"
    # Computes checksum
    sp = subprocess.Popen([sum_binary, codefile], stdout=subprocess.PIPE)
    res = sp.communicate()[0]
    key = "%X" % int(res.split(' ')[0])
    if sp.returncode != 0:
238
        print('Error while computing checksum of file %s.'%codefile)
Marc Betoule's avatar
Marc Betoule committed
239 240 241
    return key


242 243
def get_hashkey(s, starthash):
    """Return a unique key which identify code string
Maude Le Jeune's avatar
bon ...  
Maude Le Jeune committed
244
    using cheksum algorithm.
Marc Betoule's avatar
Marc Betoule committed
245
    
246
    Comment lines and blanks are not taken into account in code string.
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
247 248 249

    Parameters
    ----------
250
    s: string 
Maude Le Jeune's avatar
doc  
Maude Le Jeune committed
251 252 253 254 255 256 257 258
    starthash: an Hash instance

    Returns
    -------
    string
    
    Examples
    --------
259
    >>> print(get_hashkey("a = 5"))
Marc Betoule's avatar
Marc Betoule committed
260 261
    B6EB81FE
    """
Maude Le Jeune's avatar
bon ...  
Maude Le Jeune committed
262 263
    if not starthash:
        starthash = crc32()
264 265 266
    
    starthash.update(reduced_code_formatting(s))
    
Maude Le Jeune's avatar
bon ...  
Maude Le Jeune committed
267
    return starthash
Marc Betoule's avatar
Marc Betoule committed
268 269 270 271 272


if __name__ == "__main__":
    import doctest
    doctest.testmod()