使用 GraphQL 突变删除 github 中的分支

tow*_*wel 4 github github-api graphql

我想使用 GraphQL 突变删除 github 分支,但我还没有找到有关该deleteRef命令的足够信息。使用GraphQL 浏览器我想出了这个废话:

mutation {
  deleteRef(input: {refId: "my-branch"}) {
    __typename
  }
}
Run Code Online (Sandbox Code Playgroud)

我还不知道如何添加存储库信息以使突变具有任何意义,我添加的唯一原因__typename是该deleteRef块不能留空。我该如何修复这个突变?

Ber*_*tel 5

您无法在该突变中返回任何内容,因为它不是 类型Void。您需要定义如下所示的突变:

mutation DeleteBranch($branchRef: ID!) {
  deleteRef(input: {refId: $branchRef}) {
    __typename
    clientMutationId
  }
}
Run Code Online (Sandbox Code Playgroud)

资源管理器中,您可以定义查询和突变,并选择按下按钮时要执行的查询和突变。资源管理器中的完整示例是:

query GetBranchID {
  repository(name: "test-repo", owner: "bertrandmartel") {
    refs(refPrefix: "refs/heads/", first: 100) {
      nodes {
        id
        name
      }
    }
  }
}

mutation DeleteBranch($branchRef: ID!) {
  deleteRef(input: {refId: $branchRef}) {
    __typename
    clientMutationId
  }
}
Run Code Online (Sandbox Code Playgroud)

带变量:

{
  "branchRef": "MDM6UmVmMjQ5MDU0NzQ0Om1hc3Rlcg=="
}
Run Code Online (Sandbox Code Playgroud)

您可以在资源管理器中执行以下操作:

  • 执行GetBranchID查询
  • branchRef复制粘贴变量中的引用
  • 执行DeleteBranch

效果如下:

import requests

repo_name = "YOUR_REPO"
repo_owner = "YOUR_USERNAME"
token = "YOUR_TOKEN"

query = """
query {
  repository(name: \"""" + repo_name + """\", owner: \"""" + repo_owner + """\") {
    refs(refPrefix: "refs/heads/", first: 100) {
      nodes {
        id
        name
      }
    }
  }
}
"""

resp = requests.post('https://api.github.com/graphql', 
    json={ "query": query},
    headers= {"Authorization": f"Token {token}"}
)
body = resp.json()

for i in body["data"]["repository"]["refs"]["nodes"]:
    print(i["name"], i["id"])

chosenBranchId = input("Enter a branch ID: ")

query = """
mutation {
  deleteRef(input: {refId: \"""" + chosenBranchId + """\"}) {
    __typename
    clientMutationId
  }
}
"""

resp = requests.post('https://api.github.com/graphql', 
    json={ "query": query},
    headers= {"Authorization": f"Token {token}"}
)
print(resp.json())
Run Code Online (Sandbox Code Playgroud)