How to get all fork sources from one GitHub repo list operation?

懵懂的女人 提交于 2019-12-06 12:30:08

You can use GraphQL API v4 to get the list of forked repo for a specific user/organization and get the parent repo name :

{
  organization(login: "nmap") {
    repositories(first: 100, isFork: true) {
      edges {
        node {
          parent {
            nameWithOwner
          }
        }
      }
    }
  }
}

Try it in the explorer

An example using

:

package main

import (
    "fmt"
    "encoding/json"
    "net/http"
    "bytes"
    "io/ioutil"
)

var token string = "YOUR_ACCESS_TOKEN"

func main() {
    jsonMap := map[string]string{"query": `{
      organization(login: "nmap") {
        repositories(first: 100, isFork: true) {
          pageInfo {
            hasNextPage
            endCursor
          }
          edges {
            node {
              parent {
                nameWithOwner
              }
            }
          }
        }
      }
    }
    `}
    jsonData, _ := json.Marshal(jsonMap)

    client := &http.Client{}
    req, _ := http.NewRequest("POST", "https://api.github.com/graphql", bytes.NewBuffer(jsonData))
    req.Header.Add("Authorization",  fmt.Sprint("Token ", token))
    req.Header.Add("Content-Type", "application/json")
    resp, _ := client.Do(req)

    fmt.Println(resp.Status)
    if resp.StatusCode == http.StatusOK {
        bodyBytes, _ := ioutil.ReadAll(resp.Body)
        bodyString := string(bodyBytes)
        fmt.Println(bodyString)
    }
}

To go through pagination, you can check the hasNextPage value to check if you have to send another query to grab the next 100 forked repo, Use after in RepositoryConnection to get the 100 next value after the given cursor (store the value of previous endCursor if hasNextPage is true).

First request :

{
  organization(login: "appcelerator-forks") {
    repositories(first: 100, isFork: true) {
      pageInfo {
        hasNextPage
        endCursor
      }
      edges {
        node {
          parent {
            nameWithOwner
          }
        }
      }
    }
  }
}

gives "hasNextPage": true & "endCursor" : "Y3Vyc29yOnYyOpHOAQ1VZg==". Next request will be :

{
  organization(login: "appcelerator-forks") {
    repositories(first: 100, isFork: true, after: "Y3Vyc29yOnYyOpHOAQ1VZg==") {
      pageInfo {
        hasNextPage
        endCursor
      }
      edges {
        node {
          parent {
            nameWithOwner
          }
        }
      }
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!