【问题标题】:How to retrieve the list of all GitHub repositories of a person?如何检索一个人的所有 GitHub 存储库列表?
【发布时间】:2012-02-01 13:42:27
【问题描述】:

我们需要在 GitHub 帐户上显示一个人在他的存储库中的所有项目。

如何使用他的 git 用户名显示特定人的所有 git 存储库的名称?

【问题讨论】:

    标签: github github-api


    【解决方案1】:

    您可以为此使用github api。点击 https://api.github.com/users/USERNAME/repos 将列出用户 USERNAME 的公共存储库。

    【讨论】:

    【解决方案2】:

    使用Github API

    /users/:user/repos

    这将为您提供所有用户的公共存储库。如果您需要查找私有存储库,则需要以特定用户身份进行身份验证。然后您可以使用 REST 调用:

    /user/repos

    找到所有用户的repos。

    要在 Python 中执行此操作,请执行以下操作:

    USER='AUSER'
    API_TOKEN='ATOKEN'
    GIT_API_URL='https://api.github.com'
    
    def get_api(url):
        try:
            request = urllib2.Request(GIT_API_URL + url)
            base64string = base64.encodestring('%s/token:%s' % (USER, API_TOKEN)).replace('\n', '')
            request.add_header("Authorization", "Basic %s" % base64string)
            result = urllib2.urlopen(request)
            result.close()
        except:
            print 'Failed to get api request from %s' % url
    

    传递给函数的 url 是 REST url,如上例所示。如果您不需要进行身份验证,则只需修改方法以删除添加授权标头。然后,您可以使用简单的 GET 请求获取任何公共 api url。

    【讨论】:

    • 这只会给出结果集的第一个“页面”,默认设置为 30 个项目。您可以使用?per_page=100 来获得最大数量,但如果用户拥有超过一百个存储库,您将需要在 HTTP 的 Link 标头中跟踪多个 next URL,并与响应一起发送。
    • 感谢@Potherca,正是我想要的!
    【解决方案3】:

    尝试以下curl 命令列出存储库:

    GHUSER=CHANGEME; curl "https://api.github.com/users/$GHUSER/repos?per_page=100" | grep -o 'git@[^"]*'
    

    要列出克隆的 URL,请运行:

    GHUSER=CHANGEME; curl -s "https://api.github.com/users/$GHUSER/repos?per_page=1000" | grep -w clone_url | grep -o '[^"]\+://.\+.git'
    

    如果是私有的,您需要添加您的 API 密钥 (access_token=GITHUB_API_TOKEN),例如:

    curl "https://api.github.com/users/$GHUSER/repos?access_token=$GITHUB_API_TOKEN" | grep -w clone_url
    

    如果用户是组织,请改用/orgs/:username/repos,以返回所有存储库。

    要克隆它们,请参阅:How to clone all repos at once from GitHub?

    另见:How to download GitHub Release from private repo using command line

    【讨论】:

    • 这仅显示前 100 个存储库,与 per_page=1000 无关。
    • -s 选项添加到您的curl 命令以消除那些难看的进度条,如curl -s ...
    • 正如@jm666 所说,最大页面大小为100。要查看第二页,请执行以下操作: curl "api.github.com/users/$USER/repos?per_page=100\&page=2"
    • 私有示例不适用于该示例,/users/“复数”仅返回公共回购。您需要使用api.github.com/user/repos 并将令牌添加到请求中以获取私有令牌。
    • @kenorb 谜团解开了,用户是一个组织,所以/orgs/:username/repos 返回所有的回购,/users/... 返回其中的一部分,这确实很奇怪。用户名可以被视为用户或组织。
    【解决方案4】:

    这是 repos API 的完整规范:

    https://developer.github.com/v3/repos/#list-repositories-for-a-user

    GET /users/:username/repos

    查询字符串参数:

    前 5 个记录在上面的 API 链接中。 pageper_page 的参数记录在别处,在完整描述中很有用。

    • type(字符串):可以是allownermember 之一。默认值:owner
    • sort(字符串):可以是createdupdatedpushedfull_name 之一。默认值:full_name
    • direction(字符串):可以是ascdesc 之一。默认值:asc 使用 full_name 时,否则 desc
    • page(整数):当前页面
    • per_page(整数):每页的记录数

    由于这是一个 HTTP GET API,除了 cURL,您可以在浏览器中简单地尝试一下。例如:

    https://api.github.com/users/grokify/repos?per_page=2&page=2

    【讨论】:

      【解决方案5】:

      使用gh 命令

      您可以为此使用github cli

      $ gh api users/:owner/repos
      

      gh api orgs/:orgname/repos
      

      对于您想要的所有回购--paginate,您可以将其与--jq 结合起来,为每个回购仅显示name

      gh api orgs/:orgname/repos --paginate  --jq '.[].name' | sort
      

      【讨论】:

        【解决方案6】:

        如果您安装了jq,您可以使用以下命令列出用户的所有公共仓库

        curl -s https://api.github.com/users/<username>/repos | jq '.[]|.html_url'
        

        【讨论】:

          【解决方案7】:

          你可能需要一个 jsonp 解决方案:

          https://api.github.com/users/[user name]/repos?callback=abc

          如果你使用 jQuery:

          $.ajax({
            url: "https://api.github.com/users/blackmiaool/repos",
            jsonp: true,
            method: "GET",
            dataType: "json",
            success: function(res) {
              console.log(res)
            }
          });
          &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

          【讨论】:

            【解决方案8】:

            NPM 模块repos 获取某个用户或组的所有公共存储库的 JSON。您可以直接从npx 运行它,因此您无需安装任何东西,只需选择一个组织或用户(此处为“W3C”):

            $ npx repos W3C W3Crepos.json
            

            这将创建一个名为 W3Crepos.json 的文件。 Grep 足够好,例如获取 repos 列表:

            $ grep full_name W3Crepos.json
            

            优点:

            • 适用于 100 多个存储库(此问题的许多答案都没有)。
            • 无需输入太多内容。

            缺点:

            • 需要npx(或npm,如果你想真正安装它)。

            【讨论】:

              【解决方案9】:

              使用 Python 检索 GitHub 用户的所有公共存储库列表:

              import requests
              username = input("Enter the github username:")
              request = requests.get('https://api.github.com/users/'+username+'/repos')
              json = request.json()
              for i in range(0,len(json)):
                print("Project Number:",i+1)
                print("Project Name:",json[i]['name'])
                print("Project URL:",json[i]['svn_url'],"\n")
              

              Reference

              【讨论】:

              • 这不起作用(可能是旧的 api 版本)
              • 是的,有一个小的变化。我已经编辑了我的答案,现在效果很好。
              【解决方案10】:

              如果寻找组织的回购-

              api.github.com/orgs/$NAMEOFORG/repos

              例子:

              curl https://api.github.com/orgs/arduino-libraries/repos
              

              您还可以添加 per_page 参数以获取所有名称,以防万一出现分页问题-

              curl https://api.github.com/orgs/arduino-libraries/repos?per_page=100
              

              【讨论】:

                【解决方案11】:

                现在可以选择使用很棒的GraphQL API Explorer

                我想要一份我的组织的所有活动存储库及其各自语言的列表。这个查询就是这样做的:

                {
                  organization(login: "ORG_NAME") {
                    repositories(isFork: false, first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {
                      pageInfo {
                        endCursor
                      }
                      nodes {
                        name
                        updatedAt
                        languages(first: 5, orderBy: {field: SIZE, direction: DESC}) {
                          nodes {
                            name
                          }
                        }
                        primaryLanguage {
                          name
                        }
                      }
                    }
                  }
                }
                
                

                【讨论】:

                  【解决方案12】:

                  分页 JSON

                  下面的 JS 代码是为了在控制台中使用。

                  username = "mathieucaroff";
                  
                  w = window;
                  Promise.all(Array.from(Array(Math.ceil(1+184/30)).keys()).map(p =>
                      fetch(`//api.github.com/users/{username}/repos?page=${p}`).then(r => r.json())
                  )).then(all => {
                      w.jo = [].concat(...all);
                      // w.jo.sort();
                      // w.jof = w.jo.map(x => x.forks);
                      // w.jow = w.jo.map(x => x.watchers)
                  })
                  

                  【讨论】:

                    【解决方案13】:

                    HTML

                    <div class="repositories"></div>
                    

                    JavaScript

                    // Github 仓库

                    如果你想限制仓库列表,你可以在username/repos之后添加?per_page=3

                    例如username/repos?per_page=3

                    您可以将任何人的用户名放在 Github 上,而不是 /username/。

                    var request = new XMLHttpRequest();
                            request.open('GET','https://api.github.com/users/username/repos' , 
                            true)
                            request.onload = function() {
                                var data = JSON.parse(this.response);
                                console.log(data);
                                var statusHTML = '';
                                $.each(data, function(i, status){
                                    statusHTML += '<div class="card"> \
                                    <a href=""> \
                                        <h4>' + status.name +  '</h4> \
                                        <div class="state"> \
                                            <span class="mr-4"><i class="fa fa-star mr-2"></i>' + status.stargazers_count +  '</span> \
                                            <span class="mr-4"><i class="fa fa-code-fork mr-2"></i>' + status.forks_count + '</span> \
                                        </div> \
                                    </a> \
                                </div>';
                                });
                                $('.repositories').html(statusHTML);
                            }
                            request.send();
                    

                    【讨论】:

                      【解决方案14】:

                      答案是“/users/:user/repo”,但我在一个开源项目中拥有执行此操作的所有代码,您可以使用它在服务器上建立一个 Web 应用程序。

                      我创建了一个名为 Git-Captain 的 GitHub 项目,该项目与列出所有存储库的 GitHub API 进行通信。

                      它是使用 Node.js 构建的开源 Web 应用程序,利用 GitHub API 在众多 GitHub 存储库中查找、创建和删除分支。

                      可以为组织或单个用户设置。

                      我在自述文件中也有一步一步的设置方法。

                      【讨论】:

                        【解决方案15】:

                        获取用户的100个公共仓库的url:

                        $.getJSON("https://api.github.com/users/suhailvs/repos?per_page=100", function(json) {
                          var resp = '';
                          $.each(json, function(index, value) {
                            resp=resp+index + ' ' + value['html_url']+ ' -';
                            console.log(resp);
                          });
                        });
                        &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

                        【讨论】:

                          【解决方案16】:
                          const request = require('request');
                          const config = require('config');
                          
                          router.get('/github/:username', (req, res) => {
                              try {
                                  const options = {
                          
                                      uri: `https://api.github.com/users/${req.params.username}/repos?per_page=5
                                           &sort=created:asc
                                           &client_id=${config.get('githubClientId')}
                                           &client_secret=${config.get('githubSecret')}`,
                          
                                      method: 'GET',
                          
                                      headers: { 'user-agent': 'node.js' }
                                  };
                                  request(options, (error, response, body) => {
                                      if (error) console.log(error);
                                      if (response.statusCode !== 200) {
                                          res.status(404).json({ msg: 'No Github profile found.' })
                                      }
                                      res.json(JSON.parse(body));
                                  })
                              } catch (err) {
                                  console.log(err.message);
                                  res.status(500).send('Server Error!');
                              }
                          });
                          

                          【讨论】:

                          • 更多详情请访问 git docs-> developer.github.com/v3/repos
                          • 欢迎来到 SO!请在发布前检查this...当您发布答案并且还有更多答案时,请展示您 POV 的优点,并且请不要只是发布代码,请稍微解释一下。
                          【解决方案17】:

                          使用 Python

                          import requests
                          
                          link = ('https://api.github.com/users/{USERNAME}/repos')
                          
                          api_link = requests.get(link)
                          api_data = api_link.json()
                          
                          repos_Data = (api_data)
                          
                          repos = []
                          
                          [print(f"- {items['name']}") for items in repos_Data]
                          

                          如果您想获取列表(数组)中的所有存储库,您可以执行以下操作:

                          import requests
                          
                          link = ('https://api.github.com/users/{USERNAME}/repos')
                          
                          api_link = requests.get(link)
                          api_data = api_link.json()
                          
                          repos_Data = (api_data)
                          
                          repos = []
                          
                          [repos.append(items['name']) for items in repos_Data]
                          
                          

                          这会将所有存储库存储在“repos”数组中。

                          【讨论】:

                            【解决方案18】:

                            使用official GitHub command-line tool

                            gh auth login
                            
                            gh api graphql --paginate -f query='
                            query($endCursor: String) {
                                viewer {
                                repositories(first: 100, after: $endCursor) {
                                    nodes { nameWithOwner }
                                    pageInfo {
                                    hasNextPage
                                    endCursor
                                    }
                                }
                                }
                            }
                            ' | jq ".[] | .viewer | .repositories | .nodes | .[] | .nameWithOwner"
                            

                            注意:这将包括与您共享的所有公共、私人和其他人的存储库。

                            参考资料:

                            【讨论】:

                              【解决方案19】:

                              使用 Javascript 获取

                              async function getUserRepos(username) {
                                 const repos = await fetch(`https://api.github.com/users/${username}/repos`);
                                 return repos;
                              }
                              
                              getUserRepos("[USERNAME]")
                                    .then(repos => {
                                         console.log(repos);
                               }); 
                              

                              【讨论】:

                                【解决方案20】:

                                @joelazar 的答案略有改进,以作为清理列表:

                                gh repo list <owner> -L 400 |awk '{print $1}' |sed "s/<owner>\///"
                                

                                当然替换为所有者名称。

                                这也可以获得 >100 个 repos 的列表(在本例中为 400 个)

                                【讨论】:

                                  猜你喜欢
                                  • 2022-06-30
                                  • 2017-05-02
                                  • 2020-12-13
                                  • 1970-01-01
                                  • 2022-11-10
                                  • 2021-04-26
                                  • 2019-12-31
                                  • 2015-03-10
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多