Last active
November 11, 2020 16:39
-
-
Save matiaskorhonen/fc5d03b02dc09b36e8d62ab891402994 to your computer and use it in GitHub Desktop.
Generate SHA256 recursively in a directory tree. Uses the same checksum file format as https://linux.die.net/man/1/sha256sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require "digest" | |
require "find" | |
require "optparse" | |
options = {} | |
OptionParser.new do |opts| | |
opts.banner = "Usage: recursive-hashes [options]" | |
opts.on("-c", "--check DIR", "Check hashes") do |c| | |
options[:check] = c | |
end | |
opts.on("-g", "--generate DIR", "Generate SHA256SUMS files") do |v| | |
options[:generate] = v | |
end | |
opts.on("-h", "--help", "Prints this help") do | |
puts opts | |
exit | |
end | |
end.parse! | |
puts options.inspect | |
if options[:generate] | |
Find.find(options[:generate]) do |path| | |
if FileTest.directory?(path) | |
if File.basename(path)[0] == "." | |
Find.prune | |
# Don't look any further into this directory | |
else | |
files = Dir.glob(File.expand_path("*.*", path)).reject { |f| File.directory?(f) } | |
if files.any? | |
puts "#{files.size} file(s) in #{path}" | |
hashes = files.map do |file| | |
sha256 = Digest::SHA256.file(file) | |
[sha256.hexdigest, File.basename(file)].join(" ") | |
end | |
digest_file = File.expand_path("SHA256SUMS", path) | |
File.open(digest_file, "w+") do |f| | |
f.write hashes.join("\n") | |
f.write "\n" | |
end | |
puts " -> created SHA256SUMS" | |
end | |
next | |
end | |
end | |
end | |
end |
slavanap
commented
Aug 16, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment