javascript Github API 列出所有存储库和存储库的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14390090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:30:43  来源:igfitidea点击:

Github API List all repositories and repo's content

phpjavascriptgithubgithub-api

提问by ramr

If I was to go about displaying just MY github repositories and their contents on an external website how would i go about doing this? Are there any source code's you can provide me with, if not point me in the right direction? I'm quite a beginner to programming so any help is appreciated. Thank you everyone. Taking a glance at their website

如果我要在外部网站上仅显示我的 github 存储库及其内容,我将如何进行?如果没有指出正确的方向,是否有任何源代码可以提供给我?我是编程的初学者,因此感谢任何帮助。谢谢大家。看一眼他们的网站

I glanced over relevant links- but still have no clue how I would accomplish this.

我浏览了相关链接 - 但仍然不知道我将如何实现这一点。

-Github List all Repo's

-Github 列出所有 Repo

-Github List all Repo content

-Github 列出所有 Repo 内容

采纳答案by Decker W Brower

all of the previous answers are great. however if you are looking for a quick and dirty example of how to get a list of publicly available repos then check out my jsfiddle.

以前的所有答案都很棒。但是,如果您正在寻找有关如何获取公开可用存储库列表的快速而肮脏的示例,请查看我的jsfiddle。

which uses this ajax call to list all of a users public repos:

它使用这个 ajax 调用来列出所有用户的公共存储库:

$("#btn_get_repos").click(function() {
    $.ajax({
        type: "GET",
        url: "https://api.github.com/users/google/repos",
        dataType: "json",
        success: function(result) {
            for(var i in result ) {
                $("#repo_list").append(
                    "<li><a href='" + result[i].html_url + "' target='_blank'>" +
                    result[i].name + "</a></li>"
                );
                console.log("i: " + i);
            }
            console.log(result);
            $("#repo_count").append("Total Repos: " + result.length);
        }
    });
});

to see what kind of data is returned just check the console after clicking the button or you can install Google Chromes JSONView extension and then just visit the url that the ajax request is making i.e. https://api.github.com/users/google/repos

要查看返回的数据类型,只需在单击按钮后检查控制台,或者您可以安装 Google Chromes JSONView 扩展程序,然后只需访问 ajax 请求发出的 url,即https://api.github.com/users/google /回购

回答by Nikolay

Here is a nice way just with the curl. You should change the $user and the $token variableso to make this script work for your case. The code is tested with a valid token so I hope it will work for you. As you could see in the comments of the code the token could be generated from your github account from here https://github.com/settings/applications

这是使用卷曲的好方法。您应该更改 $user 和 $token 变量以使此脚本适用于您的情况。该代码已使用有效令牌进行测试,因此我希望它对您有用。正如您在代码的注释中看到的,令牌可以从您的 github 帐户从这里https://github.com/settings/applications 生成

<?php
  // for example your user
  $user = 'flesheater';

  // A token that you could generate from your own github 
  // go here https://github.com/settings/applications and create a token
  // then replace the next string
  $token = 'ced38b0e522a5c5e8ab10';

  // We generate the url for curl
  $curl_url = 'https://api.github.com/users/' . $user . '/repos';

  // We generate the header part for the token
  $curl_token_auth = 'Authorization: token ' . $token;

  // We make the actuall curl initialization
  $ch = curl_init($curl_url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  // We set the right headers: any user agent type, and then the custom token header part that we generated
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Awesome-Octocat-App', $curl_token_auth));

  // We execute the curl
  $output = curl_exec($ch);

  // And we make sure we close the curl       
  curl_close($ch);

  // Then we decode the output and we could do whatever we want with it
  $output = json_decode($output);

  if (!empty($output)) {
    // now you could just foreach the repos and show them
    foreach ($output as $repo) {
      print '<a href="' . $repo->html_url . '">' . $repo->name . '</a><br />';
    }
  }

?>

Also since we like github, we should cache the results in the end and fetch them once per day or so.

另外,因为我们喜欢 github,所以我们应该在最后缓存结果并每天获取一次。

回答by K-Gun

All these examples are just as pseudo without "authentication" and you can improve them yourself as you like;

所有这些例子都是假的,没有“认证”,你可以随意改进它们;

<?php
// a simple way to get a user's repo
$res = file_get_contents("https://api.github.com/repos/qeremy/mii");
$res = json_decode($res);
print_r($res);
?>
stdClass Object
(
    [language] => JavaScript
    [merges_url] => https://api.github.com/repos/qeremy/mii/merges
    [contributors_url] => https://api.github.com/repos/qeremy/mii/contributors
    [assignees_url] => https://api.github.com/repos/qeremy/mii/assignees{/user}
    [url] => https://api.github.com/repos/qeremy/mii
    [description] => Multipurpose JavaScript Library
    [ssh_url] => [email protected]:qeremy/mii.git
    [comments_url] => https://api.github.com/repos/qeremy/mii/comments{/number}
    [statuses_url] => https://api.github.com/repos/qeremy/mii/statuses/{sha}
    [keys_url] => https://api.github.com/repos/qeremy/mii/keys{/key_id}
    ...
<?php
// getting a repo's README
$res = file_get_contents("https://api.github.com/repos/qeremy/mii/readme");
$res = json_decode($res);
print_r($res);
?>
stdClass Object
(
    [_links] => stdClass Object
        (
            [self] => https://api.github.com/repos/qeremy/mii/contents/README.md
            [git] => https://api.github.com/repos/qeremy/mii/git/blobs/49f0c4d5e25ac44921ba4372aebd76d2da5128e2
            [html] => https://github.com/qeremy/mii/blob/master/README.md
        )

    [url] => https://api.github.com/repos/qeremy/mii/contents/README.md
    [type] => file
    [sha] => 49f0c4d5e25ac44921ba4372aebd76d2da5128e2
    [path] => README.md
    [size] => 8213
    [encoding] => base64
    [content] => QWN0dWFsbHksIEkga25vdyB0aGF0IHRoZXJlIGFyZSBidWNoIG9mIEphdmFT
Y3JpcHQgbGlicmFyeSwgZXZlbiBtb3JlIHBvd2VyZnVsbC4gQnV0IHNvbWV0
    ...

But, I think needs more complicated structure;

但是,我认为需要更复杂的结构;

<?php
class GRepo
{
    protected 
        // needs "user"
        $src_userRepos = "https://api.github.com/users/%s/repos",
        // needs "user,repo"
        $src_userRepoDetails = "https://api.github.com/repos/%s/%s",
        $responseCode, $responseText,
        $user;

    public function __construct($user) {
        $this->user = $user;
    }

    public function listRepos() {
        $this->_request(
            sprintf($this->src_userRepos, $this->user));
        if ($this->responseCode != 200) {
            throw new Exception('Server error!'); // e.g
        }
        return json_decode($this->responseText);
    }

    public function getRepoDetails($repo) {
        $this->_request(
            sprintf($this->src_userRepoDetails, $this->user, $repo));
        if ($this->responseCode != 200) {
            throw new Exception('Server error!'); // e.g
        }
        return json_decode($this->responseText);
    }

    // Could be extended, e.g with CURL..
    protected function _request($url) {
        $contents =@ file_get_contents($url);
        $this->responseCode = (false === $contents) ? 400 : 200;
        $this->responseText = $contents;
    }
}

// Test
$gr = new GRepo('qeremy');
print_r( $gr->listRepos() );
print_r( $gr->getRepoDetails('mii') );
?>

回答by Ivan Zuzak

When you say "display a repo and its contents" you actually say "display the state of the repo after the latest commit of the master branch", right? That's actually the better way of thinking about the problem and will be a better guide through using GitHub's API.

当您说“显示存储库及其内容”时,您实际上是在说“在主分支的最新提交后显示存储库的状态”,对吗?这实际上是思考问题的更好方式,并且将成为使用 GitHub API 的更好指南。

You need to look at the Git datapart of the API. Here's what you need to do:

您需要查看API的Git 数据部分。您需要执行以下操作:

1) fetch the list of refs for your repo using:

1) 使用以下方法获取您的 repo 的 refs 列表:

https://api.github.com/repos/:user/:repo/git/refs

Working example:

工作示例:

https://api.github.com/repos/izuzak/noam/git/refs

Notice that it lists the references in your repo and gives you links to continue.

请注意,它列出了您的 repo 中的引用并为您提供了继续的链接。

2) fetch the commit object of the ref that interests you, namely "master", using the link provided in the response to 1):

