Created
October 24, 2022 16:45
-
-
Save jqr/2734142407b8809210863b00f12433a7 to your computer and use it in GitHub Desktop.
Clean incidental code directories
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 | |
# Usage: cleanup <dir> [dir] ... | |
# Summary: Removes incidental files in code dirs | |
# Help: Recursively removes log files and does git garbage collection | |
# for the given directory. | |
dirs = ARGV | |
if !dirs.first | |
puts "ERROR: must specify directory" | |
system "help cleanup" | |
abort | |
end | |
if %w(-h --help).include?(ARGV.first) | |
system "help cleanup" | |
abort | |
end | |
require 'fileutils' | |
class Integer | |
def to_megabytes | |
to_f / 1000 / 1000 | |
end | |
def kilobytes | |
self * 1024 | |
end | |
end | |
def system_with_echo(*args) | |
puts args.join(' ') | |
system(*args) | |
end | |
total_size = 0 | |
count = 0 | |
dirs.each do |dir| | |
this_dir = File.expand_path(dir) | |
pattern = File.join(this_dir, '**', 'log', '*.log') | |
puts "Cleaning log files matching #{pattern}" | |
Dir.glob(pattern) do |match| | |
size = File.size(match) | |
total_size += size | |
puts " %9i MiB #{match}" % size.to_megabytes | |
FileUtils.rm(match) | |
count += 1 | |
end | |
puts "Deleted #{count} files totalling %i MiB" % total_size.to_megabytes | |
puts | |
total_size = 0 | |
count = 0 | |
puts "Garbage collecting all git projects..." | |
Dir.glob(File.join(this_dir, '**', '.git')) do |match| | |
repo = File.dirname(match) | |
before = `du -ks #{match}`.to_i.kilobytes | |
# --aggressive | |
system("cd #{repo} && git gc --quiet --prune; cd #{File.expand_path(this_dir)}") | |
after = `du -ks #{match}`.to_i.kilobytes | |
size = before - after | |
total_size += size | |
puts " %9i MiB #{repo}" % size.to_megabytes | |
count += 1 | |
end | |
end | |
puts "Garbage collected #{count} projects totalling %i MiB" % total_size.to_megabytes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a super old command, still works, but plenty of modern improvements to be made.
Also the help stuff only works if it's run within sub.