1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements. See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership. The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License. You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied. See the License for the
15# specific language governing permissions and limitations
16# under the License.
17from __future__ import annotations
18
19import os
20from contextlib import contextmanager
21
22from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_DAG_ID, _AIRFLOW_PARSING_CONTEXT_TASK_ID
23
24
25@contextmanager
26def _airflow_parsing_context_manager(dag_id: str | None = None, task_id: str | None = None):
27 old_dag_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_DAG_ID)
28 old_task_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_TASK_ID)
29 if dag_id is not None:
30 os.environ[_AIRFLOW_PARSING_CONTEXT_DAG_ID] = dag_id
31 if task_id is not None:
32 os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = task_id
33 yield
34 if old_task_id is not None:
35 os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = old_task_id
36 if old_dag_id is not None:
37 os.environ[_AIRFLOW_PARSING_CONTEXT_DAG_ID] = old_dag_id