Spaces:
Sleeping
Sleeping
Harden git submissions sync and auth
Browse files19 unmodified lines20212223242527 unmodified lines53545556575812 unmodified lines71727374757677787980818283848586878889909192939495961 unmodified line98991001011021031044 unmodified lines10911011111211311411511611711811912012112212312437 unmodified lines1621631641651661671681 unmodified line1701711721731741751761 unmodified line1781791801811821831842 unmodified lines18718818919019119219319419519619719819920019 unmodified linesfrom typing import Optionaldef push_submission_to_git(student_name: str,repo_url: str,27 unmodified lines# Check if Git submissions repo is configuredsubmissions_repo = os.getenv("SUBMISSIONS_REPO_URL", "").strip()git_token = os.getenv("SUBMISSIONS_GIT_TOKEN", "").strip()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)# Configure remote with token if availableif git_token:# Format: https://TOKEN@github.com/user/repo.gitrepo_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", submissions_repo],cwd=submissions_dir,check=True,capture_output=True)# Pull existing commits if repo existstry:1 unmodified line["git", "pull", "origin", "main"],cwd=submissions_dir,check=True,capture_output=True)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)subprocess.run(["git", "config", "user.name", "Legacy Code Bot"],cwd=submissions_dir,check=True,capture_output=True)print("✅ Git repository initialized")# Create submission folder nametimestamp = datetime.now().strftime("%Y-%m-%d_%H%M")37 unmodified lines["git", "add", "."],cwd=submissions_dir,check=True,capture_output=True)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)# Ensure branch is named 'main'1 unmodified line["git", "branch", "-M", "main"],cwd=submissions_dir,check=True,capture_output=True)print("🚀 Pushing to GitHub...")2 unmodified linescwd=submissions_dir,check=True,capture_output=True,timeout=30)print(f"✅ Pushed to Git: {folder_name}")return Trueexcept subprocess.CalledProcessError as e:print(f"⚠️ Git command failed: {e.stderr.decode() if e.stderr else str(e)}")return Falseexcept Exception as e:print(f"⚠️ Git submission failed: {type(e).__name__}: {e}")19 unmodified lines20212223242526272829303132333435363738394041424327 unmodified lines717273747576777812 unmodified lines9192939495969798991001011021031041051061071081 unmodified line1101111121131141151161174 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316437 unmodified lines2022032042052062072082091 unmodified line2112122132142152162172181 unmodified line2202212222232242252262272 unmodified lines23023123223323423523623723823924024124224324424524624719 unmodified linesfrom typing import Optionaldef _git_env() -> dict:env = os.environ.copy()env["GIT_TERMINAL_PROMPT"] = "0"env["GCM_INTERACTIVE"] = "Never"env["GIT_ASKPASS"] = ""return envdef _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_urlif "@" in repo_url.split("//", 1)[-1]:return repo_urlreturn 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 configuredsubmissions_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,env=git_env,)# Configure remote with token if availablesubprocess.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 existstry:1 unmodified line["git", "pull", "origin", "main"],cwd=submissions_dir,check=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,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_reposubprocess.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 nametimestamp = datetime.now().strftime("%Y-%m-%d_%H%M")37 unmodified lines["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)"1 unmodified line["git", "commit", "-m", commit_message],cwd=submissions_dir,check=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,env=git_env,)print("🚀 Pushing to GitHub...")2 unmodified linescwd=submissions_dir,check=True,capture_output=True,timeout=30,env=git_env,)print(f"✅ Pushed to Git: {folder_name}")return Trueexcept 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 Falseexcept Exception as e:print(f"⚠️ Git submission failed: {type(e).__name__}: {e}")
git_submissions_logger.py+72-25