aboutsummaryrefslogtreecommitdiffstats
path: root/rencon
blob: 30ab44f26bcd666466001d7331b29efdb84aac78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python

import argparse
import hashlib
import os
import sys
from string import Template

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Rename files based on their content.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('files', metavar='FILE', nargs='+',
                        help="files to rename")
    parser.add_argument('-m', '--mask',
                        help="file destination mask", default='${hash}.${ext}')
    parser.add_argument('-p', '--pretend', action='store_true',
                        help="do not rename, just print")

    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 >>sys.stderr, "File %s does not exists." % f
        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 >>sys.stderr, "Destination %s already exists." % dest
                elif not args.pretend:
                    os.rename(f, dest)