3

How to use REST API to create a file in GitLab and if a file with the same name existed, overwrite the old file. Does the "create" action automatically does this for me? https://docs.gitlab.com/ee/api/commits.html

E.g. I wanna upload XXX/YYY/A.txt, if XXX/YYY/A.txt already existed, replace the A.txt with the new A.txt, if not create one with the provided content.

user3489985
  • 327
  • 4
  • 18

1 Answers1

3

When you make a request to Commits API you will have to specify the action, if you want to create a new file the action would be create.
If the file already exists, gitlab will deny the request and respond with

{"message":"A file with this name already exists"}

So the action in the payload should be consistent with the repo state.

We could use a script here that it will try to commit the file with 2 payloads. One specifying the create action and the other the update action.

create.json

{

"branch": "target branch",
 "commit_message": "some commit message",
  "actions": [
    {
      "action": "create",
      "file_path": "XXX/YYY/A.txt",
      "content": "some content new"
    }]
}

update.json

{

"branch": "target branch",
 "commit_message": "some commit message",
  "actions": [
    {
      "action": "update",
      "file_path": "XXX/YYY/A.txt",
      "content": "some content new"
    }]
}

The script will originally try the create action, if it fails it will try the update action. E.g.

#!/bin/bash
curl -s -w -XPOST --header "Content-Type: application/json"  --header "PRIVATE-TOKEN: <access_token" --data "@create.json" https://gitlab.com/api/v4/projects/<project_id>/repository/commits | grep -o message
if [ $? -eq 0 ]
then

curl -s -w -XPOST --header "Content-Type: application/json"  --header "PRIVATE-TOKEN: <access_token" --data "@update.json" https://gitlab.com/api/v4/projects/<project_id>/repository/commits
fi
Tolis Gerodimos
  • 3,782
  • 2
  • 7
  • 14