11from __future__ import annotations
22
3+ import logging
4+ import sys
35import typing as t
46from dataclasses import dataclass
57from datetime import datetime
2628from sqlmesh .utils .date import TimeLike , now , to_datetime , to_timestamp
2729from sqlmesh .utils .pydantic import PydanticModel
2830
31+ logger = logging .getLogger (__name__ )
32+
2933SnapshotMapping = t .Dict [SnapshotId , t .Set [SnapshotId ]]
3034
3135
36+ if sys .version_info >= (3 , 12 ):
37+ from importlib import metadata
38+ else :
39+ import importlib_metadata as metadata # type: ignore
40+
41+
42+ IGNORED_PACKAGES = {"sqlmesh" , "sqlglot" }
43+
44+
3245class Plan (PydanticModel , frozen = True ):
3346 context_diff : ContextDiff
3447 plan_id : str
@@ -209,6 +222,23 @@ def environment(self) -> Environment:
209222 else self .context_diff .previous_finalized_snapshots
210223 )
211224
225+ requirements = {}
226+ distributions = metadata .packages_distributions ()
227+
228+ for snapshot in self .context_diff .snapshots .values ():
229+ if snapshot .is_model :
230+ for executable in snapshot .model .python_env .values ():
231+ if executable .kind == "import" :
232+ try :
233+ start = "from " if executable .payload .startswith ("from " ) else "import "
234+ lib = executable .payload .split (start )[1 ].split ()[0 ].split ("." )[0 ]
235+ if lib in distributions :
236+ for dist in distributions [lib ]:
237+ if dist not in requirements and dist not in IGNORED_PACKAGES :
238+ requirements [dist ] = metadata .version (dist )
239+ except metadata .PackageNotFoundError :
240+ logger .warning ("Failed to find package for %s" , lib )
241+
212242 return Environment (
213243 snapshots = snapshots ,
214244 start_at = self .provided_start or self ._earliest_interval_start ,
@@ -218,6 +248,7 @@ def environment(self) -> Environment:
218248 expiration_ts = expiration_ts ,
219249 promoted_snapshot_ids = promoted_snapshot_ids ,
220250 previous_finalized_snapshots = previous_finalized_snapshots ,
251+ requirements = requirements ,
221252 ** self .environment_naming_info .dict (),
222253 )
223254
0 commit comments