Last active
July 4, 2024 07:37
-
-
Save kazuho/857f71fcf6f4d9d42066a666137d1c1a to your computer and use it in GitHub Desktop.
calculate amount of disk space returned, once all the given files and directories are removed
This file contains 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 'find' | |
BLOCK_SIZE = 512 # ブロックサイズは通常 512 バイト | |
def calculate_freed_space(paths) | |
inodes = {} | |
total_blocks = 0 | |
processed_files = {} | |
Find.find(*paths) do |file| | |
normalized_file = File.expand_path(file) | |
next if processed_files.key?(normalized_file) | |
processed_files[normalized_file] = true | |
if File.exist?(normalized_file) | |
stat = File.stat(normalized_file) | |
if File.directory?(normalized_file) | |
# ディレクトリ自体のサイズを追加 | |
total_blocks += stat.blocks | |
else | |
key = [stat.dev, stat.ino] | |
inodes[key] ||= { count: 0, blocks: stat.blocks, nlink: stat.nlink } | |
inodes[key][:count] += 1 | |
end | |
else | |
puts "Warning: #{normalized_file} does not exist and will be skipped." | |
end | |
end | |
inodes.each do |key, info| | |
if info[:count] == info[:nlink] | |
total_blocks += info[:blocks] | |
end | |
end | |
total_blocks * BLOCK_SIZE | |
end | |
if ARGV.empty? | |
puts "Usage: ruby free_space_calculator.rb <path1> <path2> ..." | |
exit 1 | |
end | |
paths = ARGV | |
freed_space = calculate_freed_space(paths) | |
formatted_size = freed_space.to_s.reverse.scan(/\d{1,3}/).join(',').reverse | |
puts "Total space that would be freed: #{formatted_size} bytes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment