summaryrefslogtreecommitdiff
path: root/xmake/core/base/io.lua
diff options
context:
space:
mode:
authorruki <[email protected]>2022-10-06 00:49:41 +0800
committerruki <[email protected]>2022-10-06 00:49:41 +0800
commite8d8b9e3ab29ac0dd9a79f0354bb4faec28f3851 (patch)
tree22b2e954dc8333c901e99bcd3eee0087694bc83e /xmake/core/base/io.lua
parent8055b6a045eabe62935a550e5d58d13591950c11 (diff)
add io.insert
Diffstat (limited to 'xmake/core/base/io.lua')
-rw-r--r--xmake/core/base/io.lua37
1 files changed, 28 insertions, 9 deletions
diff --git a/xmake/core/base/io.lua b/xmake/core/base/io.lua
index 128790c98..753db8753 100644
--- a/xmake/core/base/io.lua
+++ b/xmake/core/base/io.lua
@@ -684,33 +684,52 @@ function io.gsub(filepath, pattern, replace, opt)
return data, count
end
--- replace text of the given file and return replaced data
+-- replace text of the given file and return new file data
function io.replace(filepath, pattern, replace, opt)
-
- -- init option
opt = opt or {}
-
- -- read all data from file
local data, errors = io.readfile(filepath, opt)
if not data then return nil, 0, errors end
- -- replace it
local count = 0
if type(data) == "string" then
data, count = data:replace(pattern, replace, opt)
else
return nil, 0, string.format("data is not string!")
end
-
- -- replace ok?
if count ~= 0 then
- -- write all data to file
local ok, errors = io.writefile(filepath, data, opt)
if not ok then return nil, 0, errors end
end
return data, count
end
+-- insert text before line number in the given file and return new file data
+function io.insert(filepath, lineidx, text, opt)
+ opt = opt or {}
+ local data, errors = io.readfile(filepath, opt)
+ if not data then return nil, errors end
+
+ local newdata
+ if type(data) == "string" then
+ newdata = {}
+ for idx, line in ipairs(data:split("\n")) do
+ if idx == lineidx then
+ table.insert(newdata, text)
+ end
+ table.insert(newdata, line)
+ end
+ else
+ return nil, string.format("data is not string!")
+ end
+ if newdata and #newdata > 0 then
+ local rn = data:find("\r\n", 1, true)
+ data = table.concat(newdata, rn and "\r\n" or "\n")
+ local ok, errors = io.writefile(filepath, data, opt)
+ if not ok then return nil, errors end
+ end
+ return data, count
+end
+
-- cat the given file
function io.cat(filepath, linecount, opt)