We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Celery Import Error
<!--
Please use one of our issue templates.
We reserve the right to close bug reports or feature requests who don't use our templates.
-->
Not able to import Celery module when creating simple app.

from celery import Celery
ImportError: cannot import name 'Celery' from 'celery'

Additonal info:
This issue doesn't occur when we downgrade importlib-metadata to 4.12.0
Env details
![image](https://user-images.githubusercontent.com/55486262/193540909-f96e4503-44cf-45ed-b151-79af2cc6e12c.png)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `celery/utils/imports.py`
Content:
```
1 """Utilities related to importing modules and symbols by name."""
2 import os
3 import sys
4 import warnings
5 from contextlib import contextmanager
6 from importlib import import_module, reload
7 
8 try:
9     from importlib.metadata import entry_points
10 except ImportError:
11     from importlib_metadata import entry_points
12 
13 from kombu.utils.imports import symbol_by_name
14 
15 #: Billiard sets this when execv is enabled.
16 #: We use it to find out the name of the original ``__main__``
17 #: module, so that we can properly rewrite the name of the
18 #: task to be that of ``App.main``.
19 MP_MAIN_FILE = os.environ.get('MP_MAIN_FILE')
20 
21 __all__ = (
22     'NotAPackage', 'qualname', 'instantiate', 'symbol_by_name',
23     'cwd_in_path', 'find_module', 'import_from_cwd',
24     'reload_from_cwd', 'module_file', 'gen_task_name',
25 )
26 
27 
28 class NotAPackage(Exception):
29     """Raised when importing a package, but it's not a package."""
30 
31 
32 def qualname(obj):
33     """Return object name."""
34     if not hasattr(obj, '__name__') and hasattr(obj, '__class__'):
35         obj = obj.__class__
36     q = getattr(obj, '__qualname__', None)
37     if '.' not in q:
38         q = '.'.join((obj.__module__, q))
39     return q
40 
41 
42 def instantiate(name, *args, **kwargs):
43     """Instantiate class by name.
44 
45     See Also:
46         :func:`symbol_by_name`.
47     """
48     return symbol_by_name(name)(*args, **kwargs)
49 
50 
51 @contextmanager
52 def cwd_in_path():
53     """Context adding the current working directory to sys.path."""
54     cwd = os.getcwd()
55     if cwd in sys.path:
56         yield
57     else:
58         sys.path.insert(0, cwd)
59         try:
60             yield cwd
61         finally:
62             try:
63                 sys.path.remove(cwd)
64             except ValueError:  # pragma: no cover
65                 pass
66 
67 
68 def find_module(module, path=None, imp=None):
69     """Version of :func:`imp.find_module` supporting dots."""
70     if imp is None:
71         imp = import_module
72     with cwd_in_path():
73         try:
74             return imp(module)
75         except ImportError:
76             # Raise a more specific error if the problem is that one of the
77             # dot-separated segments of the module name is not a package.
78             if '.' in module:
79                 parts = module.split('.')
80                 for i, part in enumerate(parts[:-1]):
81                     package = '.'.join(parts[:i + 1])
82                     try:
83                         mpart = imp(package)
84                     except ImportError:
85                         # Break out and re-raise the original ImportError
86                         # instead.
87                         break
88                     try:
89                         mpart.__path__
90                     except AttributeError:
91                         raise NotAPackage(package)
92             raise
93 
94 
95 def import_from_cwd(module, imp=None, package=None):
96     """Import module, temporarily including modules in the current directory.
97 
98     Modules located in the current directory has
99     precedence over modules located in `sys.path`.
100     """
101     if imp is None:
102         imp = import_module
103     with cwd_in_path():
104         return imp(module, package=package)
105 
106 
107 def reload_from_cwd(module, reloader=None):
108     """Reload module (ensuring that CWD is in sys.path)."""
109     if reloader is None:
110         reloader = reload
111     with cwd_in_path():
112         return reloader(module)
113 
114 
115 def module_file(module):
116     """Return the correct original file name of a module."""
117     name = module.__file__
118     return name[:-1] if name.endswith('.pyc') else name
119 
120 
121 def gen_task_name(app, name, module_name):
122     """Generate task name from name/module pair."""
123     module_name = module_name or '__main__'
124     try:
125         module = sys.modules[module_name]
126     except KeyError:
127         # Fix for manage.py shell_plus (Issue #366)
128         module = None
129 
130     if module is not None:
131         module_name = module.__name__
132         # - If the task module is used as the __main__ script
133         # - we need to rewrite the module part of the task name
134         # - to match App.main.
135         if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:
136             # - see comment about :envvar:`MP_MAIN_FILE` above.
137             module_name = '__main__'
138     if module_name == '__main__' and app.main:
139         return '.'.join([app.main, name])
140     return '.'.join(p for p in (module_name, name) if p)
141 
142 
143 def load_extension_class_names(namespace):
144     for ep in entry_points().get(namespace, []):
145         yield ep.name, ep.value
146 
147 
148 def load_extension_classes(namespace):
149     for name, class_name in load_extension_class_names(namespace):
150         try:
151             cls = symbol_by_name(class_name)
152         except (ImportError, SyntaxError) as exc:
153             warnings.warn(
154                 f'Cannot load {namespace} extension {class_name!r}: {exc!r}')
155         else:
156             yield name, cls
157
```

Path: `celery/bin/celery.py`
Content:
```
1 """Celery Command Line Interface."""
2 import os
3 import pathlib
4 import traceback
5 
6 try:
7     from importlib.metadata import entry_points
8 except ImportError:
9     from importlib_metadata import entry_points
10 
11 import click
12 import click.exceptions
13 from click.types import ParamType
14 from click_didyoumean import DYMGroup
15 from click_plugins import with_plugins
16 
17 from celery import VERSION_BANNER
18 from celery.app.utils import find_app
19 from celery.bin.amqp import amqp
20 from celery.bin.base import CeleryCommand, CeleryOption, CLIContext
21 from celery.bin.beat import beat
22 from celery.bin.call import call
23 from celery.bin.control import control, inspect, status
24 from celery.bin.events import events
25 from celery.bin.graph import graph
26 from celery.bin.list import list_
27 from celery.bin.logtool import logtool
28 from celery.bin.migrate import migrate
29 from celery.bin.multi import multi
30 from celery.bin.purge import purge
31 from celery.bin.result import result
32 from celery.bin.shell import shell
33 from celery.bin.upgrade import upgrade
34 from celery.bin.worker import worker
35 
36 UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND = click.style("""
37 Unable to load celery application.
38 The module {0} was not found.""", fg='red')
39 
40 UNABLE_TO_LOAD_APP_ERROR_OCCURRED = click.style("""
41 Unable to load celery application.
42 While trying to load the module {0} the following error occurred:
43 {1}""", fg='red')
44 
45 UNABLE_TO_LOAD_APP_APP_MISSING = click.style("""
46 Unable to load celery application.
47 {0}""")
48 
49 
50 class App(ParamType):
51     """Application option."""
52 
53     name = "application"
54 
55     def convert(self, value, param, ctx):
56         try:
57             return find_app(value)
58         except ModuleNotFoundError as e:
59             if e.name != value:
60                 exc = traceback.format_exc()
61                 self.fail(
62                     UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)
63                 )
64             self.fail(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(e.name))
65         except AttributeError as e:
66             attribute_name = e.args[0].capitalize()
67             self.fail(UNABLE_TO_LOAD_APP_APP_MISSING.format(attribute_name))
68         except Exception:
69             exc = traceback.format_exc()
70             self.fail(
71                 UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)
72             )
73 
74 
75 APP = App()
76 
77 
78 @with_plugins(entry_points().get('celery.commands', []))
79 @click.group(cls=DYMGroup, invoke_without_command=True)
80 @click.option('-A',
81               '--app',
82               envvar='APP',
83               cls=CeleryOption,
84               type=APP,
85               help_group="Global Options")
86 @click.option('-b',
87               '--broker',
88               envvar='BROKER_URL',
89               cls=CeleryOption,
90               help_group="Global Options")
91 @click.option('--result-backend',
92               envvar='RESULT_BACKEND',
93               cls=CeleryOption,
94               help_group="Global Options")
95 @click.option('--loader',
96               envvar='LOADER',
97               cls=CeleryOption,
98               help_group="Global Options")
99 @click.option('--config',
100               envvar='CONFIG_MODULE',
101               cls=CeleryOption,
102               help_group="Global Options")
103 @click.option('--workdir',
104               cls=CeleryOption,
105               type=pathlib.Path,
106               callback=lambda _, __, wd: os.chdir(wd) if wd else None,
107               is_eager=True,
108               help_group="Global Options")
109 @click.option('-C',
110               '--no-color',
111               envvar='NO_COLOR',
112               is_flag=True,
113               cls=CeleryOption,
114               help_group="Global Options")
115 @click.option('-q',
116               '--quiet',
117               is_flag=True,
118               cls=CeleryOption,
119               help_group="Global Options")
120 @click.option('--version',
121               cls=CeleryOption,
122               is_flag=True,
123               help_group="Global Options")
124 @click.pass_context
125 def celery(ctx, app, broker, result_backend, loader, config, workdir,
126            no_color, quiet, version):
127     """Celery command entrypoint."""
128     if version:
129         click.echo(VERSION_BANNER)
130         ctx.exit()
131     elif ctx.invoked_subcommand is None:
132         click.echo(ctx.get_help())
133         ctx.exit()
134 
135     if loader:
136         # Default app takes loader from this env (Issue #1066).
137         os.environ['CELERY_LOADER'] = loader
138     if broker:
139         os.environ['CELERY_BROKER_URL'] = broker
140     if result_backend:
141         os.environ['CELERY_RESULT_BACKEND'] = result_backend
142     if config:
143         os.environ['CELERY_CONFIG_MODULE'] = config
144     ctx.obj = CLIContext(app=app, no_color=no_color, workdir=workdir,
145                          quiet=quiet)
146 
147     # User options
148     worker.params.extend(ctx.obj.app.user_options.get('worker', []))
149     beat.params.extend(ctx.obj.app.user_options.get('beat', []))
150     events.params.extend(ctx.obj.app.user_options.get('events', []))
151 
152     for command in celery.commands.values():
153         command.params.extend(ctx.obj.app.user_options.get('preload', []))
154 
155 
156 @celery.command(cls=CeleryCommand)
157 @click.pass_context
158 def report(ctx):
159     """Shows information useful to include in bug-reports."""
160     app = ctx.obj.app
161     app.loader.import_default_modules()
162     ctx.obj.echo(app.bugreport())
163 
164 
165 celery.add_command(purge)
166 celery.add_command(call)
167 celery.add_command(beat)
168 celery.add_command(list_)
169 celery.add_command(result)
170 celery.add_command(migrate)
171 celery.add_command(status)
172 celery.add_command(worker)
173 celery.add_command(events)
174 celery.add_command(inspect)
175 celery.add_command(control)
176 celery.add_command(graph)
177 celery.add_command(upgrade)
178 celery.add_command(logtool)
179 celery.add_command(amqp)
180 celery.add_command(shell)
181 celery.add_command(multi)
182 
183 # Monkey-patch click to display a custom error
184 # when -A or --app are used as sub-command options instead of as options
185 # of the global command.
186 
187 previous_show_implementation = click.exceptions.NoSuchOption.show
188 
189 WRONG_APP_OPTION_USAGE_MESSAGE = """You are using `{option_name}` as an option of the {info_name} sub-command:
190 celery {info_name} {option_name} celeryapp <...>
191 
192 The support for this usage was removed in Celery 5.0. Instead you should use `{option_name}` as a global option:
193 celery {option_name} celeryapp {info_name} <...>"""
194 
195 
196 def _show(self, file=None):
197     if self.option_name in ('-A', '--app'):
198         self.ctx.obj.error(
199             WRONG_APP_OPTION_USAGE_MESSAGE.format(
200                 option_name=self.option_name,
201                 info_name=self.ctx.info_name),
202             fg='red'
203         )
204     previous_show_implementation(self, file=file)
205 
206 
207 click.exceptions.NoSuchOption.show = _show
208 
209 
210 def main() -> int:
211     """Start celery umbrella command.
212 
213     This function is the main entrypoint for the CLI.
214 
215     :return: The exit code of the CLI.
216     """
217     return celery(auto_envvar_prefix="CELERY")
218
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/celery/bin/celery.py b/celery/bin/celery.py
--- a/celery/bin/celery.py
+++ b/celery/bin/celery.py
@@ -1,6 +1,7 @@
 """Celery Command Line Interface."""
 import os
 import pathlib
+import sys
 import traceback
 
 try:
@@ -75,7 +76,16 @@
 APP = App()
 
 
-@with_plugins(entry_points().get('celery.commands', []))
+if sys.version_info >= (3, 10):
+    _PLUGINS = entry_points(group='celery.commands')
+else:
+    try:
+        _PLUGINS = entry_points().get('celery.commands', [])
+    except AttributeError:
+        _PLUGINS = entry_points().select(group='celery.commands')
+
+
+@with_plugins(_PLUGINS)
 @click.group(cls=DYMGroup, invoke_without_command=True)
 @click.option('-A',
               '--app',
diff --git a/celery/utils/imports.py b/celery/utils/imports.py
--- a/celery/utils/imports.py
+++ b/celery/utils/imports.py
@@ -141,7 +141,14 @@
 
 
 def load_extension_class_names(namespace):
-    for ep in entry_points().get(namespace, []):
+    if sys.version_info >= (3, 10):
+        _entry_points = entry_points(group=namespace)
+    else:
+        try:
+            _entry_points = entry_points().get(namespace, [])
+        except AttributeError:
+            _entry_points = entry_points().select(group=namespace)
+    for ep in _entry_points:
         yield ep.name, ep.value

{"golden_diff": "diff --git a/celery/bin/celery.py b/celery/bin/celery.py\n--- a/celery/bin/celery.py\n+++ b/celery/bin/celery.py\n@@ -1,6 +1,7 @@\n \"\"\"Celery Command Line Interface.\"\"\"\n import os\n import pathlib\n+import sys\n import traceback\n \n try:\n@@ -75,7 +76,16 @@\n APP = App()\n \n \n-@with_plugins(entry_points().get('celery.commands', []))\n+if sys.version_info >= (3, 10):\n+    _PLUGINS = entry_points(group='celery.commands')\n+else:\n+    try:\n+        _PLUGINS = entry_points().get('celery.commands', [])\n+    except AttributeError:\n+        _PLUGINS = entry_points().select(group='celery.commands')\n+\n+\n+@with_plugins(_PLUGINS)\n @click.group(cls=DYMGroup, invoke_without_command=True)\n @click.option('-A',\n               '--app',\ndiff --git a/celery/utils/imports.py b/celery/utils/imports.py\n--- a/celery/utils/imports.py\n+++ b/celery/utils/imports.py\n@@ -141,7 +141,14 @@\n \n \n def load_extension_class_names(namespace):\n-    for ep in entry_points().get(namespace, []):\n+    if sys.version_info >= (3, 10):\n+        _entry_points = entry_points(group=namespace)\n+    else:\n+        try:\n+            _entry_points = entry_points().get(namespace, [])\n+        except AttributeError:\n+            _entry_points = entry_points().select(group=namespace)\n+    for ep in _entry_points:\n         yield ep.name, ep.value\n", "issue": "Celery Import Error\n<!--\r\nPlease use one of our issue templates.\r\nWe reserve the right to close bug reports or feature requests who don't use our templates.\r\n-->\r\nNot able to import Celery module when creating simple app.\r\n\r\nfrom celery import Celery\r\nImportError: cannot import name 'Celery' from 'celery'\r\n\r\nAdditonal info:\r\nThis issue doesn't occur when we downgrade importlib-metadata to 4.12.0\r\nEnv details\r\n![image](https://user-images.githubusercontent.com/55486262/193540909-f96e4503-44cf-45ed-b151-79af2cc6e12c.png)\r\n\n", "before_files": [{"content": "\"\"\"Utilities related to importing modules and symbols by name.\"\"\"\nimport os\nimport sys\nimport warnings\nfrom contextlib import contextmanager\nfrom importlib import import_module, reload\n\ntry:\n    from importlib.metadata import entry_points\nexcept ImportError:\n    from importlib_metadata import entry_points\n\nfrom kombu.utils.imports import symbol_by_name\n\n#: Billiard sets this when execv is enabled.\n#: We use it to find out the name of the original ``__main__``\n#: module, so that we can properly rewrite the name of the\n#: task to be that of ``App.main``.\nMP_MAIN_FILE = os.environ.get('MP_MAIN_FILE')\n\n__all__ = (\n    'NotAPackage', 'qualname', 'instantiate', 'symbol_by_name',\n    'cwd_in_path', 'find_module', 'import_from_cwd',\n    'reload_from_cwd', 'module_file', 'gen_task_name',\n)\n\n\nclass NotAPackage(Exception):\n    \"\"\"Raised when importing a package, but it's not a package.\"\"\"\n\n\ndef qualname(obj):\n    \"\"\"Return object name.\"\"\"\n    if not hasattr(obj, '__name__') and hasattr(obj, '__class__'):\n        obj = obj.__class__\n    q = getattr(obj, '__qualname__', None)\n    if '.' not in q:\n        q = '.'.join((obj.__module__, q))\n    return q\n\n\ndef instantiate(name, *args, **kwargs):\n    \"\"\"Instantiate class by name.\n\n    See Also:\n        :func:`symbol_by_name`.\n    \"\"\"\n    return symbol_by_name(name)(*args, **kwargs)\n\n\n@contextmanager\ndef cwd_in_path():\n    \"\"\"Context adding the current working directory to sys.path.\"\"\"\n    cwd = os.getcwd()\n    if cwd in sys.path:\n        yield\n    else:\n        sys.path.insert(0, cwd)\n        try:\n            yield cwd\n        finally:\n            try:\n                sys.path.remove(cwd)\n            except ValueError:  # pragma: no cover\n                pass\n\n\ndef find_module(module, path=None, imp=None):\n    \"\"\"Version of :func:`imp.find_module` supporting dots.\"\"\"\n    if imp is None:\n        imp = import_module\n    with cwd_in_path():\n        try:\n            return imp(module)\n        except ImportError:\n            # Raise a more specific error if the problem is that one of the\n            # dot-separated segments of the module name is not a package.\n            if '.' in module:\n                parts = module.split('.')\n                for i, part in enumerate(parts[:-1]):\n                    package = '.'.join(parts[:i + 1])\n                    try:\n                        mpart = imp(package)\n                    except ImportError:\n                        # Break out and re-raise the original ImportError\n                        # instead.\n                        break\n                    try:\n                        mpart.__path__\n                    except AttributeError:\n                        raise NotAPackage(package)\n            raise\n\n\ndef import_from_cwd(module, imp=None, package=None):\n    \"\"\"Import module, temporarily including modules in the current directory.\n\n    Modules located in the current directory has\n    precedence over modules located in `sys.path`.\n    \"\"\"\n    if imp is None:\n        imp = import_module\n    with cwd_in_path():\n        return imp(module, package=package)\n\n\ndef reload_from_cwd(module, reloader=None):\n    \"\"\"Reload module (ensuring that CWD is in sys.path).\"\"\"\n    if reloader is None:\n        reloader = reload\n    with cwd_in_path():\n        return reloader(module)\n\n\ndef module_file(module):\n    \"\"\"Return the correct original file name of a module.\"\"\"\n    name = module.__file__\n    return name[:-1] if name.endswith('.pyc') else name\n\n\ndef gen_task_name(app, name, module_name):\n    \"\"\"Generate task name from name/module pair.\"\"\"\n    module_name = module_name or '__main__'\n    try:\n        module = sys.modules[module_name]\n    except KeyError:\n        # Fix for manage.py shell_plus (Issue #366)\n        module = None\n\n    if module is not None:\n        module_name = module.__name__\n        # - If the task module is used as the __main__ script\n        # - we need to rewrite the module part of the task name\n        # - to match App.main.\n        if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:\n            # - see comment about :envvar:`MP_MAIN_FILE` above.\n            module_name = '__main__'\n    if module_name == '__main__' and app.main:\n        return '.'.join([app.main, name])\n    return '.'.join(p for p in (module_name, name) if p)\n\n\ndef load_extension_class_names(namespace):\n    for ep in entry_points().get(namespace, []):\n        yield ep.name, ep.value\n\n\ndef load_extension_classes(namespace):\n    for name, class_name in load_extension_class_names(namespace):\n        try:\n            cls = symbol_by_name(class_name)\n        except (ImportError, SyntaxError) as exc:\n            warnings.warn(\n                f'Cannot load {namespace} extension {class_name!r}: {exc!r}')\n        else:\n            yield name, cls\n", "path": "celery/utils/imports.py"}, {"content": "\"\"\"Celery Command Line Interface.\"\"\"\nimport os\nimport pathlib\nimport traceback\n\ntry:\n    from importlib.metadata import entry_points\nexcept ImportError:\n    from importlib_metadata import entry_points\n\nimport click\nimport click.exceptions\nfrom click.types import ParamType\nfrom click_didyoumean import DYMGroup\nfrom click_plugins import with_plugins\n\nfrom celery import VERSION_BANNER\nfrom celery.app.utils import find_app\nfrom celery.bin.amqp import amqp\nfrom celery.bin.base import CeleryCommand, CeleryOption, CLIContext\nfrom celery.bin.beat import beat\nfrom celery.bin.call import call\nfrom celery.bin.control import control, inspect, status\nfrom celery.bin.events import events\nfrom celery.bin.graph import graph\nfrom celery.bin.list import list_\nfrom celery.bin.logtool import logtool\nfrom celery.bin.migrate import migrate\nfrom celery.bin.multi import multi\nfrom celery.bin.purge import purge\nfrom celery.bin.result import result\nfrom celery.bin.shell import shell\nfrom celery.bin.upgrade import upgrade\nfrom celery.bin.worker import worker\n\nUNABLE_TO_LOAD_APP_MODULE_NOT_FOUND = click.style(\"\"\"\nUnable to load celery application.\nThe module {0} was not found.\"\"\", fg='red')\n\nUNABLE_TO_LOAD_APP_ERROR_OCCURRED = click.style(\"\"\"\nUnable to load celery application.\nWhile trying to load the module {0} the following error occurred:\n{1}\"\"\", fg='red')\n\nUNABLE_TO_LOAD_APP_APP_MISSING = click.style(\"\"\"\nUnable to load celery application.\n{0}\"\"\")\n\n\nclass App(ParamType):\n    \"\"\"Application option.\"\"\"\n\n    name = \"application\"\n\n    def convert(self, value, param, ctx):\n        try:\n            return find_app(value)\n        except ModuleNotFoundError as e:\n            if e.name != value:\n                exc = traceback.format_exc()\n                self.fail(\n                    UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)\n                )\n            self.fail(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(e.name))\n        except AttributeError as e:\n            attribute_name = e.args[0].capitalize()\n            self.fail(UNABLE_TO_LOAD_APP_APP_MISSING.format(attribute_name))\n        except Exception:\n            exc = traceback.format_exc()\n            self.fail(\n                UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)\n            )\n\n\nAPP = App()\n\n\n@with_plugins(entry_points().get('celery.commands', []))\n@click.group(cls=DYMGroup, invoke_without_command=True)\n@click.option('-A',\n              '--app',\n              envvar='APP',\n              cls=CeleryOption,\n              type=APP,\n              help_group=\"Global Options\")\n@click.option('-b',\n              '--broker',\n              envvar='BROKER_URL',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--result-backend',\n              envvar='RESULT_BACKEND',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--loader',\n              envvar='LOADER',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--config',\n              envvar='CONFIG_MODULE',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--workdir',\n              cls=CeleryOption,\n              type=pathlib.Path,\n              callback=lambda _, __, wd: os.chdir(wd) if wd else None,\n              is_eager=True,\n              help_group=\"Global Options\")\n@click.option('-C',\n              '--no-color',\n              envvar='NO_COLOR',\n              is_flag=True,\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('-q',\n              '--quiet',\n              is_flag=True,\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--version',\n              cls=CeleryOption,\n              is_flag=True,\n              help_group=\"Global Options\")\n@click.pass_context\ndef celery(ctx, app, broker, result_backend, loader, config, workdir,\n           no_color, quiet, version):\n    \"\"\"Celery command entrypoint.\"\"\"\n    if version:\n        click.echo(VERSION_BANNER)\n        ctx.exit()\n    elif ctx.invoked_subcommand is None:\n        click.echo(ctx.get_help())\n        ctx.exit()\n\n    if loader:\n        # Default app takes loader from this env (Issue #1066).\n        os.environ['CELERY_LOADER'] = loader\n    if broker:\n        os.environ['CELERY_BROKER_URL'] = broker\n    if result_backend:\n        os.environ['CELERY_RESULT_BACKEND'] = result_backend\n    if config:\n        os.environ['CELERY_CONFIG_MODULE'] = config\n    ctx.obj = CLIContext(app=app, no_color=no_color, workdir=workdir,\n                         quiet=quiet)\n\n    # User options\n    worker.params.extend(ctx.obj.app.user_options.get('worker', []))\n    beat.params.extend(ctx.obj.app.user_options.get('beat', []))\n    events.params.extend(ctx.obj.app.user_options.get('events', []))\n\n    for command in celery.commands.values():\n        command.params.extend(ctx.obj.app.user_options.get('preload', []))\n\n\n@celery.command(cls=CeleryCommand)\n@click.pass_context\ndef report(ctx):\n    \"\"\"Shows information useful to include in bug-reports.\"\"\"\n    app = ctx.obj.app\n    app.loader.import_default_modules()\n    ctx.obj.echo(app.bugreport())\n\n\ncelery.add_command(purge)\ncelery.add_command(call)\ncelery.add_command(beat)\ncelery.add_command(list_)\ncelery.add_command(result)\ncelery.add_command(migrate)\ncelery.add_command(status)\ncelery.add_command(worker)\ncelery.add_command(events)\ncelery.add_command(inspect)\ncelery.add_command(control)\ncelery.add_command(graph)\ncelery.add_command(upgrade)\ncelery.add_command(logtool)\ncelery.add_command(amqp)\ncelery.add_command(shell)\ncelery.add_command(multi)\n\n# Monkey-patch click to display a custom error\n# when -A or --app are used as sub-command options instead of as options\n# of the global command.\n\nprevious_show_implementation = click.exceptions.NoSuchOption.show\n\nWRONG_APP_OPTION_USAGE_MESSAGE = \"\"\"You are using `{option_name}` as an option of the {info_name} sub-command:\ncelery {info_name} {option_name} celeryapp <...>\n\nThe support for this usage was removed in Celery 5.0. Instead you should use `{option_name}` as a global option:\ncelery {option_name} celeryapp {info_name} <...>\"\"\"\n\n\ndef _show(self, file=None):\n    if self.option_name in ('-A', '--app'):\n        self.ctx.obj.error(\n            WRONG_APP_OPTION_USAGE_MESSAGE.format(\n                option_name=self.option_name,\n                info_name=self.ctx.info_name),\n            fg='red'\n        )\n    previous_show_implementation(self, file=file)\n\n\nclick.exceptions.NoSuchOption.show = _show\n\n\ndef main() -> int:\n    \"\"\"Start celery umbrella command.\n\n    This function is the main entrypoint for the CLI.\n\n    :return: The exit code of the CLI.\n    \"\"\"\n    return celery(auto_envvar_prefix=\"CELERY\")\n", "path": "celery/bin/celery.py"}], "after_files": [{"content": "\"\"\"Utilities related to importing modules and symbols by name.\"\"\"\nimport os\nimport sys\nimport warnings\nfrom contextlib import contextmanager\nfrom importlib import import_module, reload\n\ntry:\n    from importlib.metadata import entry_points\nexcept ImportError:\n    from importlib_metadata import entry_points\n\nfrom kombu.utils.imports import symbol_by_name\n\n#: Billiard sets this when execv is enabled.\n#: We use it to find out the name of the original ``__main__``\n#: module, so that we can properly rewrite the name of the\n#: task to be that of ``App.main``.\nMP_MAIN_FILE = os.environ.get('MP_MAIN_FILE')\n\n__all__ = (\n    'NotAPackage', 'qualname', 'instantiate', 'symbol_by_name',\n    'cwd_in_path', 'find_module', 'import_from_cwd',\n    'reload_from_cwd', 'module_file', 'gen_task_name',\n)\n\n\nclass NotAPackage(Exception):\n    \"\"\"Raised when importing a package, but it's not a package.\"\"\"\n\n\ndef qualname(obj):\n    \"\"\"Return object name.\"\"\"\n    if not hasattr(obj, '__name__') and hasattr(obj, '__class__'):\n        obj = obj.__class__\n    q = getattr(obj, '__qualname__', None)\n    if '.' not in q:\n        q = '.'.join((obj.__module__, q))\n    return q\n\n\ndef instantiate(name, *args, **kwargs):\n    \"\"\"Instantiate class by name.\n\n    See Also:\n        :func:`symbol_by_name`.\n    \"\"\"\n    return symbol_by_name(name)(*args, **kwargs)\n\n\n@contextmanager\ndef cwd_in_path():\n    \"\"\"Context adding the current working directory to sys.path.\"\"\"\n    cwd = os.getcwd()\n    if cwd in sys.path:\n        yield\n    else:\n        sys.path.insert(0, cwd)\n        try:\n            yield cwd\n        finally:\n            try:\n                sys.path.remove(cwd)\n            except ValueError:  # pragma: no cover\n                pass\n\n\ndef find_module(module, path=None, imp=None):\n    \"\"\"Version of :func:`imp.find_module` supporting dots.\"\"\"\n    if imp is None:\n        imp = import_module\n    with cwd_in_path():\n        try:\n            return imp(module)\n        except ImportError:\n            # Raise a more specific error if the problem is that one of the\n            # dot-separated segments of the module name is not a package.\n            if '.' in module:\n                parts = module.split('.')\n                for i, part in enumerate(parts[:-1]):\n                    package = '.'.join(parts[:i + 1])\n                    try:\n                        mpart = imp(package)\n                    except ImportError:\n                        # Break out and re-raise the original ImportError\n                        # instead.\n                        break\n                    try:\n                        mpart.__path__\n                    except AttributeError:\n                        raise NotAPackage(package)\n            raise\n\n\ndef import_from_cwd(module, imp=None, package=None):\n    \"\"\"Import module, temporarily including modules in the current directory.\n\n    Modules located in the current directory has\n    precedence over modules located in `sys.path`.\n    \"\"\"\n    if imp is None:\n        imp = import_module\n    with cwd_in_path():\n        return imp(module, package=package)\n\n\ndef reload_from_cwd(module, reloader=None):\n    \"\"\"Reload module (ensuring that CWD is in sys.path).\"\"\"\n    if reloader is None:\n        reloader = reload\n    with cwd_in_path():\n        return reloader(module)\n\n\ndef module_file(module):\n    \"\"\"Return the correct original file name of a module.\"\"\"\n    name = module.__file__\n    return name[:-1] if name.endswith('.pyc') else name\n\n\ndef gen_task_name(app, name, module_name):\n    \"\"\"Generate task name from name/module pair.\"\"\"\n    module_name = module_name or '__main__'\n    try:\n        module = sys.modules[module_name]\n    except KeyError:\n        # Fix for manage.py shell_plus (Issue #366)\n        module = None\n\n    if module is not None:\n        module_name = module.__name__\n        # - If the task module is used as the __main__ script\n        # - we need to rewrite the module part of the task name\n        # - to match App.main.\n        if MP_MAIN_FILE and module.__file__ == MP_MAIN_FILE:\n            # - see comment about :envvar:`MP_MAIN_FILE` above.\n            module_name = '__main__'\n    if module_name == '__main__' and app.main:\n        return '.'.join([app.main, name])\n    return '.'.join(p for p in (module_name, name) if p)\n\n\ndef load_extension_class_names(namespace):\n    if sys.version_info >= (3, 10):\n        _entry_points = entry_points(group=namespace)\n    else:\n        try:\n            _entry_points = entry_points().get(namespace, [])\n        except AttributeError:\n            _entry_points = entry_points().select(group=namespace)\n    for ep in _entry_points:\n        yield ep.name, ep.value\n\n\ndef load_extension_classes(namespace):\n    for name, class_name in load_extension_class_names(namespace):\n        try:\n            cls = symbol_by_name(class_name)\n        except (ImportError, SyntaxError) as exc:\n            warnings.warn(\n                f'Cannot load {namespace} extension {class_name!r}: {exc!r}')\n        else:\n            yield name, cls\n", "path": "celery/utils/imports.py"}, {"content": "\"\"\"Celery Command Line Interface.\"\"\"\nimport os\nimport pathlib\nimport sys\nimport traceback\n\ntry:\n    from importlib.metadata import entry_points\nexcept ImportError:\n    from importlib_metadata import entry_points\n\nimport click\nimport click.exceptions\nfrom click.types import ParamType\nfrom click_didyoumean import DYMGroup\nfrom click_plugins import with_plugins\n\nfrom celery import VERSION_BANNER\nfrom celery.app.utils import find_app\nfrom celery.bin.amqp import amqp\nfrom celery.bin.base import CeleryCommand, CeleryOption, CLIContext\nfrom celery.bin.beat import beat\nfrom celery.bin.call import call\nfrom celery.bin.control import control, inspect, status\nfrom celery.bin.events import events\nfrom celery.bin.graph import graph\nfrom celery.bin.list import list_\nfrom celery.bin.logtool import logtool\nfrom celery.bin.migrate import migrate\nfrom celery.bin.multi import multi\nfrom celery.bin.purge import purge\nfrom celery.bin.result import result\nfrom celery.bin.shell import shell\nfrom celery.bin.upgrade import upgrade\nfrom celery.bin.worker import worker\n\nUNABLE_TO_LOAD_APP_MODULE_NOT_FOUND = click.style(\"\"\"\nUnable to load celery application.\nThe module {0} was not found.\"\"\", fg='red')\n\nUNABLE_TO_LOAD_APP_ERROR_OCCURRED = click.style(\"\"\"\nUnable to load celery application.\nWhile trying to load the module {0} the following error occurred:\n{1}\"\"\", fg='red')\n\nUNABLE_TO_LOAD_APP_APP_MISSING = click.style(\"\"\"\nUnable to load celery application.\n{0}\"\"\")\n\n\nclass App(ParamType):\n    \"\"\"Application option.\"\"\"\n\n    name = \"application\"\n\n    def convert(self, value, param, ctx):\n        try:\n            return find_app(value)\n        except ModuleNotFoundError as e:\n            if e.name != value:\n                exc = traceback.format_exc()\n                self.fail(\n                    UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)\n                )\n            self.fail(UNABLE_TO_LOAD_APP_MODULE_NOT_FOUND.format(e.name))\n        except AttributeError as e:\n            attribute_name = e.args[0].capitalize()\n            self.fail(UNABLE_TO_LOAD_APP_APP_MISSING.format(attribute_name))\n        except Exception:\n            exc = traceback.format_exc()\n            self.fail(\n                UNABLE_TO_LOAD_APP_ERROR_OCCURRED.format(value, exc)\n            )\n\n\nAPP = App()\n\n\nif sys.version_info >= (3, 10):\n    _PLUGINS = entry_points(group='celery.commands')\nelse:\n    try:\n        _PLUGINS = entry_points().get('celery.commands', [])\n    except AttributeError:\n        _PLUGINS = entry_points().select(group='celery.commands')\n\n\n@with_plugins(_PLUGINS)\n@click.group(cls=DYMGroup, invoke_without_command=True)\n@click.option('-A',\n              '--app',\n              envvar='APP',\n              cls=CeleryOption,\n              type=APP,\n              help_group=\"Global Options\")\n@click.option('-b',\n              '--broker',\n              envvar='BROKER_URL',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--result-backend',\n              envvar='RESULT_BACKEND',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--loader',\n              envvar='LOADER',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--config',\n              envvar='CONFIG_MODULE',\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--workdir',\n              cls=CeleryOption,\n              type=pathlib.Path,\n              callback=lambda _, __, wd: os.chdir(wd) if wd else None,\n              is_eager=True,\n              help_group=\"Global Options\")\n@click.option('-C',\n              '--no-color',\n              envvar='NO_COLOR',\n              is_flag=True,\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('-q',\n              '--quiet',\n              is_flag=True,\n              cls=CeleryOption,\n              help_group=\"Global Options\")\n@click.option('--version',\n              cls=CeleryOption,\n              is_flag=True,\n              help_group=\"Global Options\")\n@click.pass_context\ndef celery(ctx, app, broker, result_backend, loader, config, workdir,\n           no_color, quiet, version):\n    \"\"\"Celery command entrypoint.\"\"\"\n    if version:\n        click.echo(VERSION_BANNER)\n        ctx.exit()\n    elif ctx.invoked_subcommand is None:\n        click.echo(ctx.get_help())\n        ctx.exit()\n\n    if loader:\n        # Default app takes loader from this env (Issue #1066).\n        os.environ['CELERY_LOADER'] = loader\n    if broker:\n        os.environ['CELERY_BROKER_URL'] = broker\n    if result_backend:\n        os.environ['CELERY_RESULT_BACKEND'] = result_backend\n    if config:\n        os.environ['CELERY_CONFIG_MODULE'] = config\n    ctx.obj = CLIContext(app=app, no_color=no_color, workdir=workdir,\n                         quiet=quiet)\n\n    # User options\n    worker.params.extend(ctx.obj.app.user_options.get('worker', []))\n    beat.params.extend(ctx.obj.app.user_options.get('beat', []))\n    events.params.extend(ctx.obj.app.user_options.get('events', []))\n\n    for command in celery.commands.values():\n        command.params.extend(ctx.obj.app.user_options.get('preload', []))\n\n\n@celery.command(cls=CeleryCommand)\n@click.pass_context\ndef report(ctx):\n    \"\"\"Shows information useful to include in bug-reports.\"\"\"\n    app = ctx.obj.app\n    app.loader.import_default_modules()\n    ctx.obj.echo(app.bugreport())\n\n\ncelery.add_command(purge)\ncelery.add_command(call)\ncelery.add_command(beat)\ncelery.add_command(list_)\ncelery.add_command(result)\ncelery.add_command(migrate)\ncelery.add_command(status)\ncelery.add_command(worker)\ncelery.add_command(events)\ncelery.add_command(inspect)\ncelery.add_command(control)\ncelery.add_command(graph)\ncelery.add_command(upgrade)\ncelery.add_command(logtool)\ncelery.add_command(amqp)\ncelery.add_command(shell)\ncelery.add_command(multi)\n\n# Monkey-patch click to display a custom error\n# when -A or --app are used as sub-command options instead of as options\n# of the global command.\n\nprevious_show_implementation = click.exceptions.NoSuchOption.show\n\nWRONG_APP_OPTION_USAGE_MESSAGE = \"\"\"You are using `{option_name}` as an option of the {info_name} sub-command:\ncelery {info_name} {option_name} celeryapp <...>\n\nThe support for this usage was removed in Celery 5.0. Instead you should use `{option_name}` as a global option:\ncelery {option_name} celeryapp {info_name} <...>\"\"\"\n\n\ndef _show(self, file=None):\n    if self.option_name in ('-A', '--app'):\n        self.ctx.obj.error(\n            WRONG_APP_OPTION_USAGE_MESSAGE.format(\n                option_name=self.option_name,\n                info_name=self.ctx.info_name),\n            fg='red'\n        )\n    previous_show_implementation(self, file=file)\n\n\nclick.exceptions.NoSuchOption.show = _show\n\n\ndef main() -> int:\n    \"\"\"Start celery umbrella command.\n\n    This function is the main entrypoint for the CLI.\n\n    :return: The exit code of the CLI.\n    \"\"\"\n    return celery(auto_envvar_prefix=\"CELERY\")\n", "path": "celery/bin/celery.py"}]}