phplaravelgithub

Commit file deletions with Laravel package GrahamCampbell/Laravel-GitHub


Using GrahamCampbell/Laravel-GitHub my Laravel app can commit files like this:

public function commitFiles(string $github_nickname, string $repo_name, string $branch, string $commit_message, array $files) {
    $master_branch = $this->github_client->repo()->branches($github_nickname, $repo_name, $branch);
    $commit_parent = $master_branch["commit"]["sha"];
    $base_tree = $master_branch["commit"]["commit"]["tree"]["sha"];

    $commit_tree = array();
    foreach ($files as $file) {
        $file_blob = [
            "path" => $file["path"],
            "mode" => "100644",
            "type" => "file",
            "content" => $file["content"],
        ];
        array_push($commit_tree, $file_blob);
    }

    $new_commit_tree_response = $this->github_client->git()->trees()->create($github_nickname, $repo_name, [
        "base_tree" => $base_tree,
        "tree" => $commit_tree
    ]);

    // TODO verify commit with GPG
    $new_commit_response = $this->github_client->git()->commits()->create($github_nickname, $repo_name, [
        "message" => $commit_message,
        "parents" => [$commit_parent],
        "tree" => $new_commit_tree_response["sha"],
    ]);

    $this->github_client->git()->references()->update($github_nickname, $repo_name, "heads/".$branch, [
        "sha" => $new_commit_response["sha"],
        "force" => false,
    ]);

    return true;
}

But how can I delete files? I have not found any applicable documentation and have a really hard time figuring this out.


Solution

  • Here is a way to remove one file:

    public function deleteFile($github_nickname, $repo_name, $path, $commitMessage)
    {
    
        $committer = array('name' => 'SomeName', 'email' => 'some@email.com');
        $oldFile = $this->github_client->api('repo')->contents()->show($github_nickname, $repo_name, $path, 'master');
    
        $this->github_client->api('repo')->contents()->rm($github_nickname, $repo_name, $path, $commitMessage, $oldFile['sha'], 'master', $committer);        
    }