potiuk commented on a change in pull request #8994:
URL: https://github.com/apache/airflow/pull/8994#discussion_r429800720



##########
File path: backport_packages/refactor_backport_packages.py
##########
@@ -0,0 +1,369 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import os
+from os.path import dirname
+from shutil import copyfile, copytree, rmtree
+from typing import List
+
+from backport_packages.setup_backport_packages import (
+    get_source_airflow_folder, get_source_providers_folder, 
get_target_providers_folder,
+    get_target_providers_package_folder, is_bigquery_non_dts_module,
+)
+from bowler import LN, TOKEN, Capture, Filename, Query
+from fissix.fixer_util import Comma, KeywordArg, Name
+from fissix.pytree import Leaf
+
+CLASS_TYPES = ["hooks", "operators", "sensors", "secrets", "protocols"]
+
+
+def copy_provider_sources() -> None:
+    """
+    Copies provider sources to directory where they will be refactored.
+    """
+    def rm_build_dir() -> None:
+        """
+        Removes build directory.
+        """
+        build_dir = os.path.join(dirname(__file__), "build")
+        if os.path.isdir(build_dir):
+            rmtree(build_dir)
+
+    def ignore_bigquery_files(src: str, names: List[str]) -> List[str]:
+        """
+        Ignore files with bigquery
+        :param src: source file
+        :param names: Name of the file
+        :return:
+        """
+        ignored_names = []
+        if any([src.endswith(os.path.sep + class_type) for class_type in 
CLASS_TYPES]):
+            ignored_names = [name for name in names
+                             if is_bigquery_non_dts_module(module_name=name)]
+        if src.endswith(os.path.sep + "example_dags"):
+            for file_name in names:
+                file_path = src + os.path.sep + file_name
+                with open(file_path, "rt") as file:
+                    text = file.read()
+                if 
any([f"airflow.providers.google.cloud.{class_type}.bigquery" in text
+                        for class_type in CLASS_TYPES]) or "_to_bigquery" in 
text:
+                    print(f"Ignoring {file_path}")
+                    ignored_names.append(file_name)
+        return ignored_names
+
+    def ignore_kubernetes_files(src: str, names: List[str]) -> List[str]:
+        ignored_names = []
+        if src.endswith(os.path.sep + "example_dags"):
+            for file_name in names:
+                if "example_kubernetes" in file_name:
+                    ignored_names.append(file_name)
+        return ignored_names
+
+    def ignore_some_files(src: str, names: List[str]) -> List[str]:
+        ignored_list = ignore_bigquery_files(src=src, names=names)
+        ignored_list.extend(ignore_kubernetes_files(src=src, names=names))
+        return ignored_list
+
+    rm_build_dir()
+    package_providers_dir = get_target_providers_folder()
+    if os.path.isdir(package_providers_dir):
+        rmtree(package_providers_dir)
+    copytree(get_source_providers_folder(), get_target_providers_folder(), 
ignore=ignore_some_files)
+
+
+class RefactorBackportPackages:
+    """
+    Refactors the code of providers, so that it works in 1.10.
+
+    """
+
+    def __init__(self):
+        self.qry = Query()
+
+    def remove_class(self, class_name) -> None:
+        # noinspection PyUnusedLocal
+        def _remover(node: LN, capture: Capture, filename: Filename) -> None:
+            if node.type not in (300, 311):  # remove only definition
+                node.remove()
+
+        self.qry.select_class(class_name).modify(_remover)
+
+    def rename_deprecated_modules(self):
+        changes = [
+            ("airflow.operators.bash", "airflow.operators.bash_operator"),
+            ("airflow.operators.python", "airflow.operators.python_operator"),
+            ("airflow.utils.session", "airflow.utils.db"),
+            (
+                "airflow.providers.cncf.kubernetes.operators.kubernetes_pod",
+                "airflow.contrib.operators.kubernetes_pod_operator"
+            ),
+        ]
+        for new, old in changes:
+            self.qry.select_module(new).rename(old)
+
+    def add_provide_context_to_python_operators(self):
+        # noinspection PyUnusedLocal
+        def add_provide_context_to_python_operator(node: LN, capture: Capture, 
filename: Filename) -> None:
+            fn_args = capture['function_arguments'][0]
+            fn_args.append_child(Comma())
+
+            provide_context_arg = KeywordArg(Name('provide_context'), 
Name('True'))
+            provide_context_arg.prefix = fn_args.children[0].prefix
+            fn_args.append_child(provide_context_arg)
+
+        (
+            self.qry.
+            select_function("PythonOperator").
+            is_call().
+            is_filename(include=r"mlengine_operator_utils.py$").
+            modify(add_provide_context_to_python_operator)
+        )
+        (
+            self.qry.
+            select_function("BranchPythonOperator").
+            is_call().
+            
is_filename(include=r"example_google_api_to_s3_transfer_advanced.py$").
+            modify(add_provide_context_to_python_operator)
+        )
+
+    def remove_super_init_call(self):
+        # noinspection PyUnusedLocal
+        def remove_super_init_call_modifier(node: LN, capture: Capture, 
filename: Filename) -> None:
+            for ch in node.post_order():
+                if isinstance(ch, Leaf) and ch.value == "super":
+                    if any(c.value for c in ch.parent.post_order() if 
isinstance(c, Leaf)):
+                        ch.parent.remove()
+
+        
self.qry.select_subclass("BaseHook").modify(remove_super_init_call_modifier)
+
+    def remove_tags(self):
+        # noinspection PyUnusedLocal
+        def remove_tags_modifier(_: LN, capture: Capture, filename: Filename) 
-> None:
+            for node in capture['function_arguments'][0].post_order():
+                if isinstance(node, Leaf) and node.value == "tags" and 
node.type == TOKEN.NAME:

Review comment:
       @ashb - also - note this tag removal will only apply to examples, not to 
the code itself. If you are using the backported operators in Airflow 1.10.10 
you can still use tags. I explained that in the comments and examples I added 
in #8991 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to