Skip to content

Commit

Permalink
feat(parse): from yaml
Browse files Browse the repository at this point in the history
Signed-off-by: John Andersen <johnandersen777@protonmail.com>
  • Loading branch information
johnandersen777 committed Dec 1, 2024
0 parents commit 814a0aa
Show file tree
Hide file tree
Showing 9 changed files with 402 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Release

on:
push:
branches:
- "main"
- "v*"

jobs:
pypi-publish:
name: upload release to PyPI
runs-on: ubuntu-latest
# Specifying a GitHub environment is optional, but strongly encouraged
environment: pypi
permissions:
# IMPORTANT: this permission is mandatory for trusted publishing
id-token: write
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v4
with:
python-version: "3.x"

- name: deps
run: python -m pip install -U build

- name: build
run: python -m build

- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
verify-metadata: false
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Git based Federation

- References
- https://github.com/publicdomainrelay/reference-implementation/issues/8
- https://github.com/publicdomainrelay/reference-implementation/issues/15
- https://github.com/publicdomainrelay/gitatp
25 changes: 25 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[project]
name = "federation-git"
version = "0.0.0"
description = "Git based Federation"
readme = {file = "README.md", content-type = "text/markdown"}
authors = [
{ name = "Public Domain", email = "publicdomainrelay@protonmail.com" }
]
license = {text = "Unlicense"}
requires-python = ">=3.12"
dependencies = [
"PyYAML>=6.0.2",
"pydantic>=2.10.2",
]

[project.urls]
Repository = "https://github.com/publicdomainrelay/federation-git.git"
Issues = "https://github.com/publicdomainrelay/federation-git/issues"

[project.scripts]
federation-git = "federation_git.cli:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Empty file added src/federation_git/__init__.py
Empty file.
4 changes: 4 additions & 0 deletions src/federation_git/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .cli import main

if __name__ == "__main__":
main()
125 changes: 125 additions & 0 deletions src/federation_git/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import asyncio

import textwrap
import pathlib
import subprocess

from .git_http_backend import *

import magic
import snoop

def file_contents_bytes_to_markdown(file_path: str, content: bytes) -> str:
mime = magic.Magic(mime=True)
mime_type = mime.from_buffer(content)
string_content = content.decode('utf-8')

if pathlib.Path(file_path).suffix == ".md" or mime_type == "text/markdown":
return string_content
elif mime_type == "text/plain":
return f"```\n{string_content}\n```"
elif mime_type.startswith("text"):
code_block_type = mime_type.split('/')[1]
if code_block_type.startswith("x-script."):
code_block_type = code_block_type[len("x-script."):]
return f"```{code_block_type}\n{string_content}\n```"
else:
return f"```\n{string_content}\n```"

import markdown2
from pygments.formatters import HtmlFormatter

from fastapi import FastAPI
from aiohttp import web
from aiohttp_asgi import ASGIResource
from datetime import date
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastui import FastUI, AnyComponent, prebuilt_html, components as c
from fastui.components.display import DisplayMode, DisplayLookup
from fastui.events import GoToEvent, BackEvent
from pydantic import BaseModel, Field

# Step 1: Define your FastAPI app
fastapi_app = FastAPI()

@fastapi_app.get(
"/{repo_name}/blob/{ref}/{path:path}",
response_class=HTMLResponse,
response_model_exclude_none=True,
)
def render_content(repo_name: str, ref: str, path: str) -> HTMLResponse:
if not repo_name.endswith(".git"):
repo_name = f"{repo_name}.git"
repo_path = pathlib.Path(GIT_PROJECT_ROOT, repo_name)

cmd = [
"git",
"show",
f"{ref}:{path}"
]
try:
file_contents_bytes = subprocess.check_output(
cmd,
cwd=str(repo_path.resolve()),
)
except Exception as e:
raise HTTPException(status_code=404, detail="File not found") from e

markdown_content = file_contents_bytes_to_markdown(
path,
file_contents_bytes,
)
rendered_html = markdown2.markdown(
markdown_content,
extras=[
"fenced-code-blocks",
"code-friendly",
"highlightjs-lang",
],
)

return textwrap.dedent(
f"""
<html>
<title>{path}</title>
<body>
{rendered_html}
</body>
</html>
""".strip()
)

# Step 2: Define an aiohttp app and adapt the FastAPI app
async def init_aiohttp_app():
aiohttp_app = web.Application()

# Create ASGIResource which handle rendering
asgi_resource = ASGIResource(fastapi_app)

# Register routes
aiohttp_app.router.add_route("*", "/{repo}.git/{path:.*}", handle_git_backend_request)

# Register resource
aiohttp_app.router.register_resource(asgi_resource)

# Mount startup and shutdown events from aiohttp to ASGI app
asgi_resource.lifespan_mount(aiohttp_app)

return aiohttp_app

def main() -> None:
# Ensure there is a bare Git repository for testing
test_repo_path = os.path.join(GIT_PROJECT_ROOT, "my-repo.git")

loop = asyncio.get_event_loop()
aiohttp_app = loop.run_until_complete(init_aiohttp_app())

if not os.path.exists(test_repo_path):
os.makedirs(GIT_PROJECT_ROOT, exist_ok=True)
os.system(f"git init --bare {test_repo_path}")
os.system(f"rm -rf {test_repo_path}/hooks/")
print(f"Initialized bare repository at {test_repo_path}")

# Start the server
web.run_app(aiohttp_app, host="0.0.0.0", port=8080)
Loading

0 comments on commit 814a0aa

Please sign in to comment.