build.lua: match long comments correctly; flush and close files properly; implement fs.copy() on top of lfs

main
cinder 6 months ago
parent 3e5cfde820
commit ceec31c4fe

@ -17,6 +17,28 @@ local fs = (function()
--if we're not in minecraft, implement the functions we need on top of LuaFileSystem
local lfs = require('lfs')
local fs = {}
function fs.copy(src, dst)
--lfs doesn't seem to have this? for small files we can just `cat <src >dst`
src, err = io.open(src, 'rb')
if not src then
return nil, err
end
dst, err = io.open(dst, 'wb')
if not dst then
src:close()
return nil, err
end
--outside of opencomputers, we more than likely have more than enough ram, so read everything in one shot
local ok; ok, err = src:read('a')
if ok then ok, err = dst:write(ok) end
if ok then ok, err = dst:flush() end
src:close()
dst:close()
return ok, err
end
function fs.list(path)
local entries = {}
for name in lfs.dir(path) do
@ -84,7 +106,7 @@ local function exportFile(srcpath, dstpath)
local dstf = assert(io.open(dstpath, 'w'))
--for now, run a very minimal minifier
local longEnd --nil normally, some "]==]--" string if we're in a long comment
local longEnd --nil normally, some "]==]" string if we're in a long comment
for line in srcf:lines() do
::stripComments:: --strip comments, including weird ones like "--[[ ]]-- --[=[ ]=]-- --text" all in one line
@ -108,8 +130,8 @@ local function exportFile(srcpath, dstpath)
end
if line:byte(comment+2) == string.byte('[') then --start of a long comment
local depth = #line:sub(comment+2):match('^%[(%=*)%[') --validating syntax earlier ensures this will match
longEnd = string.format(']%s]--', string.rep('=', depth))
line = line:sub(comment + 4 + depth) -- #'--[' + depth + #'['
longEnd = string.format(']%s]', string.rep('=', depth))
line = line:sub(comment + 4 + depth) --len('--[') + depth + len('[')
goto stripComments --start from the beginning in case the comment ends on the same line it starts on
else
--found a short comment, remove to end of line
@ -121,12 +143,16 @@ local function exportFile(srcpath, dstpath)
assert(not longEnd, 'shouldn\'t emit anything in a long comment')
line = assert(line:match('^%s*(.-)%s*$')) --strip leading and trailing whitespace
if #line > 0 then
dstf:write(line, '\n')
assert(dstf:write(line, '\n'))
end
::nextLine::
end
assert(not longEnd, 'unclosed long comment')
assert(dstf:flush())
dstf:close()
srcf:close()
end
fs.makeDirectory(outdir)

Loading…
Cancel
Save