2) 使用对 1) 的响应中提供的链接获取您感兴趣的引用的提交对象,即“master”:

https://api.github.com/repos/:user/:repo/git/commits/:sha

Working example:

工作示例:

https://api.github.com/repos/izuzak/noam/git/commits/5cf12775b844664d5f7af6663706195680181374

Notice that you get back an object with a link to a tree.

请注意,您会返回一个带有指向树的链接的对象。

3) fetch the tree object of the last commit in the master ref, using the link provided in the response to 2) :

3) 使用对 2) 的响应中提供的链接,获取主引用中最后一次提交的树对象:

https://api.github.com/repos/:user/:repo/git/trees/:sha

Working example:

工作示例:

https://api.github.com/repos/izuzak/noam/git/trees/8a721bea8d2f281c87b39c74cbf5a70075d686b4

Notice that you get back a list of files in the root directory that is your repo. This is what you want. If you have subdirectories, you will get links to fetch the files in those subdirectories.

请注意,您将返回作为您的存储库的根目录中的文件列表。这就是你想要的。如果您有子目录,您将获得获取这些子目录中文件的链接。

This should be enough to get you started :). Good luck!

这应该足以让您入门:)。祝你好运!

回答by Vijay Verma

Please try following library also available on git hub: https://github.com/ornicar/php-github-api

请尝试以下在 git hub 上也可用的库:https: //github.com/ornicar/php-github-api

回答by Stefan

You need to parse the respone Githubs API sends you back. In PHP you can do this by using json_decode()which will give you an array to work with. You can use something like curlto issue the requests from PHP and then get the results and parse them as described above.
Another way to do this are REST Client classes for PHP, have a look at this one herefor example.

您需要解析 Githubs API 发送给您的响应。在 PHP 中,您可以通过使用json_decode()which来完成此操作,这将为您提供一个可以使用的数组。您可以使用类似curl的方法从 PHP 发出请求,然后获取结果并如上所述解析它们。
另一种方法是用于 PHP 的 REST 客户端类,例如在这里查看这个。

回答by Ragnarokkr

If you want some source code to analyze, about javascript you can try to start from GitHub Repositories(more specifically here), it's a nice open project for a Chrome extension which does something similiar to what you're looking for.

如果你想要一些源代码来分析,关于 javascript,你可以尝试从GitHub 存储库(更具体地说,这里)开始,这是一个很好的 Chrome 扩展的开放项目,它可以做一些类似于你正在寻找的东西。

回答by drordk

you can use github api

你可以使用github api

organization="write-here-the-organization"
githubuser="your-github-user"
token=`curl -i -u ${githubuser}  -d '{"scopes": ["repo"]}' https://api.github.com/authorizations | grep token | cut -d\" -f 4`
curl -i -H "Authorization: token ${token}" https://api.github.com/orgs/${organization}/repos 

as result of the above you will get a long json with all repositories, and their information. you can continue from here.

由于上述结果,您将获得一个包含所有存储库及其信息的长 json。你可以从这里继续。