2 # vim: set ts=4 sts=4 sw=4 textwidth=92:
5 Holds the PAR2Set base class
8 __author__ = "Ira W. Snyder (devel@irasnyder.com)"
9 __copyright__ = "Copyright (c) 2006,2007 Ira W. Snyder (devel@irasnyder.com)"
10 __license__ = "GNU GPL v2 (or, at your option, any later version)"
14 # Copyright (C) 2006,2007 Ira W. Snyder (devel@irasnyder.com)
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 # This is a fairly generic class which does all of the major things that a PAR2
37 # set will need to have done to be verified and extracted. For most "normal" types
38 # you won't need to override hardly anything.
40 # It is ok to override other functions if the need arises, just make sure that you
41 # understand why things are done the way that they are in the original versions.
43 # Assumptions made in the runVerifyAndRepair(), runExtract() and runDelete() functions:
44 # ==============================================================================
45 # The state of self.name_matched_files, self.prot_matched_files, and self.all_files
46 # will be consistent with the real, in-filesystem state at the time that they are
47 # called. This is the reason that runAll() calls update_matches() after running each
48 # operation that will possibly change the filesystem.
51 # ==============================================================================
52 # find_extraction_heads ()
53 # extraction_function ()
57 """Base class for all PAR2Set types"""
60 # ==========================================================================
61 # dir -- The directory this set lives in
62 # p2file -- The starting PAR2 file
63 # basename -- The basename of the set, guessed from the PAR2 file
64 # all_p2files -- All PAR2 files of the set, guessed from the PAR2 file name only
65 # name_matched_files -- Files in this set, guessed by name only
66 # prot_matched_files -- Files in this set, guessed by parsing the PAR2 only
68 def __init__ (self, dir, p2file):
69 """Default constructor for all PAR2Set types
72 p2file -- a PAR2 file inside the given directory"""
74 assert os.path.isdir (dir)
75 assert os.path.isfile (os.path.join (dir, p2file))
77 # The real "meat" of the class
80 self.basename = rsutil.common.get_basename (p2file)
82 # Find files that match by name only
83 self.name_matched_files = rsutil.common.find_name_matches (self.dir, self.basename)
85 # Find all par2 files for this set using name matches
86 self.all_p2files = rsutil.common.find_par2_files (self.name_matched_files)
88 # Try to get the protected files for this set
89 self.prot_matched_files = rsutil.common.parse_all_par2 (self.dir, self.p2file, self.all_p2files)
91 # Setup the all_files combined set (for convenience only)
92 self.all_files = rsutil.common.no_duplicates (self.name_matched_files + self.prot_matched_files)
94 def __eq__ (self, rhs):
95 """Check for equality between PAR2Set types"""
97 return (self.dir == rhs.dir) and (self.basename == rhs.basename) and \
98 rsutil.common.list_eq (self.name_matched_files, rhs.name_matched_files) and \
99 rsutil.common.list_eq (self.prot_matched_files, rhs.prot_matched_files)
101 def update_matches (self):
102 """Updates the contents of instance variables with the current in-filesystem state.
103 This should be run after any operation which can create or delete files."""
105 self.name_matched_files = rsutil.common.find_name_matches (self.dir, self.basename)
106 self.all_files = rsutil.common.no_duplicates (self.name_matched_files + self.prot_matched_files)
108 def runVerifyAndRepair (self):
109 """Verify and Repair a PAR2Set. This is done using the par2repair command by
112 rsutil.common.run_command(['par2repair'] + self.all_p2files, self.dir)
114 def find_deleteable_files (self):
115 """Find all files which are deletable by using the regular expression from the
116 configuration file"""
118 DELETE_REGEX = rsutil.common.config_get_value ('regular expressions', 'delete_regex')
119 dregex = re.compile (DELETE_REGEX, re.IGNORECASE)
121 return [f for f in self.all_files if dregex.match (f)]
123 def delete_list_of_files (self, dir, files, interactive=False):
124 """Attempt to delete all files given
126 dir -- the directory where the files live
127 files -- the filenames themselves
128 interactive -- prompt before deleteion"""
130 assert os.path.isdir (dir)
132 # If we are interactive, decide yes or no
135 print 'Do you want to delete the following?:'
139 s = raw_input('Delete [y/N]: ').upper()
141 # If we got a valid no answer, leave now
142 if s in ['N', 'NO', '']:
145 # If we got a valid yes answer, delete them
146 if s in ['Y', 'YES']:
149 # Not a good answer, ask again
150 print 'Invalid response'
152 # We got a yes answer (or are non-interactive), delete the files
155 # Get the full filename
156 fullname = os.path.join(dir, f)
161 logging.debug('Deleting: %s' % fullname)
163 logging.error('Failed to delete: %s' % fullname)
165 def runDelete (self):
166 """Run the delete operation and return the result"""
168 deleteable_files = self.find_deleteable_files ()
169 ret = self.delete_list_of_files (self.dir, deleteable_files, \
170 rsutil.common.options_get_value ('interactive'))
175 """Run all of the major sections in the class: repair, extraction, and deletion."""
179 self.runVerifyAndRepair ()
180 except (RuntimeError, OSError):
181 logging.critical('Repair stage failed for: %s' % self.p2file)
184 self.update_matches()
189 except (RuntimeError, OSError):
190 logging.critical('Extraction stage failed for: %s' % self.p2file)
193 self.update_matches ()
198 except (RuntimeError, OSError):
199 logging.critical('Deletion stage failed for: %s' % self.p2file)
202 logging.info ('Successfully completed: %s' % self.p2file)
204 def runExtract (self):
205 """Extract all heads of this set and return the result"""
207 # Call the extraction function on each head
208 for h in self.find_extraction_heads ():
209 full_head = rsutil.common.full_abspath (os.path.join (self.dir, h))
210 self.extraction_function (full_head, self.dir)
212 def find_extraction_heads (self):
213 """Find all extraction heads associated with this set. This must be
214 overridden for the associated PAR2Set derived class to work."""
216 assert False # You MUST override this on a per-type basis
218 def extraction_function (self, file, todir):
219 """Extract a single head of this PAR2Set's type.
221 file -- the full path to the file to be extracted
222 todir -- the directory to extract to"""
224 assert False # You MUST override this on a per-type basis