0

I have a github directory called "latviadebate". It looks like this:

$ main 
. 
├── index.html 
├── style.css 
├── images 
│   └── image1.png 
│   └── image2.png 
├── pages 
│   └── 20-03-2023.html 
│   └── 08-01-2022.html

So, what I need to do is upload new images and new pages, using Python. I managed to upload them to root directory (where index.html and style.css are), but no luck with putting them in folders (/pages/ and /images/).

My Python code looks like this:

import tkinter
import tkinter.filedialog
import base64
import os
from github import Github
from github import InputGitTreeElement
from tkinter import *
from tkinter import messagebox
from datetime import datetime, timedelta

user = 'dzhemvrot'
token = 'TOKEN'
commit_message = 'python commit'
g = Github(token)
repo = g.get_user().get_repo('latviadebate') # repo name

...

def load():
    try:
        fn = datetime.now().strftime("%Y-%m-%d")
        artic = Text.get('1.0', 'end')
        artic = artic.replace("\n", "<br>")
        artna = Name.get()
        regl = Regist.get()
        dienl = Dienas.get()
        whfi = """here was html page, it works just fine"""
        open(fn+".html", 'wt', encoding="utf-8").write(whfi)
        phots = photo()
        phot = os.path.basename(phots).split('/')[-1]
        file_list = [
        f'{fn}.html',
        f'{phot}'
    ]
        file_names = [
        f'pages\{fn}.html',
        f'images\{phot}'
    ]
        master_ref = repo.get_git_ref('heads/main')
        master_sha = master_ref.object.sha
        base_tree = repo.get_git_tree(master_sha)

        element_list = list()
        for i, entry in enumerate(file_list):
            if entry.endswith('.html'):
                with open(entry) as input_file:
                    data = input_file.read()
            #if entry.endswith('.png'): # images must be encoded
            #    data = base64.b64encode(data)
            element = InputGitTreeElement(file_names[i], '100644', 'blob', data)
            element_list.append(element)
        tree = repo.create_git_tree(element_list, base_tree)
        parent = repo.get_git_commit(master_sha)
        commit = repo.create_git_commit(commit_message, tree, [parent])
        master_ref.edit(commit.sha)
        os.remove(f"{fn}.html")

def photo():
    ftypes = [('.PNG', '*.png'), ('.JPG', '*.jpg'), ('.WEBP', '*.webp'), ('All files', '*')] 
    photo = tkinter.filedialog.Open(root, filetypes = ftypes).show()
    if photo == '':
        return
    return photo

I tried putting \ and / in front of pages{fn}.html, but there was this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:\Documents\zlib de- and compress\latviadebate.py", line 131, in load
    tree = repo.create_git_tree(element_list, base_tree)
  File "C:\Python310\lib\site-packages\github\Repository.py", line 1169, in create_git_tree
    headers, data = self._requester.requestJsonAndCheck(
  File "C:\Python310\lib\site-packages\github\Requester.py", line 400, in requestJsonAndCheck
    return self.__check(
  File "C:\Python310\lib\site-packages\github\Requester.py", line 425, in __check
    raise self.__createException(status, responseHeaders, output)
github.GithubException.GithubException: 422 {"message": "tree.path cannot start with a slash", "documentation_url": "https://docs.github.com/rest/reference/git#create-a-tree"}
2
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a minimal reproducible example. Commented Mar 14, 2023 at 20:21
  • @BlueRobin, I'm sorry, but all of it is needed. I already trimmed a lot. Commented Mar 20, 2023 at 1:18

1 Answer 1

0

what you first want to do is create a GitBlob first with your file content and then a git tree element using that blob

element_list = list()
for i, entry in enumerate(file_list):
  file_content = open(entry).read()
  blob = repo.create_git_blob(
    content=file_content,
    encoding='utf-8'
  )

  tree_element = InputGitTreeElement(
    path=file_names[i],
    mode='100644', # normal file mode
    type='blob',
    sha=blob.sha
  )

  element_list.append(tree_element)

new_tree = repo.create_git_tree(tree=element_list, base_tree=base_tree)

This is obviously a trimmed down version of what you need to fix. I'd highly recommend going over this snippet for step by step instructions: https://gist.github.com/ohaval/3c183c83ec91cb528fdc4628efe2fa01

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.