refactor (continue)

This commit is contained in:
Davide Romanini 2015-02-11 19:45:45 +01:00
parent 3138f65394
commit bfc2bed737
8 changed files with 1142 additions and 1142 deletions

View File

@ -1,140 +1,140 @@
#ifndef _UNRAR_DLL_ #ifndef _UNRAR_DLL_
#define _UNRAR_DLL_ #define _UNRAR_DLL_
#define ERAR_END_ARCHIVE 10 #define ERAR_END_ARCHIVE 10
#define ERAR_NO_MEMORY 11 #define ERAR_NO_MEMORY 11
#define ERAR_BAD_DATA 12 #define ERAR_BAD_DATA 12
#define ERAR_BAD_ARCHIVE 13 #define ERAR_BAD_ARCHIVE 13
#define ERAR_UNKNOWN_FORMAT 14 #define ERAR_UNKNOWN_FORMAT 14
#define ERAR_EOPEN 15 #define ERAR_EOPEN 15
#define ERAR_ECREATE 16 #define ERAR_ECREATE 16
#define ERAR_ECLOSE 17 #define ERAR_ECLOSE 17
#define ERAR_EREAD 18 #define ERAR_EREAD 18
#define ERAR_EWRITE 19 #define ERAR_EWRITE 19
#define ERAR_SMALL_BUF 20 #define ERAR_SMALL_BUF 20
#define ERAR_UNKNOWN 21 #define ERAR_UNKNOWN 21
#define ERAR_MISSING_PASSWORD 22 #define ERAR_MISSING_PASSWORD 22
#define RAR_OM_LIST 0 #define RAR_OM_LIST 0
#define RAR_OM_EXTRACT 1 #define RAR_OM_EXTRACT 1
#define RAR_OM_LIST_INCSPLIT 2 #define RAR_OM_LIST_INCSPLIT 2
#define RAR_SKIP 0 #define RAR_SKIP 0
#define RAR_TEST 1 #define RAR_TEST 1
#define RAR_EXTRACT 2 #define RAR_EXTRACT 2
#define RAR_VOL_ASK 0 #define RAR_VOL_ASK 0
#define RAR_VOL_NOTIFY 1 #define RAR_VOL_NOTIFY 1
#define RAR_DLL_VERSION 4 #define RAR_DLL_VERSION 4
#ifdef _UNIX #ifdef _UNIX
#define CALLBACK #define CALLBACK
#define PASCAL #define PASCAL
#define LONG long #define LONG long
#define HANDLE void * #define HANDLE void *
#define LPARAM long #define LPARAM long
#define UINT unsigned int #define UINT unsigned int
#endif #endif
struct RARHeaderData struct RARHeaderData
{ {
char ArcName[260]; char ArcName[260];
char FileName[260]; char FileName[260];
unsigned int Flags; unsigned int Flags;
unsigned int PackSize; unsigned int PackSize;
unsigned int UnpSize; unsigned int UnpSize;
unsigned int HostOS; unsigned int HostOS;
unsigned int FileCRC; unsigned int FileCRC;
unsigned int FileTime; unsigned int FileTime;
unsigned int UnpVer; unsigned int UnpVer;
unsigned int Method; unsigned int Method;
unsigned int FileAttr; unsigned int FileAttr;
char *CmtBuf; char *CmtBuf;
unsigned int CmtBufSize; unsigned int CmtBufSize;
unsigned int CmtSize; unsigned int CmtSize;
unsigned int CmtState; unsigned int CmtState;
}; };
struct RARHeaderDataEx struct RARHeaderDataEx
{ {
char ArcName[1024]; char ArcName[1024];
wchar_t ArcNameW[1024]; wchar_t ArcNameW[1024];
char FileName[1024]; char FileName[1024];
wchar_t FileNameW[1024]; wchar_t FileNameW[1024];
unsigned int Flags; unsigned int Flags;
unsigned int PackSize; unsigned int PackSize;
unsigned int PackSizeHigh; unsigned int PackSizeHigh;
unsigned int UnpSize; unsigned int UnpSize;
unsigned int UnpSizeHigh; unsigned int UnpSizeHigh;
unsigned int HostOS; unsigned int HostOS;
unsigned int FileCRC; unsigned int FileCRC;
unsigned int FileTime; unsigned int FileTime;
unsigned int UnpVer; unsigned int UnpVer;
unsigned int Method; unsigned int Method;
unsigned int FileAttr; unsigned int FileAttr;
char *CmtBuf; char *CmtBuf;
unsigned int CmtBufSize; unsigned int CmtBufSize;
unsigned int CmtSize; unsigned int CmtSize;
unsigned int CmtState; unsigned int CmtState;
unsigned int Reserved[1024]; unsigned int Reserved[1024];
}; };
struct RAROpenArchiveData struct RAROpenArchiveData
{ {
char *ArcName; char *ArcName;
unsigned int OpenMode; unsigned int OpenMode;
unsigned int OpenResult; unsigned int OpenResult;
char *CmtBuf; char *CmtBuf;
unsigned int CmtBufSize; unsigned int CmtBufSize;
unsigned int CmtSize; unsigned int CmtSize;
unsigned int CmtState; unsigned int CmtState;
}; };
struct RAROpenArchiveDataEx struct RAROpenArchiveDataEx
{ {
char *ArcName; char *ArcName;
wchar_t *ArcNameW; wchar_t *ArcNameW;
unsigned int OpenMode; unsigned int OpenMode;
unsigned int OpenResult; unsigned int OpenResult;
char *CmtBuf; char *CmtBuf;
unsigned int CmtBufSize; unsigned int CmtBufSize;
unsigned int CmtSize; unsigned int CmtSize;
unsigned int CmtState; unsigned int CmtState;
unsigned int Flags; unsigned int Flags;
unsigned int Reserved[32]; unsigned int Reserved[32];
}; };
enum UNRARCALLBACK_MESSAGES { enum UNRARCALLBACK_MESSAGES {
UCM_CHANGEVOLUME,UCM_PROCESSDATA,UCM_NEEDPASSWORD UCM_CHANGEVOLUME,UCM_PROCESSDATA,UCM_NEEDPASSWORD
}; };
typedef int (CALLBACK *UNRARCALLBACK)(UINT msg,LPARAM UserData,LPARAM P1,LPARAM P2); typedef int (CALLBACK *UNRARCALLBACK)(UINT msg,LPARAM UserData,LPARAM P1,LPARAM P2);
typedef int (PASCAL *CHANGEVOLPROC)(char *ArcName,int Mode); typedef int (PASCAL *CHANGEVOLPROC)(char *ArcName,int Mode);
typedef int (PASCAL *PROCESSDATAPROC)(unsigned char *Addr,int Size); typedef int (PASCAL *PROCESSDATAPROC)(unsigned char *Addr,int Size);
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
HANDLE PASCAL RAROpenArchive(struct RAROpenArchiveData *ArchiveData); HANDLE PASCAL RAROpenArchive(struct RAROpenArchiveData *ArchiveData);
HANDLE PASCAL RAROpenArchiveEx(struct RAROpenArchiveDataEx *ArchiveData); HANDLE PASCAL RAROpenArchiveEx(struct RAROpenArchiveDataEx *ArchiveData);
int PASCAL RARCloseArchive(HANDLE hArcData); int PASCAL RARCloseArchive(HANDLE hArcData);
int PASCAL RARReadHeader(HANDLE hArcData,struct RARHeaderData *HeaderData); int PASCAL RARReadHeader(HANDLE hArcData,struct RARHeaderData *HeaderData);
int PASCAL RARReadHeaderEx(HANDLE hArcData,struct RARHeaderDataEx *HeaderData); int PASCAL RARReadHeaderEx(HANDLE hArcData,struct RARHeaderDataEx *HeaderData);
int PASCAL RARProcessFile(HANDLE hArcData,int Operation,char *DestPath,char *DestName); int PASCAL RARProcessFile(HANDLE hArcData,int Operation,char *DestPath,char *DestName);
int PASCAL RARProcessFileW(HANDLE hArcData,int Operation,wchar_t *DestPath,wchar_t *DestName); int PASCAL RARProcessFileW(HANDLE hArcData,int Operation,wchar_t *DestPath,wchar_t *DestName);
void PASCAL RARSetCallback(HANDLE hArcData,UNRARCALLBACK Callback,LPARAM UserData); void PASCAL RARSetCallback(HANDLE hArcData,UNRARCALLBACK Callback,LPARAM UserData);
void PASCAL RARSetChangeVolProc(HANDLE hArcData,CHANGEVOLPROC ChangeVolProc); void PASCAL RARSetChangeVolProc(HANDLE hArcData,CHANGEVOLPROC ChangeVolProc);
void PASCAL RARSetProcessDataProc(HANDLE hArcData,PROCESSDATAPROC ProcessDataProc); void PASCAL RARSetProcessDataProc(HANDLE hArcData,PROCESSDATAPROC ProcessDataProc);
void PASCAL RARSetPassword(HANDLE hArcData,char *Password); void PASCAL RARSetPassword(HANDLE hArcData,char *Password);
int PASCAL RARGetDllVersion(); int PASCAL RARGetDllVersion();
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -1,80 +1,80 @@
List of unrar.dll API changes. We do not include performance and reliability List of unrar.dll API changes. We do not include performance and reliability
improvements into this list, but this library and RAR/UnRAR tools share improvements into this list, but this library and RAR/UnRAR tools share
the same source code. So the latest version of unrar.dll usually contains the same source code. So the latest version of unrar.dll usually contains
same decompression algorithm changes as the latest UnRAR version. same decompression algorithm changes as the latest UnRAR version.
============================================================================ ============================================================================
-- 18 January 2008 -- 18 January 2008
all LONG parameters of CallbackProc function were changed all LONG parameters of CallbackProc function were changed
to LPARAM type for 64 bit mode compatibility. to LPARAM type for 64 bit mode compatibility.
-- 12 December 2007 -- 12 December 2007
Added new RAR_OM_LIST_INCSPLIT open mode for function RAROpenArchive. Added new RAR_OM_LIST_INCSPLIT open mode for function RAROpenArchive.
-- 14 August 2007 -- 14 August 2007
Added NoCrypt\unrar_nocrypt.dll without decryption code for those Added NoCrypt\unrar_nocrypt.dll without decryption code for those
applications where presence of encryption or decryption code is not applications where presence of encryption or decryption code is not
allowed because of legal restrictions. allowed because of legal restrictions.
-- 14 December 2006 -- 14 December 2006
Added ERAR_MISSING_PASSWORD error type. This error is returned Added ERAR_MISSING_PASSWORD error type. This error is returned
if empty password is specified for encrypted file. if empty password is specified for encrypted file.
-- 12 June 2003 -- 12 June 2003
Added RARProcessFileW function, Unicode version of RARProcessFile Added RARProcessFileW function, Unicode version of RARProcessFile
-- 9 August 2002 -- 9 August 2002
Added RAROpenArchiveEx function allowing to specify Unicode archive Added RAROpenArchiveEx function allowing to specify Unicode archive
name and get archive flags. name and get archive flags.
-- 24 January 2002 -- 24 January 2002
Added RARReadHeaderEx function allowing to read Unicode file names Added RARReadHeaderEx function allowing to read Unicode file names
and 64 bit file sizes. and 64 bit file sizes.
-- 23 January 2002 -- 23 January 2002
Added ERAR_UNKNOWN error type (it is used for all errors which Added ERAR_UNKNOWN error type (it is used for all errors which
do not have special ERAR code yet) and UCM_NEEDPASSWORD callback do not have special ERAR code yet) and UCM_NEEDPASSWORD callback
message. message.
Unrar.dll automatically opens all next volumes not only when extracting, Unrar.dll automatically opens all next volumes not only when extracting,
but also in RAR_OM_LIST mode. but also in RAR_OM_LIST mode.
-- 27 November 2001 -- 27 November 2001
RARSetChangeVolProc and RARSetProcessDataProc are replaced by RARSetChangeVolProc and RARSetProcessDataProc are replaced by
the single callback function installed with RARSetCallback. the single callback function installed with RARSetCallback.
Unlike old style callbacks, the new function accepts the user defined Unlike old style callbacks, the new function accepts the user defined
parameter. Unrar.dll still supports RARSetChangeVolProc and parameter. Unrar.dll still supports RARSetChangeVolProc and
RARSetProcessDataProc for compatibility purposes, but if you write RARSetProcessDataProc for compatibility purposes, but if you write
a new application, better use RARSetCallback. a new application, better use RARSetCallback.
File comments support is not implemented in the new DLL version yet. File comments support is not implemented in the new DLL version yet.
Now CmtState is always 0. Now CmtState is always 0.
-- 13 August 2001 -- 13 August 2001
Added RARGetDllVersion function, so you may distinguish old unrar.dll, Added RARGetDllVersion function, so you may distinguish old unrar.dll,
which used C style callback functions and the new one with PASCAL callbacks. which used C style callback functions and the new one with PASCAL callbacks.
-- 10 May 2001 -- 10 May 2001
Callback functions in RARSetChangeVolProc and RARSetProcessDataProc Callback functions in RARSetChangeVolProc and RARSetProcessDataProc
use PASCAL style call convention now. use PASCAL style call convention now.

