File size: 3,728 Bytes
dc7c214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/env python3
"""
Patch: Fix 404 on root and /api when frontend build is missing.

Root cause: The Dockerfile creates /app/static with `mkdir -p` but the
frontend build may fail, leaving the directory empty. main.py checks
`if static_path.exists()` which returns True for an empty directory,
causing StaticFiles to mount at "/" and shadow ALL API routes with 404s.

Fix: Patch main.py to check that the static directory is non-empty
before mounting StaticFiles.
"""

import os
import sys

TARGET_FILE = "/app/backend/main.py"
PATCHED_MARKER = "# === PATCH: fix static 404 on empty dir ==="


def patch_main_py(content: str) -> tuple[str, bool]:
    changed = False

    old_block = (
        "# Serve static files (frontend build) in production\n"
        "static_path = Path(__file__).parent.parent / \"static\"\n"
        "if static_path.exists():\n"
        "    app.mount(\"/\", StaticFiles(directory=str(static_path), html=True), name=\"static\")\n"
        "    logger.info(f\"Serving static files from {static_path}\")\n"
        "else:\n"
        "    logger.info(\"No static directory found, running in API-only mode\")"
    )

    new_block = (
        "# Serve static files (frontend build) in production\n"
        "static_path = Path(__file__).parent.parent / \"static\"\n"
        f"{PATCHED_MARKER}\n"
        "# Only mount if the directory exists AND has content — an empty\n"
        "# directory would shadow all API routes with 404s.\n"
        "if static_path.exists() and any(static_path.iterdir()):\n"
        "    app.mount(\"/\", StaticFiles(directory=str(static_path), html=True), name=\"static\")\n"
        "    logger.info(f\"Serving static files from {static_path}\")\n"
        "else:\n"
        "    logger.info(\"No static files found, running in API-only mode\")"
    )

    if old_block in content:
        content = content.replace(old_block, new_block, 1)
        changed = True
        print("  + Fixed static file mounting to check for non-empty directory")
    else:
        # Try a more flexible match
        if "static_path.exists()" in content and PATCHED_MARKER not in content:
            import re
            # Replace the if condition
            pattern = r'if static_path\.exists\(\):'
            replacement = f'if static_path.exists() and any(static_path.iterdir()):\n        {PATCHED_MARKER}'
            content = re.sub(pattern, replacement, content, count=1)
            changed = True
            print("  + Fixed static file mounting (regex fallback)")
        else:
            print(f"  SKIP: pattern already patched or not found")

    return content, changed


def main():
    if not os.path.exists(TARGET_FILE):
        print(f"SKIP: {TARGET_FILE} not found")
        return

    with open(TARGET_FILE, "r", encoding="utf-8") as f:
        content = f.read()

    if PATCHED_MARKER in content:
        print(f"SKIP: {TARGET_FILE} already patched")
        return

    # Syntax-check by parsing
    import ast
    try:
        ast.parse(content)
    except SyntaxError as e:
        print(f"WARN: {TARGET_FILE} has syntax errors before patching: {e}")
        return

    content, changed = patch_main_py(content)
    if changed:
        try:
            ast.parse(content)
            with open(TARGET_FILE, "w", encoding="utf-8") as f:
                f.write(content)
            print(f"OK: {TARGET_FILE} patched")
        except SyntaxError as e:
            print(f"FAIL: patched {TARGET_FILE} has syntax error: {e}")
    else:
        print(f"SKIP: {TARGET_FILE} — no changes applied")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"WARN: patch_fix_static_404.py error: {e}")
        sys.exit(0)