PyGithub / PyGithub/PyGithub

Upload of content using github.Repository.update_file produces garbled content

Abierto
#2,972 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
Python
Estrellas
7.8k
Forks
1.9k
Merge medio
17 min
PR fusionados (30 d)
2

Descripción

Problem Introduction

When trying to upload a json stringified dict to a repository resulting content in the repository is garbled.

Example calling code with explanation

As per Repository.py inputs can either be bytes or a string that is ready to be encoded and therefore transmitted to a repository.

        content_to_transmit = json.dumps(obj)
        try:
            repo = self.github_instance.get_repo(f"{self.org_name}/{self.repo_name}")
            file_path = f"{container_name}/{self.object_files[container_name]}"
            # file_contents = repo.get_contents(file_path, ref=ref, sha=sha)
            write_response = repo.update_file(
                file_path, 
                f"Update object [{self.object_files[container_name]}]", 
                content=content_to_transmit,
                sha=sha, 
                branch=ref
            )
            return [
                True, 
                {
                    "status_msg": f"wrote object [{self.object_files[container_name]}] to container [{container_name}]",
                    "status_code": 200 
                },
                write_response
            ]
        except Exception as e:
            print(e)
            return [
                False, 
                {
                    "status_code":f"unable to write object [{self.object_files[container_name]}] to container [{container_name}] due to [{str(e)}]",
                    "status_msg": 503
                }, 
                str(e)
            ]

When this is called with just the string this error is returned 'bytes' object has no attribute 'encode' which caused me to explore github.Repository.update_file.

Problem resolution

As I inspected the file I found that the if block on line 2495 was improperly indented.

Version in main branch
if not isinstance(content, bytes):
            content = content.encode("utf-8")
content = b64encode(content).decode("utf-8")

As I looked at the code I realized that even if bytes or string was supplied the output would not be correct; therefore, I indented the if block and tried the call again.

Verified fixed version
if not isinstance(content, bytes):
           content = content.encode("utf-8")
           content = b64encode(content).decode("utf-8")

With that changed I tried the call again and was able to find the content in the repository to be correctly received, stored as json, and viewable in the repository. I've provided the original file, the fixed file and a patch file for review.

PyGithub.zip

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en Repository.py alrededor de la línea 2495 y reproduce Repository.update_file tanto con contenido string como bytes. Verifica que el JSON subido se almacene y se muestre correctamente en el repositorio, usando el parche proporcionado y el ejemplo corregido como referencias.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
api
Tipo de issue
Error
Dificultad
1/5
Tiempo estimado
Menos de una hora
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.