umnikos

du.lua

Sep 25th, 2025 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.52 KB | None | 0 0
  1.  
  2. -- run with:
  3. -- pastebin run Bvdx6gCn
  4.  
  5.  
  6. -- returns number of bytes
  7. local function du_singular(path)
  8.   if fs.getDrive(path) == "rom" then
  9.     return 0
  10.   end
  11.   if not fs.isDir(path) then
  12.     -- just a file
  13.     return fs.getSize(path)
  14.   end
  15.   local l = fs.list(path)
  16.   local size = 0
  17.   for i,entry in ipairs(l) do
  18.     local subpath = fs.combine(path,entry)
  19.     size = size + du_singular(subpath)
  20.   end
  21.   return size
  22. end
  23.  
  24. local suffixes = {" B","kB","MB","GB","TB","PB","EB"}
  25.  
  26. local function format_size(size)
  27.   local unit = 1
  28.   while size > 999 do
  29.     size = size / 1000
  30.     unit = unit + 1
  31.   end
  32.   size = string.format("%f",size)
  33.   size = string.format("%.4s",size)
  34.   size = (size:gsub("%.$"," "))
  35.   return string.format("%s %s", size, suffixes[unit])
  36. end
  37.  
  38. local workdir = shell.dir()
  39.  
  40. local listing = {}
  41.  
  42. for _,file in ipairs(fs.list(workdir)) do
  43.   local path = fs.combine(workdir, file)
  44.   if fs.isDir(path) then
  45.     file = file.."/"
  46.   end
  47.   table.insert(listing, {
  48.     file = file,
  49.     size = du_singular(path)
  50.   })
  51.   -- print(format_size(du_singular(path))..": "..entry)
  52. end
  53.  
  54. table.sort(listing, function (a, b)
  55.   if a.size ~= b.size then
  56.     return a.size > b.size
  57.   end
  58.   return a.file < b.file
  59. end)
  60.  
  61. local result = ""
  62.  
  63. for _,entry in ipairs(listing) do
  64.   result = result .. format_size(entry.size)..": "..entry.file .. "\n"
  65. end
  66. result = result:gsub("\n$","")
  67.  
  68. local _, y = term.getCursorPos()
  69.  
  70. -- FIXME: this pager sucks, I'd like a better one
  71. textutils.pagedPrint(result, y-2)
  72.  
Advertisement
Add Comment
Please, Sign In to add comment