View File

@ -1 +1 @@
This is x64 version of unrar.dll. This is x64 version of unrar.dll.

Binary file not shown.

View File

@ -1,177 +1,177 @@
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov
# #
# Permission is hereby granted, free of charge, to any person obtaining # Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the # a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including # "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, # without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to # distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to # permit persons to whom the Software is furnished to do so, subject to
# the following conditions: # the following conditions:
# #
# The above copyright notice and this permission notice shall be # The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software. # included in all copies or substantial portions of the Software.
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
""" """
pyUnRAR2 is a ctypes based wrapper around the free UnRAR.dll. pyUnRAR2 is a ctypes based wrapper around the free UnRAR.dll.
It is an modified version of Jimmy Retzlaff's pyUnRAR - more simple, It is an modified version of Jimmy Retzlaff's pyUnRAR - more simple,
stable and foolproof. stable and foolproof.
Notice that it has INCOMPATIBLE interface. Notice that it has INCOMPATIBLE interface.
It enables reading and unpacking of archives created with the It enables reading and unpacking of archives created with the
RAR/WinRAR archivers. There is a low-level interface which is very RAR/WinRAR archivers. There is a low-level interface which is very
similar to the C interface provided by UnRAR. There is also a similar to the C interface provided by UnRAR. There is also a
higher level interface which makes some common operations easier. higher level interface which makes some common operations easier.
""" """
__version__ = '0.99.3' __version__ = '0.99.3'
try: try:
WindowsError WindowsError
in_windows = True in_windows = True
except NameError: except NameError:
in_windows = False in_windows = False
if in_windows: if in_windows:
from windows import RarFileImplementation from windows import RarFileImplementation
else: else:
from unix import RarFileImplementation from unix import RarFileImplementation
import fnmatch, time, weakref import fnmatch, time, weakref
class RarInfo(object): class RarInfo(object):
"""Represents a file header in an archive. Don't instantiate directly. """Represents a file header in an archive. Don't instantiate directly.
Use only to obtain information about file. Use only to obtain information about file.
YOU CANNOT EXTRACT FILE CONTENTS USING THIS OBJECT. YOU CANNOT EXTRACT FILE CONTENTS USING THIS OBJECT.
USE METHODS OF RarFile CLASS INSTEAD. USE METHODS OF RarFile CLASS INSTEAD.
Properties: Properties:
index - index of file within the archive index - index of file within the archive
filename - name of the file in the archive including path (if any) filename - name of the file in the archive including path (if any)
datetime - file date/time as a struct_time suitable for time.strftime datetime - file date/time as a struct_time suitable for time.strftime
isdir - True if the file is a directory isdir - True if the file is a directory
size - size in bytes of the uncompressed file size - size in bytes of the uncompressed file
comment - comment associated with the file comment - comment associated with the file
Note - this is not currently intended to be a Python file-like object. Note - this is not currently intended to be a Python file-like object.
""" """
def __init__(self, rarfile, data): def __init__(self, rarfile, data):
self.rarfile = weakref.proxy(rarfile) self.rarfile = weakref.proxy(rarfile)
self.index = data['index'] self.index = data['index']
self.filename = data['filename'] self.filename = data['filename']
self.isdir = data['isdir'] self.isdir = data['isdir']
self.size = data['size'] self.size = data['size']
self.datetime = data['datetime'] self.datetime = data['datetime']
self.comment = data['comment'] self.comment = data['comment']
def __str__(self): def __str__(self):
try : try :
arcName = self.rarfile.archiveName arcName = self.rarfile.archiveName
except ReferenceError: except ReferenceError:
arcName = "[ARCHIVE_NO_LONGER_LOADED]" arcName = "[ARCHIVE_NO_LONGER_LOADED]"
return '<RarInfo "%s" in "%s">' % (self.filename, arcName) return '<RarInfo "%s" in "%s">' % (self.filename, arcName)
class RarFile(RarFileImplementation): class RarFile(RarFileImplementation):
def __init__(self, archiveName, password=None): def __init__(self, archiveName, password=None):
"""Instantiate the archive. """Instantiate the archive.
archiveName is the name of the RAR file. archiveName is the name of the RAR file.
password is used to decrypt the files in the archive. password is used to decrypt the files in the archive.
Properties: Properties:
comment - comment associated with the archive comment - comment associated with the archive
>>> print RarFile('test.rar').comment >>> print RarFile('test.rar').comment
This is a test. This is a test.
""" """
self.archiveName = archiveName self.archiveName = archiveName
RarFileImplementation.init(self, password) RarFileImplementation.init(self, password)
def __del__(self): def __del__(self):
self.destruct() self.destruct()
def infoiter(self): def infoiter(self):
"""Iterate over all the files in the archive, generating RarInfos. """Iterate over all the files in the archive, generating RarInfos.
>>> import os >>> import os
>>> for fileInArchive in RarFile('test.rar').infoiter(): >>> for fileInArchive in RarFile('test.rar').infoiter():
... print os.path.split(fileInArchive.filename)[-1], ... print os.path.split(fileInArchive.filename)[-1],
... print fileInArchive.isdir, ... print fileInArchive.isdir,
... print fileInArchive.size, ... print fileInArchive.size,
... print fileInArchive.comment, ... print fileInArchive.comment,
... print tuple(fileInArchive.datetime)[0:5], ... print tuple(fileInArchive.datetime)[0:5],
... print time.strftime('%a, %d %b %Y %H:%M', fileInArchive.datetime) ... print time.strftime('%a, %d %b %Y %H:%M', fileInArchive.datetime)
test True 0 None (2003, 6, 30, 1, 59) Mon, 30 Jun 2003 01:59 test True 0 None (2003, 6, 30, 1, 59) Mon, 30 Jun 2003 01:59
test.txt False 20 None (2003, 6, 30, 2, 1) Mon, 30 Jun 2003 02:01 test.txt False 20 None (2003, 6, 30, 2, 1) Mon, 30 Jun 2003 02:01
this.py False 1030 None (2002, 2, 8, 16, 47) Fri, 08 Feb 2002 16:47 this.py False 1030 None (2002, 2, 8, 16, 47) Fri, 08 Feb 2002 16:47
""" """
for params in RarFileImplementation.infoiter(self): for params in RarFileImplementation.infoiter(self):
yield RarInfo(self, params) yield RarInfo(self, params)
def infolist(self): def infolist(self):
"""Return a list of RarInfos, descripting the contents of the archive.""" """Return a list of RarInfos, descripting the contents of the archive."""
return list(self.infoiter()) return list(self.infoiter())
def read_files(self, condition='*'): def read_files(self, condition='*'):
"""Read specific files from archive into memory. """Read specific files from archive into memory.
If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a list of numbers, then return files which have those positions in infolist.
If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a string, then it is treated as a wildcard for names of files to extract.
If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object
and returns boolean True (extract) or False (skip). and returns boolean True (extract) or False (skip).
If "condition" is omitted, all files are returned. If "condition" is omitted, all files are returned.
Returns list of tuples (RarInfo info, str contents) Returns list of tuples (RarInfo info, str contents)
""" """
checker = condition2checker(condition) checker = condition2checker(condition)
return RarFileImplementation.read_files(self, checker) return RarFileImplementation.read_files(self, checker)
def extract(self, condition='*', path='.', withSubpath=True, overwrite=True): def extract(self, condition='*', path='.', withSubpath=True, overwrite=True):
"""Extract specific files from archive to disk. """Extract specific files from archive to disk.
If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a list of numbers, then extract files which have those positions in infolist.
If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a string, then it is treated as a wildcard for names of files to extract.
If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object
and returns either boolean True (extract) or boolean False (skip). and returns either boolean True (extract) or boolean False (skip).
DEPRECATED: If "condition" callback returns string (only supported for Windows) - DEPRECATED: If "condition" callback returns string (only supported for Windows) -
that string will be used as a new name to save the file under. that string will be used as a new name to save the file under.
If "condition" is omitted, all files are extracted. If "condition" is omitted, all files are extracted.
"path" is a directory to extract to "path" is a directory to extract to
"withSubpath" flag denotes whether files are extracted with their full path in the archive. "withSubpath" flag denotes whether files are extracted with their full path in the archive.
"overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true. "overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true.
Returns list of RarInfos for extracted files.""" Returns list of RarInfos for extracted files."""
checker = condition2checker(condition) checker = condition2checker(condition)
return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite) return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite)
def condition2checker(condition): def condition2checker(condition):
"""Converts different condition types to callback""" """Converts different condition types to callback"""
if type(condition) in [str, unicode]: if type(condition) in [str, unicode]:
def smatcher(info): def smatcher(info):
return fnmatch.fnmatch(info.filename, condition) return fnmatch.fnmatch(info.filename, condition)
return smatcher return smatcher
elif type(condition) in [list, tuple] and type(condition[0]) in [int, long]: elif type(condition) in [list, tuple] and type(condition[0]) in [int, long]:
def imatcher(info): def imatcher(info):
return info.index in condition return info.index in condition
return imatcher return imatcher
elif callable(condition): elif callable(condition):
return condition return condition
else: else:
raise TypeError raise TypeError

