Last active
April 28, 2017 00:52
-
-
Save mnbi/fe4d552ac0d0841d78bd8d62e539fdee to your computer and use it in GitHub Desktop.
Print size of specified files.
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 -w | |
# -*- coding: utf-8 -*- | |
# Print size of specified file(s) friendly and nicely for human beings | |
require 'optparse' | |
Version = '0.3.2' | |
Release = '2017-04-28' | |
class FileSize | |
include Comparable | |
def initialize(filename, parent_path) | |
@filename = filename | |
@parent_path = parent_path | |
@bsize = 0 | |
@disp_size = 0 | |
@disp_suffix = '' | |
calc | |
end | |
attr_reader :bsize, :disp_size, :disp_suffix | |
def to_s | |
"%s%s %s" % [size_str(@disp_size), @disp_suffix, @filename] | |
end | |
def <=>(other) | |
@bsize <=> other.bsize if self.class === other | |
end | |
private | |
def calc | |
# Hmm..., I don't have any terabyte, petabyte or exabyte size file. | |
path = File.expand_path(@filename, @parent_path) | |
@bsize = FileTest.size(path) | |
ksize = @bsize / 1024 | |
krest = @bsize % 1024 | |
msize = ksize / 1024 | |
mrest = ksize % 1024 | |
gsize = msize / 1024 | |
grest = msize % 1024 | |
if gsize > 0 | |
gsize += 1 if (grest > 0 or mrest > 0 or krest > 0) | |
@disp_size, @disp_suffix = gsize, "G" | |
elsif msize > 0 | |
msize += 1 if (mrest > 0 or krest > 0) | |
@disp_size, @disp_suffix = msize, "M" | |
elsif ksize > 0 | |
ksize += 1 if (krest > 0) | |
@disp_size, @disp_suffix = ksize, "K" | |
else | |
@disp_size, @disp_suffix = @bsize, " " | |
end | |
end | |
def size_str(size) | |
"%4d" % size | |
end | |
end | |
OPTS = {} | |
opt = OptionParser.new | |
opt.banner = "Usage: #{opt.program_name} [options] [files]" | |
opt.summary_width = 16 | |
opt.version = Version | |
opt.release = Release | |
opt.on('-s', '--sort', | |
'sort by size (descending order)') { |v| OPTS[:sort] = v } | |
opt.on('-r', '--reverse', | |
'sort by size (ascending order)') { |v| OPTS[:reverse] = v } | |
opt.parse!(ARGV) | |
# When no files are specified, assume files in the current directory | |
# are specified. | |
files = ((ARGV.size > 0) ? ARGV : Dir.entries('.')).select do |e| | |
path = File.expand_path(e) | |
FileTest.exist?(path) and FileTest.file?(path) | |
end | |
result = files.reduce([]) do |r, f| | |
r << FileSize.new(f, '.') | |
end | |
if result | |
result.sort! { |x, y| y <=> x } if OPTS[:sort] | |
result.sort! { |x, y| x <=> y } if OPTS[:reverse] | |
result.each { |filesize| puts filesize.to_s } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment