Further PEP8 work.

This commit is contained in:
2010-01-26 13:36:11 +00:00
parent 47c58a18de
commit 7f108e80eb

View File

@@ -19,172 +19,174 @@ import logging
class TvOrganiser(): class TvOrganiser():
_config = {} _config = {}
def __init__(self): def __init__(self):
pass pass
@property @property
def _logger(self): def _logger(self):
if not hasattr(self, "__logger"): if not hasattr(self, "__logger"):
self.__logger = logging.getLogger(self.__class__.__name__) self.__logger = logging.getLogger(self.__class__.__name__)
self.__logger.addHandler(logging.StreamHandler()) self.__logger.addHandler(logging.StreamHandler())
return self.__logger return self.__logger
def _getConfig(self, file): def _getConfig(self, file):
config = {} config = {}
configpsr = ConfigParser.RawConfigParser() configpsr = ConfigParser.RawConfigParser()
configpsr.read('tvorganise.cfg') configpsr.read('tvorganise.cfg')
if configpsr.has_section('main'): if configpsr.has_section('main'):
for k, v in configpsr.items('main'): for k, v in configpsr.items('main'):
config[k] = v config[k] = v
if configpsr.has_section('regex'): if configpsr.has_section('regex'):
regex_config = {} regex_config = {}
regex = [] regex = []
# Load in subs before reading in the regex # Load in subs before reading in the regex
for k, v in configpsr.items('regex'): for k, v in configpsr.items('regex'):
if k[:5] != 'regex': if k[:5] != 'regex':
regex_config[k] = v regex_config[k] = v
for k, v in configpsr.items('regex'): for k, v in configpsr.items('regex'):
if k[:5] == 'regex': if k[:5] == 'regex':
regex.append(re.compile(v % regex_config)) regex.append(re.compile(v % regex_config))
config['regex'] = regex config['regex'] = regex
self._config = config self._config = config
return config return config
def _findFiles(self, args): def _findFiles(self, args):
""" """
Takes a list of files/folders, grabs files inside them. Does not recurse Takes a list of files/folders, grabs files inside them. Does not
more than one level (if a folder is supplied, it will list files within) recurse more than one level (if a folder is supplied, it will list
""" files within)
allfiles = [] """
for cfile in args: allfiles = []
if os.path.isdir(cfile): for cfile in args:
for sf in os.listdir(cfile): if os.path.isdir(cfile):
newpath = os.path.join(cfile, sf) for sf in os.listdir(cfile):
if os.path.isfile(newpath): newpath = os.path.join(cfile, sf)
allfiles.append(newpath) if os.path.isfile(newpath):
elif os.path.isfile(cfile): allfiles.append(newpath)
allfiles.append(cfile) elif os.path.isfile(cfile):
return allfiles allfiles.append(cfile)
return allfiles
def processNames(self, names, verbose=False): def processNames(self, names, verbose=False):
""" """
Takes list of names, runs them though the regexs Takes list of names, runs them though the regexs
""" """
allEps = [] allEps = []
for f in names: for f in names:
filepath, filename = os.path.split(f) filepath, filename = os.path.split(f)
filename, ext = os.path.splitext(filename) filename, ext = os.path.splitext(filename)
# Remove leading . from extension # Remove leading . from extension
ext = ext.replace(".", "", 1) ext = ext.replace(".", "", 1)
for r in config['regex']: for r in config['regex']:
match = r.match(filename) match = r.match(filename)
if match: if match:
showname, seasno, epno, epname = match.groups() showname, seasno, epno, epname = match.groups()
#remove ._- characters from name (- removed only if next to end of line) #remove ._- characters from name
showname = re.sub("[\._]|\-(?=$)", " ", showname).strip() showname = re.sub("[\._]|\-(?=$)", " ", showname).strip()
seasno, epno = int(seasno), int(epno) seasno, epno = int(seasno), int(epno)
self._logger.debug("File:", filename) self._logger.debug("File:", filename)
self._logger.debug("Pattern:", r.pattern) self._logger.debug("Pattern:", r.pattern)
self._logger.debug("Showname:", showname) self._logger.debug("Showname:", showname)
self._logger.debug("Seas:", seasno) self._logger.debug("Seas:", seasno)
self._logger.debug("Ep:", epno) self._logger.debug("Ep:", epno)
allEps.append({'file_showname': showname, allEps.append({'file_showname': showname,
'seasno': seasno, 'seasno': seasno,
'epno': epno, 'epno': epno,
'filepath': filepath, 'filepath': filepath,
'filename': filename, 'filename': filename,
'ext': ext}) 'ext': ext})
break # Matched - to the next file! break # Matched - to the next file!
else: else:
self._logger.warning("Invalid name: %s" % (f)) self._logger.warning("Invalid name: %s" % (f))
return allEps return allEps
def _same_partition(f1, f2): def _same_partition(f1, f2):
return os.stat(f1).st_dev == os.stat(f2).st_dev return os.stat(f1).st_dev == os.stat(f2).st_dev
########################### ###########################
def main(self): def main(self):
parser = OptionParser(usage="%prog [options] <file or directories>") parser = OptionParser(usage="%prog [options] <file or directories>")
parser.add_option("-a", "--always", dest = "always", parser.add_option("-a", "--always", dest="always",
action = "store_true", default = False, action="store_true", default=False,
help = "Do not ask for confirmation before copying") help="Do not ask for confirmation before copying")
parser.add_option("-q", "--quiet", dest = "quiet", parser.add_option("-q", "--quiet", dest="quiet",
action = "store_true", default = False, action="store_true", default=False,
help = "Silence output") help="Silence output")
parser.add_option("-c", "--config", dest = "config", parser.add_option("-c", "--config", dest="config",
action = "store", default = "tvorganise.cfg", action="store", default="tvorganise.cfg",
help = "Use a custom configuration file") help="Use a custom configuration file")
parser.add_option("-v", "", dest = "verbose", parser.add_option("-v", "", dest="verbose",
action = "store_true", default = False, action="store_true", default=False,
help = "Verbose output") help="Verbose output")
opts, args = parser.parse_args() opts, args = parser.parse_args()
if os.path.exists(opts.config): if os.path.exists(opts.config):
config = self._getConfig(opts.config) config = self._getConfig(opts.config)
else: else:
self._logger.error('Unable to find configuration file!') self._logger.error('Unable to find configuration file!')
sys.exit(1) sys.exit(1)
files = self._findFiles(args) files = self._findFiles(args)
files = self.processNames(files, opts.verbose) files = self.processNames(files, opts.verbose)
# Warn if no files are found, then exit # Warn if no files are found, then exit
if len(files) == 0: if len(files) == 0:
self._logger.error('No files found') self._logger.error('No files found')
sys.exit(0) sys.exit(0)
for name in files: for name in files:
oldfile = os.path.join(name['filepath'], name['filename']) + "." + name['ext'] filename = "%s.%s" % (name['filename'], name['ext'])
newpath = config['target_path'] % name oldfile = os.path.join(name['filepath'], filename)
newfile = os.path.join(newpath, name['filename']) + "." + name['ext'] newpath = config['target_path'] % name
newfile = os.path.join(newpath, filename)
self._logger.info("Old path:", oldfile)
self._logger.info("New path:", newfile) self._logger.info("Old path:", oldfile)
self._logger.info("New path:", newfile)
if opts.always:
if not os.path.exists(newpath): if opts.always:
os.mkdirs(newpath) if not os.path.exists(newpath):
if os.path.exists(newfile): os.mkdirs(newpath)
self._logger.warning("[!] File already exists, not copying") if os.path.exists(newfile):
else: self._logger.warning("[!] File already exists, not copying")
if self._same_partition(oldfile, newpath): else:
self._logger.info("[*] Moving file") if self._same_partition(oldfile, newpath):
try: self._logger.info("[*] Moving file")
os.rename(oldfile, newfile) try:
except Exception, errormsg: os.rename(oldfile, newfile)
self._logger.error("[!] Error moving file! %s" % (errormsg)) except Exception, errormsg:
else: self._logger.error("[!] Error moving file! %s" % (errormsg))
self._logger.info("[*] Copying file") else:
try: self._logger.info("[*] Copying file")
shutil.copy(oldfile, newfile) try:
except Exception, errormsg: shutil.copy(oldfile, newfile)
self._logger.error("[!] Error copying file! %s" % (errormsg)) except Exception, errormsg:
else: self._logger.error("[!] Error copying file! %s" % (errormsg))
self._logger.info("[*] ..done") else:
else: self._logger.info("[*] ..done")
self._logger.warning("Skipping file") else:
self._logger.warning("Skipping file")
if __name__ == '__main__': if __name__ == '__main__':
t = TvOrganiser() t = TvOrganiser()
t.main() t.main()