Created
May 9, 2021 07:19
-
-
Save Montandalar/18cef029e9120fc33a6a3a216e4c1fb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local BLOCK_SIZE = 4096 | |
-- Internal: Open the file or die | |
-- External users should catch the error if they wish | |
local function openordie(filename, mode) | |
handle, err = io.open(filename, mode) | |
if err then | |
error(err) | |
end | |
return handle | |
end | |
-- Process the provided filename from opening it by its name until writing out | |
-- the new version. Also overwrite the original if in_place is true. | |
local function dos2unix_end2end(filename, in_place) | |
local filename_new = filename.. ".new" | |
infile = openordie(filename, "rb") | |
outfile = openordie(filename..".new", "wb") | |
dos2unix_handle(infile, outfile) | |
infile:close() | |
outfile:close() | |
if in_place then | |
os.remove(filename) | |
os.rename(filename_new, filename) | |
end | |
end | |
local function dos2unix_handle_inplace(infile) | |
local scratch = io.tmpfile() | |
-- TODO: remove all \r\n, write to tmpfile, | |
-- TODO: write tmpfile over infile | |
-- TODO: write \n\0* over the rest | |
-- rewind | |
dos2unix_handle(infile, scratch) | |
end | |
-- Rewind the provided handle, process it, then rewind it again | |
local function dos2unix_handle(infile, outfile) | |
infile:seek("set", 0) | |
repeat | |
inbuf = infile:read(BLOCK_SIZE) | |
outbuf = string.gsub(inbuf, "\r\n", "\n") | |
outfile:write(outbuf) | |
io.stderr:write("#inbuf="..tostring(#inbuf)) | |
io.stderr:write("\n") | |
until #inbuf < BLOCK_SIZE | |
infile:seek("set", 0) | |
end | |
-- STANDALONE PROGRAM CODE BELOW | |
if not (minetest and minetest.get_modpath("serialize_lib")) then | |
local function ipairs_offset(t, off) | |
local size = #t | |
local f = function(t, idx) | |
if idx >= size then | |
return nil | |
else | |
return idx+1, t[idx+1] | |
end | |
end | |
return f, t, tonumber(off-1) | |
end | |
local in_place = false | |
if arg[1] == "-i" then | |
in_place = true | |
end | |
for k,v in ipairs_offset(arg, 1+(in_place and 1 or 0)) do | |
dos2unix_end2end(v, in_place) | |
end | |
end | |
return { | |
dos2unix_end2end = dos2unix_end2end, | |
dos2unix_handle = dos2unix_handle, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment