0

I have a python script where I have created an output file as an excel table. Now I would like to add/upload this file to my Gitlab project repository directly by using python-gitlab library. I have found some solution where file was added local repository and then pushed to remote repository. How can I push/upload directly to remote repository?

OliAK
  • 73
  • 8
  • that is not how git works. see the [gitlab documentation](https://docs.gitlab.com/ee/gitlab-basics/add-file.html) on adding files. you always push committed changes from your local repository to a remote repository. there is no way to circumvent this. you might want to use a file server or something similar instead if you don't need the git features – tom Sep 07 '22 at 15:21
  • i think my comment above is quite harsh. i just can't think of a reason why you would want to circumvent the git workflow. anyway... i just saw an example in the [gitlab-python docs](https://python-gitlab.readthedocs.io/en/stable/gl_objects/commits.html#examples) on how to create commits. maybe that helps... – tom Sep 07 '22 at 15:31

1 Answers1

2

You can use the files API to create a file. If you're using the python-gitlab wrapper, you use it like so as described in the documentation:

import base64
# ... generated your excel file 

project = gl.projects.get(123) # use your project ID

with open('myfile.xlsx', 'rb') as my_file:
    contents = base64.b64encode(my_file.read()).decode('utf-8')


# create new file in the repo
f = project.files.create({'file_path': 'testfile.xlsx',
                          'branch': 'main',
                          'content': contents,
                          'encoding': 'base64',
                          'author_email': 'test@example.com',
                          'author_name': 'yourname',
                          'commit_message': 'Create testfile'})

Or to modify an existing file:

project = gl.projects.get(123)

# get the file object
f = projects.files.get(file_path='testfile.xlsx', ref='main')
# modify its contents
f.content = base64.b64encode(b'new content').decode('utf-8')

# save (commit) the new contents
f.save(branch='main', commit_message='update file', encoding='base64')
sytech
  • 29,298
  • 3
  • 45
  • 86
  • Thanks. Above script works! However, I had to change something: `with open('myfile.xlsx', 'rb') as my_file:` I have used 'rb' instead of 'wb' to avoid following error: `io.UnsupportedOperation: read` – OliAK Sep 08 '22 at 12:56
  • Thanks for pointing that out @OliAK fixed :) – sytech Sep 08 '22 at 16:17