Fixed SolvitDB's insert() function

It uses a temporary file like remove() now.
This commit is contained in:
2026-05-06 19:09:52 +03:00
parent 60283fc40e
commit 2bff0e749a
+25 -13
View File
@@ -27,21 +27,35 @@ local function readPat(handle, patLength)
return packages return packages
end end
local function insert(readHandle, writeHandle, data) local function insert(filePath, location, bytes)
--NOTE: writeHandle must be in append ("a") mode
local chunkLength = 512 local chunkLength = 512
if #data > 512 then local readHandle = assert(fs.open(filePath, "r"))
chunkLength = #data local tmpFilePath = filePath .. ".tmp"
end local writeHandle = assert(fs.open(tmpFilePath, "w"))
buf2 = data local i = 0
while true do while true do
buf1 = readHandle:read(chunkLength) local readAmount = chunkLength
writeHandle:write(buf2) if readAmount > location - i then
if not buf1 then readAmount = location - i
end
if readAmount == 0 then
break break
end end
buf2 = buf1 local data = readHandle:read(readAmount)
i = i + readAmount
assert(writeHandle:write(data))
end end
assert(writeHandle:write(bytes))
while true do
local data = readHandle:read(chunkLength)
if not data then
break
end
assert(writeHandle:write(data))
end
readHandle:close()
writeHandle:close()
fs.rename(tmpFilePath, filePath)
end end
local function remove(filePath, location, length) local function remove(filePath, location, length)
@@ -77,7 +91,6 @@ local function remove(filePath, location, length)
readHandle:close() readHandle:close()
writeHandle:close() writeHandle:close()
fs.rename(tmpFilePath, filePath) fs.rename(tmpFilePath, filePath)
fs.remove(tmpFilePath)
end end
function solvitdb.create(path) function solvitdb.create(path)
@@ -148,9 +161,8 @@ function solvitdb.set(path, name, data)
encodedString = encodedString .. "v" .. data.version .. "." encodedString = encodedString .. "v" .. data.version .. "."
end end
writeHandle:write(encodedString .. "\n") writeHandle:write(encodedString .. "\n")
writeHandle:seek("set", patLength + 8) -- + 8 because that's the length of the header
local patData = ("%s.%s;"):format(name, string.pack("<I4", newPackageLocation)) local patData = ("%s.%s;"):format(name, string.pack("<I4", newPackageLocation))
insert(readHandle, writeHandle, patData) insert(path, patLength + 8, patData)
readHandle:close() readHandle:close()
local newPatLength = patLength + #patData local newPatLength = patLength + #patData
writeHandle:seek("set", 0) writeHandle:seek("set", 0)