通過 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/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章