写了一个方法,功能是将 gitlab 群组下已有项目重命名,方法是这样的:
def rename_gitlab_project(self, project_name):
""" 重命名 GitLab 项目 """
try:
# 从 project_name 中提取工程名
project_name_parts = project_name.split('/')
if len(project_name_parts) > 1:
project_name = project_name_parts[-1]
group = self.gl.groups.get(self.group_name)
projects = {project.name: project for project in group.projects.list(all=True)}
script_action_project = projects.get(project_name)
if script_action_project:
new_project_name = f"{project_name}_delete_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
script_action_project.name = new_project_name
script_action_project.save()
logger.info(f"GitLab project {project_name} renamed to {new_project_name}")
else:
logger.error(f"GitLab project {project_name} not found for renaming")
except Exception as e:
logger.error(f'Error renaming GitLab project {project_name}: {str(e)}')
结果一直报错 script_action_project 没有 save() 方法。
尝试了好多种方式,浪费了几个小时,还是不行。
最后更新了 python-gitlab 依赖版本到最新版本,然后去官方文档查看了文档,才发现原来是这样的:
GroupProject and SharedProject objects returned by these two API calls are very limited, and do not provide all the features of Project objects. If you need to manipulate projects, create a new Project object:
first_group_project = group.projects.list()[0]
manageable_project = gl.projects.get(first_group_project.id, lazy=True)
即:
GroupProject 和 SharedProject 对象权限非常有限,不提供 Project 对象的所有功能。如果您需要操作项目,请创建一个新的 Project 对象。
原来如此!!!
最后修复方法为:
def rename_gitlab_project(self, project_name):
""" 重命名 GitLab 项目 """
try:
# 从 project_name 中提取工程名
project_name_parts = project_name.split('/')
if len(project_name_parts) > 1:
project_name = project_name_parts[-1]
group = self.gl.groups.get(self.group_name)
projects = {project.name: project for project in group.projects.list(all=True)}
script_action_project = projects.get(project_name)
if script_action_project:
new_project_name = f"{project_name}_delete_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
# GroupProject and SharedProject objects returned by these two API calls are very limited,
# and do not provide all the features of Project objects. If you need to manipulate projects,
# create a new Project object:
manageable_project = self.gl.projects.get(script_action_project.id, lazy=True)
manageable_project.name = new_project_name
manageable_project.save()
logger.info(f"GitLab project {project_name} renamed to {new_project_name}")
else:
logger.error(f"GitLab project {project_name} not found for renaming")
except Exception as e:
logger.error(f'Error renaming GitLab project {project_name}: {str(e)}')
这里印证了那句,「学习知识,查询信息,尽量到信息的源头去」。
学习要重视信息源,你的信息源需要有下面几个特质:
- 应该是第一手资料,不是被别人理解过、消化过的二手资料。尤其对于知识性的东西来说,更是这样。应该是原汁原味的,不应该是被添油加醋的。
- 应该是有佐证、有数据、有引用的,或是有权威人士或大公司生产系统背书的资料。
- 应该是被时间和实践检验过的,或是小心求证过的,不是拍脑袋野路子或是道听途说出来的资料。
- 应该是加入了一些自己的经验和思考,可以引发人深思的,是所谓信息的密集很大的文章。
2024.05.15 晚
上海 虹桥
网友评论