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