1.背景
基于当前自动化框架,每个人每次新建项目的时候,都会要重新创建一个项目,可以采用复制之前或者手动新建的方式,这里通过python脚本来实现新建项目
2.
class testcase_admin():
def __init__(self,argv=None):
self.argv = argvor sys.argv[:]
def create_project(self):
global old_path,project_name,new_path
try:
project_name =self.argv[1]
self.validate_name(project_name)
except IndexError:
print('please enter a project name')
project_path = path.join(os.getcwd(), project_name,'src')
self.create_file(project_path)
template_dir = path.join(os.getcwd(),'conf','project_template','project_name', 'src')
for root, dirs, filesin os.walk(template_dir):
for filein files:
root_file = root.split('\\')[-1]
new_dir = os.path.join(project_path, root_file)
if root_file !='src':
self.create_file(new_dir)
new_path = os.path.join(project_path, root_file,file)
else:
new_path = os.path.join(project_path, file)
old_path = os.path.join(root, file)
old_suffix ='.py-tpl'
new_suffix ='.py'
if new_path.endswith(old_suffix):
new_path = new_path[:-len(old_suffix)] + new_suffix
try:
# 复制文件
shutil.copyfile(old_path, new_path)
except IOError as e:
print(e)
try:
shutil.copymode(old_path, new_path)
self.make_writeable(new_path)
except OSError:
print("Notice: Couldn't set permission bits on %s. You're "
"probably using an uncommon filesystem setup. No "
"problem." % new_path, self.style.NOTICE)
def make_writeable(self, filename):
if not os.access(filename, os.W_OK):
st = os.stat(filename)
new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSER
os.chmod(filename, new_permissions)
def validate_name(self,name):
if name ==None:
raise CommandError('you must provide a name')
if not name.isidentifier():
raise CommandError("'{name}' is not a valid name.".format(name=name))
try:
import_module(name)
except ImportError:
pass
else:
raise CommandError("'{name}' conflicts with the name of an existing python".format(name=name))
def create_file(self,path):
if not os.path.exists(path):
try:
os.makedirs(path)
except FileExistsError:
raise CommandError("'%s' aready exists" %path)
except OSError as e:
raise CommandError(e)
if __name__ =="__main__":
testcase_admin = testcase_admin()
testcase_admin.create_project()