如何用GitHub GraphQL在新建仓库中创建首个提交?
用GitHub GraphQL实现新建仓库的首个提交
要在纯GraphQL流程中完成新建私有仓库的首个提交,你可以使用createCommitOnBranch mutation——它支持在无父提交、无现有分支的情况下,直接创建首个提交并自动生成对应的分支。
步骤1:获取目标仓库的ID
你可以从之前创建仓库的createRepository返回结果中提取repository.id;如果没有留存,也可以通过查询获取:
query GetRepositoryId($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { id } }
步骤2:创建首个提交(含自动分支创建)
使用以下mutation,空数组的parentCommitOids表示这是仓库的初始提交,指定的branchName不存在时会被自动创建:
mutation CreateInitialCommit( $repositoryId: ID! $branchName: String! $commitMessage: String! $filePath: String! $fileContent: String! ) { createCommitOnBranch( input: { repositoryId: $repositoryId branchName: $branchName message: { headline: $commitMessage } fileChanges: { additions: [ { path: $filePath content: $fileContent } ] } parentCommitOids: [] # 空数组标记为初始提交 } ) { commit { oid messageHeadline } ref { name } } }
参数说明:
repositoryId:目标仓库的唯一IDbranchName:要创建的分支名(如main或master)commitMessage:初始提交的信息(如Initial commit)filePath:要添加的文件路径(如README.md)fileContent:文件的具体内容(如# My Private Repository)
步骤3(可选):设置默认分支
通常创建首个提交后,GitHub会自动将该分支设为仓库默认分支。如果需要显式设置,可使用updateRepository mutation:
mutation SetDefaultBranch($repositoryId: ID!, $defaultBranchName: String!) { updateRepository( input: { repositoryId: $repositoryId defaultBranchName: $defaultBranchName } ) { repository { defaultBranchRef { name } } } }
内容的提问来源于stack exchange,提问作者ike
相关产品推荐
相关产品推荐