View File

@ -1,138 +1,138 @@
import os, sys import os, sys
import UnRAR2 import UnRAR2
from UnRAR2.rar_exceptions import * from UnRAR2.rar_exceptions import *
def cleanup(dir='test'): def cleanup(dir='test'):
for path, dirs, files in os.walk(dir): for path, dirs, files in os.walk(dir):
for fn in files: for fn in files:
os.remove(os.path.join(path, fn)) os.remove(os.path.join(path, fn))
for dir in dirs: for dir in dirs:
os.removedirs(os.path.join(path, dir)) os.removedirs(os.path.join(path, dir))
# basic test # basic test
cleanup() cleanup()
rarc = UnRAR2.RarFile('test.rar') rarc = UnRAR2.RarFile('test.rar')
rarc.infolist() rarc.infolist()
assert rarc.comment == "This is a test." assert rarc.comment == "This is a test."
for info in rarc.infoiter(): for info in rarc.infoiter():
saveinfo = info saveinfo = info
assert (str(info)=="""<RarInfo "test" in "test.rar">""") assert (str(info)=="""<RarInfo "test" in "test.rar">""")
break break
rarc.extract() rarc.extract()
assert os.path.exists('test'+os.sep+'test.txt') assert os.path.exists('test'+os.sep+'test.txt')
assert os.path.exists('test'+os.sep+'this.py') assert os.path.exists('test'+os.sep+'this.py')
del rarc del rarc
assert (str(saveinfo)=="""<RarInfo "test" in "[ARCHIVE_NO_LONGER_LOADED]">""") assert (str(saveinfo)=="""<RarInfo "test" in "[ARCHIVE_NO_LONGER_LOADED]">""")
cleanup() cleanup()
# extract all the files in test.rar # extract all the files in test.rar
cleanup() cleanup()
UnRAR2.RarFile('test.rar').extract() UnRAR2.RarFile('test.rar').extract()
assert os.path.exists('test'+os.sep+'test.txt') assert os.path.exists('test'+os.sep+'test.txt')
assert os.path.exists('test'+os.sep+'this.py') assert os.path.exists('test'+os.sep+'this.py')
cleanup() cleanup()
# extract all the files in test.rar matching the wildcard *.txt # extract all the files in test.rar matching the wildcard *.txt
cleanup() cleanup()
UnRAR2.RarFile('test.rar').extract('*.txt') UnRAR2.RarFile('test.rar').extract('*.txt')
assert os.path.exists('test'+os.sep+'test.txt') assert os.path.exists('test'+os.sep+'test.txt')
assert not os.path.exists('test'+os.sep+'this.py') assert not os.path.exists('test'+os.sep+'this.py')
cleanup() cleanup()
# check the name and size of each file, extracting small ones # check the name and size of each file, extracting small ones
cleanup() cleanup()
archive = UnRAR2.RarFile('test.rar') archive = UnRAR2.RarFile('test.rar')
assert archive.comment == 'This is a test.' assert archive.comment == 'This is a test.'
archive.extract(lambda rarinfo: rarinfo.size <= 1024) archive.extract(lambda rarinfo: rarinfo.size <= 1024)
for rarinfo in archive.infoiter(): for rarinfo in archive.infoiter():
if rarinfo.size <= 1024 and not rarinfo.isdir: if rarinfo.size <= 1024 and not rarinfo.isdir:
assert rarinfo.size == os.stat(rarinfo.filename).st_size assert rarinfo.size == os.stat(rarinfo.filename).st_size
assert file('test'+os.sep+'test.txt', 'rt').read() == 'This is only a test.' assert file('test'+os.sep+'test.txt', 'rt').read() == 'This is only a test.'
assert not os.path.exists('test'+os.sep+'this.py') assert not os.path.exists('test'+os.sep+'this.py')
cleanup() cleanup()
# extract this.py, overriding it's destination # extract this.py, overriding it's destination
cleanup('test2') cleanup('test2')
archive = UnRAR2.RarFile('test.rar') archive = UnRAR2.RarFile('test.rar')
archive.extract('*.py', 'test2', False) archive.extract('*.py', 'test2', False)
assert os.path.exists('test2'+os.sep+'this.py') assert os.path.exists('test2'+os.sep+'this.py')
cleanup('test2') cleanup('test2')
# extract test.txt to memory # extract test.txt to memory
cleanup() cleanup()
archive = UnRAR2.RarFile('test.rar') archive = UnRAR2.RarFile('test.rar')
entries = UnRAR2.RarFile('test.rar').read_files('*test.txt') entries = UnRAR2.RarFile('test.rar').read_files('*test.txt')
assert len(entries)==1 assert len(entries)==1
assert entries[0][0].filename.endswith('test.txt') assert entries[0][0].filename.endswith('test.txt')
assert entries[0][1]=='This is only a test.' assert entries[0][1]=='This is only a test.'
# extract all the files in test.rar with overwriting # extract all the files in test.rar with overwriting
cleanup() cleanup()
fo = open('test'+os.sep+'test.txt',"wt") fo = open('test'+os.sep+'test.txt',"wt")
fo.write("blah") fo.write("blah")
fo.close() fo.close()
UnRAR2.RarFile('test.rar').extract('*.txt') UnRAR2.RarFile('test.rar').extract('*.txt')
assert open('test'+os.sep+'test.txt',"rt").read()!="blah" assert open('test'+os.sep+'test.txt',"rt").read()!="blah"
cleanup() cleanup()
# extract all the files in test.rar without overwriting # extract all the files in test.rar without overwriting
cleanup() cleanup()
fo = open('test'+os.sep+'test.txt',"wt") fo = open('test'+os.sep+'test.txt',"wt")
fo.write("blahblah") fo.write("blahblah")
fo.close() fo.close()
UnRAR2.RarFile('test.rar').extract('*.txt', overwrite = False) UnRAR2.RarFile('test.rar').extract('*.txt', overwrite = False)
assert open('test'+os.sep+'test.txt',"rt").read()=="blahblah" assert open('test'+os.sep+'test.txt',"rt").read()=="blahblah"
cleanup() cleanup()
# list big file in an archive # list big file in an archive
list(UnRAR2.RarFile('test_nulls.rar').infoiter()) list(UnRAR2.RarFile('test_nulls.rar').infoiter())
# extract files from an archive with protected files # extract files from an archive with protected files
cleanup() cleanup()
rarc = UnRAR2.RarFile('test_protected_files.rar', password="protected") rarc = UnRAR2.RarFile('test_protected_files.rar', password="protected")
rarc.extract() rarc.extract()
assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt') assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
cleanup() cleanup()
errored = False errored = False
try: try:
UnRAR2.RarFile('test_protected_files.rar', password="proteqted").extract() UnRAR2.RarFile('test_protected_files.rar', password="proteqted").extract()
except IncorrectRARPassword: except IncorrectRARPassword:
errored = True errored = True
assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt') assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
assert errored assert errored
cleanup() cleanup()
# extract files from an archive with protected headers # extract files from an archive with protected headers
cleanup() cleanup()
UnRAR2.RarFile('test_protected_headers.rar', password="secret").extract() UnRAR2.RarFile('test_protected_headers.rar', password="secret").extract()
assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt') assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
cleanup() cleanup()
errored = False errored = False
try: try:
UnRAR2.RarFile('test_protected_headers.rar', password="seqret").extract() UnRAR2.RarFile('test_protected_headers.rar', password="seqret").extract()
except IncorrectRARPassword: except IncorrectRARPassword:
errored = True errored = True
assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt') assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
assert errored assert errored
cleanup() cleanup()
# make sure docstring examples are working # make sure docstring examples are working
import doctest import doctest
doctest.testmod(UnRAR2) doctest.testmod(UnRAR2)
# update documentation # update documentation
import pydoc import pydoc
pydoc.writedoc(UnRAR2) pydoc.writedoc(UnRAR2)
# cleanup # cleanup
try: try:
os.remove('__init__.pyc') os.remove('__init__.pyc')
except: except:
pass pass