configurationengine/source/testautomation/testautomation/unzip_file.py
changeset 0 2e8eeb919028
equal deleted inserted replaced
-1:000000000000 0:2e8eeb919028
       
     1 #
       
     2 # Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3 # All rights reserved.
       
     4 # This component and the accompanying materials are made available
       
     5 # under the terms of "Eclipse Public License v1.0"
       
     6 # which accompanies this distribution, and is available
       
     7 # at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 #
       
     9 # Initial Contributors:
       
    10 # Nokia Corporation - initial contribution.
       
    11 #
       
    12 # Contributors:
       
    13 #
       
    14 # Description: 
       
    15 #
       
    16 
       
    17 import os, zipfile, shutil
       
    18 
       
    19 def unzip_file(file, dir, delete_if_exists=False):
       
    20     if os.path.exists(dir):
       
    21         if delete_if_exists == True:
       
    22             shutil.rmtree(dir)
       
    23         else:
       
    24             raise RuntimeError("Directory '%s' already exists" % dir)
       
    25     if not os.path.exists(file):
       
    26         raise RuntimeError("File '%s' does not exist" % file)
       
    27     
       
    28     os.makedirs(dir)
       
    29     zf = zipfile.ZipFile(file)
       
    30     
       
    31     try:
       
    32         for name in zf.namelist():
       
    33             if name.endswith('/'):
       
    34                 path = os.path.join(dir, name)
       
    35                 if not os.path.exists(path):
       
    36                     os.makedirs(path)
       
    37             else:
       
    38                 path = os.path.join(dir, name)
       
    39                 dirname = os.path.dirname(path)
       
    40                 if dirname != '' and not os.path.exists(dirname):
       
    41                     os.makedirs(dirname)
       
    42                 f = open(path, 'wb')
       
    43                 try:        f.write(zf.read(name))
       
    44                 finally:    f.close()
       
    45     finally:
       
    46         zf.close()
       
    47 
       
    48 def unzip_file_if_newer(file, dir):
       
    49     if not os.path.exists(file):
       
    50         raise RuntimeError("File '%s' does not exist" % file)
       
    51     
       
    52     if not os.path.exists(dir) or os.stat(file)[8] > os.stat(dir)[8]:
       
    53         unzip_file(file, dir, True)