简而言之,它旨在更容易地管理许多不同的项目.
其中一个有用的方法是自动检测我正在处理的项目类型,以正确设置一些命令.
目前我正在使用classmethod“匹配”函数和一个迭代各种“匹配”的检测函数.
我相信可能有更好的设计,但找不到它.
有任何想法吗?
class ProjectType(object):
build_cmd = ""
@classmethod
def match(cls, _):
return True
class PythonProject(ProjectType):
build_cmd = "python setup.py develop --user"
@classmethod
def match(cls, base):
return path.isfile(path.join(base, 'setup.py'))
class AutoconfProject(ProjectType):
#TODO: there should be also a way to configure it
build_cmd = "./configure && make -j3"
@classmethod
def match(cls, base):
markers = ('configure.in', 'configure.ac', 'makefile.am')
return any(path.isfile(path.join(base, x)) for x in markers)
class MakefileOnly(ProjectType):
build_cmd = "make"
@classmethod
def match(cls, base):
# if we can count on the order the first check is not useful
return (not AutoconfProject.match(base)) and \
(path.isfile(path.join(base, 'Makefile')))
def detect_project_type(path):
prj_types = (PythonProject, AutoconfProject, MakefileOnly, ProjectType)
for p in prj_types:
if p.match(path):
return p()
解决方法:
这是合理使用工厂函数作为类方法.
一种可能的改进是让所有类继承自单个父类,该父类具有单个类方法,该类方法包含detect_project_type中的所有逻辑.
也许这样的事情会起作用:
class ProjectType(object):
build_cmd = ""
markers = []
@classmethod
def make_project(cls, path):
prj_types = (PythonProject, AutoconfProject, MakefileOnly, ProjectType)
for p in prj_types:
markers = p.markers
if any(path.isfile(path.join(path, x)) for x in markers):
return p()
class PythonProject(ProjectType):
build_cmd = "python setup.py develop --user"
markers = ['setup.py']
class AutoconfProject(ProjectType):
#TODO: there should be also a way to configure it
build_cmd = "./configure && make -j3"
markers = ['configure.in', 'configure.ac', 'makefile.am']
class MakefileOnly(ProjectType):
build_cmd = "make"
markers = ['Makefile']
标签:python
来源: https://codeday.me/bug/20190530/1185567.html