|
| 1 | +#!/usr/bin/env lua |
| 2 | + |
| 3 | + |
| 4 | +--[[ |
| 5 | + DOS and UNIX disagree on what a new line should be |
| 6 | + DOS says it's a carriage return followed by a line feed (CRLF) |
| 7 | + while UNIX says it's just a line feed on its own (LF). |
| 8 | + Many tools (Lua included) don't care while others like |
| 9 | + `TYPE` in DOS and Notepad in Windows will not display correctly. |
| 10 | + Tools like unix2dos/dos2unix exist convert line endings between the systems, |
| 11 | + however, in doing so, the CR in CRLF on the shebang line might be |
| 12 | + interpreted literally and prevent correct execution on UNIX systems. |
| 13 | +
|
| 14 | + This script named "DOS friend" will convert every line ending of the files |
| 15 | + passed to it with CRLF with the exception of the first line when a shebang |
| 16 | + is present. When this occurs, the line will instead write LFCRLF so that |
| 17 | + both types of systems can pleasantly read and run the file. |
| 18 | +--]] |
| 19 | + |
| 20 | +LF = string.char(0x0A) |
| 21 | +CRLF = string.char(0x0D) .. LF |
| 22 | + |
| 23 | +local function Shebang(inFile) |
| 24 | + inFile:seek("set", 0) |
| 25 | + local line1 = inFile:read("*l") |
| 26 | + if line1:match("^#!") then |
| 27 | + return line1 .. LF .. CRLF |
| 28 | + end |
| 29 | + return nil |
| 30 | +end |
| 31 | + |
| 32 | +if #arg < 1 then |
| 33 | + print(arg[-1] .. " " .. arg[0] .. " [FILE]...") |
| 34 | + os.exit(1) |
| 35 | +end |
| 36 | + |
| 37 | +for i = 1, #arg do |
| 38 | + local inFile, err = io.open(arg[i]) |
| 39 | + if not inFile then print(arg[i] .. ": " .. err) else |
| 40 | + local outFile |
| 41 | + outFile, err = io.open(arg[i] .. ".tmp", "wb") |
| 42 | + if not outFile then |
| 43 | + print(arg[i] .. ".tmp: " .. err) |
| 44 | + else |
| 45 | + local shebang = Shebang(inFile) |
| 46 | + if shebang then |
| 47 | + outFile:write(shebang) |
| 48 | + while true do |
| 49 | + local line = inFile:read("*l") |
| 50 | + if line then |
| 51 | + outFile:write(line .. CRLF) |
| 52 | + else |
| 53 | + break |
| 54 | + end |
| 55 | + end |
| 56 | + inFile:close() outFile:close() |
| 57 | + os.remove(arg[i]) |
| 58 | + os.rename(arg[i] .. ".tmp", arg[i]) |
| 59 | + else |
| 60 | + inFile:close() outFile:close() |
| 61 | + os.remove(arg[i] .. ".tmp") |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments