Skip to content

Instantly share code, notes, and snippets.

@ittner
Created December 20, 2010 15:15
Show Gist options
  • Save ittner/748488 to your computer and use it in GitHub Desktop.
Save ittner/748488 to your computer and use it in GitHub Desktop.
add-include-guards.lua: Quick and dirty script to add include guards to header files
#!/usr/bin/lua
-- Quick and dirty script to add include guards to header files
-- Author: Alexandre Erwin Ittner <alexandre (a) ittner x com x br>
-- License: GPLv2 or (at your option) any later version
local io = require("io")
local table = require("table")
local os = require("os")
local function process_one_file(fname)
if fname:sub(-2) ~= ".h" then
io.stderr:write(fname, ": does not end in '.h'\n")
return false
end
local fp = io.open(fname, "rb")
if not fp then
io.stderr:write(fname, ": failed to read file.\n")
return false
end
local macroname = "_" .. fname:upper():gsub("[^A-Z0-9]", "_")
local guard = "\n#ifndef " .. macroname .. "\n"
.. "#define " .. macroname
local tbl = { }
local added = false
while true do
local line = fp:read("*l")
if not line then break end
if line:find(macroname) then
io.stderr:write(fname, ": looks that this file already have ",
"the guard in the line '", line, "'.\n")
fp:close()
return false
end
tbl[#tbl+1] = line
if not added and line:gsub("%s", "") == "" then
tbl[#tbl+1] = guard
added = true
end
end
if not added then
table.insert(tbl, guard, 1)
end
tbl[#tbl+1] = "\n#endif /* " .. macroname .. " */\n"
fp:close()
local fp = io.open(fname, "wb")
if not fp then
io.stderr:write(fname, ": failed to update file.\n")
return false
end
fp:write(table.concat(tbl, "\n"))
if not fp:close() then
io.stderr:write(fname, ": failed to close file.\n")
return false
end
return true
end
if not arg or #arg < 1 then
io.stderr:write("Usage: ", arg[0], " someheader.h [...]\n")
os.exit(1)
end
local allok = true
for i = 1, #arg do
allok = process_one_file(arg[i]) and allok
end
os.exit(allok and 0 or 1)
@yukurt
Copy link

yukurt commented Sep 11, 2019

how do we use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment