aboutsummaryrefslogtreecommitdiffstats
path: root/rencon
diff options
context:
space:
mode:
authorLaurent Bachelier <laurent@bachelier.name>2014-08-24 16:02:35 +0200
committerLaurent Bachelier <laurent@bachelier.name>2014-08-24 16:02:35 +0200
commita87a3cfce441913c756d7106b793de8a1e2df7a9 (patch)
tree4d287a69255aaa68444314894c71c1989999c7cd /rencon
parentModernize code (diff)
downloadrencon-a87a3cfce441913c756d7106b793de8a1e2df7a9.tar.xz
Separate argument processing and renanimg
Diffstat (limited to 'rencon')
-rwxr-xr-xrencon41
1 files changed, 23 insertions, 18 deletions
diff --git a/rencon b/rencon
index 54946ac..9d2a9d8 100755
--- a/rencon
+++ b/rencon
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-from __future__ import absolute_import, unicode_literals, print_function
+from __future__ import absolute_import, print_function, unicode_literals
import argparse
import hashlib
@@ -7,6 +7,26 @@ import os
import sys
from string import Template
+
+def rename(fpath, mask, out=sys.stdout, err=sys.stderr):
+ if not os.path.exists(fpath):
+ print("File %s does not exists." % fpath, file=err)
+ else:
+ with open(fpath) as fp:
+ h = hashlib.sha1(fp.read()).hexdigest()
+ ext = os.path.splitext(fpath)[1][1:]
+ name = mask.substitute(hash=h, ext=ext)
+ dest = os.path.join(os.path.dirname(fpath), name)
+ if os.path.basename(fpath) == name:
+ print("OK %s" % name, file=out)
+ else:
+ print("`%s' -> `%s'" % (fpath, dest), file=out)
+ if os.path.exists(dest):
+ print("Destination %s already exists." % dest, file=err)
+ elif not args.pretend:
+ os.rename(fpath, dest)
+
+
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Rename files based on their content.",
@@ -22,20 +42,5 @@ if __name__ == '__main__':
args = parser.parse_args()
print("Renaming with mask: %s" % args.mask)
mask = Template(args.mask)
- for f in args.files:
- if not os.path.exists(f):
- print("File %s does not exists." % f, file=sys.stderr)
- else:
- with open(f) as fp:
- h = hashlib.sha1(fp.read()).hexdigest()
- ext = os.path.splitext(f)[1][1:]
- name = mask.substitute(hash=h, ext=ext)
- dest = os.path.join(os.path.dirname(f), name)
- if os.path.basename(f) == name:
- print("OK %s" % name)
- else:
- print("`%s' -> `%s'" % (f, dest))
- if os.path.exists(dest):
- print("Destination %s already exists." % dest, file=sys.stderr)
- elif not args.pretend:
- os.rename(f, dest)
+ for fpath in args.files:
+ rename(fpath, mask)