~fkfd/git.gmi

109ec9a7d86bcadb16541873d95068f737586692 — Frederick Yin 1 year, 2 months ago eb1bd1e v0.4.1
Enhance blob view

Changes:
- set maximum size of displayable blobs
- raw blobs are now of type `bytes`
- do not try to decode handle binary blobs
3 files changed, 23 insertions(+), 8 deletions(-)

M git-gmi/const.py
M git-gmi/gateway.py
M git-gmi/git.py
M git-gmi/const.py => git-gmi/const.py +2 -1
@@ 2,4 2,5 @@ STATUS_SUCCESS = "20"
STATUS_NOT_FOUND = "51 NOT FOUND"
STATUS_TEMPORARY_FAILURE = "40 TEMPORARY FAILURE"
META_GEMINI = "text/gemini"
META_PLAINTEXT = "text/plain"
\ No newline at end of file
META_PLAINTEXT = "text/plain"
MAX_DISPLAYED_BLOB_SIZE = 500 * 1024  # 500KB

M git-gmi/gateway.py => git-gmi/gateway.py +2 -1
@@ 2,6 2,7 @@ from git import *
from const import *
from config import *
from os import environ, listdir
import sys

# be careful when using print(); stdout is passed to the client.
# this cgi uses \n as newline.


@@ 56,7 57,7 @@ def handle_cgi_request(path: str, query: str):
        except FileNotFoundError:  # is file
            try:
                if query == "raw":
                    print(repo.view_raw_blob(branch, location))
                    sys.stdout.buffer.write(repo.view_raw_blob(branch, location))
                else:
                    print(repo.view_blob(branch, location))
            except FileNotFoundError:

M git-gmi/git.py => git-gmi/git.py +19 -6
@@ 263,16 263,29 @@ class GitGmiRepo:
            f"{STATUS_SUCCESS} {META_GEMINI}\r\n"
            + self.generate_header()
            + f"## {self.name}/{'/'.join(location)} | {convert_filesize(blob.size)}\n\n"
            f"=> {blob.name}?raw view raw\n\n"
            f"```\n"
        )
        response += blob.data.decode("utf-8") + "\n```"

        if blob.is_binary:
            response += (
                "This file seems to be binary. Open link below to download.\n"
                f"=> {blob.name}?raw download"
            )
        elif blob.size < MAX_DISPLAYED_BLOB_SIZE:
            response += (
                f"=> {blob.name}?raw view raw\n\n"
                "```\n" + blob.data.decode("utf-8") + "\n```"
            )
        else:
            response += (
                "This file is too large to be displayed. Open link below to download.\n"
                f"=> {blob.name}?raw download\n\n"
            )
        return response

    def view_raw_blob(self, branch: str, location=[]) -> str:
    def view_raw_blob(self, branch: str, location=[]) -> bytes:
        blob = self.get_blob(branch, location)
        # if mimetypes can't make out the type, set it to plaintext
        guessed_mimetype = mimetypes.guess_type(blob.name)[0] or META_PLAINTEXT
        response = f"{STATUS_SUCCESS} {guessed_mimetype}\r\n"
        response += blob.data.decode("utf-8")
        response = bytes(f"{STATUS_SUCCESS} {guessed_mimetype}\r\n", encoding="utf-8")
        response += blob.data
        return response