Warm tip: This article is reproduced from serverfault.com, please click

其他-如何使用PHP和Github API在Github存储库中创建和更新文件?

(其他 - How to create and update a file in a Github repository with PHP and Github API?)

发布于 2016-04-25 08:10:17

我正在尝试构建PHP函数,以通过Github API使用PHP创建和更新Github存储库中的文件。

PHP文件是通过标准的共享托管帐户运行的。因此,使用依赖于安装Composer或其他库的框架不是我的选择。因此,例如,此https://github.com/KnpLabs/php-github-api不是一个选择。

迄今为止

我已经设法使用PHP并通过此处提供的信息来访问和列出文件:

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

我使用了第二个答案和第六个答案的组合(第二个开头flesheater的卷发这是一个不错的方法,而伊万·祖扎克(Ivan Zuzak)说“显示回购及其内容”则第六个答案)。

两者都清楚列出了列出文件并获取内容所需的代码和步骤(感谢@flesheater和@Ivan Zuzak)

我为此寻求帮助或解决方案。到目前为止,我还没有找到使用PHP的任何示例,无论工作与否。

Git API文档

Git Data API信息(https://developer.github.com/v3/git/)表示:

例如,如果你想对存储库中的文件进行更改,则可以:

get the current commit object
retrieve the tree it points to
retrieve the content of the blob object that tree has for that particular file path
change the content somehow and post a new blob object with that new content, getting a blob SHA back
post a new tree object with that file path pointer replaced with your new blob SHA getting a tree SHA back
create a new commit object with the current commit SHA as the parent and the new tree SHA, getting a commit SHA back
update the reference of your branch to point to the new commit SHA

但是,没有代码示例说明了如何完成此操作,并且我不确定是否需要“提交”(如果我理解正确,这不是在创建文件,而只是在创建内容)。

Git存储库API信息(https://developer.github.com/v3/repos/contents/#create-a-file):

“创建文件”部分显示了执行此操作的方法,但没有代码示例。我确定如何或是否可以在语法上使用它。

Github API更新文件

类似线程

我认为,由于存在问题或答案,没有人提供足够的清晰度或信息来提供解决方案。因此,我不认为这是重复的。

如何使用GitHub API v3创建提交并推送到存储库中?

该线程有两个答案。其中一个只是Github API的链接,没有给出代码示例。另一个是Pearl的解决方案(看起来),但是使用了单独的Pearlframework,因此即使尝试转换所示的Pearl也不太实际。

如何创建github仓库并从PHP上传文件?

答案仅重复另一个线程,即应创建Blob。但这仅仅是通过Github API实际创建/更新文件所需要的一切的开始。该线程有一个Python示例,但该示例需要一个单独的Pearl框架。

GitHub API-写回购

这是链接到的线程。用户提出了一个不太清楚的问题,但没有任何详细信息或清晰的答案。

Questioner
Mike A
Viewed
12
Mike A 2016-04-25 21:26:55

看起来研究取得了成果,我可以回答自己的主要问题(我本来不希望这样做)-创建一个新文件。看起来可以使用相同的方法来更新现有文件(如果没有,我会回来的)。

该链接帮助:http : //www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

我意识到Github API文档(https://developer.github.com/v3/repos/contents/#get-contents)中提到的路径-创建文件部分-可以用作curl的网址,如下所示:

https://api.github.com/repos/ USER / REPO_NAME /contents/ FILENAME

并且需要进行一些调整以允许发送JSON。所以我现在有:

$curl_url = $url
$curl_token_auth = 'Authorization: token ' . $token;
$ch = curl_init($curl_url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'User-Agent: $username', $curl_token_auth ));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

$response = curl_exec($ch);  
curl_close($ch);
$response = json_decode($response);

return $response;

对于$ data,我使用了Github API页面中的JSON示例:

{
  "message": "my commit message",
  "committer": {
    "name": "Mike A",
    "email": "someemail@gmail.com"
  },
  "content": "bXkgbmV3IGZpbGUgY29udGVudHM="
}

在一个PHP文件中(在共享主机上)实现了这一点之后,没有使用其他框架,我在Github存储库中看到了新文件。