Search code examples
phpgitlabgitlab-api

gitlab commit via cURL with PHP fails


I am trying to do a commit to a gitlab repository via the gitlab API and PHP. Although the payload looks fine to me, the cURL request fails and returns

[error] => branch_name is missing, commit_message is missing, actions is missing

My code looks like the following:

$ch_git = curl_init(); 

curl_setopt($ch_git, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch_git, CURLOPT_HTTPHEADER, array('PRIVATE-TOKEN: xxx')); 
curl_setopt($ch_git, CURLOPT_URL, 'https://gitlab.com/api/v3/projects/xxx/repository/commits'); 
curl_setopt($ch_git, CURLOPT_POST, true);

$info = array(
    'id' => 'xxx',
    'branch_name' => 'master',
    'commit_message' => 'updating content...',
    'actions' => array(
        'action' => 'update', 
        'file_path' => 'filename',
        'content' => 'test 1234'
    )
);

$payload = json_encode($info, JSON_PRETTY_PRINT);

echo '<pre>';
echo $payload;
echo '</pre>';

curl_setopt($ch_git, CURLOPT_POSTFIELDS, $payload);

$res = curl_exec($ch_git);

echo '<pre>';
print_r(json_decode($res));
echo '</pre>';

As far as I can see, my payload is formatted like in the example, but maybe I am missing something.


Solution

  • I found the solution to this.

    actions does not simply expect a single array but an array of arrays which then contain the single actions that shall be executed to the repository.

    I furthermore found out, that the id parameter is optional, as I have already specified the id in the CURLOPT_URL parameter.

    So for updating a single file in the specified repository, this code works:

    $info = array(
       'branch_name' => 'master',
       'commit_message' => 'updating content...',
       'actions' => array(
          array(
             'action' => 'update', 
             'file_path' => 'filename',
             'content' => 'test 1234'
          )
       )
    );