如何通过GitLab API从组模板创建仅含main分支的新项目?
问题
我的目标
通过GitLab API,使用组级模板创建一个仅复制main分支的新项目。
已执行操作
(基于GitLab Ultimate/Enterprise版本)
- 使用FetchAPI发送POST请求(成功)
- 调用GitLab Projects API创建新项目(成功)
- 使用组级模板(成功)
- 仅复制main分支(失败 - 复制了模板的所有分支到新项目)
现有代码
const headers = new Headers(); headers.append('PRIVATE-TOKEN', `${GITLAB_TOKEN}`); headers.append('Content-Type', 'application/json'); const createProjectBody = JSON.stringify({ name: `${NAME}`, description: `generated from template`, namespace_id: `${GROUPS_ID}`, use_custom_template: true, group_with_project_templates_id: `${TEMPLATE_GROUP_ID}`, template_project_id: `${TEMPLATE_ID}` }); fetch(`${PROJECTS_URL}`, { method: 'POST', headers: headers, body: createProjectBody, }).then(response => { if (response.ok) { console.log('Project created'); } else { console.log('Error creating project'); } }).catch(error => { console.log(error) });
已尝试的解决方案
- 将
use_custom_template: true改为use_custom_template: false,返回400错误:'' not a valid template_name - 添加参数
template_name: ${TEMPLATE_NAME},返回400错误:template_project_id and template_name are mutually exclusive - 保留
template_name并移除template_project_id,返回400错误:'mytemplate' is unknown or invalid
解决方案
在GitLab API的项目创建请求体中添加only_branch参数,指定仅复制main分支即可解决问题。
修改后的请求体代码:
const createProjectBody = JSON.stringify({ name: `${NAME}`, description: `generated from template`, namespace_id: `${GROUPS_ID}`, use_custom_template: true, group_with_project_templates_id: `${TEMPLATE_GROUP_ID}`, template_project_id: `${TEMPLATE_ID}`, only_branch: 'main' // 新增此参数 });
注意事项
- 该参数要求GitLab版本在13.6及以上
only_branch仅支持指定单个分支名称,确保新项目只克隆模板的目标分支内容
内容的提问来源于stack exchange,提问作者dko
相关产品推荐
相关产品推荐

