""" git_submissions_logger.py — Push detailed submission reports to Git repository Creates a comprehensive backup folder for each submission and commits to Git: - Original prompt/challenge - Original code (before bugs) - Buggy code (what student received) - Student's solution - Full chat history - Summary JSON Each submission is automatically committed and pushed to a dedicated Git repository. """ import os import json import subprocess import re from datetime import datetime from pathlib import Path from typing import Optional def _git_env() -> dict: env = os.environ.copy() env["GIT_TERMINAL_PROMPT"] = "0" env["GCM_INTERACTIVE"] = "Never" env["GIT_ASKPASS"] = "" return env def _repo_url_with_token(repo_url: str, git_token: str) -> str: repo_url = (repo_url or "").strip() git_token = (git_token or "").strip() if not repo_url or not git_token: return repo_url if "@" in repo_url.split("//", 1)[-1]: return repo_url return repo_url.replace("https://", f"https://{git_token}@", 1) def _safe_path_component(value: str, fallback: str) -> str: value = (value or "").strip() if not value: return fallback value = value.replace("\\", "_").replace("/", "_") value = re.sub(r'[<>:"|?*\x00-\x1f]', "_", value) value = re.sub(r'\s+', " ", value).strip(" .") return value or fallback def diagnose_git_submissions() -> dict: submissions_repo = os.getenv("SUBMISSIONS_REPO_URL", "").strip() git_token = os.getenv("SUBMISSIONS_GIT_TOKEN", "").strip() if not submissions_repo: return {"ok": False, "reason": "Missing SUBMISSIONS_REPO_URL"} repo_push_url = _repo_url_with_token(submissions_repo, git_token) git_env = _git_env() submissions_dir = Path("submissions_backup") submissions_dir.mkdir(exist_ok=True) try: probe = subprocess.run( ["git", "ls-remote", repo_push_url or submissions_repo, "HEAD"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, timeout=30, ) if not probe.stdout: return {"ok": False, "reason": "Remote reachable but returned no refs"} return {"ok": True, "reason": ""} except subprocess.CalledProcessError as exc: stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "") stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") detail = stderr.strip() or stdout.strip() or str(exc) return {"ok": False, "reason": detail} except Exception as exc: return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"} def push_submission_to_git( student_name: str, repo_url: str, original_code: str, buggy_code: str, student_code: str, chat_history: list, score: int, total_tests: int, passed_tests: int, hints_used: int, challenge_prompt: str, target_file: str, submission_record: Optional[dict] = None, ) -> bool: """ Create submission folder and push to Git repository. Structure: submissions/ └── 2026-05-20_1430_StudentName_RepoName/ ├── 1_challenge_prompt.md ├── 2_original_code.py ├── 3_buggy_code.py ├── 4_student_solution.py ├── 5_chat_history.txt └── 6_summary.json Returns True if successful, False otherwise. """ # Check if Git submissions repo is configured submissions_repo = os.getenv("SUBMISSIONS_REPO_URL", "").strip() git_token = os.getenv("SUBMISSIONS_GIT_TOKEN", "").strip() repo_push_url = _repo_url_with_token(submissions_repo, git_token) git_env = _git_env() if not submissions_repo: print("⚠️ Git Submissions: SUBMISSIONS_REPO_URL not configured in .env") return False try: # Create submissions directory if it doesn't exist submissions_dir = Path("submissions_backup") submissions_dir.mkdir(exist_ok=True) # Initialize Git repo if needed git_dir = submissions_dir / ".git" if not git_dir.exists(): print("📂 Initializing Git repository...") subprocess.run( ["git", "init", "-b", "main"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) # Configure remote with token if available subprocess.run( ["git", "remote", "add", "origin", repo_push_url or submissions_repo], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) # Pull existing commits if repo exists try: subprocess.run( ["git", "pull", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) except subprocess.CalledProcessError: # Repo might be empty, that's OK pass # Configure git user (required for commits) subprocess.run( ["git", "config", "user.email", "legacy-code-bot@example.com"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) subprocess.run( ["git", "config", "user.name", "Legacy Code Bot"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) print("✅ Git repository initialized") # Always refresh the remote URL so changed tokens/config are picked up. remote_url = repo_push_url or submissions_repo subprocess.run( ["git", "remote", "set-url", "origin", remote_url], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) # Sync the local backup repo with the remote on every run so later pushes # do not fail when the remote has advanced. try: subprocess.run( ["git", "pull", "--rebase", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, timeout=30, ) except subprocess.CalledProcessError: # The remote may be empty or the branch may not exist yet. pass # Create submission folder name timestamp = datetime.now().strftime("%Y-%m-%d_%H%M") repo_name = _safe_path_component(repo_url.split('/')[-1].replace('.git', ''), "repo") safe_student_name = _safe_path_component(student_name, "anonymous") folder_name = f"{timestamp}_{safe_student_name}_{repo_name}" submission_folder = submissions_dir / folder_name submission_folder.mkdir(parents=True, exist_ok=True) print(f"📁 Creating submission: {folder_name}") # Prepare files to write files_to_write = [ ("1_challenge_prompt.md", challenge_prompt), ("2_original_code.py", f"# Original code (before bugs)\n# Target file: {target_file}\n\n{original_code}"), ("3_buggy_code.py", f"# Buggy code (what student received)\n# Target file: {target_file}\n\n{buggy_code}"), ("4_student_solution.py", f"# Student's solution\n# Target file: {target_file}\n\n{student_code}"), ("5_chat_history.txt", _format_chat_history(chat_history)), ("6_summary.json", json.dumps({ 'student_name': student_name, 'repository': repo_url, 'timestamp': datetime.now().isoformat(), 'score': score, 'total_tests': total_tests, 'passed_tests': passed_tests, 'success_rate': f"{(passed_tests/total_tests*100):.1f}%" if total_tests > 0 else "0%", 'hints_used': hints_used, 'target_file': target_file, }, ensure_ascii=False, indent=2)), ] if submission_record: files_to_write.append( ("7_submission_record.json", json.dumps(submission_record, ensure_ascii=False, indent=2)) ) test_output = submission_record.get("tests", {}).get("test_output", "") if test_output: files_to_write.append(("8_test_output.txt", test_output)) student_diff = submission_record.get("submission", {}).get("student_diff", "") if student_diff: files_to_write.append(("9_student_diff.patch", student_diff)) expected_fixed_code = submission_record.get("challenge", {}).get("expected_fixed_code", "") if expected_fixed_code: files_to_write.append( ("10_expected_fix.py", f"# Expected correct solution\n# Target file: {target_file}\n\n{expected_fixed_code}") ) # Write all files print(f"📝 Writing {len(files_to_write)} files...") for filename, content in files_to_write: file_path = submission_folder / filename file_path.write_text(content, encoding='utf-8') print(f" ✅ {filename}") # Git add, commit, push print("📤 Committing to Git...") subprocess.run( ["git", "add", "."], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) commit_message = f"Add submission: {student_name} - {repo_name} ({score}/{total_tests*10} pts)" subprocess.run( ["git", "commit", "-m", commit_message], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) # Ensure branch is named 'main' subprocess.run( ["git", "branch", "-M", "main"], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) print("🚀 Pushing to GitHub...") subprocess.run( ["git", "push", "-u", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True, timeout=30, env=git_env, ) print(f"✅ Pushed to Git: {folder_name}") return True except subprocess.CalledProcessError as e: stderr = e.stderr.decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "") stdout = e.stdout.decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or "") detail = stderr.strip() or stdout.strip() or str(e) print(f"⚠️ Git command failed: {detail}") return False except Exception as e: print(f"⚠️ Git submission failed: {type(e).__name__}: {e}") import traceback traceback.print_exc() return False def _format_chat_history(chat_history: list) -> str: """Format full chat history for text file.""" if not chat_history: return "לא השתמש בהינטים\n" lines = ["התכתבות מלאה עם הצ'אט\n"] lines.append("=" * 60 + "\n\n") for i, msg in enumerate(chat_history, 1): question = msg.get('question') or msg.get('summary', 'N/A') hint_summary = msg.get('hint_summary') or msg.get('summary', '') gave_hint = msg.get('gave_hint') title = f"הינט #{i}" if gave_hint is True else f"שיחה #{i}" lines.append(f"{title}\n") lines.append("-" * 40 + "\n") lines.append(f"שאלה: {question}\n\n") lines.append(f"תשובה:\n{msg.get('response', 'N/A')}\n\n") if hint_summary: lines.append(f"תקציר פנימי: {hint_summary}\n\n") lines.append("=" * 60 + "\n\n") return "".join(lines) # CLI testing if __name__ == "__main__": import sys from dotenv import load_dotenv # Load .env file for testing load_dotenv() if len(sys.argv) > 1 and sys.argv[1] == "test": print("Testing Git submissions integration...") submissions_repo = os.getenv("SUBMISSIONS_REPO_URL") if not submissions_repo: print("❌ SUBMISSIONS_REPO_URL not set in .env") sys.exit(1) success = push_submission_to_git( student_name="Test_Student", repo_url="https://github.com/test/repo", original_code="def hello():\n return 'world'", buggy_code="def hello():\n return 'WORLD'", student_code="def hello():\n return 'world'", chat_history=[{"summary": "How to fix?", "response": "Check the case"}], score=85, total_tests=10, passed_tests=8, hints_used=1, challenge_prompt="# Test Challenge\n\nFix the bug!", target_file="test.py", ) if success: print("✅ Test push successful!") else: print("❌ Test push failed") sys.exit(1)