11#! /usr/bin/env lua
22
3-
43help = [[
54DOS and UNIX disagree on what a new line should be
65DOS says it's a carriage return followed by a line feed (CRLF)
76while UNIX says it's just a line feed on its own (LF).
87Many tools (Lua included) don't care while others like
9- `TYPE` in DOS and Notepad in Windows will not display correctly.
8+ `TYPE` in DOS and Notepad in Windows will not work correctly.
109Tools like unix2dos/dos2unix convert line endings between the systems,
1110however, in doing so, the CR in CRLF on the shebang line might be
12- interpreted literally and prevent correct execution on UNIX systems.
11+ interpreted literally and prevent execution on UNIX systems.
1312
1413This script named "DOS friend" will convert every line ending of the files
1514passed to it with CRLF with the exception of the first line when a shebang
1615is present. When this occurs, the line will instead write LFCRLF so that
17- both types of systems can pleasantly read and run the file.
16+ both system families can pleasantly read and run the file.
1817]]
1918
2019if # arg < 1 then
@@ -40,31 +39,46 @@ local function Shebang(inFile)
4039end
4140
4241for i = 1 , # arg do
43- local inFile , err = io.open (arg [i ])
44- if not inFile then print (arg [i ] .. " : " .. err ) else
45- local outFile
46- outFile , err = io.open (arg [i ] .. " .tmp" , " wb" )
47- if not outFile then
42+ local iFile , err = io.open (arg [i ])
43+ if not iFile then print (arg [i ] .. " : " .. err ) else
44+ local oFile
45+ oFile , err = io.open (arg [i ] .. " .tmp" , " wb" )
46+ if not oFile then
4847 print (arg [i ] .. " .tmp: " .. err )
4948 else
50- local shebang = Shebang (inFile )
49+ local shebang = Shebang (iFile )
5150 if shebang then
52- outFile :write (shebang )
51+ oFile :write (shebang )
5352 while true do
54- local line = inFile :read (" *l" )
53+ local line = iFile :read (" *l" )
5554 if line then
56- outFile :write (StripCarriage (line ) .. CRLF )
55+ oFile :write (StripCarriage (line ) .. CRLF )
5756 else
5857 break
5958 end
6059 end
61- inFile :close () outFile :close ()
62- os.remove (arg [i ])
63- os.rename (arg [i ] .. " .tmp" , arg [i ])
64- else
65- inFile :close () outFile :close ()
66- os.remove (arg [i ] .. " .tmp" )
60+ iFile :close () oFile :close ()
61+
62+ --[[
63+ Swap the temporary file and original file around
64+ so that the original files is being copied to.
65+ This allows system file permissions to remain unchanged.
66+ --]]
67+
68+ iFile = io.open (arg [i ] .. " .tmp" , " rb" )
69+ oFile = io.open (arg [i ], " wb" )
70+ if iFile and oFile then
71+ while true do
72+ local data = iFile :read (1024 )
73+ if not data then
74+ break
75+ end
76+ oFile :write (data )
77+ end
78+ iFile :close () oFile :close ()
79+ end
6780 end
81+ os.remove (arg [i ] .. " .tmp" )
6882 end
6983 end
7084end
0 commit comments