diff options
author | Ted Trask <ttrask01@yahoo.com> | 2008-07-16 19:10:20 +0000 |
---|---|---|
committer | Ted Trask <ttrask01@yahoo.com> | 2008-07-16 19:10:20 +0000 |
commit | a1ad49891bbeea6c4c5cf77a574d219c9a722eab (patch) | |
tree | 595c8c08b0b45c304dc6997ebe5a4dac7f36ae5f | |
parent | d9b4b5fb0bc29a64c2e16454997b22f017ad4830 (diff) | |
download | acf-core-a1ad49891bbeea6c4c5cf77a574d219c9a722eab.tar.bz2 acf-core-a1ad49891bbeea6c4c5cf77a574d219c9a722eab.tar.xz |
Added getsection and setsection functions to getopts library.
git-svn-id: svn://svn.alpinelinux.org/acf/core/trunk@1310 ab2d0c66-481e-0410-8bed-d214d4d58bed
-rw-r--r-- | lib/getopts.lua | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/lib/getopts.lua b/lib/getopts.lua index 0579bd3..59333db 100644 --- a/lib/getopts.lua +++ b/lib/getopts.lua @@ -233,3 +233,85 @@ function getoptsfromfile (file, search_section, search_name, to_table, filter) end return opts end + +function getsection (file, search_section) + if not file or file == "" then + return nil + end + search_section = search_section or "" + local conf_file = {} + if (fs.is_file(file)) then + conf_file = fs.read_file_as_array ( file ) + else + for line in string.gmatch(file, "([^\n]*)\n") do + conf_file[#conf_file + 1] = line + end + local extra = string.match(file,"([^\n]*)$") + if extra ~= "" then + conf_file[#conf_file + 1] = extra + end + end + local sectionlines = {} + local section = "" + for i,l in ipairs(conf_file) do + -- find section name + local a = string.match ( l, "^%s*%[%s*(%S+)%s*%]" ) + if a then + if (search_section == section) then break end + section = a + elseif (search_section == section) then + sectionlines[#sectionlines + 1] = l + end + end + + return table.concat(sectionlines, "\n") +end + +function setsection (file, search_section, section_content) + if not file or file == "" then + return false, nil, "Invalid input for getopts.setoptsinfile()", file + end + search_section = search_section or "" + local conf_file = {} + if (fs.is_file(file)) then + conf_file = fs.read_file_as_array ( file ) + else + for line in string.gmatch(file, "([^\n]*)\n") do + conf_file[#conf_file + 1] = line + end + local extra = string.match(file,"([^\n]*)$") + if extra ~= "" then + conf_file[#conf_file + 1] = extra + end + end + local new_conf_file = {} + local done = false + local section = "" + for i,l in ipairs(conf_file) do + -- find section name + if not done then + local a = string.match ( l, "^%s*%[%s*(%S+)%s*%]" ) + if a then + if (search_section == section) then + done = true + else + section = a + if (search_section == section) then + l = l .. "\n" .. (section_content or "") + end + end + elseif (search_section == section) then + l = nil + end + end + new_conf_file[#new_conf_file + 1] = l + end + + if (fs.is_file(file)) then + fs.write_file(file, table.concat(new_conf_file, '\n')) + else + file = table.concat(new_conf_file, '\n') + end + + return true, "File has been modified!", nil, file +end |