aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLaurent Bachelier <laurent@bachelier.name>2014-08-25 20:06:26 +0200
committerLaurent Bachelier <laurent@bachelier.name>2014-08-25 20:06:26 +0200
commitd451e64d29f2814a6ba928b7b4892417e7a5882d (patch)
tree66d372808d9ae2a5a1addb3d2ee48ee0459ba04f
parentSupport changing algorithm (diff)
downloadrencon-d451e64d29f2814a6ba928b7b4892417e7a5882d.tar.xz
Option to reduce the hash digest length
-rwxr-xr-xrencon16
1 files changed, 14 insertions, 2 deletions
diff --git a/rencon b/rencon
index 89dcb88..72f0aac 100755
--- a/rencon
+++ b/rencon
@@ -17,7 +17,7 @@ def hashfile(hasher, fp, bs=2**16):
return h
-def rename(fpath, mask, algorithm, out=sys.stdout, err=sys.stderr):
+def rename(fpath, mask, algorithm, abbrev=None, out=sys.stdout, err=sys.stderr):
print("Renaming with mask: %s" % args.mask, file=out)
if not os.path.exists(fpath):
print("File %s does not exists." % fpath, file=err)
@@ -25,6 +25,8 @@ def rename(fpath, mask, algorithm, out=sys.stdout, err=sys.stderr):
with open(fpath) as fp:
hasher = getattr(hashlib, algorithm)
hsh = hashfile(hasher, fp).hexdigest()
+ if abbrev:
+ hsh = hsh[0:abbrev]
ext = os.path.splitext(fpath)[1][1:]
name = mask.substitute(hash=hsh, ext=ext)
dest = os.path.join(os.path.dirname(fpath), name)
@@ -43,6 +45,14 @@ if __name__ == '__main__':
description="Rename files based on their content.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+ def abbrev(arg):
+ arg = int(arg)
+ if arg == 0:
+ return None
+ if arg < 4:
+ raise argparse.ArgumentTypeError("You should use at least 4 digits.")
+ return arg
+
parser.add_argument('files', metavar='FILE', nargs='+',
help="files to rename")
parser.add_argument('-m', '--mask',
@@ -51,7 +61,9 @@ if __name__ == '__main__':
help="do not rename, just print")
parser.add_argument('-a', '--algorithm',
help="hash algorithm", choices=hashlib.algorithms, default='sha1')
+ parser.add_argument('-b', '--abbrev', metavar='N', type=abbrev,
+ help="use the first N digits", default=None)
args = parser.parse_args()
for fpath in args.files:
- rename(fpath, Template(args.mask), args.algorithm)
+ rename(fpath, Template(args.mask), args.algorithm, args.abbrev)