通过 GitHub 的 API 获取代码

GitHub 的 API 功能很强大,也很规范。基本都是以 GET 方式从 https://api.github.com/ 取得。
假如要获得代码库里的 readme,使用使用 GET /repos/:owner/:repo/readme
比如 Typecho 的肥皂库 https://api.github.com/repos/typecho-fans/plugins/readme
通过浏览器输入地址,或是使用curl或者其他方法取得页面内容,注意通过curl等方式要设置User-Agent。
返回值为 json 编码的 stdClass,content 属性为源码的 base64 编码,去掉'\n'再用 base64 方式解码就取得文件源码。

如果要取得代码文件内容,需要获取相应的目录和文件内容:

GET /repos/:owner/:repo/contents/:path

比如要获取肥皂库的根目录下的内容:

https://api.github.com/repos/typecho-fans/plugins/contents/

[
  {
  "name": "At",
  "path": "At",
  "sha": "668a750a5aae5d9187cebfd74f10e43e47d338bc",
  "size": null,
  "url": "https://api.github.com/repos/typecho-fans/plugins/contents/At?ref=master",
  "html_url": "https://github.com/typecho-fans/plugins/tree/master/At",
  "git_url": "https://api.github.com/repos/typecho-fans/plugins/git/trees/668a750a5aae5d9187cebfd74f10e43e47d338bc",
  "type": "dir",
  "_links": {
  "self": "https://api.github.com/repos/typecho-fans/plugins/contents/At?ref=master",
  "git": "https://api.github.com/repos/typecho-fans/plugins/git/trees/668a750a5aae5d9187cebfd74f10e43e47d338bc",
  "html": "https://github.com/typecho-fans/plugins/tree/master/At"
  }
  },
  {
  "name": "AutoSlug",
  "path": "AutoSlug",
  "sha": "e0832144c0af0f5bccfd4f44faa4cfde1e5017cf",
  "size": null,
  "url": "https://api.github.com/repos/typecho-fans/plugins/contents/AutoSlug?ref=master",
  "html_url": "https://github.com/typecho-fans/plugins/tree/master/AutoSlug",
  "git_url": "https://api.github.com/repos/typecho-fans/plugins/git/trees/e0832144c0af0f5bccfd4f44faa4cfde1e5017cf",
  "type": "dir",
  "_links": {
  "self": "https://api.github.com/repos/typecho-fans/plugins/contents/AutoSlug?ref=master",
  "git": "https://api.github.com/repos/typecho-fans/plugins/git/trees/e0832144c0af0f5bccfd4f44faa4cfde1e5017cf",
  "html": "https://github.com/typecho-fans/plugins/tree/master/AutoSlug"
  }
  },
//省略掉了很多
  {
  "name": "XiaMiPlayer",
  "path": "XiaMiPlayer",
  "sha": "6fe21b2edf53e975e8ee4268aff5b757f2ea744d",
  "size": null,
  "url": "https://api.github.com/repos/typecho-fans/plugins/contents/XiaMiPlayer?ref=master",
  "html_url": "https://github.com/typecho-fans/plugins/tree/master/XiaMiPlayer",
  "git_url": "https://api.github.com/repos/typecho-fans/plugins/git/trees/6fe21b2edf53e975e8ee4268aff5b757f2ea744d",
  "type": "dir",
  "_links": {
  "self": "https://api.github.com/repos/typecho-fans/plugins/contents/XiaMiPlayer?ref=master",
  "git": "https://api.github.com/repos/typecho-fans/plugins/git/trees/6fe21b2edf53e975e8ee4268aff5b757f2ea744d",
  "html": "https://github.com/typecho-fans/plugins/tree/master/XiaMiPlayer"
  }
  }
]

获取目录的返回值为一个 json 编码的数组,数组的每项为一个 stdClass。通过循环读取对应的url就可以取得所有文件内容。
库内其他文件或目录的获取方式就在 contents/ 后面加上对于的路径,比如:

https://api.github.com/repos/typecho-fans/plugins/contents/At/Plugin.php

再配合 Cron 就可以定时同步 GitHub 上的代码了。

https://github.com/typecho-fans/plugins
http://stackedit.io/


你可能感兴趣的:(github,api)