#!/usr/bin/ruby # find all files with a certain extension in a given directory, and create .md5 sum files # for each file. require 'getoptlong' require 'digest/md5' require 'digest/sha1' # call using "mk_md5sums.rb -d . -s rpm" opts = GetoptLong.new( ["--dir", "-d", GetoptLong::REQUIRED_ARGUMENT ], ["--suffix", "-s", GetoptLong::REQUIRED_ARGUMENT ], # ["--check", "-c", GetoptLong::NO_ARGUMENT ], ["--nocheck", "-n", GetoptLong::NO_ARGUMENT ], ["--fix", "-f", GetoptLong::NO_ARGUMENT ], ["--verbose", "-v", GetoptLong::NO_ARGUMENT ] ) # process and display the parsed options: $check = true $fix = nil $verbose = false dir = nil suffix = nil opts.each do |opt,arg| puts "Option: #{opt}, arg #{arg.inspect}" case opt when '--dir' dir = arg when '--suffix' suffix = arg.split(',') when '--check' $check = true when '--nocheck' $check = false when '--fix' $fix = true # will overwrite existing md5-sum files when '--verbose' $verbose = true # will display if existing md5-sum files are equal else end end # puts "Remaining args: #{ARGV.join(', ')}" puts "usage: #{$0} --dir directory_name --suffix suffix1,suffix2,suffix3 " if (! dir) || (! suffix) # compile a RegExp matching several given file suffixes: # str = suffix.join('|') # regexp = Regexp.new("[.](#{str})$") # or shorter: regexp = Regexp.new("[.](#{suffix.join('|')})$") puts "Dir: #{dir}" puts "Suffix: #{suffix}" puts "RegExp: #{regexp}" # ------------------------------------------------------------------------------ # digest_directory # recursively decends into directory, and computes md5 or sha1 checksum # files for each file matching the given regular expression. def digest_directory(dir,regexp) Dir.chdir(dir) Dir.foreach(dir) { |item| next if item =~ /^[.]+$/ # ignore '.' and '..' # recursive decend if we encounter a directory: digest_directory( File.join(Dir.getwd , item) , regexp) if File.directory?(item) next if item !~ regexp # ignore files not matching the given suffixes # compute the MD5 sum of this file md5 = Digest::MD5.hexdigest(File.read(item)) # check if an md5-file is already there.. md5file = item + '.md5' if File.exists?( md5file ) # if there is an md5-file, we check if the contents are right! old_md5 = File.read(md5file).chomp if $check if md5 == old_md5 puts "CHECKED OK! #{item} : new: #{md5} == old: #{old_md5}" if $verbose else puts "WARNING! #{item} : new: #{md5} != old: #{old_md5}" if $fix puts "RE-GENERATING MD5-file: #{item} : #{md5}" out = File.open( md5file , "w") # over-writing pre-existing md5-file out.puts "#{md5}" out.close end end end else # if there's no md5-file, we'll create a new one! puts "NEW MD5-file: #{item} : #{md5}" out = File.open( md5file , "w") out.puts "#{md5}" out.close end } end # ------------------------------------------------------------------------------ digest_directory(dir,regexp)