Skip to content

Instantly share code, notes, and snippets.

@EliseAv
Created September 20, 2015 03:49
Show Gist options
  • Save EliseAv/828b1ed3462a516c3c54 to your computer and use it in GitHub Desktop.
Save EliseAv/828b1ed3462a516c3c54 to your computer and use it in GitHub Desktop.
Make sure files are named after their hashes.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2015, Ekevoo.com.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
#
from hashlib import md5
from logging import getLogger, DEBUG, StreamHandler
from os import rename
from os.path import splitext, split, join
from sys import argv
log = getLogger('renmd5')
def main(params):
if params:
params = map(renmd5, params)
return sum(params)
else:
log.fatal('No filenames provided.')
return 1
def renmd5(name):
try:
newname = get_hash(name)
parentpath, filename = split(name)
filename, extension = splitext(filename)
newname += extension
if parentpath:
newname = join(parentpath, newname)
if name != newname:
log.info('%s -> %s', name, newname)
rename(name, newname)
else:
log.info('%s: no change.', name)
return 0
except IOError as e:
log.exception(e)
return 1
def get_hash(name):
block = 0x1000
hasher = md5()
with open(name, 'rb') as f:
buffer = f.read(block)
while buffer:
hasher.update(buffer)
buffer = f.read(block)
return hasher.hexdigest()
if __name__ == '__main__':
log.level = DEBUG
log.addHandler(StreamHandler())
exit(main(argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment