Permalink
Browse files

Create conf module.

Remove DictBase class to conf module from base module.
Rename DictBase to PYConf.
Add INIConf to conf module.
Make a conf module test.
  • Loading branch information...
1 parent 962ee3d commit 2cff1b2fbe2314c92cc124ebcace2120ca7f6069 @zrong committed Jun 14, 2015
Showing with 1,340 additions and 561 deletions.
  1. +0 −90 rookout/base.py
  2. +121 −0 rookout/conf.py
  3. +19 −0 tests/config.ini
  4. +2 −43 tests/testbase.py
  5. +55 −0 tests/testconf.py
  6. +11 −0 tests/testftp.py
  7. +2 −2 tests/testgettext.py
  8. +1 −1 tests/testgit.py
  9. +1 −1 tests/testlua.py
  10. +1,128 −424 tests/zh_cn.po
View
@@ -25,96 +25,6 @@
from string import Template
from rookout import slog
-
-class DictBase(dict):
- """作为配置文件的基类。
-
- dict 默认不适合当作配置文件对象使用。如要有下面几点不便:
-
- #. 对于不存在的 key,会 raise KeyError 错误;
- #. dict不能使用 ``.`` 语法访问。
-
- :class:`DictBase` 解决了这些问题,还另外提供了一些方法在使用上更加方便。
-
- """
-
- def __missing__(self, key):
- return None
-
- def __getattr__(self, name):
- return self[name]
-
- def __setattr__(self, name, value):
- self[name] = value
-
- def __delattr__(self, name):
- del self[name]
-
- def copy_from_dict(self, adict, parent=None):
- """从一个已经存在的 dict 中复制所有的值。
-
- :param adict: 被复制的 dict。
- :type adict: dict
- :param parent: 复制到哪个父对象。
- 若为 None 则复制到 self 。
- :type parent: DictBase
-
- """
- if not parent:
- parent = self
- for k,v in adict.items():
- if isinstance(v, dict):
- vDict = DictBase(v)
- self.copy_from_dict(v, vDict)
- parent[k] = vDict
- else:
- parent[k] = v
-
- def dump(self, human=False):
- """将自身内容打印成字符串
-
- :param bool human: 若值为 True ,则打印成易读格式。
-
- """
- txt = str(self)
- if human:
- txt = txt.replace(", '", ",\n'")
- txt = txt.replace("{", "{\n")
- txt = txt.replace("}", "\n}")
- txt = txt.replace("[", "[\n")
- txt = txt.replace("]", "\n]")
- return txt
-
- def save_to_file(self, path, human=True):
- """将自身内容保存到文件。
-
- :param str path: 保存的文件路径。
- :param bool human: 参见 :func:`dump()`
-
- """
- write_file(path, self.dump(human))
- slog.info("Save %a done.", path)
-
- def read_from_file(self, path):
- """从一个文本文件中读入信息。
- 假设该文本文件的格式与 :func:`dump()` 相同。
-
- :param str path: 待读入的文件路径。
-
- """
- if not os.path.exists(path):
- slog.warning("The file %s is not exist.", path)
- return False
- txt = read_file(path)
- dic = eval(txt)
- self.copy_from_dict(dic)
- return True
-
- copyFromDict = copy_from_dict
- saveToFile = save_to_file
- readFromFile = read_from_file
-
-
def list_dir(sourceDir, include_source=None, include_file=True):
"""与 :func:`os.listdir()` 类似,但提供一些筛选功能,且返回生成器对象。
View
@@ -0,0 +1,121 @@
+########################################
+# conf.py
+# Author zrong(zengrong.net)
+#
+# Creation 2015-06-14
+# Last Editing 2015-06-14
+########################################
+
+import re
+from rookout import slog
+from rookout.base import (read_file, write_file)
+from configparser import (ConfigParser, NoSectionError)
+
+class PYConf(dict):
+ """作为配置文件的基类。
+
+ dict 默认不适合当作配置文件对象使用。如要有下面几点不便:
+
+ #. 对于不存在的 key,会 raise KeyError 错误;
+ #. dict不能使用 ``.`` 语法访问。
+
+ :class:`PYConf` 解决了这些问题,还另外提供了一些方法在使用上更加方便。
+
+ """
+
+ def __missing__(self, key):
+ return None
+
+ def __getattr__(self, name):
+ return self[name]
+
+ def __setattr__(self, name, value):
+ self[name] = value
+
+ def __delattr__(self, name):
+ del self[name]
+
+ def copy_from_dict(self, adict, parent=None):
+ """从一个已经存在的 dict 中复制所有的值。
+
+ :param adict: 被复制的 dict。
+ :type adict: dict
+ :param parent: 复制到哪个父对象。
+ 若为 None 则复制到 self 。
+ :type parent: PYConf
+
+ """
+ if not parent:
+ parent = self
+ for k,v in adict.items():
+ if isinstance(v, dict):
+ vDict = PYConf(v)
+ self.copy_from_dict(v, vDict)
+ parent[k] = vDict
+ else:
+ parent[k] = v
+
+ def dump(self, human=False):
+ """将自身内容打印成字符串
+
+ :param bool human: 若值为 True ,则打印成易读格式。
+
+ """
+ txt = str(self)
+ if human:
+ txt = txt.replace(", '", ",\n'")
+ txt = txt.replace("{", "{\n")
+ txt = txt.replace("}", "\n}")
+ txt = txt.replace("[", "[\n")
+ txt = txt.replace("]", "\n]")
+ return txt
+
+ def save_to_file(self, path, human=True):
+ """将自身内容保存到文件。
+
+ :param str path: 保存的文件路径。
+ :param bool human: 参见 :func:`dump()`
+
+ """
+ write_file(path, self.dump(human))
+ slog.info("Save %a done.", path)
+
+ def read_from_file(self, path):
+ """从一个文本文件中读入信息。
+ 假设该文本文件的格式与 :func:`dump()` 相同。
+
+ :param str path: 待读入的文件路径。
+
+ """
+ if not os.path.exists(path):
+ slog.warning("The file %s is not exist.", path)
+ return False
+ txt = read_file(path)
+ dic = eval(txt)
+ self.copy_from_dict(dic)
+ return True
+
+class INIConf(ConfigParser):
+
+ _LIST_TMPL = r"""
+ @(list)? # @ or @list
+ \s*(?P<header>\w+) # very permissive!
+ """
+
+ LISTCRE = re.compile(_LIST_TMPL, re.VERBOSE)
+
+ def __init__(self):
+ super().__init__(allow_no_value=True)
+
+ def list(self, section):
+ if not self.LISTCRE.match(section):
+ section = "@list "+section
+ return self.options(section)
+
+ def lists(self):
+ list_sections = []
+ for name in self.sections():
+ m = self.LISTCRE.search(name)
+ if m:
+ list_sections.append(m.group('header'))
+ return list_sections
View
@@ -0,0 +1,19 @@
+# test
+
+[default]
+
+a = 1
+b = 2
+c
+
+[@list tt]
+
+a
+b
+
+c
+#14
+d
+e
+f
+g
View
@@ -1,42 +1,9 @@
import os
import shutil
-import ftplib
-from zrong import base
+from rookout import base
workDir = None
-class TestDictBase:
- def __init__(self):
- super(TestDictBase, self).__init__()
- self._dict = base.DictBase({"name":"neo", "sex":"unknown"})
-
- def test_getattr(self):
- self._dict.name;
-
- def test_setattr(self):
- self._dict.name = "zrong";
-
- def test_delattr(self):
- del self._dict.name
-
- def test_dump(self):
- self._dict.dump()
-
- def test_copy_from_dict(self):
- nestedDict = dict(
- a = 1,
- b = {'bb':{'bbb':{'bbbb':2}}},
- )
- newDict = base.DictBase()
- newDict.copy_from_dict(nestedDict)
- assert newDict.a == 1 and newDict.b.bb.bbb.bbbb == 2
-
- def test_save_to_file(self):
- fileName = "__TEST_DICT_BASE_WRITE_TO_FILE__.py"
- filePath = os.path.join(workDir, fileName)
- self._dict.save_to_file(filePath)
- os.remove(filePath)
-
def setup():
global workDir
workDir = os.path.split(os.path.abspath(__file__))[0]
@@ -47,7 +14,7 @@ def test_list_dir():
def test_copy_dir():
dirName = "__TEST_COPY_DIR__"
dstPath = os.path.join(workDir, dirName)
- souPath = os.path.join(workDir, os.pardir, 'zrong')
+ souPath = os.path.join(workDir, os.pardir, 'rookout')
base.copy_dir(souPath, dstPath, True)
shutil.rmtree(dstPath)
@@ -66,11 +33,3 @@ def test_write_file():
def test_get_md5():
assert len(base.get_md5(__file__)) == 32
-def test_get_ftp():
- ftpobj = base.get_ftp({
- 'server':'127.0.0.1',
- 'user':'user',
- 'password':'password',
- })[0]
- print(ftpobj)
- assert isinstance(ftpobj, ftplib.FTP)
View
@@ -0,0 +1,55 @@
+import os
+from rookout.conf import (PYConf, INIConf)
+
+workDir = os.path.split(os.path.abspath(__file__))[0]
+
+# setup is called behind TestPYConf and TestINIConf
+# def setup():
+# global workDir
+# workDir = os.path.split(os.path.abspath(__file__))[0]
+# print('setup', workDir)
+
+class TestPYConf(object):
+ def __init__(self):
+ self._dict = PYConf({"name":"neo", "sex":"unknown"})
+
+ def test_getattr(self):
+ self._dict.name;
+
+ def test_setattr(self):
+ self._dict.name = "zrong";
+
+ def test_delattr(self):
+ del self._dict.name
+
+ def test_dump(self):
+ self._dict.dump()
+
+ def test_copy_from_dict(self):
+ nestedDict = dict(
+ a = 1,
+ b = {'bb':{'bbb':{'bbbb':2}}},
+ )
+ newDict = PYConf()
+ newDict.copy_from_dict(nestedDict)
+ assert newDict.a == 1 and newDict.b.bb.bbb.bbbb == 2
+
+ def test_save_to_file(self):
+ # print('test_save_to_file', workDir)
+ fileName = "__TEST_DICT_BASE_WRITE_TO_FILE__.py"
+ filePath = os.path.join(workDir, fileName)
+ self._dict.save_to_file(filePath)
+ os.remove(filePath)
+
+class TestINIConf(object):
+ def __init__(self):
+ self._conf = INIConf()
+ self._conf.read(os.path.join(workDir, 'config.ini'))
+
+ def test_lists(self):
+ assert len(self._conf.lists()) == 1
+
+ def test_list(self):
+ assert self._conf.list('tt')
+ assert self._conf.list('@list tt')
+
View
@@ -0,0 +1,11 @@
+import ftplib
+from rookout.ftp import get_ftp
+
+def test_get_ftp():
+ ftpobj = get_ftp({
+ 'server':'127.0.0.1',
+ 'user':'user',
+ 'password':'password',
+ })[0]
+ print(ftpobj)
+ assert isinstance(ftpobj, ftplib.FTP)
@@ -1,6 +1,6 @@
import os
-from zrong.gettext import Gettext
-from zrong.base import get_files
+from rookout.gettext import Gettext
+from rookout.base import get_files
gt = None
workdir = None
View
@@ -1,4 +1,4 @@
-from zrong import git
+from rookout import git
def setup():
pass
View
@@ -1,6 +1,6 @@
# The test is from https://github.com/SirAnthony/slpp
-import zrong.lua as lua
+import rookout.lua as lua
import os
def setup():
Oops, something went wrong.

0 comments on commit 2cff1b2

Please sign in to comment.