| 1 |
|
| 2 |
|
| 3 |
n |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
"""Rename files""" |
| 10 |
|
| 11 |
from .common import PostProcessor |
| 12 |
from .. import formatter |
| 13 |
import os |
| 14 |
|
| 15 |
|
| 16 |
class RenamePP(PostProcessor): |
| 17 |
|
| 18 |
def __init__(self, job, options): |
| 19 |
PostProcessor.__init__(self, job) |
| 20 |
|
| 21 |
self.skip = options.get("skip", True) |
| 22 |
old = options.get("from") |
| 23 |
new = options.get("to") |
| 24 |
|
| 25 |
if old: |
| 26 |
self._old = self._apply_format(old) |
| 27 |
self._new = (self._apply_format(new) if new else |
| 28 |
self._apply_pathfmt) |
| 29 |
job.register_hooks({ |
| 30 |
"prepare": self.rename_from, |
| 31 |
}, options) |
| 32 |
|
| 33 |
elif new: |
| 34 |
self._old = self._apply_pathfmt |
| 35 |
self._new = self._apply_format(new) |
| 36 |
job.register_hooks({ |
| 37 |
"skip" : self.rename_to_skip, |
| 38 |
"prepare-after": self.rename_to_pafter, |
| 39 |
}, options) |
| 40 |
|
| 41 |
else: |
| 42 |
raise ValueError("Option 'from' or 'to' is required") |
| 43 |
|
| 44 |
def rename_from(self, pathfmt): |
| 45 |
name_old = self._old(pathfmt) |
| 46 |
path_old = pathfmt.realdirectory + name_old |
| 47 |
|
| 48 |
if os.path.exists(path_old): |
| 49 |
name_new = self._new(pathfmt) |
| 50 |
path_new = pathfmt.realdirectory + name_new |
| 51 |
self._rename(path_old, name_old, path_new, name_new) |
| 52 |
|
| 53 |
def rename_to_skip(self, pathfmt): |
| 54 |
name_old = self._old(pathfmt) |
| 55 |
path_old = pathfmt.realdirectory + name_old |
| 56 |
|
| 57 |
if os.path.exists(path_old): |
| 58 |
pathfmt.filename = name_new = self._new(pathfmt) |
| 59 |
pathfmt.path = pathfmt.directory + name_new |
| 60 |
pathfmt.realpath = path_new = pathfmt.realdirectory + name_new |
| 61 |
self._rename(path_old, name_old, path_new, name_new) |
| 62 |
|
| 63 |
def rename_to_pafter(self, pathfmt): |
| 64 |
pathfmt.filename = name_new = self._new(pathfmt) |
| 65 |
pathfmt.path = pathfmt.directory + name_new |
| 66 |
pathfmt.realpath = pathfmt.realdirectory + name_new |
| 67 |
pathfmt.kwdict["_file_recheck"] = True |
| 68 |
|
| 69 |
def _rename(self, path_old, name_old, path_new, name_new): |
| 70 |
if self.skip and os.path.exists(path_new): |
| 71 |
return self.log.warning( |
| 72 |
"Not renaming '%s' to '%s' since another file with the " |
| 73 |
"same name exists", name_old, name_new) |
| 74 |
|
| 75 |
self.log.info("'%s' -> '%s'", name_old, name_new) |
| 76 |
os.replace(path_old, path_new) |
| 77 |
|
| 78 |
def _apply_pathfmt(self, pathfmt): |
| 79 |
return pathfmt.build_filename(pathfmt.kwdict) |
| 80 |
|
| 81 |
def _apply_format(self, format_string): |
| 82 |
fmt = formatter.parse(format_string).format_map |
| 83 |
|
| 84 |
def apply(pathfmt): |
| 85 |
return pathfmt.clean_path(pathfmt.clean_segment(fmt( |
| 86 |
pathfmt.kwdict))) |
| 87 |
|
| 88 |
return apply |
| 89 |
|
| 90 |
|
| 91 |
__postprocessor__ = RenamePP |