Skip to content

Instantly share code, notes, and snippets.

@MasonGulu
Created February 21, 2024 05:13
Show Gist options
  • Save MasonGulu/8269646cca054e901782877a781affb2 to your computer and use it in GitHub Desktop.
Save MasonGulu/8269646cca054e901782877a781affb2 to your computer and use it in GitHub Desktop.
Useful scripts for managing resource loading across multiple disks in ComputerCraft
-- overwrite _G.fs.open to search all disks connected to the computer for the file
-- create a cache of filenames -> locations
---@type table<string,string>
local filePaths = {}
local function cacheDir(dir)
for k,v in pairs(fs.list(dir)) do
local fn = fs.combine(dir, v)
if fs.isDir(fn) then
cacheDir(fn)
else
filePaths[v] = fn
end
end
end
cacheDir("/")
local oldOpen = fs.open
---@diagnostic disable-next-line: duplicate-set-field
fs.open = function (path, mode)
if filePaths[path] then
return oldOpen(filePaths[path], mode)
end
return oldOpen(path,mode)
end
local fn = ({...})[1]
assert(fs.exists(fn), "File does not exist.")
loadfile(fn, "t", _ENV)()
--- take an input folder, an output folder pattern, and maximum folder size
--- then split the files in the input folder into equally sized output folders
if #arg < 2 then
print("splitter input size")
return
end
local maxSize = assert(tonumber(arg[2]), "Second argument must be a number")
local input = arg[1]
assert(fs.isDir(input), "Input must be a directory")
fs.delete("split")
fs.makeDir("split")
local fileNames = fs.list(input)
---@type {name:string,size:integer}[]
local remainingFiles = {}
for _, v in ipairs(fileNames) do
if not fs.isDir(v) then
-- is a file
local size = fs.getSize(fs.combine(input, v))
remainingFiles[#remainingFiles + 1] = {
name = fs.combine(input, v),
size = size
}
if size > maxSize then
error(("File %s too large."):format(v))
end
end
end
table.sort(remainingFiles, function(a, b)
return a.size < b.size
end)
local di = 1
while #remainingFiles > 0 do
fs.makeDir(fs.combine("split", "disk" .. di))
local folderSize = 0
while true do
local fileFit = false
for i = #remainingFiles, 1, -1 do
if folderSize + remainingFiles[i].size < maxSize then
-- add the file
local file = remainingFiles[i]
folderSize = folderSize + file.size
fs.copy(file.name, fs.combine("split", "disk" .. di, fs.getName(file.name)))
table.remove(remainingFiles, i)
fileFit = true
break
end
end
if not fileFit then
break
end
end
di = di + 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment