osnosn

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

用于openwrt中操作ini配置文件的两个lua脚本_golang操作ini文件

转载注明来源: 本文链接 来自osnosn的博客,写于 2023-03-19.

参考

说明

给有需要的人参考。主要是参考思路。
这个思路,我也是在网上搜的。
写的不好,还能再优化。测试过,确实能用。
凑合看,凑合用。

lua操作shell配置文件

op中没有bash。它的sh不支持数组。

# filename: test-pw.sh
# 此文件将会被程序重写。支持注释,用'#'。
# This file will be rewrited by program. allow comments with '#'.
# 配置项中不要包含引号(' ")否则会出错。
 user_0='username0'   #id
 pwd_0='password0'   #pwd
 type_0='type0'
 user_1='user2'   #id
 pwd_1='password2'   #pwd
 type_1='type2'
#!/usr/bin/lua
aa=assert(dofile('./shell_file.lua'))
inifile='/path_to/test-pw.sh'
bb=aa.read(inifile)
print(aa.get('1','user'))
print(aa.set('1','user','123456'))
print(aa.save())
#!/usr/bin/lua
-- filename: shell_file.lua

local MM={}
MM.filename=nil

function MM.read(statfile)
   MM.ini={}
   MM.filename=statfile
   local fp=io.open(statfile,"rb")

   if fp==nil then  -- file not exists
      return 'stat file not found'
   else
      local sect
      for line in fp:lines() do
        repeat  -- use break as continue
          line=MM.trim_sp(line)
          if line:find('#')==1 then break end
          local n1=line:find('=')   -- find =
          if n1 ~= nil and n1>0 then
            local num,key,val=MM.split_conf(line)
            n1,n2,sect=val:find('^(.-)%s+#')  --#
            if sect ~= nil and #sect>0 then
              val=sect
            end
            if num ~= nil and key ~= nil then
              if MM.ini[num] == nil then
                MM.ini[num]={}
              end
              MM.ini[num][key]=MM.trim(val)
            end
          end
        until true
      end
      fp:close()
   end
   return nil
end
function MM.get(node,key)  -- get data
  if MM.ini[node] ~= nil then
     if MM.ini[node][key] ~= nil then
        return MM.ini[node][key]
     end
  end
  return ''
end
function MM.set(node,key,val)  -- set data
  if MM.ini[node] ~= nil then
     if MM.ini[node][key] ~= nil then
        MM.ini[node][key]=val
        return nil
     end
  end
  return 'Not set'
end
function MM.trim_sp(s)
   s=s:match("^%s*(.-)%s*$")
   return s
end
function MM.trim(s)
   s=s:match("^[%s\"']*(.-)[%s\"']*$")
   return s
end
function MM.split_conf(str)
   local n1,n2,kk,vv=string.find(str, '^%s*(.-)%s*=%s*(.-)%s*$')
   if kk ~= nil or vv ~= nil then
      if #kk > 0 then
        local n1,n2,k1,k2=string.find(kk, '^(.-)_(%d*)$')
        if k1 ~= nil or k2 ~= nil then
          if #k1 <1 then
            return nil,nil,nil
          end
          if #k2 >0 then
            return k2,k1,vv
          end
          return '_',k1,vv
        end
        return '_',kk,vv
      end
      return nil,nil,nil
   end
   return nil,nil,nil
end
function MM.save()
   if MM.filename == nil then return nil end
   local nixio=require "nixio"
   local fp=io.open(MM.filename,"rb")
   local wfp=nixio.open(MM.filename..'.cache',"w")

   if fp==nil then  -- file not exists
      return 'stat file not found'
   end
   if wfp==nil then  -- write file fail
      fp:close()
      return 'write file fail'
   end
   if true then
      wfp:lock('lock')  --这是一个阻塞操作,防止多个例程同时写,POSIX lockf()
      for line_org in fp:lines() do
        repeat  -- use break as continue
          local line=MM.trim_sp(line_org)
          if line:find('#')==1 then wfp:write(line_org..'\n') break end
          local comment=''
          local cmt
          local n1=line:find('=')   --find =
          if n1 ~= nil and n1>0 then
            local num,key,val=MM.split_conf(line)
            n1,n2,sect,cmt=val:find('^(.-)%s+(#.*)$')  --#
            if sect ~= nil and #sect>0 then
              val=sect   --ignored
              comment=cmt
            end
            if #comment>0 then comment='   '..comment end
            if num ~= nil and MM.ini[num] ~= nil and  MM.ini[num][key] ~= nil then
                wfp:write(' '..key..'_'..num.."='"..MM.ini[num][key].."'"..comment..'\n')
            else
              wfp:write(line_org..'\n')
            end
          else
            wfp:write(line_org..'\n')
          end
        until true
      end
      fp:close()
      wfp:lock('ulock')
      wfp:close()
      local fs=require "nixio.fs"
      fs.move(MM.filename,MM.filename..os.date('-%Y%m%d_%H%M%S.bak'))
      fs.move(MM.filename..'.cache',MM.filename)
   end
   return nil
end

return MM

lua操作ini配置文件

 # filename: myini.ini
 # 配置项中不要含有引号(' "),否则会出错。
 //test
[list]    //test
 // test
   id22 = testtesttest   //test
[auth]
   id22 = read,modify   #权限列表
   id33 = read,write
#!/usr/bin/lua
aa=assert(dofile('./ini_file.lua'))
inifile='/path_to/myini.ini'
bb=aa.read(inifile)
print(aa.get('list','id22'))
aa.set('list','id22','test123test')
print(aa.save())
#!/usr/bin/lua
-- filename: ini_file.lua

local MM={}
MM.sep='\t*\t'
MM.filename=nil

function MM.read(statfile)  -- get data from .ini
   MM.ini={}
   MM.filename=statfile
   local sector='_'
   local fp=io.open(statfile,"rb")

   if fp==nil then  -- file not exists
      return 'stat file not found'
   else
      for line in fp:lines() do
        repeat  -- use break as continue
          line=MM.trim_sp(line)
          if line:find('#')==1 then break end
          if line:find('//')==1 then break end
          local n1,n2,sect=line:find('^%[(.-)%]')  --find sector
          if sect ~= nil and #sect>0 then
            sector=sect
            break
          end
          local n1=line:find('=')   -- find =
          if n1 ~= nil and n1>0 then
            local key,val=MM.split_conf(line)
            n1,n2,sect=val:find('^(.-)%s+//') --//
            if sect ~= nil and #sect>0 then
              val=sect
            end
            n1,n2,sect=val:find('^(.-)%s+#')  --#
            if sect ~= nil and #sect>0 then
              val=sect
            end
            if key ~= nil then
              if MM.ini[sector] == nil then
                MM.ini[sector]={}
              end
              MM.ini[sector][key]=MM.trim(val)
            end
          end
        until true
      end
      fp:close()
   end
   return nil
end
function MM.get(node,key)  -- get data
  if MM.ini[node] ~= nil then
     if MM.ini[node][key] ~= nil then
        return MM.ini[node][key]
     end
  end
  return ''
end
function MM.set(node,key,val)  -- set data
  if MM.ini[node] ~= nil then
     if MM.ini[node][key] ~= nil then
        MM.ini[node][key]=val
        return nil
     end
  end
  return 'Not set'
end
function MM.trim_sp(s)
   s=s:match("^%s*(.-)%s*$")
   return s
end
function MM.trim(s)
   s=s:match("^[%s\"']*(.-)[%s\"']*$")
   return s
end
function MM.split_conf(str)
   local n1,n2,kk,vv=string.find(str, '^%s*(.-)%s*=%s*(.-)%s*$')
   if kk ~= nil or vv ~= nil then
      if #kk > 0 then
        return kk,vv
      end
      return nil,nil
   end
   return nil,nil
end
function MM.save()
   if MM.filename == nil then return nil end
   local sector='_'
   local nixio=require "nixio"
   local fp=io.open(MM.filename,"rb")
   local wfp=nixio.open(MM.filename..'.cache',"wb")

   if fp==nil then  -- file not exists
      return 'stat file not found'
   end
   if wfp==nil then  -- write file fail
      fp:close()
      return 'write file fail'
   end
   if true then
      wfp:lock('lock')  --这是一个阻塞操作,防止多个例程同时写,POSIX lockf()
      for line_org in fp:lines() do
        repeat  -- use break as continue
          local line=MM.trim_sp(line_org)
          if line:find('#')==1 then wfp:write(line_org..'\n') break end
          if line:find('//')==1 then wfp:write(line_org..'\n') break end
          local n1,n2,sect=line:find('^%[(.-)%]')   --find sector
          if sect ~= nil and #sect>0 then
            sector=sect
            wfp:write(line_org..'\n')
            break
          end
          local comment=''
          local cmt
          local n1=line:find('=')   --find =
          if n1 ~= nil and n1>0 then
            local key,val=MM.split_conf(line)
            n1,n2,sect,cmt=val:find('^(.-)%s+(//.*)$') --//
            if sect ~= nil and #sect>0 then
              val=sect  --ignored
              comment=cmt
            end
            n1,n2,sect,cmt=val:find('^(.-)%s+(#.*)$')  --#
            if sect ~= nil and #sect>0 then
              val=sect  --ignored
              comment=cmt
            end
            if #comment>0 then comment='   '..comment end
            if key ~= nil and MM.ini[sector] ~= nil and  MM.ini[sector][key] ~= nil then
                wfp:write('   '..key..' = '..MM.ini[sector][key]..comment..'\n')
            else
              wfp:write(line_org..'\n')
            end
          else
            wfp:write(line_org..'\n')
          end
        until true
      end
      fp:close()
      wfp:lock('ulock')
      wfp:close()
      local fs=require "nixio.fs"
      fs.move(MM.filename,MM.filename..os.date('-%Y%m%d_%H%M%S.bak'))
      fs.move(MM.filename..'.cache',MM.filename)
   end
   return nil
end

return MM

golang操作ini

package main
import (
   "mypkg/configfile"
}
func main() {
   var myConfig *configfile.Config = nil
   myConfig = new(configfile.Config)
   myConfig.InitConfig("/path_to/myini.ini")
   path := myConfig.Read("default", "path")
}
package configfile
//这个程序,是只读操作,所以没加锁。如果要修改ini文件,就需要加文件锁

import (
        "bufio"
        "io"
        "os"
        "strings"
)
/*
# unix 风格配置文件
[default]
path= c:/go
version = 1.44

[test]
num =   666
something  = wrong  #注释1
#fdfdfd = fdfdfd    注释整行
refer= refer       //注释3

#----调用方法---
myConfig := new(configfile.Config)
myConfig.InitConfig("c:/config.txt")
fmt.Println(myConfig.Read("default", "path"))
*/

//const middle = "\t*\t"

type Config struct {
        Mymap  map[string]string
        strcet string
        Sep string
}

func (c *Config) InitConfig(path string) {
        c.Mymap = make(map[string]string)
        c.Sep="\t*\t" //middle

        f, err := os.Open(path)
        if err != nil {
                panic(err)
        }
        defer f.Close()

        r := bufio.NewReader(f)
        for {
                b, _, err := r.ReadLine()
                if err != nil {
                        if err == io.EOF {
                                break
                        }
                        panic(err)
                }

                s := strings.TrimSpace(string(b))
                if strings.Index(s, "#") == 0 {
                        continue
                }
                if strings.Index(s, "//") == 0 {
                        continue
                }

                n1 := strings.Index(s, "[")
                n2 := strings.LastIndex(s, "]")
                if n1 > -1 && n2 > -1 && n2 > n1+1 {
                        c.strcet = strings.TrimSpace(s[n1+1 : n2])
                        continue
                }

                if len(c.strcet) == 0 {
                        continue
                }
                index := strings.Index(s, "=")
                if index < 0 {
                        continue
                }

                frist := strings.TrimSpace(s[:index])
                if len(frist) == 0 {
                        continue
                }
                second := strings.TrimSpace(s[index+1:])

                pos := strings.Index(second, "\t#")
                if pos > -1 {
                        second = second[0:pos]
                }

                pos = strings.Index(second, " #")
                if pos > -1 {
                        second = second[0:pos]
                }

                pos = strings.Index(second, "\t//")
                if pos > -1 {
                        second = second[0:pos]
                }

                pos = strings.Index(second, " //")
                if pos > -1 {
                        second = second[0:pos]
                }

                second=strings.TrimSpace(second)

                /*
                if len(second) == 0 {
                        continue
                }
                */

                key := c.strcet + c.Sep + frist
                c.Mymap[key] = second
        }
}

func (c Config) Read(node, key string) string {
        key = node + c.Sep + key
        v, found := c.Mymap[key]
        if !found {
                return ""
        }
        return v
}

----end----


转载注明来源: 本文链接 https://www.cnblogs.com/osnosn/p/17232829.html
来自 osnosn的博客 https://www.cnblogs.com/osnosn/ .


posted on 2023-03-19 17:00  osnosn  阅读(157)  评论(0编辑  收藏  举报