|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from getpass import getpass |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | + |
| 7 | +def parse_gs_url(url: str) -> tuple[str, str, str | None]: |
| 8 | + """ |
| 9 | + Parse a Google Cloud Storage URL into components. |
| 10 | +
|
| 11 | + Args: |
| 12 | + url: URL in format gs://bucket/path/to/file[@version] |
| 13 | +
|
| 14 | + Returns: |
| 15 | + Tuple of (bucket, file_path, version) |
| 16 | + version is None if not specified |
| 17 | + """ |
| 18 | + if not url.startswith("gs://"): |
| 19 | + raise ValueError( |
| 20 | + f"Invalid gs:// URL format: {url}. " |
| 21 | + "Expected format: gs://bucket/path/to/file[@version]" |
| 22 | + ) |
| 23 | + |
| 24 | + # Remove the "gs://" prefix |
| 25 | + path = url[5:] |
| 26 | + parts = path.split("/", 1) |
| 27 | + |
| 28 | + if len(parts) < 2 or not parts[1]: |
| 29 | + raise ValueError( |
| 30 | + f"Invalid gs:// URL format: {url}. " |
| 31 | + "Expected format: gs://bucket/path/to/file[@version]" |
| 32 | + ) |
| 33 | + |
| 34 | + bucket = parts[0] |
| 35 | + file_path = parts[1] |
| 36 | + |
| 37 | + version = None |
| 38 | + if "@" in file_path: |
| 39 | + file_path, version = file_path.rsplit("@", 1) |
| 40 | + |
| 41 | + return bucket, file_path, version |
| 42 | + |
| 43 | + |
| 44 | +def download_gcs_file( |
| 45 | + bucket: str, |
| 46 | + file_path: str, |
| 47 | + version: str = None, |
| 48 | + local_path: str = None, |
| 49 | +): |
| 50 | + """ |
| 51 | + Download a file from Google Cloud Storage. |
| 52 | +
|
| 53 | + Args: |
| 54 | + bucket: The GCS bucket name. |
| 55 | + file_path: The path to the file within the bucket. |
| 56 | + version: The generation/version of the file (optional). |
| 57 | + local_path: The local path to save the file to. If None, downloads to a temp directory. |
| 58 | +
|
| 59 | + Returns: |
| 60 | + The local path where the file was saved. |
| 61 | + """ |
| 62 | + try: |
| 63 | + from google.cloud import storage |
| 64 | + import google.auth |
| 65 | + except ImportError: |
| 66 | + raise ImportError( |
| 67 | + "google-cloud-storage is required for gs:// URLs. " |
| 68 | + "Install it with: pip install google-cloud-storage" |
| 69 | + ) |
| 70 | + |
| 71 | + credentials, project_id = _get_gcs_credentials() |
| 72 | + |
| 73 | + storage_client = storage.Client( |
| 74 | + credentials=credentials, project=project_id |
| 75 | + ) |
| 76 | + |
| 77 | + bucket_obj = storage_client.bucket(bucket) |
| 78 | + blob = bucket_obj.blob(file_path) |
| 79 | + |
| 80 | + if version: |
| 81 | + blob = bucket_obj.blob(file_path, generation=int(version)) |
| 82 | + |
| 83 | + if local_path is None: |
| 84 | + # Download to a temp directory, preserving the filename |
| 85 | + filename = Path(file_path).name |
| 86 | + local_path = os.path.join(tempfile.gettempdir(), filename) |
| 87 | + |
| 88 | + blob.download_to_filename(local_path) |
| 89 | + return local_path |
| 90 | + |
| 91 | + |
| 92 | +def upload_gcs_file( |
| 93 | + bucket: str, |
| 94 | + file_path: str, |
| 95 | + local_path: str, |
| 96 | + version_metadata: str = None, |
| 97 | +): |
| 98 | + """ |
| 99 | + Upload a file to Google Cloud Storage. |
| 100 | +
|
| 101 | + Args: |
| 102 | + bucket: The GCS bucket name. |
| 103 | + file_path: The path to upload to within the bucket. |
| 104 | + local_path: The local path of the file to upload. |
| 105 | + version_metadata: Optional version string to store in blob metadata. |
| 106 | + """ |
| 107 | + try: |
| 108 | + from google.cloud import storage |
| 109 | + import google.auth |
| 110 | + except ImportError: |
| 111 | + raise ImportError( |
| 112 | + "google-cloud-storage is required for gs:// URLs. " |
| 113 | + "Install it with: pip install google-cloud-storage" |
| 114 | + ) |
| 115 | + |
| 116 | + credentials, project_id = _get_gcs_credentials() |
| 117 | + |
| 118 | + storage_client = storage.Client( |
| 119 | + credentials=credentials, project=project_id |
| 120 | + ) |
| 121 | + |
| 122 | + bucket_obj = storage_client.bucket(bucket) |
| 123 | + blob = bucket_obj.blob(file_path) |
| 124 | + blob.upload_from_filename(local_path) |
| 125 | + |
| 126 | + if version_metadata: |
| 127 | + blob.metadata = {"version": version_metadata} |
| 128 | + blob.patch() |
| 129 | + |
| 130 | + return f"gs://{bucket}/{file_path}" |
| 131 | + |
| 132 | + |
| 133 | +def _get_gcs_credentials(): |
| 134 | + """ |
| 135 | + Get GCS credentials, prompting for service account key path if needed. |
| 136 | +
|
| 137 | + Returns: |
| 138 | + Tuple of (credentials, project_id) |
| 139 | + """ |
| 140 | + try: |
| 141 | + import google.auth |
| 142 | + from google.auth import exceptions as auth_exceptions |
| 143 | + except ImportError: |
| 144 | + raise ImportError( |
| 145 | + "google-cloud-storage is required for gs:// URLs. " |
| 146 | + "Install it with: pip install google-cloud-storage" |
| 147 | + ) |
| 148 | + |
| 149 | + # First try default credentials (e.g., from gcloud auth, service account, etc.) |
| 150 | + try: |
| 151 | + credentials, project_id = google.auth.default() |
| 152 | + return credentials, project_id |
| 153 | + except auth_exceptions.DefaultCredentialsError: |
| 154 | + pass |
| 155 | + |
| 156 | + # If no default credentials, check for service account key in environment |
| 157 | + key_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") |
| 158 | + |
| 159 | + if key_path is None: |
| 160 | + key_path = getpass( |
| 161 | + "Enter path to GCS service account key JSON " |
| 162 | + "(or set GOOGLE_APPLICATION_CREDENTIALS): " |
| 163 | + ) |
| 164 | + os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = key_path |
| 165 | + |
| 166 | + # Try again with the provided credentials |
| 167 | + credentials, project_id = google.auth.default() |
| 168 | + return credentials, project_id |
0 commit comments