Spaces:
Sleeping
Sleeping
Harden git submissions sync and auth
Browse files19 unmodified lines20212223242526272829303132333435363738394041424327 unmodified lines717273747576777812 unmodified lines91929374949596979878798081828384858687991001011021031041058889909192931061071081 unmodified line1101111121011131141151161174 unmodified lines12212312411212512612712812913013111813213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316437 unmodified lines2022032041652052062072082091 unmodified line2112122131732142152162172181 unmodified line2202212221812232242252262272 unmodified lines23023123219023323423523623723823924019724124224324424524624719 unmodified linesfrom 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 push_submission_to_git( student_name: str, repo_url: str,27 unmodified lines # 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")12 unmodified lines ["git", "init", "-b", "main"], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) # Configure remote with token if available if git_token: # Format: https://TOKEN@github.com/user/repo.git repo_with_token = submissions_repo.replace("https://", f"https://{git_token}@") subprocess.run( ["git", "remote", "add", "origin", repo_with_token], cwd=submissions_dir, check=True, capture_output=True ) else: subprocess.run( ["git", "remote", "add", "origin", repo_push_url or submissions_repo], cwd=submissions_dir, check=True, capture_output=True, env=git_env, ) subprocess.run( ["git", "remote", "add", "origin", submissions_repo], cwd=submissions_dir, check=True, capture_output=True ) # Pull existing commits if repo exists try:1 unmodified line ["git", "pull", "origin", "main"], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) except subprocess.CalledProcessError: # Repo might be empty, that's OK4 unmodified lines ["git", "config", "user.email", "legacy-code-bot@example.com"], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) subprocess.run( ["git", "config", "user.name", "Legacy Code Bot"], cwd=submissions_dir, check=True, capture_output=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")37 unmodified lines ["git", "add", "."], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) commit_message = f"Add submission: {student_name} - {repo_name} ({score}/{total_tests*10} pts)"1 unmodified line ["git", "commit", "-m", commit_message], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) # Ensure branch is named 'main'1 unmodified line ["git", "branch", "-M", "main"], cwd=submissions_dir, check=True, capture_output=True capture_output=True, env=git_env, ) print("🚀 Pushing to GitHub...")2 unmodified lines cwd=submissions_dir, check=True, capture_output=True, timeout=30 timeout=30, env=git_env, ) print(f"✅ Pushed to Git: {folder_name}") return True except subprocess.CalledProcessError as e: print(f"⚠️ Git command failed: {e.stderr.decode() if e.stderr else str(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}")git_submissions_logger.py+72-25