Spaces:
Sleeping
Sleeping
Harden submission logger paths and sheet diagnostics
Browse filesFiles changed (2)
14 unmodified lines1516171819202117 unmodified lines39404142434445464748495051525354152 unmodified lines20720820919920021021121221321420321521621721814 unmodified linesimport osimport jsonimport subprocessimport refrom datetime import datetimefrom pathlib import Pathfrom typing import Optional17 unmodified lines 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()152 unmodified lines # Create submission folder name timestamp = datetime.now().strftime("%Y-%m-%d_%H%M") repo_name = repo_url.split('/')[-1].replace('.git', '') folder_name = f"{timestamp}_{student_name}_{repo_name}" 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(exist_ok=True) submission_folder.mkdir(parents=True, exist_ok=True) print(f"📁 Creating submission: {folder_name}") # Prepare files to write5 unmodified lines678910111220 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778796 unmodified lines8687884789909110 unmodified lines1021031046410510610710842 unmodified lines15115215311315415515673 unmodified lines2302312321932332342352365 unmodified lines"""
import osimport jsonfrom datetime import datetimefrom typing import Optional
20 unmodified lines]
def _service_account_identity(service_account_json: str) -> str: if not service_account_json: return "" try: info = json.loads(service_account_json) except Exception: return "" return info.get("client_email", "")
def _format_google_sheets_error(exc: Exception, sheet_id: str, service_account_json: str) -> str: service_account_email = _service_account_identity(service_account_json) spreadsheet_hint = ( f"Spreadsheet {sheet_id} was not found or is not shared with {service_account_email}." if service_account_email else f"Spreadsheet {sheet_id} was not found." )
try: import gspread
if isinstance(exc, gspread.exceptions.SpreadsheetNotFound): return spreadsheet_hint if isinstance(exc, gspread.exceptions.APIError): response = exc.response status_code = getattr(response, "status_code", "unknown") detail = "" try: payload = response.json() detail = payload.get("error", {}).get("message", "") except Exception: detail = getattr(response, "text", "") or str(exc) if status_code == 404: return f"HTTP 404 from Google Sheets API. {spreadsheet_hint} Details: {detail}".strip() return f"Google Sheets API error {status_code}: {detail or exc}" except Exception: pass
return f"{type(exc).__name__}: {exc}"
def diagnose_google_sheets() -> dict: sheet_id = os.getenv("GOOGLE_SHEET_ID", "").strip() service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()6 unmodified lines
try: import gspread import json from google.oauth2.service_account import Credentials
scopes = [10 unmodified lines client.open_by_key(sheet_id).sheet1 return {"ok": True, "reason": ""} except Exception as exc: return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"} return {"ok": False, "reason": _format_google_sheets_error(exc, sheet_id, service_account_json)}
def _ensure_sheet_headers(sheet) -> None:42 unmodified lines try: import gspread import json from google.oauth2.service_account import Credentials # Try to get service account from environment variable first (for cloud deployment)73 unmodified lines print("⚠️ Google Sheets: gspread not installed (pip install gspread google-auth)") return False except Exception as e: print(f"⚠️ Google Sheets logging failed: {e}") print(f"⚠️ Google Sheets logging failed: {_format_google_sheets_error(e, sheet_id, service_account_json or '')}") return False
git_submissions_logger.py+15-3
google_sheets_logger.py+44-4