Extract list_tree as a method and separate from removals

This commit is contained in:
Nobuyoshi Nakada 2024-04-22 11:01:32 +09:00
parent c65bc2e5d9
commit 44d2b59491
No known key found for this signature in database
GPG Key ID: 3582D74E1FEE4465

View File

@ -21,39 +21,65 @@ END {
rescue Errno::ENOTEMPTY rescue Errno::ENOTEMPTY
require_relative "colorize" require_relative "colorize"
colorize = Colorize.new colorize = Colorize.new
mode_inspect = ->(m, s) { ls = Struct.new(:colorize) do
[ def mode_inspect(m, s)
(m & 0o4 == 0 ? ?- : ?r), [
(m & 0o2 == 0 ? ?- : ?w), (m & 0o4 == 0 ? ?- : ?r),
(m & 0o1 == 0 ? (s ? s.upcase : ?-) : (s || ?x)), (m & 0o2 == 0 ? ?- : ?w),
] (m & 0o1 == 0 ? (s ? s.upcase : ?-) : (s || ?x)),
} ]
filecolor = ->(st) { end
st.directory? ? "bold;blue" : st.symlink? ? "bold;cyan" : st.executable? ? "bold;green" : nil def decorate_path(path, st)
} case
list_tree = ->(parent, indent = " ") { when st.directory?
Dir.children(parent).each do |child| color = "bold;blue"
path = File.join(parent, child) type = "/"
st = File.lstat(path) when st.symlink?
m = st.mode color = "bold;cyan"
m = [ # type = "@"
(st.file? ? ?- : st.ftype[0]), when st.executable?
mode_inspect[m >> 6, (?s unless m & 04000 == 0)], color = "bold;green"
mode_inspect[m >> 3, (?s unless m & 02000 == 0)], type = "*"
mode_inspect[m, (?t unless m & 01000 == 0)], when path.end_with?(".gem")
].join("") color = "green"
warn [ end
indent, m, st.nlink, st.size, st.mtime, colorize.decorate(path, color) + (type || "")
colorize.decorate(child, filecolor[st]), end
(["->", colorize.cyan(File.readlink(path))] if st.symlink?), def list_tree(parent, indent = "", &block)
].compact.join(" ") children = Dir.children(parent).map do |child|
if st.directory? [child, path = File.join(parent, child), File.lstat(path)]
list_tree[File.join(parent, child), indent + " "] end
nlink_width = children.map {|child, path, st| st.nlink}.max.to_s.size
size_width = children.map {|child, path, st| st.size}.max.to_s.size
children.each do |child, path, st|
m = st.mode
m = [
(st.file? ? ?- : st.ftype[0]),
mode_inspect(m >> 6, (?s unless m & 04000 == 0)),
mode_inspect(m >> 3, (?s unless m & 02000 == 0)),
mode_inspect(m, (?t unless m & 01000 == 0)),
].join("")
warn sprintf("%s* %s %*d %*d %s % s%s",
indent, m, nlink_width, st.nlink, size_width, st.size,
st.mtime.to_s, decorate_path(child, st),
(" -> " + decorate_path(File.readlink(path), File.stat(path)) if
st.symlink?))
if st.directory?
list_tree(File.join(parent, child), indent + " ", &block)
end
yield path, st if block
end end
end end
} end.new(colorize)
warn colorize.notice("Children under ")+colorize.fail(tmpdir)+":" warn colorize.notice("Children under ")+colorize.fail(tmpdir)+":"
list_tree[tmpdir] ls.list_tree(tmpdir) do |path, st|
if st.directory?
Dir.rmdir(path)
else
File.unlink(path)
end
end
FileUtils.rm_rf(tmpdir) FileUtils.rm_rf(tmpdir)
end end
end end