-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrnimg.rb
executable file
·78 lines (68 loc) · 1.99 KB
/
rnimg.rb
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/ruby -w
require 'rubygems'
require 'exifr'
require 'date'
class Rnimg
def initialize(file = File, exif = EXIFR::JPEG, dir = Dir)
@file = file
@exif = exif
@dir = dir
end
def rename(*paths)
map = getFilesToRename(*paths)
makeNewNamesUnique!(map)
renameFiles(map)
end
private
def formatDate(date)
"#{date.strftime('%Y%m%d_%H%M%S')}.jpg"
end
def getFilesToRename(*paths)
renameMap = Hash.new
paths.each do |path|
if @file.directory? path then
@dir.entries(path).each { |file|
unless file =~ /^(\.|\.\.)/ then
joinedPath = @file.join(path, file)
filesToRename = getFilesToRename(joinedPath)
renameMap.merge!(filesToRename)
end
}
else
begin
modified = @exif.new(path).date_time
rescue RuntimeError
else
newName = @file.join(@file.dirname(path), formatDate(modified))
renameMap[path] = newName
end
end
end
renameMap
end
def makeNewNamesUnique!(map)
inverted = {}
map.each {|old, new|
inverted[new] = inverted[new] || []
inverted[new] << old
}
map.clear
inverted.each {|newName, oldNames|
if oldNames.count == 1 then map[oldNames[0]] = newName; next end
oldNames.sort!
newName =~ /^(.*)\.(.*)$/
match = Regexp.last_match
file, extension = match[1,2]
postfixValue = 1
oldNames.each { |oldName|
map[oldName] = "%s_%02d.%s" % [file, postfixValue, extension]
postfixValue += 1
}
}
end
def renameFiles(map)
map.each {|old, new|
@file.rename(old, new)
}
end
end