Skip to content

Instantly share code, notes, and snippets.

@tst2005
Created July 24, 2020 16:06
Show Gist options
  • Save tst2005/54a6f4f0ad993898230c0c042bca6718 to your computer and use it in GitHub Desktop.
Save tst2005/54a6f4f0ad993898230c0c042bca6718 to your computer and use it in GitHub Desktop.
#!/usr/bin/env lua
-- pattern to disable as comment (in lua regexp % is the backquote character)
local pat1=[[<vmw:Config ovf:required="false" vmw:key="cpuAllocation%.shares%.shares" vmw:value="[^"]*"/>]]
local pat2=[[<vmw:Config ovf:required="false" vmw:key="cpuAllocation%.shares%.level" vmw:value="[^"]*"/>]]
-- pattern to enable a comment entry (in lua regexp % is the backquote character)
local patu=[[<!%-%-:Config ovf:required="false" vmw:key="[^"]*" vmw:value="[^"]*%-%->]]
-- read blocksize
local BS = 1024
local maxread = 10*1024*1024 -- work only in the first 10MB
--local maxread = nil -- uncomment it to search in the whole file
local function comment(data)
assert(data:sub(1,1) == "<", "capture data didn't start by '<'")
assert(data:sub(-1,-1)==">", "capture data didn't end by '>'")
assert(#data > 4+3, "capture data is too short") -- '<!--' + '-->'
return "<!--"..data:sub(5,-4).."-->"
end
local function uncomment(data)
assert(data:sub(1,1) == "<", "capture data didn't start by '<'")
assert(data:sub(-1,-1)==">", "capture data didn't end by '>'")
assert(#data > 4+3, "capture data is too short") -- '<!--' + '-->'
assert(data:sub(1,11)=="<!--:Config", "seems not like a vmw:Config xml entry :"..tostring(data:sub(1,11)))
return "<vmw"..data:sub(5,-4)..'"/>'
end
local function inline_search_and_apply(fd, pat, apply)
local lastline = ""
while true do
local seg = fd:read(BS)
if not seg then break end
if maxread and (fd:seek() > maxread) then break end
local line = lastline .. seg
local s1,e1 = line:find(pat)
if s1 then
local pos = fd:seek()
local rel_start = s1 -#line
local abs_start = pos + rel_start -1
local matchsize = e1 -s1 +1
fd:seek("set", abs_start)
local capture = fd:read(matchsize)
local replace = apply(capture)
print("at offset ".. abs_start)
print("-"..capture)
print("+"..replace)
fd:seek("set", abs_start)
fd:write(replace)
fd:flush()
break
end
lastline=seg
end
end
local action=comment
if arg[1] == "-u" then
--print("ACTION: uncomment")
pat1 = patu
pat2 = patu
action = uncomment
table.remove(arg, 1)
assert(arg[1]~="-u")
end
local file = assert(arg[1], "argument #1 must be the file to patch")
local fd = assert(io.open(file, "r+"))
inline_search_and_apply(fd, pat1, action)
fd:seek("set", 0) -- rewind
inline_search_and_apply(fd, pat2, action)
fd:close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment