404
+{% trans %}Page not found{% endtrans %}
+diff --git a/404.html b/404.html index 1c6e8fcb..2be59c8d 100644 --- a/404.html +++ b/404.html @@ -12,16 +12,19 @@ - - - + + + + + + @@ -133,14 +136,12 @@
Documentation built with MkDocs.
- - - - + +Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) +Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) +Copyright 2004 Manfred Stienstra (the original version)
+All rights reserved.
+Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met:
+THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE.
{% debug %}+ + .. code-block:: text + + {'context': {'cycler':
{{ column }} | + {%- endfor %} +
page content
') + + @tempdir(files={'testing.html': 'page content
'}) + def test_populate_page_dirty_modified(self, site_dir): + cfg = load_config(site_dir=site_dir) + file = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + page = Page('Foo', file, cfg) + build._populate_page(page, cfg, Files([file]), dirty=True) + self.assertTrue(page.markdown.startswith('# Welcome to MkDocs')) + self.assertTrue( + page.content.startswith('page content
'}) + def test_populate_page_dirty_not_modified(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + file = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + page = Page('Foo', file, cfg) + build._populate_page(page, cfg, Files([file]), dirty=True) + # Content is empty as file read was skipped + self.assertEqual(page.markdown, None) + self.assertEqual(page.content, None) + + @tempdir(files={'index.md': 'new page content'}) + @mock.patch('mkdocs.structure.pages.open', side_effect=OSError('Error message.')) + def test_populate_page_read_error(self, docs_dir, mock_open): + cfg = load_config(docs_dir=docs_dir) + file = File('missing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + page = Page('Foo', file, cfg) + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(OSError): + build._populate_page(page, cfg, Files([file])) + self.assertEqual( + cm.output, + [ + 'ERROR:mkdocs.structure.pages:File not found: missing.md', + "ERROR:mkdocs.commands.build:Error reading page 'missing.md': Error message.", + ], + ) + mock_open.assert_called_once() + + @tempdir(files={'index.md': 'page content'}) + @mock.patch( + 'mkdocs.plugins.PluginCollection.run_event', side_effect=PluginError('Error message.') + ) + def test_populate_page_read_plugin_error(self, docs_dir, mock_open): + cfg = load_config(docs_dir=docs_dir) + file = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + page = Page('Foo', file, cfg) + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(PluginError): + build._populate_page(page, cfg, Files([file])) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error reading page 'index.md':", + ) + mock_open.assert_called_once() + + # Test build._build_page + + @tempdir() + def test_build_page(self, site_dir): + cfg = load_config(site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = 'page content
' + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertPathIsFile(site_dir, 'index.html') + + @tempdir() + @mock.patch('jinja2.environment.Template.render', return_value='') + def test_build_page_empty(self, site_dir, render_mock): + cfg = load_config(site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + with self.assertLogs('mkdocs') as cm: + build._build_page( + files.documentation_pages()[0].page, cfg, files, nav, cfg['theme'].get_env() + ) + self.assertEqual( + '\n'.join(cm.output), + "INFO:mkdocs.commands.build:Page skipped: 'index.md'. Generated empty output.", + ) + self.assertPathNotFile(site_dir, 'index.html') + render_mock.assert_called_once() + + @tempdir(files={'index.md': 'page content'}) + @tempdir(files={'index.html': 'page content
'}) + @mock.patch('mkdocs.utils.write_file') + def test_build_page_dirty_modified(self, site_dir, docs_dir, mock_write_file): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'new page content' + page.content = 'new page content
' + build._build_page( + page, cfg, files, nav, self._get_env_with_null_translations(cfg), dirty=True + ) + mock_write_file.assert_not_called() + + @tempdir(files={'testing.html': 'page content
'}) + @mock.patch('mkdocs.utils.write_file') + def test_build_page_dirty_not_modified(self, site_dir, mock_write_file): + cfg = load_config(site_dir=site_dir, nav=['testing.md'], plugins=[]) + fs = [File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = 'page content
' + build._build_page( + page, cfg, files, nav, self._get_env_with_null_translations(cfg), dirty=True + ) + mock_write_file.assert_called_once() + + @tempdir() + def test_build_page_custom_template(self, site_dir): + cfg = load_config(site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.meta = {'template': '404.html'} + page.markdown = 'page content' + page.content = 'page content
' + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertPathIsFile(site_dir, 'index.html') + + @tempdir() + @mock.patch('mkdocs.utils.write_file', side_effect=OSError('Error message.')) + def test_build_page_error(self, site_dir, mock_write_file): + cfg = load_config(site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = 'page content
' + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(OSError): + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error building page 'index.md': Error message.", + ) + mock_write_file.assert_called_once() + + @tempdir() + @mock.patch( + 'mkdocs.plugins.PluginCollection.run_event', side_effect=PluginError('Error message.') + ) + def test_build_page_plugin_error(self, site_dir, mock_write_file): + cfg = load_config(site_dir=site_dir, nav=['index.md'], plugins=[]) + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = 'page content
' + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(PluginError): + build._build_page(page, cfg, files, nav, cfg['theme'].get_env()) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error building page 'index.md':", + ) + mock_write_file.assert_called_once() + + # Test build.build + + @tempdir( + files={ + 'index.md': 'page content', + 'empty.md': '', + 'img.jpg': '', + 'static.html': 'content', + '.hidden': 'content', + '.git/hidden': 'content', + } + ) + @tempdir() + def test_copying_media(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + build.build(cfg) + + # Verify that only non-empty md file (converted to html), static HTML file and image are copied. + self.assertPathIsFile(site_dir, 'index.html') + self.assertPathIsFile(site_dir, 'img.jpg') + self.assertPathIsFile(site_dir, 'static.html') + self.assertPathNotExists(site_dir, 'empty.md') + self.assertPathNotExists(site_dir, '.hidden') + self.assertPathNotExists(site_dir, '.git/hidden') + + @tempdir(files={'index.md': 'page content'}) + @tempdir() + def test_copy_theme_files(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + build.build(cfg) + + # Verify only theme media are copied, not templates, Python or localization files. + self.assertPathIsFile(site_dir, 'index.html') + self.assertPathIsFile(site_dir, '404.html') + self.assertPathIsDir(site_dir, 'js') + self.assertPathIsDir(site_dir, 'css') + self.assertPathIsDir(site_dir, 'img') + self.assertPathIsDir(site_dir, 'fonts') + self.assertPathNotExists(site_dir, '__init__.py') + self.assertPathNotExists(site_dir, '__init__.pyc') + self.assertPathNotExists(site_dir, 'base.html') + self.assertPathNotExists(site_dir, 'content.html') + self.assertPathNotExists(site_dir, 'main.html') + self.assertPathNotExists(site_dir, 'locales') + + # Test build.site_directory_contains_stale_files + + @tempdir(files=['index.html']) + def test_site_dir_contains_stale_files(self, site_dir): + self.assertTrue(build.site_directory_contains_stale_files(site_dir)) + + @tempdir() + def test_not_site_dir_contains_stale_files(self, site_dir): + self.assertFalse(build.site_directory_contains_stale_files(site_dir)) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/cli_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/cli_tests.py new file mode 100644 index 00000000..67c40d64 --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/cli_tests.py @@ -0,0 +1,626 @@ +#!/usr/bin/env python + +import io +import logging +import unittest +from unittest import mock + +from click.testing import CliRunner + +from mkdocs import __main__ as cli + + +class CLITests(unittest.TestCase): + def setUp(self): + self.runner = CliRunner() + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_default(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve"], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_config_file(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", "--config-file", "mkdocs.yml"], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_serve.call_count, 1) + args, kwargs = mock_serve.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_dev_addr(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--dev-addr', '0.0.0.0:80'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr='0.0.0.0:80', + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_strict(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_theme(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_use_directory_urls(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_no_directory_urls(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_livereload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--livereload'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_no_livereload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--no-livereload'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='no-livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_dirtyreload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--dirtyreload'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='dirty', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_watch_theme(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--watch-theme'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload='livereload', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=True, + watch=(), + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_defaults(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.INFO) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_clean(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--clean'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_dirty(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--dirty'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertTrue(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_config_file(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--config-file', 'mkdocs.yml'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + args, kwargs = mock_load_config.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_strict(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_theme(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_use_directory_urls(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_no_directory_urls(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_site_dir(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--site-dir', 'custom'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir='custom', + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_verbose(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--verbose'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.DEBUG) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_quiet(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--quiet'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.ERROR) + + @mock.patch('mkdocs.commands.new.new', autospec=True) + def test_new(self, mock_new): + result = self.runner.invoke(cli.cli, ["new", "project"], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_new.assert_called_once_with('project') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_defaults(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('message' in g_kwargs) + self.assertEqual(g_kwargs['message'], None) + self.assertTrue('force' in g_kwargs) + self.assertEqual(g_kwargs['force'], False) + self.assertTrue('ignore_version' in g_kwargs) + self.assertEqual(g_kwargs['ignore_version'], False) + self.assertEqual(mock_build.call_count, 1) + b_args, b_kwargs = mock_build.call_args + self.assertTrue('dirty' in b_kwargs) + self.assertFalse(b_kwargs['dirty']) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_clean(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--clean'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_dirty(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--dirty'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertTrue(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_config_file(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--config-file', 'mkdocs.yml'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + args, kwargs = mock_load_config.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_message(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--message', 'A commit message'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('message' in g_kwargs) + self.assertEqual(g_kwargs['message'], 'A commit message') + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_remote_branch(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--remote-branch', 'foo'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch='foo', + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_remote_name(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--remote-name', 'foo'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name='foo', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_force(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--force'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('force' in g_kwargs) + self.assertEqual(g_kwargs['force'], True) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_ignore_version(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--ignore-version'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('ignore_version' in g_kwargs) + self.assertEqual(g_kwargs['ignore_version'], True) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_strict(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_theme(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_use_directory_urls(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_no_directory_urls(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_site_dir(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--site-dir', 'custom'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir='custom', + ) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__init__.py b/web/lib/python3.11/site-packages/mkdocs/tests/config/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..ac2bd157 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-311.pyc new file mode 100644 index 00000000..4de0523a Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-311.pyc new file mode 100644 index 00000000..73a3de27 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-311.pyc new file mode 100644 index 00000000..9d323eb1 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-311.pyc new file mode 100644 index 00000000..19014694 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/base_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/config/base_tests.py new file mode 100644 index 00000000..1a2a85a3 --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/config/base_tests.py @@ -0,0 +1,284 @@ +import os +import unittest + +from mkdocs import exceptions +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.config import defaults +from mkdocs.config.base import ValidationError +from mkdocs.tests.base import change_dir, tempdir + + +class ConfigBaseTests(unittest.TestCase): + def test_unrecognised_keys(self): + conf = defaults.MkDocsConfig() + conf.load_dict( + { + 'not_a_valid_config_option': "test", + } + ) + + failed, warnings = conf.validate() + + self.assertEqual( + warnings, + [ + ( + 'not_a_valid_config_option', + 'Unrecognised configuration name: not_a_valid_config_option', + ) + ], + ) + + def test_missing_required(self): + conf = defaults.MkDocsConfig() + + errors, warnings = conf.validate() + + self.assertEqual( + errors, [('site_name', ValidationError('Required configuration not provided.'))] + ) + self.assertEqual(warnings, []) + + @tempdir() + def test_load_from_file(self, temp_dir): + """ + Users can explicitly set the config file using the '--config' option. + Allows users to specify a config other than the default `mkdocs.yml`. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + cfg = base.load_config(config_file=config_file.name) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + + @tempdir() + def test_load_default_file(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + + @tempdir + def test_load_default_file_with_yaml(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yaml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + + @tempdir() + def test_load_default_file_prefer_yml(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file1: + config_file1.write("site_name: MkDocs Test1\n") + with open(os.path.join(temp_dir, 'mkdocs.yaml'), 'w') as config_file2: + config_file2.write("site_name: MkDocs Test2\n") + + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test1') + + def test_load_from_missing_file(self): + with self.assertRaisesRegex( + exceptions.ConfigurationError, "Config file 'missing_file.yml' does not exist." + ): + base.load_config(config_file='missing_file.yml') + + @tempdir() + def test_load_from_open_file(self, temp_path): + """ + `load_config` can accept an open file descriptor. + """ + config_fname = os.path.join(temp_path, 'mkdocs.yml') + config_file = open(config_fname, 'w+') + config_file.write("site_name: MkDocs Test\n") + config_file.flush() + os.mkdir(os.path.join(temp_path, 'docs')) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + # load_config will always close the file + self.assertTrue(config_file.closed) + + @tempdir() + def test_load_from_closed_file(self, temp_dir): + """ + The `serve` command with auto-reload may pass in a closed file descriptor. + Ensure `load_config` reloads the closed file. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + + @tempdir + def test_load_missing_required(self, temp_dir): + """ + `site_name` is a required setting. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_dir: output\nsite_url: https://www.mkdocs.org\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(exceptions.Abort): + base.load_config(config_file=config_file.name) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.config:Config value 'site_name': Required configuration not provided.", + ) + + def test_pre_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + raise ValidationError('pre_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('pre_validation error'))]) + self.assertEqual(warnings, []) + + def test_run_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def run_validation(self, value): + raise ValidationError('run_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('run_validation error'))]) + self.assertEqual(warnings, []) + + def test_post_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def post_validation(self, config, key_name): + raise ValidationError('post_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('post_validation error'))]) + self.assertEqual(warnings, []) + + def test_pre_and_run_validation_errors(self): + """A pre_validation error does not stop run_validation from running.""" + + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + raise ValidationError('pre_validation error') + + def run_validation(self, value): + raise ValidationError('run_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual( + errors, + [ + ('invalid_option', ValidationError('pre_validation error')), + ('invalid_option', ValidationError('run_validation error')), + ], + ) + self.assertEqual(warnings, []) + + def test_run_and_post_validation_errors(self): + """A run_validation error stops post_validation from running.""" + + class InvalidConfigOption(c.BaseConfigOption): + def run_validation(self, value): + raise ValidationError('run_validation error') + + def post_validation(self, config, key_name): + raise ValidationError('post_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('run_validation error'))]) + self.assertEqual(warnings, []) + + def test_validation_warnings(self): + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + self.warnings.append('pre_validation warning') + + def run_validation(self, value): + self.warnings.append('run_validation warning') + + def post_validation(self, config, key_name): + self.warnings.append('post_validation warning') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, []) + self.assertEqual( + warnings, + [ + ('invalid_option', 'pre_validation warning'), + ('invalid_option', 'run_validation warning'), + ('invalid_option', 'post_validation warning'), + ], + ) + + @tempdir() + def test_load_from_file_with_relative_paths(self, config_dir): + """ + When explicitly setting a config file, paths should be relative to the + config file, not the working directory. + """ + config_fname = os.path.join(config_dir, 'mkdocs.yml') + with open(config_fname, 'w') as config_file: + config_file.write("docs_dir: src\nsite_name: MkDocs Test\n") + docs_dir = os.path.join(config_dir, 'src') + os.mkdir(docs_dir) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg['site_name'], 'MkDocs Test') + self.assertEqual(cfg['docs_dir'], docs_dir) + self.assertEqual(cfg.config_file_path, config_fname) + self.assertIsInstance(cfg.config_file_path, str) + + def test_get_schema(self): + class FooConfig: + z = c.URL() + aa = c.Type(int) + + self.assertEqual( + base.get_schema(FooConfig), + ( + ('z', FooConfig.z), + ('aa', FooConfig.aa), + ), + ) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/config/config_options_legacy_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/config/config_options_legacy_tests.py new file mode 100644 index 00000000..9b07e5bc --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/config/config_options_legacy_tests.py @@ -0,0 +1,1638 @@ +import contextlib +import copy +import io +import os +import re +import sys +import textwrap +import unittest +from typing import Any, Dict +from unittest.mock import patch + +import mkdocs +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.tests.base import tempdir +from mkdocs.utils import write_file, yaml_load + + +class UnexpectedError(Exception): + pass + + +class TestCase(unittest.TestCase): + @contextlib.contextmanager + def expect_error(self, **kwargs): + [(key, msg)] = kwargs.items() + with self.assertRaises(UnexpectedError) as cm: + yield + if isinstance(msg, re.Pattern): + self.assertRegex(str(cm.exception), f'^{key}="{msg.pattern}"$') + else: + self.assertEqual(f'{key}="{msg}"', str(cm.exception)) + + def get_config( + self, + schema: type, + cfg: Dict[str, Any], + warnings: Dict[str, str] = {}, + config_file_path=None, + ): + config = base.LegacyConfig(base.get_schema(schema), config_file_path=config_file_path) + config.load_dict(cfg) + actual_errors, actual_warnings = config.validate() + if actual_errors: + raise UnexpectedError(', '.join(f'{key}="{msg}"' for key, msg in actual_errors)) + self.assertEqual(warnings, dict(actual_warnings)) + return config + + +class OptionallyRequiredTest(TestCase): + def test_empty(self): + class Schema: + option = c.OptionallyRequired() + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], None) + + self.assertEqual(Schema.option.required, False) + + def test_required(self): + class Schema: + option = c.OptionallyRequired(required=True) + + with self.expect_error(option="Required configuration not provided."): + self.get_config(Schema, {'option': None}) + + self.assertEqual(Schema.option.required, True) + + def test_required_no_default(self): + class Schema: + option = c.OptionallyRequired(required=True) + + conf = self.get_config(Schema, {'option': 2}) + self.assertEqual(conf['option'], 2) + + def test_default(self): + class Schema: + option = c.OptionallyRequired(default=1) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], 1) + + def test_replace_default(self): + class Schema: + option = c.OptionallyRequired(default=1) + + conf = self.get_config(Schema, {'option': 2}) + self.assertEqual(conf['option'], 2) + + +class TypeTest(TestCase): + def test_single_type(self): + class Schema: + option = c.Type(str) + + conf = self.get_config(Schema, {'option': "Testing"}) + self.assertEqual(conf['option'], "Testing") + + def test_multiple_types(self): + class Schema: + option = c.Type((list, tuple)) + + conf = self.get_config(Schema, {'option': [1, 2, 3]}) + self.assertEqual(conf['option'], [1, 2, 3]) + + conf = self.get_config(Schema, {'option': (1, 2, 3)}) + self.assertEqual(conf['option'], (1, 2, 3)) + + with self.expect_error( + option="Expected type: (hi", + "empty.html": "", + "multi_body.html": "
foobar", + } + ) + def test_serves_modified_html(self, site_dir): + with testing_server(site_dir) as server: + server.watch(site_dir) + + headers, output = do_request(server, "GET /normal.html") + self.assertRegex(output, fr"^hello{SCRIPT_REGEX}$") + self.assertEqual(headers.get("content-type"), "text/html") + self.assertEqual(headers.get("content-length"), str(len(output))) + + _, output = do_request(server, "GET /no_body.html") + self.assertRegex(output, fr"^hi{SCRIPT_REGEX}$") + + headers, output = do_request(server, "GET /empty.html") + self.assertRegex(output, fr"^{SCRIPT_REGEX}$") + self.assertEqual(headers.get("content-length"), str(len(output))) + + _, output = do_request(server, "GET /multi_body.html") + self.assertRegex(output, fr"^
foobar{SCRIPT_REGEX}$") + + @tempdir({"index.html": "aaa", "foo/index.html": "bbb"}) + def test_serves_directory_index(self, site_dir): + with testing_server(site_dir) as server: + headers, output = do_request(server, "GET /") + self.assertRegex(output, r"^aaa$") + self.assertEqual(headers["_status"], "200 OK") + self.assertEqual(headers.get("content-type"), "text/html") + self.assertEqual(headers.get("content-length"), str(len(output))) + + for path in "/foo/", "/foo/index.html": + _, output = do_request(server, "GET /foo/") + self.assertRegex(output, r"^bbb$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /foo/index.html/") + self.assertEqual(headers["_status"], "404 Not Found") + + @tempdir( + { + "foo/bar/index.html": "aaa", + "foo/測試/index.html": "bbb", + } + ) + def test_redirects_to_directory(self, site_dir): + with testing_server(site_dir, mount_path="/sub") as server: + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/bar") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/bar/") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/測試") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/%E6%B8%AC%E8%A9%A6/") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/%E6%B8%AC%E8%A9%A6") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/%E6%B8%AC%E8%A9%A6/") + + @tempdir({"я.html": "aaa", "测试2/index.html": "bbb"}) + def test_serves_with_unicode_characters(self, site_dir): + with testing_server(site_dir) as server: + _, output = do_request(server, "GET /я.html") + self.assertRegex(output, r"^aaa$") + _, output = do_request(server, "GET /%D1%8F.html") + self.assertRegex(output, r"^aaa$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /%D1.html") + self.assertEqual(headers["_status"], "404 Not Found") + + _, output = do_request(server, "GET /测试2/") + self.assertRegex(output, r"^bbb$") + _, output = do_request(server, "GET /%E6%B5%8B%E8%AF%952/index.html") + self.assertRegex(output, r"^bbb$") + + @tempdir() + def test_serves_polling_instantly(self, site_dir): + with testing_server(site_dir) as server: + _, output = do_request(server, "GET /livereload/0/0") + self.assertTrue(output.isdigit()) + + @tempdir() + def test_serves_polling_with_mount_path(self, site_dir): + with testing_server(site_dir, mount_path="/test/f*o") as server: + _, output = do_request(server, "GET /livereload/0/0") + self.assertTrue(output.isdigit()) + + @tempdir() + @tempdir() + def test_serves_polling_after_event(self, site_dir, docs_dir): + with testing_server(site_dir) as server: + initial_epoch = server._visible_epoch + + server.watch(docs_dir) + time.sleep(0.01) + + Path(docs_dir, "foo.docs").write_text("b") + + _, output = do_request(server, f"GET /livereload/{initial_epoch}/0") + + self.assertNotEqual(server._visible_epoch, initial_epoch) + self.assertEqual(output, str(server._visible_epoch)) + + @tempdir() + def test_serves_polling_with_timeout(self, site_dir): + with testing_server(site_dir) as server: + server.poll_response_timeout = 0.2 + initial_epoch = server._visible_epoch + + start_time = time.monotonic() + _, output = do_request(server, f"GET /livereload/{initial_epoch}/0") + self.assertGreaterEqual(time.monotonic(), start_time + 0.2) + self.assertEqual(output, str(initial_epoch)) + + @tempdir() + def test_error_handler(self, site_dir): + with testing_server(site_dir) as server: + server.error_handler = lambda code: b"[%d]" % code + with self.assertLogs("mkdocs.livereload") as cm: + headers, output = do_request(server, "GET /missing") + + self.assertEqual(headers["_status"], "404 Not Found") + self.assertEqual(output, "[404]") + self.assertRegex( + "\n".join(cm.output), + r'^WARNING:mkdocs.livereload:.*"GET /missing HTTP/1.1" code 404', + ) + + @tempdir() + def test_bad_error_handler(self, site_dir): + self.maxDiff = None + with testing_server(site_dir) as server: + server.error_handler = lambda code: 0 / 0 + with self.assertLogs("mkdocs.livereload") as cm: + headers, output = do_request(server, "GET /missing") + + self.assertEqual(headers["_status"], "404 Not Found") + self.assertIn("404", output) + self.assertRegex( + "\n".join(cm.output), r"Failed to render an error message[\s\S]+/missing.+code 404" + ) + + @tempdir( + { + "test.html": "\nhi", + "test.xml": '\nContent
") + + self.assertEqual(stripper.stripped_html, "Testing\nContent") + + def test_content_parser(self): + parser = search_index.ContentParser() + + parser.feed('Content 1
+Content 2
+Content 3
+ """ + + base_cfg = load_config() + pages = [ + Page( + 'Home', + File( + 'index.md', + base_cfg['docs_dir'], + base_cfg['site_dir'], + base_cfg['use_directory_urls'], + ), + base_cfg, + ), + Page( + 'About', + File( + 'about.md', + base_cfg['docs_dir'], + base_cfg['site_dir'], + base_cfg['use_directory_urls'], + ), + base_cfg, + ), + ] + + md = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + + full_content = ''.join(f"Heading{i}Content{i}" for i in range(1, 4)) + + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({}) + + for page in pages: + # Fake page.read_source() and page.render() + page.markdown = md + page.toc = toc + page.content = html_content + + index = search_index.SearchIndex(**plugin.config) + index.add_entry_from_context(page) + + self.assertEqual(len(index._entries), 4) + + loc = page.url + + self.assertEqual(index._entries[0]['title'], page.title) + self.assertEqual(strip_whitespace(index._entries[0]['text']), full_content) + self.assertEqual(index._entries[0]['location'], loc) + + self.assertEqual(index._entries[1]['title'], "Heading 1") + self.assertEqual(index._entries[1]['text'], "Content 1") + self.assertEqual(index._entries[1]['location'], f"{loc}#heading-1") + + self.assertEqual(index._entries[2]['title'], "Heading 2") + self.assertEqual(strip_whitespace(index._entries[2]['text']), "Content2") + self.assertEqual(index._entries[2]['location'], f"{loc}#heading-2") + + self.assertEqual(index._entries[3]['title'], "Heading 3") + self.assertEqual(strip_whitespace(index._entries[3]['text']), "Content3") + self.assertEqual(index._entries[3]['location'], f"{loc}#heading-3") + + def test_search_indexing_options(self): + def test_page(title, filename, config): + test_page = Page( + title, + File(filename, config.docs_dir, config.site_dir, config.use_directory_urls), + config, + ) + test_page.content = """ +Content 1
+Content 2
+Content 3
""" + test_page.markdown = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3""" + ) + test_page.toc = get_toc(get_markdown_toc(test_page.markdown)) + return test_page + + def validate_full(data, page): + self.assertEqual(len(data), 4) + for x in data: + self.assertTrue(x['title']) + self.assertTrue(x['text']) + + def validate_sections(data, page): + # Sanity + self.assertEqual(len(data), 4) + # Page + self.assertEqual(data[0]['title'], page.title) + self.assertFalse(data[0]['text']) + # Headings + for x in data[1:]: + self.assertTrue(x['title']) + self.assertFalse(x['text']) + + def validate_titles(data, page): + # Sanity + self.assertEqual(len(data), 1) + for x in data: + self.assertFalse(x['text']) + + for option, validate in { + 'full': validate_full, + 'sections': validate_sections, + 'titles': validate_titles, + }.items(): + with self.subTest(option): + plugin = search.SearchPlugin() + + # Load plugin config, overriding indexing for test case + errors, warnings = plugin.load_config({'indexing': option}) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + base_cfg = load_config() + base_cfg['plugins']['search'].config.indexing = option + + pages = [ + test_page('Home', 'index.md', base_cfg), + test_page('About', 'about.md', base_cfg), + ] + + for page in pages: + index = search_index.SearchIndex(**plugin.config) + index.add_entry_from_context(page) + data = index.generate_search_index() + validate(json.loads(data)['docs'], page) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_returns_error(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('', 'Some Error') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: Some Error', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_raises_ioerror(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.side_effect = OSError + mock_popen_obj.returncode = 1 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True, side_effect=OSError) + def test_prebuild_index_raises_oserror(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('foo', 'bar') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 0) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_false(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('', '') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=False) + expected = { + 'docs': [], + 'config': {'prebuild_index': False}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 0) + self.assertEqual(mock_popen_obj.communicate.call_count, 0) + self.assertEqual(result, expected) + + @unittest.skipUnless(search_index.haslunrpy, 'lunr.py is not installed') + @mock.patch('mkdocs.contrib.search.search_index.lunr', autospec=True) + def test_prebuild_index_python(self, mock_lunr): + mock_lunr.return_value.serialize.return_value = {'mock': 'index'} + index = search_index.SearchIndex(prebuild_index='python', lang='en') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'python', 'lang': 'en'}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_lunr.call_count, 1) + self.assertEqual(result, expected) + + @unittest.skipIf(search_index.haslunrpy, 'lunr.py is installed') + def test_prebuild_index_python_missing_lunr(self): + # When the lunr.py dependencies are not installed no prebuilt index is created. + index = search_index.SearchIndex(prebuild_index='python', lang='en') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'python', 'lang': 'en'}, + } + with self.assertLogs('mkdocs', level='WARNING'): + result = json.loads(index.generate_search_index()) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_node(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index='node') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'node'}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__init__.py b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..10c428ec Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-311.pyc new file mode 100644 index 00000000..66da1675 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-311.pyc new file mode 100644 index 00000000..6516d3e0 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-311.pyc new file mode 100644 index 00000000..2a4848d5 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-311.pyc new file mode 100644 index 00000000..dfb213c7 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/file_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/structure/file_tests.py new file mode 100644 index 00000000..8d8257f0 --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/structure/file_tests.py @@ -0,0 +1,754 @@ +import os +import sys +import unittest +from unittest import mock + +from mkdocs.structure.files import File, Files, _filter_paths, _sort_files, get_files +from mkdocs.tests.base import PathAssertionMixin, load_config, tempdir + + +class TestFiles(PathAssertionMixin, unittest.TestCase): + def test_file_eq(self): + file = File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertTrue( + file == File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + ) + + def test_file_ne(self): + file = File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + # Different filename + self.assertTrue( + file != File('b.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + ) + # Different src_path + self.assertTrue( + file != File('a.md', '/path/to/other', '/path/to/site', use_directory_urls=False) + ) + # Different URL + self.assertTrue( + file != File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + ) + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_src_path_windows(self): + f = File('foo\\a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/a.md') + self.assertEqual(f.src_path, 'foo\\a.md') + f.src_uri = 'foo/b.md' + self.assertEqual(f.src_uri, 'foo/b.md') + self.assertEqual(f.src_path, 'foo\\b.md') + f.src_path = 'foo/c.md' + self.assertEqual(f.src_uri, 'foo/c.md') + self.assertEqual(f.src_path, 'foo\\c.md') + f.src_path = 'foo\\d.md' + self.assertEqual(f.src_uri, 'foo/d.md') + self.assertEqual(f.src_path, 'foo\\d.md') + f.src_uri = 'foo\\e.md' + self.assertEqual(f.src_uri, 'foo\\e.md') + self.assertEqual(f.src_path, 'foo\\e.md') + + def test_sort_files(self): + self.assertEqual( + _sort_files(['b.md', 'bb.md', 'a.md', 'index.md', 'aa.md']), + ['index.md', 'a.md', 'aa.md', 'b.md', 'bb.md'], + ) + + self.assertEqual( + _sort_files(['b.md', 'index.html', 'a.md', 'index.md']), + ['index.html', 'index.md', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['a.md', 'index.md', 'b.md', 'index.html']), + ['index.md', 'index.html', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['.md', '_.md', 'a.md', 'index.md', '1.md']), + ['index.md', '.md', '1.md', '_.md', 'a.md'], + ) + + self.assertEqual( + _sort_files(['a.md', 'b.md', 'a.md']), + ['a.md', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['A.md', 'B.md', 'README.md']), + ['README.md', 'A.md', 'B.md'], + ) + + def test_md_file(self): + f = File('foo.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo.md') + self.assertEqual(f.dest_uri, 'foo.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo.html') + self.assertEqual(f.url, 'foo.html') + self.assertEqual(f.name, 'foo') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_use_directory_urls(self): + f = File('foo.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/') + self.assertEqual(f.name, 'foo') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_nested(self): + f = File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.md') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_nested_use_directory_urls(self): + f = File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.md') + self.assertEqual(f.dest_uri, 'foo/bar/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar/index.html') + self.assertEqual(f.url, 'foo/bar/') + self.assertEqual(f.name, 'bar') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file(self): + f = File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/index.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, 'index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_readme_index_file(self): + f = File('README.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'README.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/README.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, 'index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_use_directory_urls(self): + f = File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/index.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, './') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_readme_index_file_use_directory_urls(self): + f = File('README.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'README.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/README.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, './') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_nested(self): + f = File('foo/index.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/index.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_nested_use_directory_urls(self): + f = File('foo/index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/index.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_static_file(self): + f = File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.html') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertTrue(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_static_file_use_directory_urls(self): + f = File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.html') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertTrue(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_media_file(self): + f = File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.jpg') + self.assertEqual(f.dest_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.jpg') + self.assertEqual(f.url, 'foo/bar.jpg') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_media_file_use_directory_urls(self): + f = File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.jpg') + self.assertEqual(f.dest_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.jpg') + self.assertEqual(f.url, 'foo/bar.jpg') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_javascript_file(self): + f = File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.js') + self.assertEqual(f.dest_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.js') + self.assertEqual(f.url, 'foo/bar.js') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertTrue(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_javascript_file_use_directory_urls(self): + f = File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.js') + self.assertEqual(f.dest_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.js') + self.assertEqual(f.url, 'foo/bar.js') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertTrue(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_css_file(self): + f = File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.css') + self.assertEqual(f.dest_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.css') + self.assertEqual(f.url, 'foo/bar.css') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertTrue(f.is_css()) + + def test_css_file_use_directory_urls(self): + f = File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.css') + self.assertEqual(f.dest_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.css') + self.assertEqual(f.url, 'foo/bar.css') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertTrue(f.is_css()) + + def test_file_name_with_space(self): + f = File('foo bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo bar.md') + self.assertEqual(f.dest_uri, 'foo bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo bar.html') + self.assertEqual(f.url, 'foo%20bar.html') + self.assertEqual(f.name, 'foo bar') + + def test_files(self): + fs = [ + File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True), + ] + files = Files(fs) + self.assertEqual([f for f in files], fs) + self.assertEqual(len(files), 6) + self.assertEqual(files.documentation_pages(), [fs[0], fs[1]]) + self.assertEqual(files.static_pages(), [fs[2]]) + self.assertEqual(files.media_files(), [fs[3], fs[4], fs[5]]) + self.assertEqual(files.javascript_files(), [fs[4]]) + self.assertEqual(files.css_files(), [fs[5]]) + self.assertEqual(files.get_file_from_path('foo/bar.jpg'), fs[3]) + self.assertEqual(files.get_file_from_path('foo/bar.jpg'), fs[3]) + self.assertEqual(files.get_file_from_path('missing.jpg'), None) + self.assertTrue(fs[2].src_uri in files.src_uris) + self.assertTrue(fs[2].src_uri in files.src_uris) + extra_file = File('extra.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertFalse(extra_file.src_uri in files.src_uris) + files.append(extra_file) + self.assertEqual(len(files), 7) + self.assertTrue(extra_file.src_uri in files.src_uris) + self.assertEqual(files.documentation_pages(), [fs[0], fs[1], extra_file]) + + @tempdir( + files=[ + 'favicon.ico', + 'index.md', + ] + ) + @tempdir( + files=[ + 'base.html', + 'favicon.ico', + 'style.css', + 'foo.md', + 'README', + '.ignore.txt', + '.ignore/file.txt', + 'foo/.ignore.txt', + 'foo/.ignore/file.txt', + ] + ) + def test_add_files_from_theme(self, tdir, ddir): + config = load_config(docs_dir=ddir, theme={'name': None, 'custom_dir': tdir}) + env = config.theme.get_env() + files = get_files(config) + self.assertEqual( + [file.src_path for file in files], + ['index.md', 'favicon.ico'], + ) + files.add_files_from_theme(env, config) + self.assertEqual( + [file.src_path for file in files], + ['index.md', 'favicon.ico', 'style.css'], + ) + # Ensure theme file does not override docs_dir file + self.assertEqual( + files.get_file_from_path('favicon.ico').abs_src_path, + os.path.normpath(os.path.join(ddir, 'favicon.ico')), + ) + + def test_filter_paths(self): + # Root level file + self.assertFalse(_filter_paths('foo.md', 'foo.md', False, ['bar.md'])) + self.assertTrue(_filter_paths('foo.md', 'foo.md', False, ['foo.md'])) + + # Nested file + self.assertFalse(_filter_paths('foo.md', 'baz/foo.md', False, ['bar.md'])) + self.assertTrue(_filter_paths('foo.md', 'baz/foo.md', False, ['foo.md'])) + + # Wildcard + self.assertFalse(_filter_paths('foo.md', 'foo.md', False, ['*.txt'])) + self.assertTrue(_filter_paths('foo.md', 'foo.md', False, ['*.md'])) + + # Root level dir + self.assertFalse(_filter_paths('bar', 'bar', True, ['/baz'])) + self.assertFalse(_filter_paths('bar', 'bar', True, ['/baz/'])) + self.assertTrue(_filter_paths('bar', 'bar', True, ['/bar'])) + self.assertTrue(_filter_paths('bar', 'bar', True, ['/bar/'])) + + # Nested dir + self.assertFalse(_filter_paths('bar', 'foo/bar', True, ['/bar'])) + self.assertFalse(_filter_paths('bar', 'foo/bar', True, ['/bar/'])) + self.assertTrue(_filter_paths('bar', 'foo/bar', True, ['bar/'])) + + # Files that look like dirs (no extension). Note that `is_dir` is `False`. + self.assertFalse(_filter_paths('bar', 'bar', False, ['bar/'])) + self.assertFalse(_filter_paths('bar', 'foo/bar', False, ['bar/'])) + + def test_get_relative_url_use_directory_urls(self): + to_files = [ + 'index.md', + 'foo/index.md', + 'foo/bar/index.md', + 'foo/bar/baz/index.md', + 'foo.md', + 'foo/bar.md', + 'foo/bar/baz.md', + ] + + to_file_urls = [ + './', + 'foo/', + 'foo/bar/', + 'foo/bar/baz/', + 'foo/', + 'foo/bar/', + 'foo/bar/baz/', + ] + + from_file = File('img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + expected = [ + 'img.jpg', # img.jpg relative to . + '../img.jpg', # img.jpg relative to foo/ + '../../img.jpg', # img.jpg relative to foo/bar/ + '../../../img.jpg', # img.jpg relative to foo/bar/baz/ + '../img.jpg', # img.jpg relative to foo + '../../img.jpg', # img.jpg relative to foo/bar + '../../../img.jpg', # img.jpg relative to foo/bar/baz + ] + + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'img.jpg') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('foo/img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + expected = [ + 'foo/img.jpg', # foo/img.jpg relative to . + 'img.jpg', # foo/img.jpg relative to foo/ + '../img.jpg', # foo/img.jpg relative to foo/bar/ + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz/ + 'img.jpg', # foo/img.jpg relative to foo + '../img.jpg', # foo/img.jpg relative to foo/bar + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz + ] + + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'foo/img.jpg') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('index.html', '/path/to/docs', '/path/to/site', use_directory_urls=True) + expected = [ + './', # . relative to . + '../', # . relative to foo/ + '../../', # . relative to foo/bar/ + '../../../', # . relative to foo/bar/baz/ + '../', # . relative to foo + '../../', # . relative to foo/bar + '../../../', # . relative to foo/bar/baz + ] + + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, './') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('file.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + expected = [ + 'file/', # file relative to . + '../file/', # file relative to foo/ + '../../file/', # file relative to foo/bar/ + '../../../file/', # file relative to foo/bar/baz/ + '../file/', # file relative to foo + '../../file/', # file relative to foo/bar + '../../../file/', # file relative to foo/bar/baz + ] + + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'file/') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + def test_get_relative_url(self): + to_files = [ + 'index.md', + 'foo/index.md', + 'foo/bar/index.md', + 'foo/bar/baz/index.md', + 'foo.md', + 'foo/bar.md', + 'foo/bar/baz.md', + ] + + to_file_urls = [ + 'index.html', + 'foo/index.html', + 'foo/bar/index.html', + 'foo/bar/baz/index.html', + 'foo.html', + 'foo/bar.html', + 'foo/bar/baz.html', + ] + + from_file = File('img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + expected = [ + 'img.jpg', # img.jpg relative to . + '../img.jpg', # img.jpg relative to foo/ + '../../img.jpg', # img.jpg relative to foo/bar/ + '../../../img.jpg', # img.jpg relative to foo/bar/baz/ + 'img.jpg', # img.jpg relative to foo.html + '../img.jpg', # img.jpg relative to foo/bar.html + '../../img.jpg', # img.jpg relative to foo/bar/baz.html + ] + + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'img.jpg') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('foo/img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + expected = [ + 'foo/img.jpg', # foo/img.jpg relative to . + 'img.jpg', # foo/img.jpg relative to foo/ + '../img.jpg', # foo/img.jpg relative to foo/bar/ + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz/ + 'foo/img.jpg', # foo/img.jpg relative to foo.html + 'img.jpg', # foo/img.jpg relative to foo/bar.html + '../img.jpg', # foo/img.jpg relative to foo/bar/baz.html + ] + + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'foo/img.jpg') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('index.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + expected = [ + 'index.html', # index.html relative to . + '../index.html', # index.html relative to foo/ + '../../index.html', # index.html relative to foo/bar/ + '../../../index.html', # index.html relative to foo/bar/baz/ + 'index.html', # index.html relative to foo.html + '../index.html', # index.html relative to foo/bar.html + '../../index.html', # index.html relative to foo/bar/baz.html + ] + + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'index.html') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('file.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + expected = [ + 'file.html', # file.html relative to . + '../file.html', # file.html relative to foo/ + '../../file.html', # file.html relative to foo/bar/ + '../../../file.html', # file.html relative to foo/bar/baz/ + 'file.html', # file.html relative to foo.html + '../file.html', # file.html relative to foo/bar.html + '../../file.html', # file.html relative to foo/bar/baz.html + ] + + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'file.html') + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + @tempdir( + files=[ + 'index.md', + 'readme.md', + 'bar.css', + 'bar.html', + 'bar.jpg', + 'bar.js', + 'bar.md', + '.dotfile', + 'templates/foo.html', + ] + ) + def test_get_files(self, tdir): + config = load_config(docs_dir=tdir, extra_css=['bar.css'], extra_javascript=['bar.js']) + files = get_files(config) + expected = ['index.md', 'bar.css', 'bar.html', 'bar.jpg', 'bar.js', 'bar.md', 'readme.md'] + self.assertIsInstance(files, Files) + self.assertEqual(len(files), len(expected)) + self.assertEqual([f.src_path for f in files], expected) + + @tempdir( + files=[ + 'README.md', + 'foo.md', + ] + ) + def test_get_files_include_readme_without_index(self, tdir): + config = load_config(docs_dir=tdir) + files = get_files(config) + expected = ['README.md', 'foo.md'] + self.assertIsInstance(files, Files) + self.assertEqual(len(files), len(expected)) + self.assertEqual([f.src_path for f in files], expected) + + @tempdir( + files=[ + 'index.md', + 'README.md', + 'foo.md', + ] + ) + def test_get_files_exclude_readme_with_index(self, tdir): + config = load_config(docs_dir=tdir) + with self.assertLogs('mkdocs') as cm: + files = get_files(config) + self.assertRegex( + '\n'.join(cm.output), + r"^WARNING:mkdocs.structure.files:Both index.md and README.md found. Skipping README.md .+$", + ) + expected = ['index.md', 'foo.md'] + self.assertIsInstance(files, Files) + self.assertEqual(len(files), len(expected)) + self.assertEqual([f.src_path for f in files], expected) + + @tempdir() + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + dest_path = os.path.join(dest_dir, 'test.txt') + self.assertPathNotExists(dest_path) + file.copy_file() + self.assertPathIsFile(dest_path) + + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_same_file(self, dest_dir): + file = File('test.txt', dest_dir, dest_dir, use_directory_urls=False) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file() + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_clean_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=True) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=False) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_dirty_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=True) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=True) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_dirty_not_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=False) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=True) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'destination content') + + def test_files_append_remove_src_paths(self): + fs = [ + File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True), + ] + files = Files(fs) + self.assertEqual(len(files), 6) + self.assertEqual(len(files.src_uris), 6) + extra_file = File('extra.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertFalse(extra_file.src_uri in files.src_uris) + files.append(extra_file) + self.assertEqual(len(files), 7) + self.assertEqual(len(files.src_uris), 7) + self.assertTrue(extra_file.src_uri in files.src_uris) + files.remove(extra_file) + self.assertEqual(len(files), 6) + self.assertEqual(len(files.src_uris), 6) + self.assertFalse(extra_file.src_uri in files.src_uris) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/nav_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/structure/nav_tests.py new file mode 100644 index 00000000..b576ba2a --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/structure/nav_tests.py @@ -0,0 +1,477 @@ +#!/usr/bin/env python + +import sys +import unittest + +from mkdocs.structure.files import File, Files +from mkdocs.structure.nav import Section, _get_by_type, get_navigation +from mkdocs.structure.pages import Page +from mkdocs.tests.base import dedent, load_config + + +class SiteNavigationTests(unittest.TestCase): + maxDiff = None + + def test_simple_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Page(title='About', url='/about/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File( + list(item.values())[0], cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'] + ) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/')") + + def test_nav_no_directory_urls(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/index.html') + Page(title='About', url='/about.html') + """ + ) + cfg = load_config(nav=nav_cfg, use_directory_urls=False, site_url='http://example.com/') + fs = [ + File( + list(item.values())[0], cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'] + ) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/index.html')") + + def test_nav_missing_page(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + File('page_not_in_nav.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 1) + self.assertEqual(len(site_navigation.pages), 1) + for file in files: + self.assertIsInstance(file.page, Page) + + def test_nav_no_title(self): + nav_cfg = [ + 'index.md', + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title='About', url='/about/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(nav_cfg[0], cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + File(nav_cfg[1]['About'], cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + + def test_nav_external_links(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Local': '/local.html'}, + {'External': 'http://example.com/external.html'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Link(title='Local', url='/local.html') + Link(title='External', url='http://example.com/external.html') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + with self.assertLogs('mkdocs', level='DEBUG') as cm: + site_navigation = get_navigation(files, cfg) + self.assertEqual( + cm.output, + [ + "DEBUG:mkdocs.structure.nav:An absolute path to '/local.html' is included in the " + "'nav' configuration, which presumably points to an external resource.", + "DEBUG:mkdocs.structure.nav:An external link to 'http://example.com/external.html' " + "is included in the 'nav' configuration.", + ], + ) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 1) + + def test_nav_bad_links(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Missing': 'missing.html'}, + {'Bad External': 'example.com'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Link(title='Missing', url='missing.html') + Link(title='Bad External', url='example.com') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + with self.assertLogs('mkdocs') as cm: + site_navigation = get_navigation(files, cfg) + self.assertEqual( + cm.output, + [ + "WARNING:mkdocs.structure.nav:A relative path to 'missing.html' is included " + "in the 'nav' configuration, which is not found in the documentation files", + "WARNING:mkdocs.structure.nav:A relative path to 'example.com' is included " + "in the 'nav' configuration, which is not found in the documentation files", + ], + ) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 1) + + def test_indented_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + { + 'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + { + 'Advanced': [ + {'Part 1': 'api-guide/advanced/part-1.md'}, + ] + }, + ] + }, + { + 'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': '/license.html'}, + ] + }, + {'External': 'https://example.com/'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Section(title='API Guide') + Page(title='Running', url='/api-guide/running/') + Page(title='Testing', url='/api-guide/testing/') + Page(title='Debugging', url='/api-guide/debugging/') + Section(title='Advanced') + Page(title='Part 1', url='/api-guide/advanced/part-1/') + Section(title='About') + Page(title='Release notes', url='/about/release-notes/') + Link(title='License', url='/license.html') + Link(title='External', url='https://example.com/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + 'index.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/debugging.md', + 'api-guide/advanced/part-1.md', + 'about/release-notes.md', + ] + files = Files( + [File(s, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) for s in fs] + ) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 4) + self.assertEqual(len(site_navigation.pages), 6) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/')") + self.assertIsNone(site_navigation.items[0].parent) + self.assertEqual(site_navigation.items[0].ancestors, []) + self.assertIsNone(site_navigation.items[1].parent) + self.assertEqual(site_navigation.items[1].ancestors, []) + self.assertEqual(len(site_navigation.items[1].children), 4) + self.assertEqual( + repr(site_navigation.items[1].children[0].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[0].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[1].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[1].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[2].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[2].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[3].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[3].ancestors, [site_navigation.items[1]]) + self.assertEqual(len(site_navigation.items[1].children[3].children), 1) + self.assertEqual( + repr(site_navigation.items[1].children[3].children[0].parent), + "Section(title='Advanced')", + ) + self.assertEqual( + site_navigation.items[1].children[3].children[0].ancestors, + [site_navigation.items[1].children[3], site_navigation.items[1]], + ) + self.assertIsNone(site_navigation.items[2].parent) + self.assertEqual(len(site_navigation.items[2].children), 2) + self.assertEqual( + repr(site_navigation.items[2].children[0].parent), "Section(title='About')" + ) + self.assertEqual(site_navigation.items[2].children[0].ancestors, [site_navigation.items[2]]) + self.assertEqual( + repr(site_navigation.items[2].children[1].parent), "Section(title='About')" + ) + self.assertEqual(site_navigation.items[2].children[1].ancestors, [site_navigation.items[2]]) + self.assertIsNone(site_navigation.items[3].parent) + self.assertEqual(site_navigation.items[3].ancestors, []) + self.assertIsNone(site_navigation.items[3].children) + + def test_nested_ungrouped_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Contact': 'about/contact.md'}, + {'License Title': 'about/sub/license.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Page(title='Contact', url='/about/contact/') + Page(title='License Title', url='/about/sub/license/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File( + list(item.values())[0], cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'] + ) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + + def test_nested_ungrouped_nav_no_titles(self): + nav_cfg = [ + 'index.md', + 'about/contact.md', + 'about/sub/license.md', + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/contact/') + Page(title=[blank], url='/about/sub/license/') + """ + ) + + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(item, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_nested_ungrouped_no_titles_windows(self): + nav_cfg = [ + 'index.md', + 'about\\contact.md', + 'about\\sub\\license.md', + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/contact/') + Page(title=[blank], url='/about/sub/license/') + """ + ) + + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(item, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + + def test_nav_from_files(self): + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/') + """ + ) + cfg = load_config(site_url='http://example.com/') + fs = [ + File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + File('about.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + def test_nav_from_nested_files(self): + expected = dedent( + """ + Page(title=[blank], url='/') + Section(title='About') + Page(title=[blank], url='/about/license/') + Page(title=[blank], url='/about/release-notes/') + Section(title='Api guide') + Page(title=[blank], url='/api-guide/debugging/') + Page(title=[blank], url='/api-guide/running/') + Page(title=[blank], url='/api-guide/testing/') + Section(title='Advanced') + Page(title=[blank], url='/api-guide/advanced/part-1/') + """ + ) + cfg = load_config(site_url='http://example.com/') + fs = [ + 'index.md', + 'about/license.md', + 'about/release-notes.md', + 'api-guide/debugging.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/advanced/part-1.md', + ] + files = Files( + [File(s, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) for s in fs] + ) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 7) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + def test_active(self): + nav_cfg = [ + {'Home': 'index.md'}, + { + 'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + { + 'Advanced': [ + {'Part 1': 'api-guide/advanced/part-1.md'}, + ] + }, + ] + }, + { + 'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': 'about/license.md'}, + ] + }, + ] + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + 'index.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/debugging.md', + 'api-guide/advanced/part-1.md', + 'about/release-notes.md', + 'about/license.md', + ] + files = Files( + [File(s, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) for s in fs] + ) + site_navigation = get_navigation(files, cfg) + # Confirm nothing is active + self.assertTrue(all(page.active is False for page in site_navigation.pages)) + self.assertTrue(all(item.active is False for item in site_navigation.items)) + # Activate + site_navigation.items[1].children[3].children[0].active = True + # Confirm ancestors are activated + self.assertTrue(site_navigation.items[1].children[3].children[0].active) + self.assertTrue(site_navigation.items[1].children[3].active) + self.assertTrue(site_navigation.items[1].active) + # Confirm non-ancestors are not activated + self.assertFalse(site_navigation.items[0].active) + self.assertFalse(site_navigation.items[1].children[0].active) + self.assertFalse(site_navigation.items[1].children[1].active) + self.assertFalse(site_navigation.items[1].children[2].active) + self.assertFalse(site_navigation.items[2].active) + self.assertFalse(site_navigation.items[2].children[0].active) + self.assertFalse(site_navigation.items[2].children[1].active) + # Deactivate + site_navigation.items[1].children[3].children[0].active = False + # Confirm ancestors are deactivated + self.assertFalse(site_navigation.items[1].children[3].children[0].active) + self.assertFalse(site_navigation.items[1].children[3].active) + self.assertFalse(site_navigation.items[1].active) + + def test_get_by_type_nested_sections(self): + nav_cfg = [ + { + 'Section 1': [ + { + 'Section 2': [ + {'Page': 'page.md'}, + ] + }, + ] + }, + ] + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('page.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'])] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(len(_get_by_type(site_navigation, Section)), 2) diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/structure/page_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/structure/page_tests.py new file mode 100644 index 00000000..9ccd9ff8 --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/tests/structure/page_tests.py @@ -0,0 +1,815 @@ +import functools +import os +import sys +import unittest +from unittest import mock + +from mkdocs.structure.files import File, Files +from mkdocs.structure.pages import Page +from mkdocs.tests.base import dedent, load_config, tempdir + +load_config = functools.lru_cache(maxsize=None)(load_config) + + +class PageTests(unittest.TestCase): + DOCS_DIR = os.path.join( + os.path.abspath(os.path.dirname(__file__)), '../integration/subpages/docs' + ) + + def test_homepage(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + self.assertIsNone(fl.page) + pg = Page('Foo', fl, cfg) + self.assertEqual(fl.page, pg) + self.assertEqual(pg.url, '') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertTrue(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('sub1/index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + pg.parent = 'foo' + self.assertEqual(pg.url, 'sub1/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertFalse(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, 'foo') + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page_no_parent(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('sub1/index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + pg.parent = None # non-homepage at nav root level; see #1919. + self.assertEqual(pg.url, 'sub1/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page_no_parent_no_directory_urls(self): + cfg = load_config(docs_dir=self.DOCS_DIR, use_directory_urls=False) + fl = File('sub1/index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + pg.parent = None # non-homepage at nav root level; see #1919. + self.assertEqual(pg.url, 'sub1/index.html') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_nonindex_page(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('sub1/non-index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + pg.parent = 'foo' + self.assertEqual(pg.url, 'sub1/non-index/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertFalse(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, 'foo') + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_defaults(self): + cfg = load_config() + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertRegex(pg.update_date, r'\d{4}-\d{2}-\d{2}') + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_no_directory_url(self): + cfg = load_config(use_directory_urls=False) + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing.html') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url(self): + cfg = load_config(site_url='http://example.com') + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url_nested(self): + cfg = load_config(site_url='http://example.com/foo/') + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/foo/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/foo/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url_nested_no_slash(self): + cfg = load_config(site_url='http://example.com/foo') + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/foo/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/foo/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_predefined_page_title(self): + cfg = load_config() + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Page Title', fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Page Title') + self.assertEqual(pg.toc, []) + + def test_page_title_from_markdown(self): + cfg = load_config() + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Welcome to MkDocs') + self.assertEqual(pg.toc, []) + + def test_page_title_from_meta(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('metadata.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'metadata/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {'title': 'A Page Title'}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'A Page Title') + self.assertEqual(pg.toc, []) + + def test_page_title_from_filename(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('page-title.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'page-title/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('Page content.\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Page title') + self.assertEqual(pg.toc, []) + + def test_page_title_from_capitalized_filename(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('pageTitle.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'pageTitle/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('Page content.\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'pageTitle') + self.assertEqual(pg.toc, []) + + def test_page_title_from_homepage_filename(self): + cfg = load_config(docs_dir=self.DOCS_DIR) + fl = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, '') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertTrue(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('## Test')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Home') + self.assertEqual(pg.toc, []) + + def test_page_eq(self): + cfg = load_config() + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertTrue(pg == Page('Foo', fl, cfg)) + + def test_page_ne(self): + cfg = load_config() + f1 = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + f2 = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', f1, cfg) + # Different Title + self.assertTrue(pg != Page('Bar', f1, cfg)) + # Different File + self.assertTrue(pg != Page('Foo', f2, cfg)) + + @tempdir() + def test_BOM(self, docs_dir): + md_src = '# An UTF-8 encoded file with a BOM' + cfg = load_config(docs_dir=docs_dir) + fl = File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page(None, fl, cfg) + # Create an UTF-8 Encoded file with BOM (as Microsoft editors do). See #1186 + with open(fl.abs_src_path, 'w', encoding='utf-8-sig') as f: + f.write(md_src) + # Now read the file. + pg.read_source(cfg) + # Ensure the BOM (`\ufeff`) is removed + self.assertNotIn('\ufeff', pg.markdown) + self.assertEqual(pg.markdown, md_src) + self.assertEqual(pg.meta, {}) + + def test_page_edit_url( + self, paths={'testing.md': 'testing/', 'sub1/non-index.md': 'sub1/non-index/'} + ): + for case in [ + dict( + config={'repo_url': 'http://github.com/mkdocs/mkdocs'}, + edit_url='http://github.com/mkdocs/mkdocs/edit/master/docs/testing.md', + edit_url2='http://github.com/mkdocs/mkdocs/edit/master/docs/sub1/non-index.md', + ), + dict( + config={'repo_url': 'https://github.com/mkdocs/mkdocs/'}, + edit_url='https://github.com/mkdocs/mkdocs/edit/master/docs/testing.md', + edit_url2='https://github.com/mkdocs/mkdocs/edit/master/docs/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com'}, + edit_url=None, + edit_url2=None, + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': 'edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': '/edit/master/'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo', 'edit_uri': '/edit/master/'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': '/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': 'edit/master/'}, + edit_url='http://example.com/foo/edit/master/testing.md', + edit_url2='http://example.com/foo/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo', 'edit_uri': 'edit/master/'}, + edit_url='http://example.com/foo/edit/master/testing.md', + edit_url2='http://example.com/foo/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '?query=edit/master'}, + edit_url='http://example.com?query=edit/master/testing.md', + edit_url2='http://example.com?query=edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/', 'edit_uri': '?query=edit/master/'}, + edit_url='http://example.com/?query=edit/master/testing.md', + edit_url2='http://example.com/?query=edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '#edit/master'}, + edit_url='http://example.com#edit/master/testing.md', + edit_url2='http://example.com#edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/', 'edit_uri': '#edit/master/'}, + edit_url='http://example.com/#edit/master/testing.md', + edit_url2='http://example.com/#edit/master/sub1/non-index.md', + ), + dict( + config={'edit_uri': 'http://example.com/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'edit_uri_template': 'https://github.com/project/repo/wiki/{path_noext}'}, + edit_url='https://github.com/project/repo/wiki/testing', + edit_url2='https://github.com/project/repo/wiki/sub1/non-index', + ), + dict( + config={ + 'repo_url': 'https://github.com/project/repo/wiki', + 'edit_uri_template': '{path_noext}/_edit', + }, + edit_url='https://github.com/project/repo/wiki/testing/_edit', + edit_url2='https://github.com/project/repo/wiki/sub1/non-index/_edit', + ), + dict( + config={ + 'repo_url': 'https://gitlab.com/project/repo', + 'edit_uri_template': '-/sse/master/docs%2F{path!q}', + }, + edit_url='https://gitlab.com/project/repo/-/sse/master/docs%2Ftesting.md', + edit_url2='https://gitlab.com/project/repo/-/sse/master/docs%2Fsub1%2Fnon-index.md', + ), + dict( + config={ + 'repo_url': 'https://bitbucket.org/project/repo/', + 'edit_uri_template': 'src/master/docs/{path}?mode=edit', + }, + edit_url='https://bitbucket.org/project/repo/src/master/docs/testing.md?mode=edit', + edit_url2='https://bitbucket.org/project/repo/src/master/docs/sub1/non-index.md?mode=edit', + ), + dict( + config={ + 'repo_url': 'http://example.com', + 'edit_uri': '', + 'edit_uri_template': '', + }, # Set to blank value + edit_url=None, + edit_url2=None, + ), + dict(config={}, edit_url=None, edit_url2=None), # Nothing defined + ]: + for i, path in enumerate(paths, 1): + edit_url_key = f'edit_url{i}' if i > 1 else 'edit_url' + with self.subTest(case['config'], path=path): + cfg = load_config(**case['config']) + fl = File(path, cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, paths[path]) + self.assertEqual(pg.edit_url, case[edit_url_key]) + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_page_edit_url_windows(self): + self.test_page_edit_url( + paths={'testing.md': 'testing/', 'sub1\\non-index.md': 'sub1/non-index/'} + ) + + def test_page_edit_url_warning(self): + for case in [ + dict( + config={'edit_uri': 'edit/master'}, + edit_url='edit/master/testing.md', + warning="WARNING:mkdocs.structure.pages:edit_uri: " + "'edit/master/testing.md' is not a valid URL, it should include the http:// (scheme)", + ), + ]: + with self.subTest(case['config']): + with self.assertLogs('mkdocs') as cm: + cfg = load_config(**case['config']) + fl = File( + 'testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls'] + ) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.edit_url, case['edit_url']) + self.assertEqual(cm.output, [case['warning']]) + + def test_page_render(self): + cfg = load_config() + fl = File('testing.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']) + pg = Page('Foo', fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.content, None) + self.assertEqual(pg.toc, []) + pg.render(cfg, [fl]) + self.assertTrue( + pg.content.startswith('not a link.
', + ) + + @mock.patch('mkdocs.structure.pages.open', mock.mock_open(read_data='[link](non-existent.md)')) + def test_bad_relative_html_link(self): + with self.assertLogs('mkdocs') as cm: + self.assertEqual( + self.get_rendered_result(['index.md']), + '', + ) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.structure.pages:Documentation file 'index.md' contains a link " + "to 'non-existent.md' which is not found in the documentation files.", + ) + + @mock.patch( + 'mkdocs.structure.pages.open', + mock.mock_open(read_data='[external](http://example.com/index.md)'), + ) + def test_external_link(self): + self.assertEqual( + self.get_rendered_result(['index.md']), + '', + ) + + @mock.patch( + 'mkdocs.structure.pages.open', mock.mock_open(read_data='[absolute link](/path/to/file.md)') + ) + def test_absolute_link(self): + self.assertEqual( + self.get_rendered_result(['index.md']), + '', + ) + + @mock.patch( + 'mkdocs.structure.pages.open', + mock.mock_open(read_data='[absolute local path](\\image.png)'), + ) + def test_absolute_win_local_path(self): + self.assertEqual( + self.get_rendered_result(['index.md']), + '', + ) + + @mock.patch('mkdocs.structure.pages.open', mock.mock_open(read_data='Heading
2
+ ## Heading 3
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 1)
+
+ def test_flat_toc(self):
+ md = dedent(
+ """
+ # Heading 1
+ # Heading 2
+ # Heading 3
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 3)
+
+ def test_flat_h2_toc(self):
+ md = dedent(
+ """
+ ## Heading 1
+ ## Heading 2
+ ## Heading 3
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 3)
+
+ def test_mixed_toc(self):
+ md = dedent(
+ """
+ # Heading 1
+ ## Heading 2
+ # Heading 3
+ ### Heading 4
+ ### Heading 5
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ Heading 4 - #heading-4
+ Heading 5 - #heading-5
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 2)
+
+ def test_mixed_html(self):
+ md = dedent(
+ """
+ # Heading 1
+ ## Heading 2
+ # Heading 3
+ ### Heading 4
+ ### Heading 5
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ Heading 4 - #heading-4
+ Heading 5 - #heading-5
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 2)
+
+ def test_nested_anchor(self):
+ md = dedent(
+ """
+ # Heading 1
+ ## Heading 2
+ # Heading 3
+ ### Heading 4
+ ### Heading 5
+ """
+ )
+ expected = dedent(
+ """
+ Heading 1 - #heading-1
+ Heading 2 - #heading-2
+ Heading 3 - #heading-3
+ Heading 4 - #heading-4
+ Heading 5 - #heading-5
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 2)
+
+ def test_entityref(self):
+ md = dedent(
+ """
+ # Heading & 1
+ ## Heading > 2
+ ### Heading < 3
+ """
+ )
+ expected = dedent(
+ """
+ Heading & 1 - #heading-1
+ Heading > 2 - #heading-2
+ Heading < 3 - #heading-3
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 1)
+
+ def test_charref(self):
+ md = '# @Header'
+ expected = '@Header - #header'
+ toc = get_toc(get_markdown_toc(md))
+ self.assertEqual(str(toc).strip(), expected)
+ self.assertEqual(len(toc), 1)
+
+ def test_level(self):
+ md = dedent(
+ """
+ # Heading 1
+ ## Heading 1.1
+ ### Heading 1.1.1
+ ### Heading 1.1.2
+ ## Heading 1.2
+ """
+ )
+ toc = get_toc(get_markdown_toc(md))
+
+ def get_level_sequence(items):
+ for item in items:
+ yield item.level
+ yield from get_level_sequence(item.children)
+
+ self.assertEqual(tuple(get_level_sequence(toc)), (1, 2, 3, 3, 2))
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/theme_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/theme_tests.py
new file mode 100644
index 00000000..213e2644
--- /dev/null
+++ b/web/lib/python3.11/site-packages/mkdocs/tests/theme_tests.py
@@ -0,0 +1,108 @@
+import os
+import unittest
+from unittest import mock
+
+import mkdocs
+from mkdocs.localization import parse_locale
+from mkdocs.tests.base import tempdir
+from mkdocs.theme import Theme
+
+abs_path = os.path.abspath(os.path.dirname(__file__))
+mkdocs_dir = os.path.abspath(os.path.dirname(mkdocs.__file__))
+mkdocs_templates_dir = os.path.join(mkdocs_dir, 'templates')
+theme_dir = os.path.abspath(os.path.join(mkdocs_dir, 'themes'))
+
+
+def get_vars(theme):
+ """Return dict of theme vars."""
+ return {k: theme[k] for k in iter(theme)}
+
+
+class ThemeTests(unittest.TestCase):
+ def test_simple_theme(self):
+ theme = Theme(name='mkdocs')
+ self.assertEqual(
+ theme.dirs,
+ [os.path.join(theme_dir, 'mkdocs'), mkdocs_templates_dir],
+ )
+ self.assertEqual(theme.static_templates, {'404.html', 'sitemap.xml'})
+ self.assertEqual(
+ get_vars(theme),
+ {
+ 'name': 'mkdocs',
+ 'locale': parse_locale('en'),
+ 'include_search_page': False,
+ 'search_index_only': False,
+ 'analytics': {'gtag': None},
+ 'highlightjs': True,
+ 'hljs_style': 'github',
+ 'hljs_languages': [],
+ 'navigation_depth': 2,
+ 'nav_style': 'primary',
+ 'shortcuts': {'help': 191, 'next': 78, 'previous': 80, 'search': 83},
+ },
+ )
+
+ @tempdir()
+ def test_custom_dir(self, custom):
+ theme = Theme(name='mkdocs', custom_dir=custom)
+ self.assertEqual(
+ theme.dirs,
+ [
+ custom,
+ os.path.join(theme_dir, 'mkdocs'),
+ mkdocs_templates_dir,
+ ],
+ )
+
+ @tempdir()
+ def test_custom_dir_only(self, custom):
+ theme = Theme(name=None, custom_dir=custom)
+ self.assertEqual(
+ theme.dirs,
+ [custom, mkdocs_templates_dir],
+ )
+
+ def static_templates(self):
+ theme = Theme(name='mkdocs', static_templates='foo.html')
+ self.assertEqual(
+ theme.static_templates,
+ {'404.html', 'sitemap.xml', 'foo.html'},
+ )
+
+ def test_vars(self):
+ theme = Theme(name='mkdocs', foo='bar', baz=True)
+ self.assertEqual(theme['foo'], 'bar')
+ self.assertEqual(theme['baz'], True)
+ self.assertTrue('new' not in theme)
+ with self.assertRaises(KeyError):
+ theme['new']
+ theme['new'] = 42
+ self.assertTrue('new' in theme)
+ self.assertEqual(theme['new'], 42)
+
+ @mock.patch('mkdocs.utils.yaml_load', return_value=None)
+ def test_no_theme_config(self, m):
+ theme = Theme(name='mkdocs')
+ self.assertEqual(m.call_count, 1)
+ self.assertEqual(theme.static_templates, {'sitemap.xml'})
+
+ def test_inherited_theme(self):
+ m = mock.Mock(
+ side_effect=[
+ {'extends': 'readthedocs', 'static_templates': ['child.html']},
+ {'static_templates': ['parent.html']},
+ ]
+ )
+ with mock.patch('mkdocs.utils.yaml_load', m) as m:
+ theme = Theme(name='mkdocs')
+ self.assertEqual(m.call_count, 2)
+ self.assertEqual(
+ theme.dirs,
+ [
+ os.path.join(theme_dir, 'mkdocs'),
+ os.path.join(theme_dir, 'readthedocs'),
+ mkdocs_templates_dir,
+ ],
+ )
+ self.assertEqual(theme.static_templates, {'sitemap.xml', 'child.html', 'parent.html'})
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/__init__.py b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 00000000..69fc9394
Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-311.pyc
new file mode 100644
index 00000000..59427b75
Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-311.pyc differ
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-311.pyc
new file mode 100644
index 00000000..006093c8
Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-311.pyc differ
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/babel_stub_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/utils/babel_stub_tests.py
new file mode 100644
index 00000000..ec810471
--- /dev/null
+++ b/web/lib/python3.11/site-packages/mkdocs/tests/utils/babel_stub_tests.py
@@ -0,0 +1,55 @@
+import unittest
+
+from mkdocs.utils.babel_stub import Locale, UnknownLocaleError
+
+
+class BabelStubTests(unittest.TestCase):
+ def test_locale_language_only(self):
+ locale = Locale('es')
+ self.assertEqual(locale.language, 'es')
+ self.assertEqual(locale.territory, '')
+ self.assertEqual(str(locale), 'es')
+
+ def test_locale_language_territory(self):
+ locale = Locale('es', 'ES')
+ self.assertEqual(locale.language, 'es')
+ self.assertEqual(locale.territory, 'ES')
+ self.assertEqual(str(locale), 'es_ES')
+
+ def test_parse_locale_language_only(self):
+ locale = Locale.parse('fr', '_')
+ self.assertEqual(locale.language, 'fr')
+ self.assertEqual(locale.territory, '')
+ self.assertEqual(str(locale), 'fr')
+
+ def test_parse_locale_language_territory(self):
+ locale = Locale.parse('fr_FR', '_')
+ self.assertEqual(locale.language, 'fr')
+ self.assertEqual(locale.territory, 'FR')
+ self.assertEqual(str(locale), 'fr_FR')
+
+ def test_parse_locale_language_territory_sep(self):
+ locale = Locale.parse('fr-FR', '-')
+ self.assertEqual(locale.language, 'fr')
+ self.assertEqual(locale.territory, 'FR')
+ self.assertEqual(str(locale), 'fr_FR')
+
+ def test_parse_locale_bad_type(self):
+ with self.assertRaises(TypeError):
+ Locale.parse(['list'], '_')
+
+ def test_parse_locale_invalid_characters(self):
+ with self.assertRaises(ValueError):
+ Locale.parse('42', '_')
+
+ def test_parse_locale_bad_format(self):
+ with self.assertRaises(ValueError):
+ Locale.parse('en-GB', '_')
+
+ def test_parse_locale_bad_format_sep(self):
+ with self.assertRaises(ValueError):
+ Locale.parse('en_GB', '-')
+
+ def test_parse_locale_unknown_locale(self):
+ with self.assertRaises(UnknownLocaleError):
+ Locale.parse('foo', '_')
diff --git a/web/lib/python3.11/site-packages/mkdocs/tests/utils/utils_tests.py b/web/lib/python3.11/site-packages/mkdocs/tests/utils/utils_tests.py
new file mode 100644
index 00000000..5b7a2d13
--- /dev/null
+++ b/web/lib/python3.11/site-packages/mkdocs/tests/utils/utils_tests.py
@@ -0,0 +1,691 @@
+#!/usr/bin/env python
+
+import datetime
+import logging
+import os
+import posixpath
+import stat
+import unittest
+from unittest import mock
+
+from mkdocs import exceptions, utils
+from mkdocs.structure.files import File
+from mkdocs.structure.pages import Page
+from mkdocs.tests.base import dedent, load_config, tempdir
+from mkdocs.utils import meta
+
+BASEYML = """
+INHERIT: parent.yml
+foo: bar
+baz:
+ sub1: replaced
+ sub3: new
+deep1:
+ deep2-1:
+ deep3-1: replaced
+"""
+PARENTYML = """
+foo: foo
+baz:
+ sub1: 1
+ sub2: 2
+deep1:
+ deep2-1:
+ deep3-1: foo
+ deep3-2: bar
+ deep2-2: baz
+"""
+
+
+class UtilsTests(unittest.TestCase):
+ def test_is_markdown_file(self):
+ expected_results = {
+ 'index.md': True,
+ 'index.markdown': True,
+ 'index.MARKDOWN': False,
+ 'index.txt': False,
+ 'indexmd': False,
+ }
+ for path, expected_result in expected_results.items():
+ with self.subTest(path):
+ is_markdown = utils.is_markdown_file(path)
+ self.assertEqual(is_markdown, expected_result)
+
+ def test_get_relative_url(self):
+ for case in [
+ dict(url='foo/bar', other='foo', expected='bar'),
+ dict(url='foo/bar.txt', other='foo', expected='bar.txt'),
+ dict(url='foo', other='foo/bar', expected='..'),
+ dict(url='foo', other='foo/bar.txt', expected='.'),
+ dict(url='foo/../../bar', other='.', expected='bar'),
+ dict(url='foo/../../bar', other='foo', expected='../bar'),
+ dict(url='foo//./bar/baz', other='foo/bar/baz', expected='.'),
+ dict(url='a/b/.././../c', other='.', expected='c'),
+ dict(url='a/b/c/d/ee', other='a/b/c/d/e', expected='../ee'),
+ dict(url='a/b/c/d/ee', other='a/b/z/d/e', expected='../../../c/d/ee'),
+ dict(url='foo', other='bar.', expected='foo'),
+ dict(url='foo', other='bar./', expected='../foo'),
+ dict(url='foo', other='foo/bar./', expected='..'),
+ dict(url='foo', other='foo/bar./.', expected='..'),
+ dict(url='foo', other='foo/bar././', expected='..'),
+ dict(url='foo/', other='foo/bar././', expected='../'),
+ dict(url='foo', other='foo', expected='.'),
+ dict(url='.foo', other='.foo', expected='.foo'),
+ dict(url='.foo/', other='.foo', expected='.foo/'),
+ dict(url='.foo', other='.foo/', expected='.'),
+ dict(url='.foo/', other='.foo/', expected='./'),
+ dict(url='///', other='', expected='./'),
+ dict(url='a///', other='', expected='a/'),
+ dict(url='a///', other='a', expected='./'),
+ dict(url='.', other='here', expected='..'),
+ dict(url='..', other='here', expected='..'),
+ dict(url='../..', other='here', expected='..'),
+ dict(url='../../a', other='here', expected='../a'),
+ dict(url='..', other='here.txt', expected='.'),
+ dict(url='a', other='', expected='a'),
+ dict(url='a', other='..', expected='a'),
+ dict(url='a', other='b', expected='../a'),
+ # The dots are considered a file. Documenting a long-standing bug:
+ dict(url='a', other='b/..', expected='../a'),
+ dict(url='a', other='b/../..', expected='a'),
+ dict(url='a/..../b', other='a/../b', expected='../a/..../b'),
+ dict(url='a/я/b', other='a/я/c', expected='../b'),
+ dict(url='a/я/b', other='a/яя/c', expected='../../я/b'),
+ ]:
+ url, other, expected = case['url'], case['other'], case['expected']
+ with self.subTest(url=url, other=other):
+ # Leading slash intentionally ignored
+ self.assertEqual(utils.get_relative_url(url, other), expected)
+ self.assertEqual(utils.get_relative_url('/' + url, other), expected)
+ self.assertEqual(utils.get_relative_url(url, '/' + other), expected)
+ self.assertEqual(utils.get_relative_url('/' + url, '/' + other), expected)
+
+ def test_get_relative_url_empty(self):
+ for url in ['', '.', '/.']:
+ for other in ['', '.', '/', '/.']:
+ with self.subTest(url=url, other=other):
+ self.assertEqual(utils.get_relative_url(url, other), '.')
+
+ self.assertEqual(utils.get_relative_url('/', ''), './')
+ self.assertEqual(utils.get_relative_url('/', '/'), './')
+ self.assertEqual(utils.get_relative_url('/', '.'), './')
+ self.assertEqual(utils.get_relative_url('/', '/.'), './')
+
+ def test_create_media_urls(self):
+ expected_results = {
+ 'https://media.cdn.org/jq.js': [
+ 'https://media.cdn.org/jq.js',
+ 'https://media.cdn.org/jq.js',
+ 'https://media.cdn.org/jq.js',
+ ],
+ 'http://media.cdn.org/jquery.js': [
+ 'http://media.cdn.org/jquery.js',
+ 'http://media.cdn.org/jquery.js',
+ 'http://media.cdn.org/jquery.js',
+ ],
+ '//media.cdn.org/jquery.js': [
+ '//media.cdn.org/jquery.js',
+ '//media.cdn.org/jquery.js',
+ '//media.cdn.org/jquery.js',
+ ],
+ 'media.cdn.org/jquery.js': [
+ 'media.cdn.org/jquery.js',
+ 'media.cdn.org/jquery.js',
+ '../media.cdn.org/jquery.js',
+ ],
+ 'local/file/jquery.js': [
+ 'local/file/jquery.js',
+ 'local/file/jquery.js',
+ '../local/file/jquery.js',
+ ],
+ 'image.png': [
+ 'image.png',
+ 'image.png',
+ '../image.png',
+ ],
+ 'style.css?v=20180308c': [
+ 'style.css?v=20180308c',
+ 'style.css?v=20180308c',
+ '../style.css?v=20180308c',
+ ],
+ '#some_id': [
+ '#some_id',
+ '#some_id',
+ '#some_id',
+ ],
+ }
+
+ cfg = load_config(use_directory_urls=False)
+ pages = [
+ Page(
+ 'Home',
+ File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'About',
+ File('about.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'FooBar',
+ File('foo/bar.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ ]
+
+ for i, page in enumerate(pages):
+ urls = utils.create_media_urls(expected_results.keys(), page)
+ self.assertEqual([v[i] for v in expected_results.values()], urls)
+
+ def test_create_media_urls_use_directory_urls(self):
+ expected_results = {
+ 'https://media.cdn.org/jq.js': [
+ 'https://media.cdn.org/jq.js',
+ 'https://media.cdn.org/jq.js',
+ 'https://media.cdn.org/jq.js',
+ ],
+ 'http://media.cdn.org/jquery.js': [
+ 'http://media.cdn.org/jquery.js',
+ 'http://media.cdn.org/jquery.js',
+ 'http://media.cdn.org/jquery.js',
+ ],
+ '//media.cdn.org/jquery.js': [
+ '//media.cdn.org/jquery.js',
+ '//media.cdn.org/jquery.js',
+ '//media.cdn.org/jquery.js',
+ ],
+ 'media.cdn.org/jquery.js': [
+ 'media.cdn.org/jquery.js',
+ '../media.cdn.org/jquery.js',
+ '../../media.cdn.org/jquery.js',
+ ],
+ 'local/file/jquery.js': [
+ 'local/file/jquery.js',
+ '../local/file/jquery.js',
+ '../../local/file/jquery.js',
+ ],
+ 'image.png': [
+ 'image.png',
+ '../image.png',
+ '../../image.png',
+ ],
+ 'style.css?v=20180308c': [
+ 'style.css?v=20180308c',
+ '../style.css?v=20180308c',
+ '../../style.css?v=20180308c',
+ ],
+ '#some_id': [
+ '#some_id',
+ '#some_id',
+ '#some_id',
+ ],
+ }
+
+ cfg = load_config(use_directory_urls=True)
+ pages = [
+ Page(
+ 'Home',
+ File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'About',
+ File('about.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'FooBar',
+ File('foo/bar.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ ]
+
+ for i, page in enumerate(pages):
+ urls = utils.create_media_urls(expected_results.keys(), page)
+ self.assertEqual([v[i] for v in expected_results.values()], urls)
+
+ # TODO: This shouldn't pass on Linux
+ # @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
+ def test_create_media_urls_windows(self):
+ expected_results = {
+ 'local\\windows\\file\\jquery.js': [
+ 'local/windows/file/jquery.js',
+ 'local/windows/file/jquery.js',
+ '../local/windows/file/jquery.js',
+ ],
+ }
+
+ cfg = load_config(use_directory_urls=False)
+ pages = [
+ Page(
+ 'Home',
+ File('index.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'About',
+ File('about.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ Page(
+ 'FooBar',
+ File('foo/bar.md', cfg['docs_dir'], cfg['site_dir'], cfg['use_directory_urls']),
+ cfg,
+ ),
+ ]
+
+ with self.assertLogs('mkdocs', level='WARNING'):
+ for i, page in enumerate(pages):
+ urls = utils.create_media_urls(expected_results.keys(), page)
+ self.assertEqual([v[i] for v in expected_results.values()], urls)
+
+ def test_reduce_list(self):
+ self.assertEqual(
+ utils.reduce_list([1, 2, 3, 4, 5, 5, 2, 4, 6, 7, 8]),
+ [1, 2, 3, 4, 5, 6, 7, 8],
+ )
+
+ def test_insort(self):
+ a = [1, 2, 3]
+ utils.insort(a, 5)
+ self.assertEqual(a, [1, 2, 3, 5])
+ utils.insort(a, -1)
+ self.assertEqual(a, [-1, 1, 2, 3, 5])
+ utils.insort(a, 2)
+ self.assertEqual(a, [-1, 1, 2, 2, 3, 5])
+ utils.insort(a, 4)
+ self.assertEqual(a, [-1, 1, 2, 2, 3, 4, 5])
+
+ def test_insort_key(self):
+ a = [(1, 'a'), (1, 'b'), (2, 'c')]
+ utils.insort(a, (1, 'a'), key=lambda v: v[0])
+ self.assertEqual(a, [(1, 'a'), (1, 'b'), (1, 'a'), (2, 'c')])
+
+ def test_get_themes(self):
+ themes = utils.get_theme_names()
+ self.assertIn('mkdocs', themes)
+ self.assertIn('readthedocs', themes)
+
+ @mock.patch('mkdocs.utils.entry_points', autospec=True)
+ def test_get_theme_dir(self, mock_iter):
+ path = 'some/path'
+
+ theme = mock.Mock()
+ theme.name = 'mkdocs2'
+ theme.dist.name = 'mkdocs2'
+ theme.load().__file__ = os.path.join(path, '__init__.py')
+
+ mock_iter.return_value = [theme]
+
+ self.assertEqual(utils.get_theme_dir(theme.name), os.path.abspath(path))
+
+ def test_get_theme_dir_keyerror(self):
+ with self.assertRaises(KeyError):
+ utils.get_theme_dir('nonexistanttheme')
+
+ @mock.patch('mkdocs.utils.entry_points', autospec=True)
+ def test_get_theme_dir_importerror(self, mock_iter):
+ theme = mock.Mock()
+ theme.name = 'mkdocs2'
+ theme.dist.name = 'mkdocs2'
+ theme.load.side_effect = ImportError()
+
+ mock_iter.return_value = [theme]
+
+ with self.assertRaises(ImportError):
+ utils.get_theme_dir(theme.name)
+
+ @mock.patch('mkdocs.utils.entry_points', autospec=True)
+ def test_get_themes_warning(self, mock_iter):
+ theme1 = mock.Mock()
+ theme1.name = 'mkdocs2'
+ theme1.dist.name = 'mkdocs2'
+ theme1.load().__file__ = "some/path1"
+
+ theme2 = mock.Mock()
+ theme2.name = 'mkdocs2'
+ theme2.dist.name = 'mkdocs3'
+ theme2.load().__file__ = "some/path2"
+
+ mock_iter.return_value = [theme1, theme2]
+
+ with self.assertLogs('mkdocs') as cm:
+ theme_names = utils.get_theme_names()
+ self.assertEqual(
+ '\n'.join(cm.output),
+ "WARNING:mkdocs.utils:A theme named 'mkdocs2' is provided by the Python "
+ "packages 'mkdocs3' and 'mkdocs2'. The one in 'mkdocs3' will be used.",
+ )
+ self.assertCountEqual(theme_names, ['mkdocs2'])
+
+ @mock.patch('mkdocs.utils.entry_points', autospec=True)
+ def test_get_themes_error(self, mock_iter):
+ theme1 = mock.Mock()
+ theme1.name = 'mkdocs'
+ theme1.dist.name = 'mkdocs'
+ theme1.load().__file__ = "some/path1"
+
+ theme2 = mock.Mock()
+ theme2.name = 'mkdocs'
+ theme2.dist.name = 'mkdocs2'
+ theme2.load().__file__ = "some/path2"
+
+ mock_iter.return_value = [theme1, theme2]
+
+ with self.assertRaisesRegex(
+ exceptions.ConfigurationError,
+ "The theme 'mkdocs' is a builtin theme but the package 'mkdocs2' "
+ "attempts to provide a theme with the same name.",
+ ):
+ utils.get_theme_names()
+
+ def test_nest_paths(self, j=posixpath.join):
+ result = utils.nest_paths(
+ [
+ 'index.md',
+ j('user-guide', 'configuration.md'),
+ j('user-guide', 'styling-your-docs.md'),
+ j('user-guide', 'writing-your-docs.md'),
+ j('about', 'contributing.md'),
+ j('about', 'license.md'),
+ j('about', 'release-notes.md'),
+ ]
+ )
+
+ self.assertEqual(
+ result,
+ [
+ 'index.md',
+ {
+ 'User guide': [
+ j('user-guide', 'configuration.md'),
+ j('user-guide', 'styling-your-docs.md'),
+ j('user-guide', 'writing-your-docs.md'),
+ ]
+ },
+ {
+ 'About': [
+ j('about', 'contributing.md'),
+ j('about', 'license.md'),
+ j('about', 'release-notes.md'),
+ ]
+ },
+ ],
+ )
+
+ def test_nest_paths_native(self):
+ self.test_nest_paths(os.path.join)
+
+ def test_unicode_yaml(self):
+ yaml_src = dedent(
+ '''
+ key: value
+ key2:
+ - value
+ '''
+ ).encode('utf-8')
+
+ config = utils.yaml_load(yaml_src)
+ self.assertTrue(isinstance(config['key'], str))
+ self.assertTrue(isinstance(config['key2'][0], str))
+
+ @mock.patch.dict(os.environ, {'VARNAME': 'Hello, World!', 'BOOLVAR': 'false'})
+ def test_env_var_in_yaml(self):
+ yaml_src = dedent(
+ '''
+ key1: !ENV VARNAME
+ key2: !ENV UNDEFINED
+ key3: !ENV [UNDEFINED, default]
+ key4: !ENV [UNDEFINED, VARNAME, default]
+ key5: !ENV BOOLVAR
+ '''
+ )
+ config = utils.yaml_load(yaml_src)
+ self.assertEqual(config['key1'], 'Hello, World!')
+ self.assertIsNone(config['key2'])
+ self.assertEqual(config['key3'], 'default')
+ self.assertEqual(config['key4'], 'Hello, World!')
+ self.assertIs(config['key5'], False)
+
+ @tempdir(files={'base.yml': BASEYML, 'parent.yml': PARENTYML})
+ def test_yaml_inheritance(self, tdir):
+ expected = {
+ 'foo': 'bar',
+ 'baz': {
+ 'sub1': 'replaced',
+ 'sub2': 2,
+ 'sub3': 'new',
+ },
+ 'deep1': {
+ 'deep2-1': {
+ 'deep3-1': 'replaced',
+ 'deep3-2': 'bar',
+ },
+ 'deep2-2': 'baz',
+ },
+ }
+ with open(os.path.join(tdir, 'base.yml')) as fd:
+ result = utils.yaml_load(fd)
+ self.assertEqual(result, expected)
+
+ @tempdir(files={'base.yml': BASEYML})
+ def test_yaml_inheritance_missing_parent(self, tdir):
+ with open(os.path.join(tdir, 'base.yml')) as fd:
+ with self.assertRaises(exceptions.ConfigurationError):
+ utils.yaml_load(fd)
+
+ @tempdir()
+ @tempdir()
+ def test_copy_files(self, src_dir, dst_dir):
+ cases = [
+ dict(
+ src_path='foo.txt',
+ dst_path='foo.txt',
+ expected='foo.txt',
+ ),
+ dict(
+ src_path='bar.txt',
+ dst_path='foo/', # ensure src filename is appended
+ expected='foo/bar.txt',
+ ),
+ dict(
+ src_path='baz.txt',
+ dst_path='foo/bar/baz.txt', # ensure missing dirs are created
+ expected='foo/bar/baz.txt',
+ ),
+ ]
+
+ for case in cases:
+ src, dst, expected = case['src_path'], case['dst_path'], case['expected']
+ with self.subTest(src):
+ src = os.path.join(src_dir, src)
+ with open(src, 'w') as f:
+ f.write('content')
+ dst = os.path.join(dst_dir, dst)
+ utils.copy_file(src, dst)
+ self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected)))
+
+ @tempdir()
+ @tempdir()
+ def test_copy_files_without_permissions(self, src_dir, dst_dir):
+ cases = [
+ dict(src_path='foo.txt', expected='foo.txt'),
+ dict(src_path='bar.txt', expected='bar.txt'),
+ dict(src_path='baz.txt', expected='baz.txt'),
+ ]
+
+ try:
+ for case in cases:
+ src, expected = case['src_path'], case['expected']
+ with self.subTest(src):
+ src = os.path.join(src_dir, src)
+ with open(src, 'w') as f:
+ f.write('content')
+ # Set src file to read-only
+ os.chmod(src, stat.S_IRUSR)
+ utils.copy_file(src, dst_dir)
+ self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected)))
+ self.assertNotEqual(
+ os.stat(src).st_mode, os.stat(os.path.join(dst_dir, expected)).st_mode
+ )
+ # While src was read-only, dst must remain writable
+ self.assertTrue(os.access(os.path.join(dst_dir, expected), os.W_OK))
+ finally:
+ for case in cases:
+ # Undo read-only so we can delete temp files
+ src = os.path.join(src_dir, case['src_path'])
+ if os.path.exists(src):
+ os.chmod(src, stat.S_IRUSR | stat.S_IWUSR)
+
+ def test_mm_meta_data(self):
+ doc = dedent(
+ """
+ Title: Foo Bar
+ Date: 2018-07-10
+ Summary: Line one
+ Line two
+ Tags: foo
+ Tags: bar
+
+ Doc body
+ """
+ )
+ self.assertEqual(
+ meta.get_data(doc),
+ (
+ "Doc body",
+ {
+ 'title': 'Foo Bar',
+ 'date': '2018-07-10',
+ 'summary': 'Line one Line two',
+ 'tags': 'foo bar',
+ },
+ ),
+ )
+
+ def test_mm_meta_data_blank_first_line(self):
+ doc = '\nfoo: bar\nDoc body'
+ self.assertEqual(meta.get_data(doc), (doc.lstrip(), {}))
+
+ def test_yaml_meta_data(self):
+ doc = dedent(
+ """
+ ---
+ Title: Foo Bar
+ Date: 2018-07-10
+ Summary: Line one
+ Line two
+ Tags:
+ - foo
+ - bar
+ ---
+ Doc body
+ """
+ )
+ self.assertEqual(
+ meta.get_data(doc),
+ (
+ "Doc body",
+ {
+ 'Title': 'Foo Bar',
+ 'Date': datetime.date(2018, 7, 10),
+ 'Summary': 'Line one Line two',
+ 'Tags': ['foo', 'bar'],
+ },
+ ),
+ )
+
+ def test_yaml_meta_data_not_dict(self):
+ doc = dedent(
+ """
+ ---
+ - List item
+ ---
+ Doc body
+ """
+ )
+ self.assertEqual(meta.get_data(doc), (doc, {}))
+
+ def test_yaml_meta_data_invalid(self):
+ doc = dedent(
+ """
+ ---
+ foo: bar: baz
+ ---
+ Doc body
+ """
+ )
+ self.assertEqual(meta.get_data(doc), (doc, {}))
+
+ def test_no_meta_data(self):
+ doc = dedent(
+ """
+ Doc body
+ """
+ )
+ self.assertEqual(meta.get_data(doc), (doc, {}))
+
+
+class LogCounterTests(unittest.TestCase):
+ def setUp(self):
+ self.log = logging.getLogger('dummy')
+ self.log.propagate = False
+ self.log.setLevel(1)
+ self.counter = utils.CountHandler()
+ self.log.addHandler(self.counter)
+
+ def tearDown(self):
+ self.log.removeHandler(self.counter)
+
+ def test_default_values(self):
+ self.assertEqual(self.counter.get_counts(), [])
+
+ def test_count_critical(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.critical('msg')
+ self.assertEqual(self.counter.get_counts(), [('CRITICAL', 1)])
+
+ def test_count_error(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.error('msg')
+ self.assertEqual(self.counter.get_counts(), [('ERROR', 1)])
+
+ def test_count_warning(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.warning('msg')
+ self.assertEqual(self.counter.get_counts(), [('WARNING', 1)])
+
+ def test_count_info(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.info('msg')
+ self.assertEqual(self.counter.get_counts(), [('INFO', 1)])
+
+ def test_count_debug(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.debug('msg')
+ self.assertEqual(self.counter.get_counts(), [('DEBUG', 1)])
+
+ def test_count_multiple(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.log.warning('msg 1')
+ self.assertEqual(self.counter.get_counts(), [('WARNING', 1)])
+ self.log.warning('msg 2')
+ self.assertEqual(self.counter.get_counts(), [('WARNING', 2)])
+ self.log.debug('msg 3')
+ self.assertEqual(self.counter.get_counts(), [('WARNING', 2), ('DEBUG', 1)])
+ self.log.error('mdg 4')
+ self.assertEqual(self.counter.get_counts(), [('ERROR', 1), ('WARNING', 2), ('DEBUG', 1)])
+
+ def test_log_level(self):
+ self.assertEqual(self.counter.get_counts(), [])
+ self.counter.setLevel(logging.ERROR)
+ self.log.error('counted')
+ self.log.warning('not counted')
+ self.log.info('not counted')
+ self.assertEqual(self.counter.get_counts(), [('ERROR', 1)])
+ self.counter.setLevel(logging.WARNING)
+ self.log.error('counted')
+ self.log.warning('counted')
+ self.log.info('not counted')
+ self.assertEqual(self.counter.get_counts(), [('ERROR', 2), ('WARNING', 1)])
diff --git a/web/lib/python3.11/site-packages/mkdocs/theme.py b/web/lib/python3.11/site-packages/mkdocs/theme.py
new file mode 100644
index 00000000..06b69d46
--- /dev/null
+++ b/web/lib/python3.11/site-packages/mkdocs/theme.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any, Optional
+
+import jinja2
+
+from mkdocs import localization, utils
+from mkdocs.config.base import ValidationError
+from mkdocs.utils import filters
+
+log = logging.getLogger(__name__)
+
+
+class Theme:
+ """
+ A Theme object.
+
+ Keywords:
+
+ name: The name of the theme as defined by its entrypoint.
+
+ custom_dir: User defined directory for custom templates.
+
+ static_templates: A list of templates to render as static pages.
+
+ All other keywords are passed as-is and made available as a key/value mapping.
+
+ """
+
+ def __init__(self, name: Optional[str] = None, **user_config) -> None:
+ self.name = name
+ self._vars = {'name': name, 'locale': 'en'}
+
+ # MkDocs provided static templates are always included
+ package_dir = os.path.abspath(os.path.dirname(__file__))
+ mkdocs_templates = os.path.join(package_dir, 'templates')
+ self.static_templates = set(os.listdir(mkdocs_templates))
+
+ # Build self.dirs from various sources in order of precedence
+ self.dirs = []
+
+ if 'custom_dir' in user_config:
+ self.dirs.append(user_config.pop('custom_dir'))
+
+ if name:
+ self._load_theme_config(name)
+
+ # Include templates provided directly by MkDocs (outside any theme)
+ self.dirs.append(mkdocs_templates)
+
+ # Handle remaining user configs. Override theme configs (if set)
+ self.static_templates.update(user_config.pop('static_templates', []))
+ self._vars.update(user_config)
+
+ # Validate locale and convert to Locale object
+ self._vars['locale'] = localization.parse_locale(self._vars['locale'])
+
+ def __repr__(self) -> str:
+ return "{}(name='{}', dirs={}, static_templates={}, {})".format(
+ self.__class__.__name__,
+ self.name,
+ self.dirs,
+ list(self.static_templates),
+ ', '.join(f'{k}={v!r}' for k, v in self._vars.items()),
+ )
+
+ def __getitem__(self, key: str) -> Any:
+ return self._vars[key]
+
+ def __setitem__(self, key, value):
+ self._vars[key] = value
+
+ def __contains__(self, item: str) -> bool:
+ return item in self._vars
+
+ def __iter__(self):
+ return iter(self._vars)
+
+ def _load_theme_config(self, name: str) -> None:
+ """Recursively load theme and any parent themes."""
+
+ theme_dir = utils.get_theme_dir(name)
+ self.dirs.append(theme_dir)
+
+ try:
+ file_path = os.path.join(theme_dir, 'mkdocs_theme.yml')
+ with open(file_path, 'rb') as f:
+ theme_config = utils.yaml_load(f)
+ if theme_config is None:
+ theme_config = {}
+ except OSError as e:
+ log.debug(e)
+ raise ValidationError(
+ f"The theme '{name}' does not appear to have a configuration file. "
+ f"Please upgrade to a current version of the theme."
+ )
+
+ log.debug(f"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}")
+
+ parent_theme = theme_config.pop('extends', None)
+ if parent_theme:
+ themes = utils.get_theme_names()
+ if parent_theme not in themes:
+ raise ValidationError(
+ f"The theme '{name}' inherits from '{parent_theme}', which does not appear to be installed. "
+ f"The available installed themes are: {', '.join(themes)}"
+ )
+ self._load_theme_config(parent_theme)
+
+ self.static_templates.update(theme_config.pop('static_templates', []))
+ self._vars.update(theme_config)
+
+ def get_env(self) -> jinja2.Environment:
+ """Return a Jinja environment for the theme."""
+
+ loader = jinja2.FileSystemLoader(self.dirs)
+ # No autoreload because editing a template in the middle of a build is not useful.
+ env = jinja2.Environment(loader=loader, auto_reload=False)
+ env.filters['url'] = filters.url_filter
+ localization.install_translations(env, self._vars['locale'], self.dirs)
+ return env
diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/__init__.py b/web/lib/python3.11/site-packages/mkdocs/themes/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/themes/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 00000000..f6f1c752
Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/themes/__pycache__/__init__.cpython-311.pyc differ
diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/mkdocs/404.html b/web/lib/python3.11/site-packages/mkdocs/themes/mkdocs/404.html
new file mode 100644
index 00000000..c0503d74
--- /dev/null
+++ b/web/lib/python3.11/site-packages/mkdocs/themes/mkdocs/404.html
@@ -0,0 +1,12 @@
+{% extends "base.html" %}
+
+{% block content %}
+
+ {% trans %}Page not found{% endtrans %}
+t |
{% trans %}Keys{% endtrans %} | +{% trans %}Action{% endtrans %} | +
---|---|
? | +{% trans %}Open this help{% endtrans %} | +
n | +{% trans %}Next page{% endtrans %} | +
p | +{% trans %}Previous page{% endtrans %} | +
s | +{% trans %}Search{% endtrans %} | +
{% trans %}From here you can search these documents. Enter your search terms below.{% endtrans %}
+ + +{% trans %}Page not found{% endtrans %}
+ +{% endblock %} diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/__init__.py b/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..0d5c4119 Binary files /dev/null and b/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/base.html b/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/base.html new file mode 100644 index 00000000..7683e706 --- /dev/null +++ b/web/lib/python3.11/site-packages/mkdocs/themes/readthedocs/base.html @@ -0,0 +1,191 @@ + + + + {%- block site_meta %} + + + + {%- if page and page.is_homepage %}{%- endif %} + {%- if config.site_author %}{%- endif %} + {%- if page and page.canonical_url %}{%- endif %} + {%- if config.site_favicon %} + + {%- else %} + + {%- endif %} + {%- endblock %} + + {%- block htmltitle %} +# pre-release + [-_\.]? + (?P(a|b|c|rc|alpha|beta|pre|preview)) + [-_\.]? + (?P [0-9]+)? + )? + (?P # post release + (?:-(?P [0-9]+)) + | + (?: + [-_\.]? + (?P post|rev|r) + [-_\.]? + (?P [0-9]+)? + ) + )? + (?P # dev release + [-_\.]? + (?P dev) + [-_\.]? + (?P [0-9]+)? + )? + ) + (?:\+(?P [a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version +""" + +VERSION_PATTERN = _VERSION_PATTERN +""" +A string containing the regular expression used to match a valid version. + +The pattern is not anchored at either end, and is intended for embedding in larger +expressions (for example, matching a version number as part of a file name). The +regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE`` +flags set. + +:meta hide-value: +""" + + +class Version(_BaseVersion): + """This class abstracts handling of a project's versions. + + A :class:`Version` instance is comparison aware and can be compared and + sorted using the standard Python interfaces. + + >>> v1 = Version("1.0a5") + >>> v2 = Version("1.0") + >>> v1 + + >>> v2 + + >>> v1 < v2 + True + >>> v1 == v2 + False + >>> v1 > v2 + False + >>> v1 >= v2 + False + >>> v1 <= v2 + True + """ + + _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE) + + def __init__(self, version: str) -> None: + """Initialize a Version object. + + :param version: + The string representation of a version which will be parsed and normalized + before use. + :raises InvalidVersion: + If the ``version`` does not conform to PEP 440 in any way then this + exception will be raised. + """ + + # Validate the version and parse it into pieces + match = self._regex.search(version) + if not match: + raise InvalidVersion(f"Invalid version: '{version}'") + + # Store the parsed out pieces of the version + self._version = _Version( + epoch=int(match.group("epoch")) if match.group("epoch") else 0, + release=tuple(int(i) for i in match.group("release").split(".")), + pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")), + post=_parse_letter_version( + match.group("post_l"), match.group("post_n1") or match.group("post_n2") + ), + dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")), + local=_parse_local_version(match.group("local")), + ) + + # Generate a key which will be used for sorting + self._key = _cmpkey( + self._version.epoch, + self._version.release, + self._version.pre, + self._version.post, + self._version.dev, + self._version.local, + ) + + def __repr__(self) -> str: + """A representation of the Version that shows all internal state. + + >>> Version('1.0.0') + + """ + return f" " + + def __str__(self) -> str: + """A string representation of the version that can be rounded-tripped. + + >>> str(Version("1.0a5")) + '1.0a5' + """ + parts = [] + + # Epoch + if self.epoch != 0: + parts.append(f"{self.epoch}!") + + # Release segment + parts.append(".".join(str(x) for x in self.release)) + + # Pre-release + if self.pre is not None: + parts.append("".join(str(x) for x in self.pre)) + + # Post-release + if self.post is not None: + parts.append(f".post{self.post}") + + # Development release + if self.dev is not None: + parts.append(f".dev{self.dev}") + + # Local version segment + if self.local is not None: + parts.append(f"+{self.local}") + + return "".join(parts) + + @property + def epoch(self) -> int: + """The epoch of the version. + + >>> Version("2.0.0").epoch + 0 + >>> Version("1!2.0.0").epoch + 1 + """ + _epoch: int = self._version.epoch + return _epoch + + @property + def release(self) -> Tuple[int, ...]: + """The components of the "release" segment of the version. + + >>> Version("1.2.3").release + (1, 2, 3) + >>> Version("2.0.0").release + (2, 0, 0) + >>> Version("1!2.0.0.post0").release + (2, 0, 0) + + Includes trailing zeroes but not the epoch or any pre-release / development / + post-release suffixes. + """ + _release: Tuple[int, ...] = self._version.release + return _release + + @property + def pre(self) -> Optional[Tuple[str, int]]: + """The pre-release segment of the version. + + >>> print(Version("1.2.3").pre) + None + >>> Version("1.2.3a1").pre + ('a', 1) + >>> Version("1.2.3b1").pre + ('b', 1) + >>> Version("1.2.3rc1").pre + ('rc', 1) + """ + _pre: Optional[Tuple[str, int]] = self._version.pre + return _pre + + @property + def post(self) -> Optional[int]: + """The post-release number of the version. + + >>> print(Version("1.2.3").post) + None + >>> Version("1.2.3.post1").post + 1 + """ + return self._version.post[1] if self._version.post else None + + @property + def dev(self) -> Optional[int]: + """The development number of the version. + + >>> print(Version("1.2.3").dev) + None + >>> Version("1.2.3.dev1").dev + 1 + """ + return self._version.dev[1] if self._version.dev else None + + @property + def local(self) -> Optional[str]: + """The local version segment of the version. + + >>> print(Version("1.2.3").local) + None + >>> Version("1.2.3+abc").local + 'abc' + """ + if self._version.local: + return ".".join(str(x) for x in self._version.local) + else: + return None + + @property + def public(self) -> str: + """The public portion of the version. + + >>> Version("1.2.3").public + '1.2.3' + >>> Version("1.2.3+abc").public + '1.2.3' + >>> Version("1.2.3+abc.dev1").public + '1.2.3' + """ + return str(self).split("+", 1)[0] + + @property + def base_version(self) -> str: + """The "base version" of the version. + + >>> Version("1.2.3").base_version + '1.2.3' + >>> Version("1.2.3+abc").base_version + '1.2.3' + >>> Version("1!1.2.3+abc.dev1").base_version + '1!1.2.3' + + The "base version" is the public version of the project without any pre or post + release markers. + """ + parts = [] + + # Epoch + if self.epoch != 0: + parts.append(f"{self.epoch}!") + + # Release segment + parts.append(".".join(str(x) for x in self.release)) + + return "".join(parts) + + @property + def is_prerelease(self) -> bool: + """Whether this version is a pre-release. + + >>> Version("1.2.3").is_prerelease + False + >>> Version("1.2.3a1").is_prerelease + True + >>> Version("1.2.3b1").is_prerelease + True + >>> Version("1.2.3rc1").is_prerelease + True + >>> Version("1.2.3dev1").is_prerelease + True + """ + return self.dev is not None or self.pre is not None + + @property + def is_postrelease(self) -> bool: + """Whether this version is a post-release. + + >>> Version("1.2.3").is_postrelease + False + >>> Version("1.2.3.post1").is_postrelease + True + """ + return self.post is not None + + @property + def is_devrelease(self) -> bool: + """Whether this version is a development release. + + >>> Version("1.2.3").is_devrelease + False + >>> Version("1.2.3.dev1").is_devrelease + True + """ + return self.dev is not None + + @property + def major(self) -> int: + """The first item of :attr:`release` or ``0`` if unavailable. + + >>> Version("1.2.3").major + 1 + """ + return self.release[0] if len(self.release) >= 1 else 0 + + @property + def minor(self) -> int: + """The second item of :attr:`release` or ``0`` if unavailable. + + >>> Version("1.2.3").minor + 2 + >>> Version("1").minor + 0 + """ + return self.release[1] if len(self.release) >= 2 else 0 + + @property + def micro(self) -> int: + """The third item of :attr:`release` or ``0`` if unavailable. + + >>> Version("1.2.3").micro + 3 + >>> Version("1").micro + 0 + """ + return self.release[2] if len(self.release) >= 3 else 0 + + +def _parse_letter_version( + letter: str, number: Union[str, bytes, SupportsInt] +) -> Optional[Tuple[str, int]]: + + if letter: + # We consider there to be an implicit 0 in a pre-release if there is + # not a numeral associated with it. + if number is None: + number = 0 + + # We normalize any letters to their lower case form + letter = letter.lower() + + # We consider some words to be alternate spellings of other words and + # in those cases we want to normalize the spellings to our preferred + # spelling. + if letter == "alpha": + letter = "a" + elif letter == "beta": + letter = "b" + elif letter in ["c", "pre", "preview"]: + letter = "rc" + elif letter in ["rev", "r"]: + letter = "post" + + return letter, int(number) + if not letter and number: + # We assume if we are given a number, but we are not given a letter + # then this is using the implicit post release syntax (e.g. 1.0-1) + letter = "post" + + return letter, int(number) + + return None + + +_local_version_separators = re.compile(r"[\._-]") + + +def _parse_local_version(local: str) -> Optional[LocalType]: + """ + Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). + """ + if local is not None: + return tuple( + part.lower() if not part.isdigit() else int(part) + for part in _local_version_separators.split(local) + ) + return None + + +def _cmpkey( + epoch: int, + release: Tuple[int, ...], + pre: Optional[Tuple[str, int]], + post: Optional[Tuple[str, int]], + dev: Optional[Tuple[str, int]], + local: Optional[Tuple[SubLocalType]], +) -> CmpKey: + + # When we compare a release version, we want to compare it with all of the + # trailing zeros removed. So we'll use a reverse the list, drop all the now + # leading zeros until we come to something non zero, then take the rest + # re-reverse it back into the correct order and make it a tuple and use + # that for our sorting key. + _release = tuple( + reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))) + ) + + # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0. + # We'll do this by abusing the pre segment, but we _only_ want to do this + # if there is not a pre or a post segment. If we have one of those then + # the normal sorting rules will handle this case correctly. + if pre is None and post is None and dev is not None: + _pre: PrePostDevType = NegativeInfinity + # Versions without a pre-release (except as noted above) should sort after + # those with one. + elif pre is None: + _pre = Infinity + else: + _pre = pre + + # Versions without a post segment should sort before those with one. + if post is None: + _post: PrePostDevType = NegativeInfinity + + else: + _post = post + + # Versions without a development segment should sort after those with one. + if dev is None: + _dev: PrePostDevType = Infinity + + else: + _dev = dev + + if local is None: + # Versions without a local segment should sort before those with one. + _local: LocalType = NegativeInfinity + else: + # Versions with a local segment need that segment parsed to implement + # the sorting rules in PEP440. + # - Alpha numeric segments sort before numeric segments + # - Alpha numeric segments sort lexicographically + # - Numeric segments sort numerically + # - Shorter versions sort before longer versions when the prefixes + # match exactly + _local = tuple( + (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local + ) + + return epoch, _release, _pre, _post, _dev, _local diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/INSTALLER b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/INSTALLER new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/LICENSE.txt b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/LICENSE.txt new file mode 100644 index 00000000..8e7b65ea --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2008-present The pip developers (see AUTHORS.txt file) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/METADATA b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/METADATA new file mode 100644 index 00000000..e935e1a5 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/METADATA @@ -0,0 +1,88 @@ +Metadata-Version: 2.1 +Name: pip +Version: 22.3.1 +Summary: The PyPA recommended tool for installing Python packages. +Home-page: https://pip.pypa.io/ +Author: The pip developers +Author-email: distutils-sig@python.org +License: MIT +Project-URL: Documentation, https://pip.pypa.io +Project-URL: Source, https://github.com/pypa/pip +Project-URL: Changelog, https://pip.pypa.io/en/stable/news/ +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Topic :: Software Development :: Build Tools +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.7 +License-File: LICENSE.txt + +pip - The Python Package Installer +================================== + +.. image:: https://img.shields.io/pypi/v/pip.svg + :target: https://pypi.org/project/pip/ + +.. image:: https://readthedocs.org/projects/pip/badge/?version=latest + :target: https://pip.pypa.io/en/latest + +pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes. + +Please take a look at our documentation for how to install and use pip: + +* `Installation`_ +* `Usage`_ + +We release updates regularly, with a new version every 3 months. Find more details in our documentation: + +* `Release notes`_ +* `Release process`_ + +In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right. + +**Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3. + +If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms: + +* `Issue tracking`_ +* `Discourse channel`_ +* `User IRC`_ + +If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms: + +* `GitHub page`_ +* `Development documentation`_ +* `Development IRC`_ + +Code of Conduct +--------------- + +Everyone interacting in the pip project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _package installer: https://packaging.python.org/guides/tool-recommendations/ +.. _Python Package Index: https://pypi.org +.. _Installation: https://pip.pypa.io/en/stable/installation/ +.. _Usage: https://pip.pypa.io/en/stable/ +.. _Release notes: https://pip.pypa.io/en/stable/news.html +.. _Release process: https://pip.pypa.io/en/latest/development/release-process/ +.. _GitHub page: https://github.com/pypa/pip +.. _Development documentation: https://pip.pypa.io/en/latest/development +.. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html +.. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020 +.. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html +.. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support +.. _Issue tracking: https://github.com/pypa/pip/issues +.. _Discourse channel: https://discuss.python.org/c/packaging +.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa +.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/RECORD b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/RECORD new file mode 100644 index 00000000..47a696f8 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/RECORD @@ -0,0 +1,992 @@ +../../../bin/pip,sha256=4P5jVUk9u63Kc5ECQ3psLLKkWTYmQ5xOWBfs7I-2KsA,267 +../../../bin/pip3,sha256=4P5jVUk9u63Kc5ECQ3psLLKkWTYmQ5xOWBfs7I-2KsA,267 +../../../bin/pip3.11,sha256=4P5jVUk9u63Kc5ECQ3psLLKkWTYmQ5xOWBfs7I-2KsA,267 +pip-22.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pip-22.3.1.dist-info/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093 +pip-22.3.1.dist-info/METADATA,sha256=a9COYc5qzklDgbGlrKYkypMXon4A6IDgpeUTWLr7zzY,4072 +pip-22.3.1.dist-info/RECORD,, +pip-22.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip-22.3.1.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +pip-22.3.1.dist-info/entry_points.txt,sha256=xg35gOct0aY8S3ftLtweJ0uw3KBAIVyW4k-0Jx1rkNE,125 +pip-22.3.1.dist-info/top_level.txt,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pip/__init__.py,sha256=Z2hXGRMvmdhpmmqr0OW1fA2Jje8tnmU0uzibRoUF-w8,357 +pip/__main__.py,sha256=mXwWDftNLMKfwVqKFWGE_uuBZvGSIiUELhLkeysIuZc,1198 +pip/__pip-runner__.py,sha256=EnrfKmKMzWAdqg_JicLCOP9Y95Ux7zHh4ObvqLtQcjo,1444 +pip/__pycache__/__init__.cpython-311.pyc,, +pip/__pycache__/__main__.cpython-311.pyc,, +pip/__pycache__/__pip-runner__.cpython-311.pyc,, +pip/_internal/__init__.py,sha256=nnFCuxrPMgALrIDxSoy-H6Zj4W4UY60D-uL1aJyq0pc,573 +pip/_internal/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/__pycache__/build_env.cpython-311.pyc,, +pip/_internal/__pycache__/cache.cpython-311.pyc,, +pip/_internal/__pycache__/configuration.cpython-311.pyc,, +pip/_internal/__pycache__/exceptions.cpython-311.pyc,, +pip/_internal/__pycache__/main.cpython-311.pyc,, +pip/_internal/__pycache__/pyproject.cpython-311.pyc,, +pip/_internal/__pycache__/self_outdated_check.cpython-311.pyc,, +pip/_internal/__pycache__/wheel_builder.cpython-311.pyc,, +pip/_internal/build_env.py,sha256=gEAT8R6SuWbg2mcrsmOTKWMw_x5pedMzvSTxQS57JZs,10234 +pip/_internal/cache.py,sha256=C3n78VnBga9rjPXZqht_4A4d-T25poC7K0qBM7FHDhU,10734 +pip/_internal/cli/__init__.py,sha256=FkHBgpxxb-_gd6r1FjnNhfMOzAUYyXoXKJ6abijfcFU,132 +pip/_internal/cli/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/cli/__pycache__/autocompletion.cpython-311.pyc,, +pip/_internal/cli/__pycache__/base_command.cpython-311.pyc,, +pip/_internal/cli/__pycache__/cmdoptions.cpython-311.pyc,, +pip/_internal/cli/__pycache__/command_context.cpython-311.pyc,, +pip/_internal/cli/__pycache__/main.cpython-311.pyc,, +pip/_internal/cli/__pycache__/main_parser.cpython-311.pyc,, +pip/_internal/cli/__pycache__/parser.cpython-311.pyc,, +pip/_internal/cli/__pycache__/progress_bars.cpython-311.pyc,, +pip/_internal/cli/__pycache__/req_command.cpython-311.pyc,, +pip/_internal/cli/__pycache__/spinners.cpython-311.pyc,, +pip/_internal/cli/__pycache__/status_codes.cpython-311.pyc,, +pip/_internal/cli/autocompletion.py,sha256=wY2JPZY2Eji1vhR7bVo-yCBPJ9LCy6P80iOAhZD1Vi8,6676 +pip/_internal/cli/base_command.py,sha256=t1D5x40Hfn9HnPnMt-iSxvqL14nht2olBCacW74pc-k,7842 +pip/_internal/cli/cmdoptions.py,sha256=Jlarlzz9qv9tC_tCaEbcc_jVvrPreFLBBUnDgoyWflw,29381 +pip/_internal/cli/command_context.py,sha256=RHgIPwtObh5KhMrd3YZTkl8zbVG-6Okml7YbFX4Ehg0,774 +pip/_internal/cli/main.py,sha256=ioJ8IVlb2K1qLOxR-tXkee9lURhYV89CDM71MKag7YY,2472 +pip/_internal/cli/main_parser.py,sha256=laDpsuBDl6kyfywp9eMMA9s84jfH2TJJn-vmL0GG90w,4338 +pip/_internal/cli/parser.py,sha256=tWP-K1uSxnJyXu3WE0kkH3niAYRBeuUaxeydhzOdhL4,10817 +pip/_internal/cli/progress_bars.py,sha256=So4mPoSjXkXiSHiTzzquH3VVyVD_njXlHJSExYPXAow,1968 +pip/_internal/cli/req_command.py,sha256=ypTutLv4j_efxC2f6C6aCQufxre-zaJdi5m_tWlLeBk,18172 +pip/_internal/cli/spinners.py,sha256=hIJ83GerdFgFCdobIA23Jggetegl_uC4Sp586nzFbPE,5118 +pip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116 +pip/_internal/commands/__init__.py,sha256=5oRO9O3dM2vGuh0bFw4HOVletryrz5HHMmmPWwJrH9U,3882 +pip/_internal/commands/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/commands/__pycache__/cache.cpython-311.pyc,, +pip/_internal/commands/__pycache__/check.cpython-311.pyc,, +pip/_internal/commands/__pycache__/completion.cpython-311.pyc,, +pip/_internal/commands/__pycache__/configuration.cpython-311.pyc,, +pip/_internal/commands/__pycache__/debug.cpython-311.pyc,, +pip/_internal/commands/__pycache__/download.cpython-311.pyc,, +pip/_internal/commands/__pycache__/freeze.cpython-311.pyc,, +pip/_internal/commands/__pycache__/hash.cpython-311.pyc,, +pip/_internal/commands/__pycache__/help.cpython-311.pyc,, +pip/_internal/commands/__pycache__/index.cpython-311.pyc,, +pip/_internal/commands/__pycache__/inspect.cpython-311.pyc,, +pip/_internal/commands/__pycache__/install.cpython-311.pyc,, +pip/_internal/commands/__pycache__/list.cpython-311.pyc,, +pip/_internal/commands/__pycache__/search.cpython-311.pyc,, +pip/_internal/commands/__pycache__/show.cpython-311.pyc,, +pip/_internal/commands/__pycache__/uninstall.cpython-311.pyc,, +pip/_internal/commands/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/commands/cache.py,sha256=muaT0mbL-ZUpn6AaushVAipzTiMwE4nV2BLbJBwt_KQ,7582 +pip/_internal/commands/check.py,sha256=0gjXR7j36xJT5cs2heYU_dfOfpnFfzX8OoPNNoKhqdM,1685 +pip/_internal/commands/completion.py,sha256=H0TJvGrdsoleuIyQKzJbicLFppYx2OZA0BLNpQDeFjI,4129 +pip/_internal/commands/configuration.py,sha256=NB5uf8HIX8-li95YLoZO09nALIWlLCHDF5aifSKcBn8,9815 +pip/_internal/commands/debug.py,sha256=kVjn-O1ixLk0webD0w9vfFFq_GCTUTd2hmLOnYtDCig,6573 +pip/_internal/commands/download.py,sha256=LwKEyYMG2L67nQRyGo8hQdNEeMU2bmGWqJfcB8JDXas,5289 +pip/_internal/commands/freeze.py,sha256=gCjoD6foBZPBAAYx5t8zZLkJhsF_ZRtnb3dPuD7beO8,2951 +pip/_internal/commands/hash.py,sha256=EVVOuvGtoPEdFi8SNnmdqlCQrhCxV-kJsdwtdcCnXGQ,1703 +pip/_internal/commands/help.py,sha256=gcc6QDkcgHMOuAn5UxaZwAStsRBrnGSn_yxjS57JIoM,1132 +pip/_internal/commands/index.py,sha256=1VVXXj5MsI2qH-N7uniQQyVkg-KCn_RdjiyiUmkUS5U,4762 +pip/_internal/commands/inspect.py,sha256=mRJ9aIkBQN0IJ7Um8pzaxAzVPIgL8KfWHx1fWKJgUAQ,3374 +pip/_internal/commands/install.py,sha256=_XbW0PyxtZCMMNqo8mDaOq3TBRiJNFM-94CR27mburc,31726 +pip/_internal/commands/list.py,sha256=Fk1TSxB33NlRS4qlLQ0xwnytnF9-zkQJbKQYv2xc4Q4,12343 +pip/_internal/commands/search.py,sha256=sbBZiARRc050QquOKcCvOr2K3XLsoYebLKZGRi__iUI,5697 +pip/_internal/commands/show.py,sha256=CJI8q4SSY0X346K1hi4Th8Nbyhl4nxPTBJUuzOlTaYE,6129 +pip/_internal/commands/uninstall.py,sha256=0JQhifYxecNrJAwoILFwjm9V1V3liXzNT-y4bgRXXPw,3680 +pip/_internal/commands/wheel.py,sha256=mbFJd4dmUfrVFJkQbK8n2zHyRcD3AI91f7EUo9l3KYg,7396 +pip/_internal/configuration.py,sha256=uBKTus43pDIO6IzT2mLWQeROmHhtnoabhniKNjPYvD0,13529 +pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858 +pip/_internal/distributions/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/distributions/__pycache__/base.cpython-311.pyc,, +pip/_internal/distributions/__pycache__/installed.cpython-311.pyc,, +pip/_internal/distributions/__pycache__/sdist.cpython-311.pyc,, +pip/_internal/distributions/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/distributions/base.py,sha256=jrF1Vi7eGyqFqMHrieh1PIOrGU7KeCxhYPZnbvtmvGY,1221 +pip/_internal/distributions/installed.py,sha256=NI2OgsgH9iBq9l5vB-56vOg5YsybOy-AU4VE5CSCO2I,729 +pip/_internal/distributions/sdist.py,sha256=SQBdkatXSigKGG_SaD0U0p1Jwdfrg26UCNcHgkXZfdA,6494 +pip/_internal/distributions/wheel.py,sha256=m-J4XO-gvFerlYsFzzSXYDvrx8tLZlJFTCgDxctn8ig,1164 +pip/_internal/exceptions.py,sha256=BfvcyN2iEv3Sf00SVmSk59lEeZEBHELqkuoN2KeIWKc,20942 +pip/_internal/index/__init__.py,sha256=vpt-JeTZefh8a-FC22ZeBSXFVbuBcXSGiILhQZJaNpQ,30 +pip/_internal/index/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/index/__pycache__/collector.cpython-311.pyc,, +pip/_internal/index/__pycache__/package_finder.cpython-311.pyc,, +pip/_internal/index/__pycache__/sources.cpython-311.pyc,, +pip/_internal/index/collector.py,sha256=Pb9FW9STH2lwaApCIdMCivsbPP5pSYQp5bh3nLQBkDU,16503 +pip/_internal/index/package_finder.py,sha256=kmcMu5_i-BP6v3NQGY0_am1ezxM2Gk4t00arZMmm4sc,37596 +pip/_internal/index/sources.py,sha256=SVyPitv08-Qalh2_Bk5diAJ9GAA_d-a93koouQodAG0,6557 +pip/_internal/locations/__init__.py,sha256=QhB-Y6TNyaU010cimm2T4wM5loe8oRdjLwJ6xmsGc-k,17552 +pip/_internal/locations/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/locations/__pycache__/_distutils.cpython-311.pyc,, +pip/_internal/locations/__pycache__/_sysconfig.cpython-311.pyc,, +pip/_internal/locations/__pycache__/base.cpython-311.pyc,, +pip/_internal/locations/_distutils.py,sha256=wgHDvHGNZHtlcHkQjYovHzkEUBzisR0iOh7OqCIkB5g,6302 +pip/_internal/locations/_sysconfig.py,sha256=nM-DiVHXWTxippdmN0MGVl5r7OIfIMy3vgDMlo8c_oo,7867 +pip/_internal/locations/base.py,sha256=ufyDqPwZ4jLbScD44u8AwTVI-3ft8O78UGrroQI5f68,2573 +pip/_internal/main.py,sha256=r-UnUe8HLo5XFJz8inTcOOTiu_sxNhgHb6VwlGUllOI,340 +pip/_internal/metadata/__init__.py,sha256=84j1dPJaIoz5Q2ZTPi0uB1iaDAHiUNfKtYSGQCfFKpo,4280 +pip/_internal/metadata/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/metadata/__pycache__/_json.cpython-311.pyc,, +pip/_internal/metadata/__pycache__/base.cpython-311.pyc,, +pip/_internal/metadata/__pycache__/pkg_resources.cpython-311.pyc,, +pip/_internal/metadata/_json.py,sha256=BTkWfFDrWFwuSodImjtbAh8wCL3isecbnjTb5E6UUDI,2595 +pip/_internal/metadata/base.py,sha256=vIwIo1BtoqegehWMAXhNrpLGYBq245rcaCNkBMPnTU8,25277 +pip/_internal/metadata/importlib/__init__.py,sha256=9ZVO8BoE7NEZPmoHp5Ap_NJo0HgNIezXXg-TFTtt3Z4,107 +pip/_internal/metadata/importlib/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/metadata/importlib/__pycache__/_compat.cpython-311.pyc,, +pip/_internal/metadata/importlib/__pycache__/_dists.cpython-311.pyc,, +pip/_internal/metadata/importlib/__pycache__/_envs.cpython-311.pyc,, +pip/_internal/metadata/importlib/_compat.py,sha256=GAe_prIfCE4iUylrnr_2dJRlkkBVRUbOidEoID7LPoE,1882 +pip/_internal/metadata/importlib/_dists.py,sha256=BUV8y6D0PePZrEN3vfJL-m1FDqZ6YPRgAiBeBinHhNg,8181 +pip/_internal/metadata/importlib/_envs.py,sha256=7BxanCh3T7arusys__O2ZHJdnmDhQXFmfU7x1-jB5xI,7457 +pip/_internal/metadata/pkg_resources.py,sha256=WjwiNdRsvxqxL4MA5Tb5a_q3Q3sUhdpbZF8wGLtPMI0,9773 +pip/_internal/models/__init__.py,sha256=3DHUd_qxpPozfzouoqa9g9ts1Czr5qaHfFxbnxriepM,63 +pip/_internal/models/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/models/__pycache__/candidate.cpython-311.pyc,, +pip/_internal/models/__pycache__/direct_url.cpython-311.pyc,, +pip/_internal/models/__pycache__/format_control.cpython-311.pyc,, +pip/_internal/models/__pycache__/index.cpython-311.pyc,, +pip/_internal/models/__pycache__/installation_report.cpython-311.pyc,, +pip/_internal/models/__pycache__/link.cpython-311.pyc,, +pip/_internal/models/__pycache__/scheme.cpython-311.pyc,, +pip/_internal/models/__pycache__/search_scope.cpython-311.pyc,, +pip/_internal/models/__pycache__/selection_prefs.cpython-311.pyc,, +pip/_internal/models/__pycache__/target_python.cpython-311.pyc,, +pip/_internal/models/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/models/candidate.py,sha256=6pcABsaR7CfIHlbJbr2_kMkVJFL_yrYjTx6SVWUnCPQ,990 +pip/_internal/models/direct_url.py,sha256=HLO0sL2aYB6n45bwmd72TDN05sLHJlOQI8M01l2SH3I,5877 +pip/_internal/models/format_control.py,sha256=DJpMYjxeYKKQdwNcML2_F0vtAh-qnKTYe-CpTxQe-4g,2520 +pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030 +pip/_internal/models/installation_report.py,sha256=ad1arqtxrSFBvWnm6mRqmG12HLV3pZZcZcHrlTFIiqU,2617 +pip/_internal/models/link.py,sha256=9HWL14UQTMxRCnY6dmAz09rGElJrMAcHn2OJZCBx0tk,18083 +pip/_internal/models/scheme.py,sha256=3EFQp_ICu_shH1-TBqhl0QAusKCPDFOlgHFeN4XowWs,738 +pip/_internal/models/search_scope.py,sha256=iGPQQ6a4Lau8oGQ_FWj8aRLik8A21o03SMO5KnSt-Cg,4644 +pip/_internal/models/selection_prefs.py,sha256=KZdi66gsR-_RUXUr9uejssk3rmTHrQVJWeNA2sV-VSY,1907 +pip/_internal/models/target_python.py,sha256=qKpZox7J8NAaPmDs5C_aniwfPDxzvpkrCKqfwndG87k,3858 +pip/_internal/models/wheel.py,sha256=YqazoIZyma_Q1ejFa1C7NHKQRRWlvWkdK96VRKmDBeI,3600 +pip/_internal/network/__init__.py,sha256=jf6Tt5nV_7zkARBrKojIXItgejvoegVJVKUbhAa5Ioc,50 +pip/_internal/network/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/network/__pycache__/auth.cpython-311.pyc,, +pip/_internal/network/__pycache__/cache.cpython-311.pyc,, +pip/_internal/network/__pycache__/download.cpython-311.pyc,, +pip/_internal/network/__pycache__/lazy_wheel.cpython-311.pyc,, +pip/_internal/network/__pycache__/session.cpython-311.pyc,, +pip/_internal/network/__pycache__/utils.cpython-311.pyc,, +pip/_internal/network/__pycache__/xmlrpc.cpython-311.pyc,, +pip/_internal/network/auth.py,sha256=a3C7Xaa8kTJjXkdi_wrUjqaySc8Z9Yz7U6QIbXfzMyc,12190 +pip/_internal/network/cache.py,sha256=hgXftU-eau4MWxHSLquTMzepYq5BPC2zhCkhN3glBy8,2145 +pip/_internal/network/download.py,sha256=HvDDq9bVqaN3jcS3DyVJHP7uTqFzbShdkf7NFSoHfkw,6096 +pip/_internal/network/lazy_wheel.py,sha256=PbPyuleNhtEq6b2S7rufoGXZWMD15FAGL4XeiAQ8FxA,7638 +pip/_internal/network/session.py,sha256=BpDOJ7_Xw5VkgPYWsePzcaqOfcyRZcB2AW7W0HGBST0,18443 +pip/_internal/network/utils.py,sha256=6A5SrUJEEUHxbGtbscwU2NpCyz-3ztiDlGWHpRRhsJ8,4073 +pip/_internal/network/xmlrpc.py,sha256=AzQgG4GgS152_cqmGr_Oz2MIXsCal-xfsis7fA7nmU0,1791 +pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/operations/__pycache__/check.cpython-311.pyc,, +pip/_internal/operations/__pycache__/freeze.cpython-311.pyc,, +pip/_internal/operations/__pycache__/prepare.cpython-311.pyc,, +pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/build/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/build_tracker.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/metadata.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/metadata_editable.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/wheel_editable.cpython-311.pyc,, +pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-311.pyc,, +pip/_internal/operations/build/build_tracker.py,sha256=vf81EwomN3xe9G8qRJED0VGqNikmRQRQoobNsxi5Xrs,4133 +pip/_internal/operations/build/metadata.py,sha256=ES_uRmAvhrNm_nDTpZxshBfUsvnXtkj-g_4rZrH9Rww,1404 +pip/_internal/operations/build/metadata_editable.py,sha256=_Rai0VZjxoeJUkjkuICrq45LtjwFoDOveosMYH43rKc,1456 +pip/_internal/operations/build/metadata_legacy.py,sha256=o-eU21As175hDC7dluM1fJJ_FqokTIShyWpjKaIpHZw,2198 +pip/_internal/operations/build/wheel.py,sha256=AO9XnTGhTgHtZmU8Dkbfo1OGr41rBuSDjIgAa4zUKgE,1063 +pip/_internal/operations/build/wheel_editable.py,sha256=TVETY-L_M_dSEKBhTIcQOP75zKVXw8tuq1U354Mm30A,1405 +pip/_internal/operations/build/wheel_legacy.py,sha256=C9j6rukgQI1n_JeQLoZGuDdfUwzCXShyIdPTp6edbMQ,3064 +pip/_internal/operations/check.py,sha256=ca4O9CkPt9Em9sLCf3H0iVt1GIcW7M8C0U5XooaBuT4,5109 +pip/_internal/operations/freeze.py,sha256=mwTZ2uML8aQgo3k8MR79a7SZmmmvdAJqdyaknKbavmg,9784 +pip/_internal/operations/install/__init__.py,sha256=mX7hyD2GNBO2mFGokDQ30r_GXv7Y_PLdtxcUv144e-s,51 +pip/_internal/operations/install/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/operations/install/__pycache__/editable_legacy.cpython-311.pyc,, +pip/_internal/operations/install/__pycache__/legacy.cpython-311.pyc,, +pip/_internal/operations/install/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/operations/install/editable_legacy.py,sha256=ee4kfJHNuzTdKItbfAsNOSEwq_vD7DRPGkBdK48yBhU,1354 +pip/_internal/operations/install/legacy.py,sha256=cHdcHebyzf8w7OaOLwcsTNSMSSV8WBoAPFLay_9CjE8,4105 +pip/_internal/operations/install/wheel.py,sha256=CxzEg2wTPX4SxNTPIx0ozTqF1X7LhpCyP3iM2FjcKUE,27407 +pip/_internal/operations/prepare.py,sha256=BeYXrLFpRoV5XBnRXQHxRA2plyC36kK9Pms5D9wjCo4,25091 +pip/_internal/pyproject.py,sha256=ob0Gb0l12YLZNxjdpZGRfWHgjqhZTnSVv96RuJyNOfs,7074 +pip/_internal/req/__init__.py,sha256=rUQ9d_Sh3E5kNYqX9pkN0D06YL-LrtcbJQ-LiIonq08,2807 +pip/_internal/req/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/req/__pycache__/constructors.cpython-311.pyc,, +pip/_internal/req/__pycache__/req_file.cpython-311.pyc,, +pip/_internal/req/__pycache__/req_install.cpython-311.pyc,, +pip/_internal/req/__pycache__/req_set.cpython-311.pyc,, +pip/_internal/req/__pycache__/req_uninstall.cpython-311.pyc,, +pip/_internal/req/constructors.py,sha256=ypjtq1mOQ3d2mFkFPMf_6Mr8SLKeHQk3tUKHA1ddG0U,16611 +pip/_internal/req/req_file.py,sha256=N6lPO3c0to_G73YyGAnk7VUYmed5jV4Qxgmt1xtlXVg,17646 +pip/_internal/req/req_install.py,sha256=4tzyVGPHJ1-GXowm6PBT52BGIlbc4w7fhVqf-55bmRg,35600 +pip/_internal/req/req_set.py,sha256=j3esG0s6SzoVReX9rWn4rpYNtyET_fwxbwJPRimvRxo,2858 +pip/_internal/req/req_uninstall.py,sha256=ZFQfgSNz6H1BMsgl87nQNr2iaQCcbFcmXpW8rKVQcic,24045 +pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/resolution/__pycache__/base.cpython-311.pyc,, +pip/_internal/resolution/base.py,sha256=qlmh325SBVfvG6Me9gc5Nsh5sdwHBwzHBq6aEXtKsLA,583 +pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/legacy/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/resolution/legacy/__pycache__/resolver.cpython-311.pyc,, +pip/_internal/resolution/legacy/resolver.py,sha256=9em8D5TcSsEN4xZM1WreaRShOnyM4LlvhMSHpUPsocE,24129 +pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/base.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-311.pyc,, +pip/_internal/resolution/resolvelib/base.py,sha256=u1O4fkvCO4mhmu5i32xrDv9AX5NgUci_eYVyBDQhTIM,5220 +pip/_internal/resolution/resolvelib/candidates.py,sha256=6kQZeMzwibnL4lO6bW0hUQQjNEvXfADdFphRRkRvOtc,18963 +pip/_internal/resolution/resolvelib/factory.py,sha256=OnjkLIgyk5Tol7uOOqapA1D4qiRHWmPU18DF1yN5N8o,27878 +pip/_internal/resolution/resolvelib/found_candidates.py,sha256=hvL3Hoa9VaYo-qEOZkBi2Iqw251UDxPz-uMHVaWmLpE,5705 +pip/_internal/resolution/resolvelib/provider.py,sha256=Vd4jW_NnyifB-HMkPYtZIO70M3_RM0MbL5YV6XyBM-w,9914 +pip/_internal/resolution/resolvelib/reporter.py,sha256=3ZVVYrs5PqvLFJkGLcuXoMK5mTInFzl31xjUpDBpZZk,2526 +pip/_internal/resolution/resolvelib/requirements.py,sha256=B1ndvKPSuyyyTEXt9sKhbwminViSWnBrJa7qO2ln4Z0,5455 +pip/_internal/resolution/resolvelib/resolver.py,sha256=nYZ9bTFXj5c1ILKnkSgU7tUCTYyo5V5J-J0sKoA7Wzg,11533 +pip/_internal/self_outdated_check.py,sha256=R3MmjCyUt_lkUNMc6p3xVSx7vX28XiDh3VDs5OrYn6Q,8020 +pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/utils/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/utils/__pycache__/_log.cpython-311.pyc,, +pip/_internal/utils/__pycache__/appdirs.cpython-311.pyc,, +pip/_internal/utils/__pycache__/compat.cpython-311.pyc,, +pip/_internal/utils/__pycache__/compatibility_tags.cpython-311.pyc,, +pip/_internal/utils/__pycache__/datetime.cpython-311.pyc,, +pip/_internal/utils/__pycache__/deprecation.cpython-311.pyc,, +pip/_internal/utils/__pycache__/direct_url_helpers.cpython-311.pyc,, +pip/_internal/utils/__pycache__/distutils_args.cpython-311.pyc,, +pip/_internal/utils/__pycache__/egg_link.cpython-311.pyc,, +pip/_internal/utils/__pycache__/encoding.cpython-311.pyc,, +pip/_internal/utils/__pycache__/entrypoints.cpython-311.pyc,, +pip/_internal/utils/__pycache__/filesystem.cpython-311.pyc,, +pip/_internal/utils/__pycache__/filetypes.cpython-311.pyc,, +pip/_internal/utils/__pycache__/glibc.cpython-311.pyc,, +pip/_internal/utils/__pycache__/hashes.cpython-311.pyc,, +pip/_internal/utils/__pycache__/inject_securetransport.cpython-311.pyc,, +pip/_internal/utils/__pycache__/logging.cpython-311.pyc,, +pip/_internal/utils/__pycache__/misc.cpython-311.pyc,, +pip/_internal/utils/__pycache__/models.cpython-311.pyc,, +pip/_internal/utils/__pycache__/packaging.cpython-311.pyc,, +pip/_internal/utils/__pycache__/setuptools_build.cpython-311.pyc,, +pip/_internal/utils/__pycache__/subprocess.cpython-311.pyc,, +pip/_internal/utils/__pycache__/temp_dir.cpython-311.pyc,, +pip/_internal/utils/__pycache__/unpacking.cpython-311.pyc,, +pip/_internal/utils/__pycache__/urls.cpython-311.pyc,, +pip/_internal/utils/__pycache__/virtualenv.cpython-311.pyc,, +pip/_internal/utils/__pycache__/wheel.cpython-311.pyc,, +pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015 +pip/_internal/utils/appdirs.py,sha256=swgcTKOm3daLeXTW6v5BUS2Ti2RvEnGRQYH_yDXklAo,1665 +pip/_internal/utils/compat.py,sha256=ACyBfLgj3_XG-iA5omEDrXqDM0cQKzi8h8HRBInzG6Q,1884 +pip/_internal/utils/compatibility_tags.py,sha256=ydin8QG8BHqYRsPY4OL6cmb44CbqXl1T0xxS97VhHkk,5377 +pip/_internal/utils/datetime.py,sha256=m21Y3wAtQc-ji6Veb6k_M5g6A0ZyFI4egchTdnwh-pQ,242 +pip/_internal/utils/deprecation.py,sha256=OLc7GzDwPob9y8jscDYCKUNBV-9CWwqFplBOJPLOpBM,5764 +pip/_internal/utils/direct_url_helpers.py,sha256=6F1tc2rcKaCZmgfVwsE6ObIe_Pux23mUVYA-2D9wCFc,3206 +pip/_internal/utils/distutils_args.py,sha256=bYUt4wfFJRaeGO4VHia6FNaA8HlYXMcKuEq1zYijY5g,1115 +pip/_internal/utils/egg_link.py,sha256=5MVlpz5LirT4iLQq86OYzjXaYF0D4Qk1dprEI7ThST4,2203 +pip/_internal/utils/encoding.py,sha256=qqsXDtiwMIjXMEiIVSaOjwH5YmirCaK-dIzb6-XJsL0,1169 +pip/_internal/utils/entrypoints.py,sha256=YlhLTRl2oHBAuqhc-zmL7USS67TPWVHImjeAQHreZTQ,3064 +pip/_internal/utils/filesystem.py,sha256=RhMIXUaNVMGjc3rhsDahWQ4MavvEQDdqXqgq-F6fpw8,5122 +pip/_internal/utils/filetypes.py,sha256=i8XAQ0eFCog26Fw9yV0Yb1ygAqKYB1w9Cz9n0fj8gZU,716 +pip/_internal/utils/glibc.py,sha256=tDfwVYnJCOC0BNVpItpy8CGLP9BjkxFHdl0mTS0J7fc,3110 +pip/_internal/utils/hashes.py,sha256=1WhkVNIHNfuYLafBHThIjVKGplxFJXSlQtuG2mXNlJI,4831 +pip/_internal/utils/inject_securetransport.py,sha256=o-QRVMGiENrTJxw3fAhA7uxpdEdw6M41TjHYtSVRrcg,795 +pip/_internal/utils/logging.py,sha256=U2q0i1n8hPS2gQh8qcocAg5dovGAa_bR24akmXMzrk4,11632 +pip/_internal/utils/misc.py,sha256=49Rs2NgrD4JGTKFt0farCm7FIAi-rjyoxgioArhCW_0,21617 +pip/_internal/utils/models.py,sha256=5GoYU586SrxURMvDn_jBMJInitviJg4O5-iOU-6I0WY,1193 +pip/_internal/utils/packaging.py,sha256=5Wm6_x7lKrlqVjPI5MBN_RurcRHwVYoQ7Ksrs84de7s,2108 +pip/_internal/utils/setuptools_build.py,sha256=4i3CuS34yNrkePnZ73rR47pyDzpZBo-SX9V5PNDSSHY,5662 +pip/_internal/utils/subprocess.py,sha256=MYySbvY7qBevRxq_RFfOsDqG4vMqrB4vDoL_eyPE6Bo,9197 +pip/_internal/utils/temp_dir.py,sha256=aCX489gRa4Nu0dMKRFyGhV6maJr60uEynu5uCbKR4Qg,7702 +pip/_internal/utils/unpacking.py,sha256=SBb2iV1crb89MDRTEKY86R4A_UOWApTQn9VQVcMDOlE,8821 +pip/_internal/utils/urls.py,sha256=AhaesUGl-9it6uvG6fsFPOr9ynFpGaTMk4t5XTX7Z_Q,1759 +pip/_internal/utils/virtualenv.py,sha256=4_48qMzCwB_F5jIK5BC_ua7uiAMVifmQWU9NdaGUoVA,3459 +pip/_internal/utils/wheel.py,sha256=lXOgZyTlOm5HmK8tw5iw0A3_5A6wRzsXHOaQkIvvloU,4549 +pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596 +pip/_internal/vcs/__pycache__/__init__.cpython-311.pyc,, +pip/_internal/vcs/__pycache__/bazaar.cpython-311.pyc,, +pip/_internal/vcs/__pycache__/git.cpython-311.pyc,, +pip/_internal/vcs/__pycache__/mercurial.cpython-311.pyc,, +pip/_internal/vcs/__pycache__/subversion.cpython-311.pyc,, +pip/_internal/vcs/__pycache__/versioncontrol.cpython-311.pyc,, +pip/_internal/vcs/bazaar.py,sha256=zq-Eu2NtJffc6kOsyv2kmRTnKg9qeIXE-KH5JeKck70,3518 +pip/_internal/vcs/git.py,sha256=mjhwudCx9WlLNkxZ6_kOKmueF0rLoU2i1xeASKF6yiQ,18116 +pip/_internal/vcs/mercurial.py,sha256=Bzbd518Jsx-EJI0IhIobiQqiRsUv5TWYnrmRIFWE0Gw,5238 +pip/_internal/vcs/subversion.py,sha256=AeUVE9d9qp-0QSOMiUvuFHy1TK950E3QglN7ipP13sI,11728 +pip/_internal/vcs/versioncontrol.py,sha256=KUOc-hN51em9jrqxKwUR3JnkgSE-xSOqMiiJcSaL6B8,22811 +pip/_internal/wheel_builder.py,sha256=8cObBCu4mIsMJqZM7xXI9DO3vldiAnRNa1Gt6izPPTs,13079 +pip/_vendor/__init__.py,sha256=fNxOSVD0auElsD8fN9tuq5psfgMQ-RFBtD4X5gjlRkg,4966 +pip/_vendor/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/__pycache__/six.cpython-311.pyc,, +pip/_vendor/__pycache__/typing_extensions.cpython-311.pyc,, +pip/_vendor/cachecontrol/__init__.py,sha256=hrxlv3q7upsfyMw8k3gQ9vagBax1pYHSGGqYlZ0Zk0M,465 +pip/_vendor/cachecontrol/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/adapter.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/cache.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/compat.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/controller.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/serialize.cpython-311.pyc,, +pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-311.pyc,, +pip/_vendor/cachecontrol/_cmd.py,sha256=lxUXqfNTVx84zf6tcWbkLZHA6WVBRtJRpfeA9ZqhaAY,1379 +pip/_vendor/cachecontrol/adapter.py,sha256=ew9OYEQHEOjvGl06ZsuX8W3DAvHWsQKHwWAxISyGug8,5033 +pip/_vendor/cachecontrol/cache.py,sha256=Tty45fOjH40fColTGkqKQvQQmbYsMpk-nCyfLcv2vG4,1535 +pip/_vendor/cachecontrol/caches/__init__.py,sha256=h-1cUmOz6mhLsjTjOrJ8iPejpGdLCyG4lzTftfGZvLg,242 +pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-311.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-311.pyc,, +pip/_vendor/cachecontrol/caches/file_cache.py,sha256=GpexcE29LoY4MaZwPUTcUBZaDdcsjqyLxZFznk8Hbr4,5271 +pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=mp-QWonP40I3xJGK3XVO-Gs9a3UjzlqqEmp9iLJH9F4,1033 +pip/_vendor/cachecontrol/compat.py,sha256=LNx7vqBndYdHU8YuJt53ab_8rzMGTXVrvMb7CZJkxG0,778 +pip/_vendor/cachecontrol/controller.py,sha256=bAYrt7x_VH4toNpI066LQxbHpYGpY1MxxmZAhspplvw,16416 +pip/_vendor/cachecontrol/filewrapper.py,sha256=X4BAQOO26GNOR7nH_fhTzAfeuct2rBQcx_15MyFBpcs,3946 +pip/_vendor/cachecontrol/heuristics.py,sha256=8kAyuZLSCyEIgQr6vbUwfhpqg9ows4mM0IV6DWazevI,4154 +pip/_vendor/cachecontrol/serialize.py,sha256=_U1NU_C-SDgFzkbAxAsPDgMTHeTWZZaHCQnZN_jh0U8,7105 +pip/_vendor/cachecontrol/wrapper.py,sha256=X3-KMZ20Ho3VtqyVaXclpeQpFzokR5NE8tZSfvKVaB8,774 +pip/_vendor/certifi/__init__.py,sha256=luDjIGxDSrQ9O0zthdz5Lnt069Z_7eR1GIEefEaf-Ys,94 +pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255 +pip/_vendor/certifi/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/certifi/__pycache__/__main__.cpython-311.pyc,, +pip/_vendor/certifi/__pycache__/core.cpython-311.pyc,, +pip/_vendor/certifi/cacert.pem,sha256=3l8CcWt_qL42030rGieD3SLufICFX0bYtGhDl_EXVPI,286370 +pip/_vendor/certifi/core.py,sha256=ZwiOsv-sD_ouU1ft8wy_xZ3LQ7UbcVzyqj2XNyrsZis,4279 +pip/_vendor/chardet/__init__.py,sha256=9-r0i294avRciob2HKVcKf6GJmXPHpgMqIijVrqHBDU,3705 +pip/_vendor/chardet/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/big5freq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/big5prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/chardistribution.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/charsetgroupprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/charsetprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/codingstatemachine.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/cp949prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/enums.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/escprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/escsm.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/eucjpprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/euckrfreq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/euckrprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/euctwfreq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/euctwprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/gb2312freq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/gb2312prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/hebrewprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/jisfreq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/johabfreq.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/johabprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/jpcntx.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langbulgarianmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langgreekmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langhebrewmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langhungarianmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langrussianmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langthaimodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/langturkishmodel.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/latin1prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/mbcharsetprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/mbcsgroupprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/mbcssm.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/sbcharsetprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/sbcsgroupprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/sjisprober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/universaldetector.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/utf1632prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/utf8prober.cpython-311.pyc,, +pip/_vendor/chardet/__pycache__/version.cpython-311.pyc,, +pip/_vendor/chardet/big5freq.py,sha256=ltcfP-3PjlNHCoo5e4a7C4z-2DhBTXRfY6jbMbB7P30,31274 +pip/_vendor/chardet/big5prober.py,sha256=neUXIlq35507yibstiznZWFzyNcMn6EXrqJaUJVPWKg,1741 +pip/_vendor/chardet/chardistribution.py,sha256=M9NTKdM72KieFKy4TT5eml4PP0WaVcXuY5PpWSFD0FA,9608 +pip/_vendor/chardet/charsetgroupprober.py,sha256=CaIBAmNitEsYuSgMvgAsMREN4cLxMj5OYwMhVo6MAxk,3817 +pip/_vendor/chardet/charsetprober.py,sha256=Eo3w8sCmbvnVKOGNW1iy50KATVs8xV-gF7cQ0VG85dQ,4801 +pip/_vendor/chardet/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/chardet/cli/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/chardet/cli/__pycache__/chardetect.cpython-311.pyc,, +pip/_vendor/chardet/cli/chardetect.py,sha256=1qMxT3wrp5vP6ugSf1-Zz3BWwlbCWJ0jzeCuhgX85vw,2406 +pip/_vendor/chardet/codingstatemachine.py,sha256=BiGR9kgTYbS4gJI5qBmE52HMOBOR_roDvXf7aIehdEk,3559 +pip/_vendor/chardet/cp949prober.py,sha256=kCQEaOCzMntqv7pAyXEobWTRgIUxYfoiUr0btXO1nI8,1838 +pip/_vendor/chardet/enums.py,sha256=Rodw4p61Vg9U-oCo6eUuT7uDzKwIbCaA15HwbvCoCNk,1619 +pip/_vendor/chardet/escprober.py,sha256=girD61r3NsQLnMQXsWWBU4hHuRJzTH3V7-VfTUr-nQY,3864 +pip/_vendor/chardet/escsm.py,sha256=0Vs4iPPovberMoSxxnK5pI161Xf-mtKgOl14g5Xc7zg,12021 +pip/_vendor/chardet/eucjpprober.py,sha256=pGgs4lINwCEDV2bxqIZ6hXpaj2j4l2oLsMx6kuOK_zQ,3676 +pip/_vendor/chardet/euckrfreq.py,sha256=3mHuRvXfsq_QcQysDQFb8qSudvTiol71C6Ic2w57tKM,13566 +pip/_vendor/chardet/euckrprober.py,sha256=qBuSS2zXWaoUmGdzz3owAnD1GNhuKR_8bYzDC3yxe6I,1731 +pip/_vendor/chardet/euctwfreq.py,sha256=2alILE1Lh5eqiFJZjzRkMQXolNJRHY5oBQd-vmZYFFM,36913 +pip/_vendor/chardet/euctwprober.py,sha256=SLnCoJC94jZL8PJio60Q8PZACJA1rVPtUdWMa1W8Pwk,1731 +pip/_vendor/chardet/gb2312freq.py,sha256=49OrdXzD-HXqwavkqjo8Z7gvs58hONNzDhAyMENNkvY,20735 +pip/_vendor/chardet/gb2312prober.py,sha256=NS_i52jZE0TnWGkKqFduvu9fzW0nMcS2XbYJ8qSX8hY,1737 +pip/_vendor/chardet/hebrewprober.py,sha256=1l1hXF8-2IWDrPkf85UvAO1GVtMfY1r11kDgOqa-gU4,13919 +pip/_vendor/chardet/jisfreq.py,sha256=mm8tfrwqhpOd3wzZKS4NJqkYBQVcDfTM2JiQ5aW932E,25796 +pip/_vendor/chardet/johabfreq.py,sha256=dBpOYG34GRX6SL8k_LbS9rxZPMjLjoMlgZ03Pz5Hmqc,42498 +pip/_vendor/chardet/johabprober.py,sha256=C18osd4vMPfy9facw-Y1Lor_9UrW0PeV-zxM2fu441c,1730 +pip/_vendor/chardet/jpcntx.py,sha256=m1gDpPkRca4EDwym8XSL5YdoILFnFsDbNBYMQV7_-NE,26797 +pip/_vendor/chardet/langbulgarianmodel.py,sha256=vmbvYFP8SZkSxoBvLkFqKiH1sjma5ihk3PTpdy71Rr4,104562 +pip/_vendor/chardet/langgreekmodel.py,sha256=JfB7bupjjJH2w3X_mYnQr9cJA_7EuITC2cRW13fUjeI,98484 +pip/_vendor/chardet/langhebrewmodel.py,sha256=3HXHaLQPNAGcXnJjkIJfozNZLTvTJmf4W5Awi6zRRKc,98196 +pip/_vendor/chardet/langhungarianmodel.py,sha256=WxbeQIxkv8YtApiNqxQcvj-tMycsoI4Xy-fwkDHpP_Y,101363 +pip/_vendor/chardet/langrussianmodel.py,sha256=s395bTZ87ESTrZCOdgXbEjZ9P1iGPwCl_8xSsac_DLY,128035 +pip/_vendor/chardet/langthaimodel.py,sha256=7bJlQitRpTnVGABmbSznHnJwOHDy3InkTvtFUx13WQI,102774 +pip/_vendor/chardet/langturkishmodel.py,sha256=XY0eGdTIy4eQ9Xg1LVPZacb-UBhHBR-cq0IpPVHowKc,95372 +pip/_vendor/chardet/latin1prober.py,sha256=u_iGcQMUcZLXvj4B_WXx4caA0C5oaE2Qj1KTpz_RQ1I,5260 +pip/_vendor/chardet/mbcharsetprober.py,sha256=iKKuB6o_FF80NynRLBDT0UtwOnpLqmL_OspRPMib7CM,3367 +pip/_vendor/chardet/mbcsgroupprober.py,sha256=1D_kp9nv2_NQRddq9I2WDvB35OJh7Tfpo-OYTnL3B5o,2056 +pip/_vendor/chardet/mbcssm.py,sha256=EfORNu1WXgnFvpFarU8uJHS8KFif63xmgrHOB4DdDdY,30068 +pip/_vendor/chardet/metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/chardet/metadata/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/chardet/metadata/__pycache__/languages.cpython-311.pyc,, +pip/_vendor/chardet/metadata/languages.py,sha256=HcaBygWtZq3gR8prIkJp_etvkhm2V4pUIToqjPZhgrc,13280 +pip/_vendor/chardet/sbcharsetprober.py,sha256=VvtWiNRLbHDZ5xgnofsmP1u8VQIkkaAuw3Ir9m1zDzQ,6199 +pip/_vendor/chardet/sbcsgroupprober.py,sha256=mekr4E3hgT4onmwi8oi1iEGW1CN-Z-BArG6kOtCunJw,4129 +pip/_vendor/chardet/sjisprober.py,sha256=sLfWS25PVFr5cDGhEf6h_s-RJsyeSteA-4ynsTl_UvA,3749 +pip/_vendor/chardet/universaldetector.py,sha256=BHeNWt1kn0yQgnR6xNtLAjiNmEQpSHYlKEvuZ9QyR1k,13288 +pip/_vendor/chardet/utf1632prober.py,sha256=N42YJEOkVDB67c38t5aJhXMG1QvnyWWDMNY5ERzniU0,8289 +pip/_vendor/chardet/utf8prober.py,sha256=mnLaSBV4gg-amt2WmxKFKWy4vVBedMNgjdbvgzBo0Dc,2709 +pip/_vendor/chardet/version.py,sha256=u_QYi-DXU1s7fyC_Rwa0I0-UcxMVmH7Co6c7QGKbe3g,242 +pip/_vendor/colorama/__init__.py,sha256=ihDoWQOkapwF7sqQ99AoDoEF3vGYm40OtmgW211cLZw,239 +pip/_vendor/colorama/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/colorama/__pycache__/ansi.cpython-311.pyc,, +pip/_vendor/colorama/__pycache__/ansitowin32.cpython-311.pyc,, +pip/_vendor/colorama/__pycache__/initialise.cpython-311.pyc,, +pip/_vendor/colorama/__pycache__/win32.cpython-311.pyc,, +pip/_vendor/colorama/__pycache__/winterm.cpython-311.pyc,, +pip/_vendor/colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +pip/_vendor/colorama/ansitowin32.py,sha256=gGrO7MVtwc-j1Sq3jKfZpERT1JWmYSOsTVDiTnFbZU4,10830 +pip/_vendor/colorama/initialise.py,sha256=PprovDNxMTrvoNHFcL2NZjpH2XzDc8BLxLxiErfUl4k,1915 +pip/_vendor/colorama/win32.py,sha256=bJ8Il9jwaBN5BJ8bmN6FoYZ1QYuMKv2j8fGrXh7TJjw,5404 +pip/_vendor/colorama/winterm.py,sha256=2y_2b7Zsv34feAsP67mLOVc-Bgq51mdYGo571VprlrM,6438 +pip/_vendor/distlib/__init__.py,sha256=acgfseOC55dNrVAzaBKpUiH3Z6V7Q1CaxsiQ3K7pC-E,581 +pip/_vendor/distlib/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/compat.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/database.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/index.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/locators.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/manifest.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/markers.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/metadata.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/resources.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/scripts.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/util.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/version.cpython-311.pyc,, +pip/_vendor/distlib/__pycache__/wheel.cpython-311.pyc,, +pip/_vendor/distlib/compat.py,sha256=tfoMrj6tujk7G4UC2owL6ArgDuCKabgBxuJRGZSmpko,41259 +pip/_vendor/distlib/database.py,sha256=o_mw0fAr93NDAHHHfqG54Y1Hi9Rkfrp2BX15XWZYK50,51697 +pip/_vendor/distlib/index.py,sha256=HFiDG7LMoaBs829WuotrfIwcErOOExUOR_AeBtw_TCU,20834 +pip/_vendor/distlib/locators.py,sha256=wNzG-zERzS_XGls-nBPVVyLRHa2skUlkn0-5n0trMWA,51991 +pip/_vendor/distlib/manifest.py,sha256=nQEhYmgoreaBZzyFzwYsXxJARu3fo4EkunU163U16iE,14811 +pip/_vendor/distlib/markers.py,sha256=TpHHHLgkzyT7YHbwj-2i6weRaq-Ivy2-MUnrDkjau-U,5058 +pip/_vendor/distlib/metadata.py,sha256=g_DIiu8nBXRzA-mWPRpatHGbmFZqaFoss7z9TG7QSUU,39801 +pip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820 +pip/_vendor/distlib/scripts.py,sha256=BmkTKmiTk4m2cj-iueliatwz3ut_9SsABBW51vnQnZU,18102 +pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792 +pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784 +pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032 +pip/_vendor/distlib/util.py,sha256=31dPXn3Rfat0xZLeVoFpuniyhe6vsbl9_QN-qd9Lhlk,66262 +pip/_vendor/distlib/version.py,sha256=WG__LyAa2GwmA6qSoEJtvJE8REA1LZpbSizy8WvhJLk,23513 +pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648 +pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448 +pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888 +pip/_vendor/distlib/wheel.py,sha256=Rgqs658VsJ3R2845qwnZD8XQryV2CzWw2mghwLvxxsI,43898 +pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981 +pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64 +pip/_vendor/distro/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/distro/__pycache__/__main__.cpython-311.pyc,, +pip/_vendor/distro/__pycache__/distro.cpython-311.pyc,, +pip/_vendor/distro/distro.py,sha256=UYQG_9H_iSOt422uasA92HlY7aXeTnWKdV-IhsSAdwQ,48841 +pip/_vendor/idna/__init__.py,sha256=KJQN1eQBr8iIK5SKrJ47lXvxG0BJ7Lm38W4zT0v_8lk,849 +pip/_vendor/idna/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/codec.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/compat.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/core.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/idnadata.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/intranges.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/package_data.cpython-311.pyc,, +pip/_vendor/idna/__pycache__/uts46data.cpython-311.pyc,, +pip/_vendor/idna/codec.py,sha256=6ly5odKfqrytKT9_7UrlGklHnf1DSK2r9C6cSM4sa28,3374 +pip/_vendor/idna/compat.py,sha256=0_sOEUMT4CVw9doD3vyRhX80X19PwqFoUBs7gWsFME4,321 +pip/_vendor/idna/core.py,sha256=1JxchwKzkxBSn7R_oCE12oBu3eVux0VzdxolmIad24M,12950 +pip/_vendor/idna/idnadata.py,sha256=xUjqKqiJV8Ho_XzBpAtv5JFoVPSupK-SUXvtjygUHqw,44375 +pip/_vendor/idna/intranges.py,sha256=YBr4fRYuWH7kTKS2tXlFjM24ZF1Pdvcir-aywniInqg,1881 +pip/_vendor/idna/package_data.py,sha256=C_jHJzmX8PI4xq0jpzmcTMxpb5lDsq4o5VyxQzlVrZE,21 +pip/_vendor/idna/uts46data.py,sha256=zvjZU24s58_uAS850Mcd0NnD0X7_gCMAMjzWNIeUJdc,206539 +pip/_vendor/msgpack/__init__.py,sha256=NryGaKLDk_Egd58ZxXpnuI7OWO27AXz7S6CBFRM3sAY,1132 +pip/_vendor/msgpack/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/msgpack/__pycache__/exceptions.cpython-311.pyc,, +pip/_vendor/msgpack/__pycache__/ext.cpython-311.pyc,, +pip/_vendor/msgpack/__pycache__/fallback.cpython-311.pyc,, +pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081 +pip/_vendor/msgpack/ext.py,sha256=TuldJPkYu8Wo_Xh0tFGL2l06-gY88NSR8tOje9fo2Wg,6080 +pip/_vendor/msgpack/fallback.py,sha256=OORDn86-fHBPlu-rPlMdM10KzkH6S_Rx9CHN1b7o4cg,34557 +pip/_vendor/packaging/__about__.py,sha256=ugASIO2w1oUyH8_COqQ2X_s0rDhjbhQC3yJocD03h2c,661 +pip/_vendor/packaging/__init__.py,sha256=b9Kk5MF7KxhhLgcDmiUWukN-LatWFxPdNug0joPhHSk,497 +pip/_vendor/packaging/__pycache__/__about__.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/_manylinux.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/_musllinux.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/_structures.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/markers.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/requirements.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/specifiers.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/tags.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/utils.cpython-311.pyc,, +pip/_vendor/packaging/__pycache__/version.cpython-311.pyc,, +pip/_vendor/packaging/_manylinux.py,sha256=XcbiXB-qcjv3bcohp6N98TMpOP4_j3m-iOA8ptK2GWY,11488 +pip/_vendor/packaging/_musllinux.py,sha256=_KGgY_qc7vhMGpoqss25n2hiLCNKRtvz9mCrS7gkqyc,4378 +pip/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +pip/_vendor/packaging/markers.py,sha256=AJBOcY8Oq0kYc570KuuPTkvuqjAlhufaE2c9sCUbm64,8487 +pip/_vendor/packaging/requirements.py,sha256=NtDlPBtojpn1IUC85iMjPNsUmufjpSlwnNA-Xb4m5NA,4676 +pip/_vendor/packaging/specifiers.py,sha256=LRQ0kFsHrl5qfcFNEEJrIFYsnIHQUJXY9fIsakTrrqE,30110 +pip/_vendor/packaging/tags.py,sha256=lmsnGNiJ8C4D_Pf9PbM0qgbZvD9kmB9lpZBQUZa3R_Y,15699 +pip/_vendor/packaging/utils.py,sha256=dJjeat3BS-TYn1RrUFVwufUMasbtzLfYRoy_HXENeFQ,4200 +pip/_vendor/packaging/version.py,sha256=_fLRNrFrxYcHVfyo8vk9j8s6JM8N_xsSxVFr6RJyco8,14665 +pip/_vendor/pep517/__init__.py,sha256=QJpRfzTpk6YSPgjcxp9-MCAiS5dEdzf9Bh0UXophG6c,130 +pip/_vendor/pep517/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/_compat.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/build.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/check.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/colorlog.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/dirtools.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/envbuild.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/meta.cpython-311.pyc,, +pip/_vendor/pep517/__pycache__/wrappers.cpython-311.pyc,, +pip/_vendor/pep517/_compat.py,sha256=by6evrYnqkisiM-MQcvOKs5bgDMzlOSgZqRHNqf04zE,138 +pip/_vendor/pep517/build.py,sha256=VLtq0hOvNWCfX0FkdvTKEr-TmyrbaX0UqghpU7bHO1w,3443 +pip/_vendor/pep517/check.py,sha256=o0Mp_PX1yOM2WNq1ZdDph3YA7RObj2UGQUCUF-46RaU,6083 +pip/_vendor/pep517/colorlog.py,sha256=eCV1W52xzBjA-sOlKzUcvabRiFa11Y7hA791u-85_c8,3994 +pip/_vendor/pep517/dirtools.py,sha256=JiZ1Hlt2LNaLZEhNa_pm1YyG3MUoRh7KxY6hJ8ac-w0,607 +pip/_vendor/pep517/envbuild.py,sha256=nkTt1ZY7MXVgYOhPTyTr-VOxQ-q_Qc1touXfQgM56Bs,6081 +pip/_vendor/pep517/in_process/__init__.py,sha256=4yDanGyKTXQtLhqRo9eEZ1CsLFezEAEZMfqEd88xrvY,872 +pip/_vendor/pep517/in_process/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pep517/in_process/__pycache__/_in_process.cpython-311.pyc,, +pip/_vendor/pep517/in_process/_in_process.py,sha256=JDpTxlKMDN1QfN_ey4IDtE6ZVSWtzP0_WLSqt1TyGaA,10801 +pip/_vendor/pep517/meta.py,sha256=budDWsV3I2OnnpSvXQ_ycuTqxh8G7DABoazAq-j8OlQ,2520 +pip/_vendor/pep517/wrappers.py,sha256=jcxIy-1Kl8I2xAZgbr6qNjF5b_6Q5gTndf9cxF0p5gM,12721 +pip/_vendor/pkg_resources/__init__.py,sha256=NnpQ3g6BCHzpMgOR_OLBmYtniY4oOzdKpwqghfq_6ug,108287 +pip/_vendor/pkg_resources/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pkg_resources/__pycache__/py31compat.cpython-311.pyc,, +pip/_vendor/pkg_resources/py31compat.py,sha256=CRk8fkiPRDLsbi5pZcKsHI__Pbmh_94L8mr9Qy9Ab2U,562 +pip/_vendor/platformdirs/__init__.py,sha256=x0aUmmovXXuRFVrVQBtwIiovX12B7rUkdV4F9UlLz0Y,12831 +pip/_vendor/platformdirs/__main__.py,sha256=ZmsnTxEOxtTvwa-Y_Vfab_JN3X4XCVeN8X0yyy9-qnc,1176 +pip/_vendor/platformdirs/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/__main__.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/android.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/api.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/macos.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/unix.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/version.cpython-311.pyc,, +pip/_vendor/platformdirs/__pycache__/windows.cpython-311.pyc,, +pip/_vendor/platformdirs/android.py,sha256=GKizhyS7ESRiU67u8UnBJLm46goau9937EchXWbPBlk,4068 +pip/_vendor/platformdirs/api.py,sha256=MXKHXOL3eh_-trSok-JUTjAR_zjmmKF3rjREVABjP8s,4910 +pip/_vendor/platformdirs/macos.py,sha256=-3UXQewbT0yMhMdkzRXfXGAntmLIH7Qt4a9Hlf8I5_Y,2655 +pip/_vendor/platformdirs/unix.py,sha256=b4aVYTz0qZ50HntwOXo8r6tp82jAa3qTjxw-WlnC2yc,6910 +pip/_vendor/platformdirs/version.py,sha256=tsBKKPDX3LLh39yHXeTYauGRbRd-AmOJr9SwKldlFIU,78 +pip/_vendor/platformdirs/windows.py,sha256=ISruopR5UGBePC0BxCxXevkZYfjJsIZc49YWU5iYfQ4,6439 +pip/_vendor/pygments/__init__.py,sha256=5oLcMLXD0cTG8YcHBPITtK1fS0JBASILEvEnWkTezgE,2999 +pip/_vendor/pygments/__main__.py,sha256=p0_rz3JZmNZMNZBOqDojaEx1cr9wmA9FQZX_TYl74lQ,353 +pip/_vendor/pygments/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/__main__.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/cmdline.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/console.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/filter.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/formatter.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/lexer.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/modeline.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/plugin.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/regexopt.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/scanner.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/sphinxext.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/style.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/token.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/unistring.cpython-311.pyc,, +pip/_vendor/pygments/__pycache__/util.cpython-311.pyc,, +pip/_vendor/pygments/cmdline.py,sha256=rc0fah4eknRqFgn1wKNEwkq0yWnSqYOGaA4PaIeOxVY,23685 +pip/_vendor/pygments/console.py,sha256=hQfqCFuOlGk7DW2lPQYepsw-wkOH1iNt9ylNA1eRymM,1697 +pip/_vendor/pygments/filter.py,sha256=NglMmMPTRRv-zuRSE_QbWid7JXd2J4AvwjCW2yWALXU,1938 +pip/_vendor/pygments/filters/__init__.py,sha256=b5YuXB9rampSy2-cMtKxGQoMDfrG4_DcvVwZrzTlB6w,40386 +pip/_vendor/pygments/filters/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pygments/formatter.py,sha256=6-TS2Y8pUMeWIUolWwr1O8ruC-U6HydWDwOdbAiJgJQ,2917 +pip/_vendor/pygments/formatters/__init__.py,sha256=YTqGeHS17fNXCLMZpf7oCxBCKLB9YLsZ8IAsjGhawyg,4810 +pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/groff.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/html.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/img.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/irc.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/latex.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/other.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/svg.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-311.pyc,, +pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-311.pyc,, +pip/_vendor/pygments/formatters/_mapping.py,sha256=fCZgvsM6UEuZUG7J6lr47eVss5owKd_JyaNbDfxeqmQ,4104 +pip/_vendor/pygments/formatters/bbcode.py,sha256=JrL4ITjN-KzPcuQpPMBf1pm33eW2sDUNr8WzSoAJsJA,3314 +pip/_vendor/pygments/formatters/groff.py,sha256=xrOFoLbafSA9uHsSLRogy79_Zc4GWJ8tMK2hCdTJRsw,5086 +pip/_vendor/pygments/formatters/html.py,sha256=QNt9prPgxmbKx2M-nfDwoR1bIg06-sNouQuWnE434Wc,35441 +pip/_vendor/pygments/formatters/img.py,sha256=h75Y7IRZLZxDEIwyoOsdRLTwm7kLVPbODKkgEiJ0iKI,21938 +pip/_vendor/pygments/formatters/irc.py,sha256=iwk5tDJOxbCV64SCmOFyvk__x6RD60ay0nUn7ko9n7U,5871 +pip/_vendor/pygments/formatters/latex.py,sha256=thPbytJCIs2AUXsO3NZwqKtXJ-upOlcXP4CXsx94G4w,19351 +pip/_vendor/pygments/formatters/other.py,sha256=PczqK1Rms43lz6iucOLPeBMxIncPKOGBt-195w1ynII,5073 +pip/_vendor/pygments/formatters/pangomarkup.py,sha256=ZZzMsKJKXrsDniFeMTkIpe7aQ4VZYRHu0idWmSiUJ2U,2212 +pip/_vendor/pygments/formatters/rtf.py,sha256=abrKlWjipBkQvhIICxtjYTUNv6WME0iJJObFvqVuudE,5014 +pip/_vendor/pygments/formatters/svg.py,sha256=6MM9YyO8NhU42RTQfTWBiagWMnsf9iG5gwhqSriHORE,7335 +pip/_vendor/pygments/formatters/terminal.py,sha256=NpEGvwkC6LgMLQTjVzGrJXji3XcET1sb5JCunSCzoRo,4674 +pip/_vendor/pygments/formatters/terminal256.py,sha256=4v4OVizvsxtwWBpIy_Po30zeOzE5oJg_mOc1-rCjMDk,11753 +pip/_vendor/pygments/lexer.py,sha256=ZPB_TGn_qzrXodRFwEdPzzJk6LZBo9BlfSy3lacc6zg,32005 +pip/_vendor/pygments/lexers/__init__.py,sha256=8d80-XfL5UKDCC1wRD1a_ZBZDkZ2HOe7Zul8SsnNYFE,11174 +pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-311.pyc,, +pip/_vendor/pygments/lexers/__pycache__/python.cpython-311.pyc,, +pip/_vendor/pygments/lexers/_mapping.py,sha256=zEiCV5FPiBioMJQJjw9kk7IJ5Y9GwknS4VJPYlcNchs,70232 +pip/_vendor/pygments/lexers/python.py,sha256=gZROs9iNSOA18YyVghP1cUCD0OwYZ04a6PCwgSOCeSA,53376 +pip/_vendor/pygments/modeline.py,sha256=gIbMSYrjSWPk0oATz7W9vMBYkUyTK2OcdVyKjioDRvA,986 +pip/_vendor/pygments/plugin.py,sha256=5rPxEoB_89qQMpOs0nI4KyLOzAHNlbQiwEMOKxqNmv8,2591 +pip/_vendor/pygments/regexopt.py,sha256=c6xcXGpGgvCET_3VWawJJqAnOp0QttFpQEdOPNY2Py0,3072 +pip/_vendor/pygments/scanner.py,sha256=F2T2G6cpkj-yZtzGQr-sOBw5w5-96UrJWveZN6va2aM,3092 +pip/_vendor/pygments/sphinxext.py,sha256=F8L0211sPnXaiWutN0lkSUajWBwlgDMIEFFAbMWOvZY,4630 +pip/_vendor/pygments/style.py,sha256=RRnussX1YiK9Z7HipIvKorImxu3-HnkdpPCO4u925T0,6257 +pip/_vendor/pygments/styles/__init__.py,sha256=iZDZ7PBKb55SpGlE1--cx9cbmWx5lVTH4bXO87t2Vok,3419 +pip/_vendor/pygments/styles/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pygments/token.py,sha256=vA2yNHGJBHfq4jNQSah7C9DmIOp34MmYHPA8P-cYAHI,6184 +pip/_vendor/pygments/unistring.py,sha256=gP3gK-6C4oAFjjo9HvoahsqzuV4Qz0jl0E0OxfDerHI,63187 +pip/_vendor/pygments/util.py,sha256=KgwpWWC3By5AiNwxGTI7oI9aXupH2TyZWukafBJe0Mg,9110 +pip/_vendor/pyparsing/__init__.py,sha256=ZPdI7pPo4IYXcABw-51AcqOzsxVvDtqnQbyn_qYWZvo,9171 +pip/_vendor/pyparsing/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/actions.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/common.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/core.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/exceptions.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/helpers.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/results.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/testing.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/unicode.cpython-311.pyc,, +pip/_vendor/pyparsing/__pycache__/util.cpython-311.pyc,, +pip/_vendor/pyparsing/actions.py,sha256=wU9i32e0y1ymxKE3OUwSHO-SFIrt1h_wv6Ws0GQjpNU,6426 +pip/_vendor/pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936 +pip/_vendor/pyparsing/core.py,sha256=AzTm1KFT1FIhiw2zvXZJmrpQoAwB0wOmeDCiR6SYytw,213344 +pip/_vendor/pyparsing/diagram/__init__.py,sha256=KW0PV_TvWKnL7jysz0pQbZ24nzWWu2ZfNaeyUIIywIg,23685 +pip/_vendor/pyparsing/diagram/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/pyparsing/exceptions.py,sha256=3LbSafD32NYb1Tzt85GHNkhEAU1eZkTtNSk24cPMemo,9023 +pip/_vendor/pyparsing/helpers.py,sha256=QpUOjW0-psvueMwWb9bQpU2noqKCv98_wnw1VSzSdVo,39129 +pip/_vendor/pyparsing/results.py,sha256=HgNvWVXBdQP-Q6PtJfoCEeOJk2nwEvG-2KVKC5sGA30,25341 +pip/_vendor/pyparsing/testing.py,sha256=7tu4Abp4uSeJV0N_yEPRmmNUhpd18ZQP3CrX41DM814,13402 +pip/_vendor/pyparsing/unicode.py,sha256=fwuhMj30SQ165Cv7HJpu-rSxGbRm93kN9L4Ei7VGc1Y,10787 +pip/_vendor/pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805 +pip/_vendor/requests/__init__.py,sha256=3XN75ZS4slWy3TQsEGF7-Q6l2R146teU-s2_rXNhxhU,5178 +pip/_vendor/requests/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/__version__.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/_internal_utils.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/adapters.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/api.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/auth.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/certs.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/compat.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/cookies.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/exceptions.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/help.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/hooks.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/models.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/packages.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/sessions.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/status_codes.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/structures.cpython-311.pyc,, +pip/_vendor/requests/__pycache__/utils.cpython-311.pyc,, +pip/_vendor/requests/__version__.py,sha256=nJVa3ef2yRyeYMhy7yHnRyjjpnNTDykZsE4Sp9irBC4,440 +pip/_vendor/requests/_internal_utils.py,sha256=aSPlF4uDhtfKxEayZJJ7KkAxtormeTfpwKSBSwtmAUw,1397 +pip/_vendor/requests/adapters.py,sha256=GFEz5koZaMZD86v0SHXKVB5SE9MgslEjkCQzldkNwVM,21443 +pip/_vendor/requests/api.py,sha256=dyvkDd5itC9z2g0wHl_YfD1yf6YwpGWLO7__8e21nks,6377 +pip/_vendor/requests/auth.py,sha256=h-HLlVx9j8rKV5hfSAycP2ApOSglTz77R0tz7qCbbEE,10187 +pip/_vendor/requests/certs.py,sha256=PVPooB0jP5hkZEULSCwC074532UFbR2Ptgu0I5zwmCs,575 +pip/_vendor/requests/compat.py,sha256=IhK9quyX0RRuWTNcg6d2JGSAOUbM6mym2p_2XjLTwf4,1286 +pip/_vendor/requests/cookies.py,sha256=kD3kNEcCj-mxbtf5fJsSaT86eGoEYpD3X0CSgpzl7BM,18560 +pip/_vendor/requests/exceptions.py,sha256=FA-_kVwBZ2jhXauRctN_ewHVK25b-fj0Azyz1THQ0Kk,3823 +pip/_vendor/requests/help.py,sha256=FnAAklv8MGm_qb2UilDQgS6l0cUttiCFKUjx0zn2XNA,3879 +pip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733 +pip/_vendor/requests/models.py,sha256=GZRMMrGwDOLVvVfFHLUq0qTfIWDla3NcFHa1f5xs9Q8,35287 +pip/_vendor/requests/packages.py,sha256=njJmVifY4aSctuW3PP5EFRCxjEwMRDO6J_feG2dKWsI,695 +pip/_vendor/requests/sessions.py,sha256=KUqJcRRLovNefUs7ScOXSUVCcfSayTFWtbiJ7gOSlTI,30180 +pip/_vendor/requests/status_codes.py,sha256=FvHmT5uH-_uimtRz5hH9VCbt7VV-Nei2J9upbej6j8g,4235 +pip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912 +pip/_vendor/requests/utils.py,sha256=0gzSOcx9Ya4liAbHnHuwt4jM78lzCZZoDFgkmsInNUg,33240 +pip/_vendor/resolvelib/__init__.py,sha256=UL-B2BDI0_TRIqkfGwLHKLxY-LjBlomz7941wDqzB1I,537 +pip/_vendor/resolvelib/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/resolvelib/__pycache__/providers.cpython-311.pyc,, +pip/_vendor/resolvelib/__pycache__/reporters.cpython-311.pyc,, +pip/_vendor/resolvelib/__pycache__/resolvers.cpython-311.pyc,, +pip/_vendor/resolvelib/__pycache__/structs.cpython-311.pyc,, +pip/_vendor/resolvelib/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-311.pyc,, +pip/_vendor/resolvelib/compat/collections_abc.py,sha256=uy8xUZ-NDEw916tugUXm8HgwCGiMO0f-RcdnpkfXfOs,156 +pip/_vendor/resolvelib/providers.py,sha256=roVmFBItQJ0TkhNua65h8LdNny7rmeqVEXZu90QiP4o,5872 +pip/_vendor/resolvelib/reporters.py,sha256=fW91NKf-lK8XN7i6Yd_rczL5QeOT3sc6AKhpaTEnP3E,1583 +pip/_vendor/resolvelib/resolvers.py,sha256=2wYzVGBGerbmcIpH8cFmgSKgLSETz8jmwBMGjCBMHG4,17592 +pip/_vendor/resolvelib/structs.py,sha256=IVIYof6sA_N4ZEiE1C1UhzTX495brCNnyCdgq6CYq28,4794 +pip/_vendor/rich/__init__.py,sha256=zREyQ22R3zKg8gMdhiikczdVQYtZNeayHNrbBg5scm0,5944 +pip/_vendor/rich/__main__.py,sha256=BmTmBWI93ytq75IEPi1uAAdeRYzFfDbgaAXjsX1ogig,8808 +pip/_vendor/rich/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/__main__.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_cell_widths.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_emoji_codes.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_emoji_replace.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_export_format.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_extension.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_inspect.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_log_render.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_loop.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_palettes.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_pick.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_ratio.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_spinners.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_stack.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_timer.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_win32_console.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_windows.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_windows_renderer.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/_wrap.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/abc.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/align.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/ansi.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/bar.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/box.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/cells.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/color.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/color_triplet.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/columns.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/console.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/constrain.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/containers.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/control.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/default_styles.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/diagnose.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/emoji.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/errors.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/file_proxy.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/filesize.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/highlighter.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/json.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/jupyter.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/layout.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/live.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/live_render.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/logging.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/markup.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/measure.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/padding.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/pager.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/palette.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/panel.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/pretty.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/progress.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/progress_bar.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/prompt.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/protocol.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/region.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/repr.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/rule.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/scope.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/screen.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/segment.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/spinner.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/status.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/style.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/styled.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/syntax.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/table.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/terminal_theme.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/text.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/theme.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/themes.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/traceback.cpython-311.pyc,, +pip/_vendor/rich/__pycache__/tree.cpython-311.pyc,, +pip/_vendor/rich/_cell_widths.py,sha256=2n4EiJi3X9sqIq0O16kUZ_zy6UYMd3xFfChlKfnW1Hc,10096 +pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235 +pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064 +pip/_vendor/rich/_export_format.py,sha256=nHArqOljIlYn6NruhWsAsh-fHo7oJC3y9BDJyAa-QYQ,2114 +pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265 +pip/_vendor/rich/_inspect.py,sha256=oZJGw31e64dwXSCmrDnvZbwVb1ZKhWfU8wI3VWohjJk,9695 +pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225 +pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236 +pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063 +pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423 +pip/_vendor/rich/_ratio.py,sha256=2lLSliL025Y-YMfdfGbutkQDevhcyDqc-DtUYW9mU70,5472 +pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919 +pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351 +pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417 +pip/_vendor/rich/_win32_console.py,sha256=P0vxI2fcndym1UU1S37XAzQzQnkyY7YqAKmxm24_gug,22820 +pip/_vendor/rich/_windows.py,sha256=dvNl9TmfPzNVxiKk5WDFihErZ5796g2UC9-KGGyfXmk,1926 +pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783 +pip/_vendor/rich/_wrap.py,sha256=xfV_9t0Sg6rzimmrDru8fCVmUlalYAcHLDfrJZnbbwQ,1840 +pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890 +pip/_vendor/rich/align.py,sha256=FV6_GS-8uhIyViMng3hkIWSFaTgMohK1Oqyjl8I8mGE,10368 +pip/_vendor/rich/ansi.py,sha256=HtaPG7dvgL6_yo0sQmx5CM05DJ4_1goY5SWXXOYNaKs,6820 +pip/_vendor/rich/bar.py,sha256=a7UD303BccRCrEhGjfMElpv5RFYIinaAhAuqYqhUvmw,3264 +pip/_vendor/rich/box.py,sha256=1Iv1sUWqjtp5XwLwGH-AJ8HgyXZ7dRFUkO0z3M_bRl8,9864 +pip/_vendor/rich/cells.py,sha256=zMjFI15wCpgjLR14lHdfFMVC6qMDi5OsKIB0PYZBBMk,4503 +pip/_vendor/rich/color.py,sha256=kp87L8V4-3qayE6CUxtW_nP8Ujfew_-DAhNwYMXBMOY,17957 +pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054 +pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131 +pip/_vendor/rich/console.py,sha256=bTT9DNX03V4cQXefg22d-gLSs_e_ZY2zdCvLIlEyU2Q,95885 +pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288 +pip/_vendor/rich/containers.py,sha256=aKgm5UDHn5Nmui6IJaKdsZhbHClh_X7D-_Wg8Ehrr7s,5497 +pip/_vendor/rich/control.py,sha256=DSkHTUQLorfSERAKE_oTAEUFefZnZp4bQb4q8rHbKws,6630 +pip/_vendor/rich/default_styles.py,sha256=WqVh-RPNEsx0Wxf3fhS_fCn-wVqgJ6Qfo-Zg7CoCsLE,7954 +pip/_vendor/rich/diagnose.py,sha256=an6uouwhKPAlvQhYpNNpGq9EJysfMIOvvCbO3oSoR24,972 +pip/_vendor/rich/emoji.py,sha256=omTF9asaAnsM4yLY94eR_9dgRRSm1lHUszX20D1yYCQ,2501 +pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642 +pip/_vendor/rich/file_proxy.py,sha256=4gCbGRXg0rW35Plaf0UVvj3dfENHuzc_n8I_dBqxI7o,1616 +pip/_vendor/rich/filesize.py,sha256=yShoVpARafJBreyZFaAhC4OhnJ6ydC1WXR-Ez4wU_YQ,2507 +pip/_vendor/rich/highlighter.py,sha256=3WW6PACGlq0e3YDjfqiMBQ0dYZwu7pcoFYUgJy01nb0,9585 +pip/_vendor/rich/json.py,sha256=RCm4lXBXrjvXHpqrWPH8wdGP0jEo4IohLmkddlhRY18,5051 +pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252 +pip/_vendor/rich/layout.py,sha256=E3xJ4fomizUADwime3VA0lBXoMSPl9blEokIzVBjO0Q,14074 +pip/_vendor/rich/live.py,sha256=emVaLUua-FKSYqZXmtJJjBIstO99CqMOuA6vMAKVkO0,14172 +pip/_vendor/rich/live_render.py,sha256=zElm3PrfSIvjOce28zETHMIUf9pFYSUA5o0AflgUP64,3667 +pip/_vendor/rich/logging.py,sha256=10j13lPr-QuYqEEBz_2aRJp8gNYvSN2wmCUlUqJcPLM,11471 +pip/_vendor/rich/markup.py,sha256=xzF4uAafiEeEYDJYt_vUnJOGoTU8RrH-PH7WcWYXjCg,8198 +pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305 +pip/_vendor/rich/padding.py,sha256=kTFGsdGe0os7tXLnHKpwTI90CXEvrceeZGCshmJy5zw,4970 +pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828 +pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396 +pip/_vendor/rich/panel.py,sha256=CzdojkDAjxAKgvDxis47nWzUh1V2NniOqkJJQajosG8,8744 +pip/_vendor/rich/pretty.py,sha256=CalVLVW3mvTn1hvI9Pgi2v-y4S-5zUWBK-PH7SlVs-U,36576 +pip/_vendor/rich/progress.py,sha256=zjQRwd3TmDnAvSjTPsNPHFjmqE9GOEX3bf0Lj56hIL8,59746 +pip/_vendor/rich/progress_bar.py,sha256=zHHaFPEfIhW2fq6Fnl5vBY7AUpP1N0HVGElISUHsnqw,8161 +pip/_vendor/rich/prompt.py,sha256=x0mW-pIPodJM4ry6grgmmLrl8VZp99kqcmdnBe70YYA,11303 +pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391 +pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166 +pip/_vendor/rich/repr.py,sha256=Je91CIrZN_av9L3FRCKCs5yoX2LvczrCNKqUbVsjUvQ,4449 +pip/_vendor/rich/rule.py,sha256=V6AWI0wCb6DB0rvN967FRMlQrdlG7HoZdfEAHyeG8CM,4773 +pip/_vendor/rich/scope.py,sha256=HX13XsJfqzQHpPfw4Jn9JmJjCsRj9uhHxXQEqjkwyLA,2842 +pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591 +pip/_vendor/rich/segment.py,sha256=6XdX0MfL18tUCaUWDWncIqx0wpq3GiaqzhYP779JvRA,24224 +pip/_vendor/rich/spinner.py,sha256=7b8MCleS4fa46HX0AzF98zfu6ZM6fAL0UgYzPOoakF4,4374 +pip/_vendor/rich/status.py,sha256=gJsIXIZeSo3urOyxRUjs6VrhX5CZrA0NxIQ-dxhCnwo,4425 +pip/_vendor/rich/style.py,sha256=4WnUEkHNMp9Tfmd8cmbxWGby7QeTk2LUTQzFSs46EQc,26240 +pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258 +pip/_vendor/rich/syntax.py,sha256=_M08KbE11nNWNBPooFLKAA7lWkThPzlGUsuesxQYsuA,34697 +pip/_vendor/rich/table.py,sha256=r_lahmj45cINCWLYaIjq9yEv3gve8E6bkYTP8NDqApE,39515 +pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370 +pip/_vendor/rich/text.py,sha256=oajdGIeHcLcSdOwbC48_20ylDsHAS5fsPZD_Ih0clyA,44666 +pip/_vendor/rich/theme.py,sha256=GKNtQhDBZKAzDaY0vQVQQFzbc0uWfFe6CJXA-syT7zQ,3627 +pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102 +pip/_vendor/rich/traceback.py,sha256=MORQpXH7AvhAAThW8oIbtwffXb8M6XRkSkcJ52JuA3g,26060 +pip/_vendor/rich/tree.py,sha256=BMbUYNjS9uodNPfvtY_odmU09GA5QzcMbQ5cJZhllQI,9169 +pip/_vendor/six.py,sha256=TOOfQi7nFGfMrIvtdr6wX4wyHH8M7aknmuLfo2cBBrM,34549 +pip/_vendor/tenacity/__init__.py,sha256=rjcWJVq5PcNJNC42rt-TAGGskM-RUEkZbDKu1ra7IPo,18364 +pip/_vendor/tenacity/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/_asyncio.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/_utils.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/after.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/before.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/before_sleep.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/nap.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/retry.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/stop.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/tornadoweb.cpython-311.pyc,, +pip/_vendor/tenacity/__pycache__/wait.cpython-311.pyc,, +pip/_vendor/tenacity/_asyncio.py,sha256=HEb0BVJEeBJE9P-m9XBxh1KcaF96BwoeqkJCL5sbVcQ,3314 +pip/_vendor/tenacity/_utils.py,sha256=-y68scDcyoqvTJuJJ0GTfjdSCljEYlbCYvgk7nM4NdM,1944 +pip/_vendor/tenacity/after.py,sha256=dlmyxxFy2uqpLXDr838DiEd7jgv2AGthsWHGYcGYsaI,1496 +pip/_vendor/tenacity/before.py,sha256=7XtvRmO0dRWUp8SVn24OvIiGFj8-4OP5muQRUiWgLh0,1376 +pip/_vendor/tenacity/before_sleep.py,sha256=ThyDvqKU5yle_IvYQz_b6Tp6UjUS0PhVp6zgqYl9U6Y,1908 +pip/_vendor/tenacity/nap.py,sha256=fRWvnz1aIzbIq9Ap3gAkAZgDH6oo5zxMrU6ZOVByq0I,1383 +pip/_vendor/tenacity/retry.py,sha256=Cy504Ss3UrRV7lnYgvymF66WD1wJ2dbM869kDcjuDes,7550 +pip/_vendor/tenacity/stop.py,sha256=sKHmHaoSaW6sKu3dTxUVKr1-stVkY7lw4Y9yjZU30zQ,2790 +pip/_vendor/tenacity/tornadoweb.py,sha256=E8lWO2nwe6dJgoB-N2HhQprYLDLB_UdSgFnv-EN6wKE,2145 +pip/_vendor/tenacity/wait.py,sha256=tdLTESRm5E237VHG0SxCDXRa0DHKPKVq285kslHVURc,8011 +pip/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396 +pip/_vendor/tomli/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/tomli/__pycache__/_parser.cpython-311.pyc,, +pip/_vendor/tomli/__pycache__/_re.cpython-311.pyc,, +pip/_vendor/tomli/__pycache__/_types.cpython-311.pyc,, +pip/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633 +pip/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943 +pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +pip/_vendor/typing_extensions.py,sha256=VKZ_nHsuzDbKOVUY2CTdavwBgfZ2EXRyluZHRzUYAbg,80114 +pip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333 +pip/_vendor/urllib3/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/_collections.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/_version.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/connection.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/connectionpool.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/exceptions.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/fields.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/filepost.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/poolmanager.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/request.cpython-311.pyc,, +pip/_vendor/urllib3/__pycache__/response.cpython-311.pyc,, +pip/_vendor/urllib3/_collections.py,sha256=Rp1mVyBgc_UlAcp6M3at1skJBXR5J43NawRTvW2g_XY,10811 +pip/_vendor/urllib3/_version.py,sha256=GhuGBUT_MtRxHEHDb-LYs5yLPeYWlCwFBPjGZmVJbVg,64 +pip/_vendor/urllib3/connection.py,sha256=8976wL6sGeVMW0JnXvx5mD00yXu87uQjxtB9_VL8dx8,20070 +pip/_vendor/urllib3/connectionpool.py,sha256=vEzk1iJEw1qR2vHBo7m3Y98iDfna6rKkUz3AyK5lJKQ,39093 +pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957 +pip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-311.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632 +pip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922 +pip/_vendor/urllib3/contrib/appengine.py,sha256=lfzpHFmJiO82shClLEm3QB62SYgHWnjpZOH_2JhU5Tc,11034 +pip/_vendor/urllib3/contrib/ntlmpool.py,sha256=ej9gGvfAb2Gt00lafFp45SIoRz-QwrQ4WChm6gQmAlM,4538 +pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=rt9NEIP8iMBLxxRhH0jLnmshW-OFP83jEayxMSqu2MU,17182 +pip/_vendor/urllib3/contrib/securetransport.py,sha256=yhZdmVjY6PI6EeFbp7qYOp6-vp1Rkv2NMuOGaEj7pmc,34448 +pip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097 +pip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217 +pip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579 +pip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440 +pip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/packages/__pycache__/six.cpython-311.pyc,, +pip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-311.pyc,, +pip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417 +pip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665 +pip/_vendor/urllib3/poolmanager.py,sha256=0KOOJECoeLYVjUHvv-0h4Oq3FFQQ2yb-Fnjkbj8gJO0,19786 +pip/_vendor/urllib3/request.py,sha256=ZFSIqX0C6WizixecChZ3_okyu7BEv0lZu1VT0s6h4SM,5985 +pip/_vendor/urllib3/response.py,sha256=p3VBYPhwBca77wCZfmoXvEDVVC3SdF7yxQ6TXuxy1BI,30109 +pip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155 +pip/_vendor/urllib3/util/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/connection.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/proxy.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/queue.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/request.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/response.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/retry.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/timeout.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/url.cpython-311.pyc,, +pip/_vendor/urllib3/util/__pycache__/wait.cpython-311.pyc,, +pip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901 +pip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605 +pip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498 +pip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997 +pip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510 +pip/_vendor/urllib3/util/retry.py,sha256=iESg2PvViNdXBRY4MpL4h0kqwOOkHkxmLn1kkhFHPU8,22001 +pip/_vendor/urllib3/util/ssl_.py,sha256=X4-AqW91aYPhPx6-xbf66yHFQKbqqfC_5Zt4WkLX1Hc,17177 +pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758 +pip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895 +pip/_vendor/urllib3/util/timeout.py,sha256=QSbBUNOB9yh6AnDn61SrLQ0hg5oz0I9-uXEG91AJuIg,10003 +pip/_vendor/urllib3/util/url.py,sha256=49HwObaTUUjqVe4qvSUvIjZyf3ghgNA6-OLm3kmkFKM,14287 +pip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403 +pip/_vendor/vendor.txt,sha256=07gLL_CcEHdl1XM0g4PH2L4gsTTMlJr8WWIC11yEyMo,469 +pip/_vendor/webencodings/__init__.py,sha256=qOBJIuPy_4ByYH6W_bNgJF-qYQ2DoU-dKsDu5yRWCXg,10579 +pip/_vendor/webencodings/__pycache__/__init__.cpython-311.pyc,, +pip/_vendor/webencodings/__pycache__/labels.cpython-311.pyc,, +pip/_vendor/webencodings/__pycache__/mklabels.cpython-311.pyc,, +pip/_vendor/webencodings/__pycache__/tests.cpython-311.pyc,, +pip/_vendor/webencodings/__pycache__/x_user_defined.cpython-311.pyc,, +pip/_vendor/webencodings/labels.py,sha256=4AO_KxTddqGtrL9ns7kAPjb0CcN6xsCIxbK37HY9r3E,8979 +pip/_vendor/webencodings/mklabels.py,sha256=GYIeywnpaLnP0GSic8LFWgd0UVvO_l1Nc6YoF-87R_4,1305 +pip/_vendor/webencodings/tests.py,sha256=OtGLyjhNY1fvkW1GvLJ_FV9ZoqC9Anyjr7q3kxTbzNs,6563 +pip/_vendor/webencodings/x_user_defined.py,sha256=yOqWSdmpytGfUgh_Z6JYgDNhoc-BAHyyeeT15Fr42tM,4307 +pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286 diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/REQUESTED b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/REQUESTED new file mode 100644 index 00000000..e69de29b diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/WHEEL b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/WHEEL new file mode 100644 index 00000000..57e3d840 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/entry_points.txt b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/entry_points.txt new file mode 100644 index 00000000..bcf704db --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +pip = pip._internal.cli.main:main +pip3 = pip._internal.cli.main:main +pip3.11 = pip._internal.cli.main:main diff --git a/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/top_level.txt b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/top_level.txt new file mode 100644 index 00000000..a1b589e3 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip-22.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +pip diff --git a/web/lib/python3.11/site-packages/pip/__init__.py b/web/lib/python3.11/site-packages/pip/__init__.py new file mode 100644 index 00000000..5563b5d5 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/__init__.py @@ -0,0 +1,13 @@ +from typing import List, Optional + +__version__ = "22.3.1" + + +def main(args: Optional[List[str]] = None) -> int: + """This is an internal API only meant for use by pip's own console scripts. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/web/lib/python3.11/site-packages/pip/__main__.py b/web/lib/python3.11/site-packages/pip/__main__.py new file mode 100644 index 00000000..fe34a7b7 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/__main__.py @@ -0,0 +1,31 @@ +import os +import sys +import warnings + +# Remove '' and current working directory from the first entry +# of sys.path, if present to avoid using current directory +# in pip commands check, freeze, install, list and show, +# when invoked as python -m pip +if sys.path[0] in ("", os.getcwd()): + sys.path.pop(0) + +# If we are running from a wheel, add the wheel to sys.path +# This allows the usage python pip-*.whl/pip install pip-*.whl +if __package__ == "": + # __file__ is pip-*.whl/pip/__main__.py + # first dirname call strips of '/__main__.py', second strips off '/pip' + # Resulting path is the name of the wheel itself + # Add that to sys.path so we can import pip + path = os.path.dirname(os.path.dirname(__file__)) + sys.path.insert(0, path) + +if __name__ == "__main__": + # Work around the error reported in #9540, pending a proper fix. + # Note: It is essential the warning filter is set *before* importing + # pip, as the deprecation happens at import time, not runtime. + warnings.filterwarnings( + "ignore", category=DeprecationWarning, module=".*packaging\\.version" + ) + from pip._internal.cli.main import main as _main + + sys.exit(_main()) diff --git a/web/lib/python3.11/site-packages/pip/__pip-runner__.py b/web/lib/python3.11/site-packages/pip/__pip-runner__.py new file mode 100644 index 00000000..49a148a0 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/__pip-runner__.py @@ -0,0 +1,50 @@ +"""Execute exactly this copy of pip, within a different environment. + +This file is named as it is, to ensure that this module can't be imported via +an import statement. +""" + +# /!\ This version compatibility check section must be Python 2 compatible. /!\ + +import sys + +# Copied from setup.py +PYTHON_REQUIRES = (3, 7) + + +def version_str(version): # type: ignore + return ".".join(str(v) for v in version) + + +if sys.version_info[:2] < PYTHON_REQUIRES: + raise SystemExit( + "This version of pip does not support python {} (requires >={}).".format( + version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) + ) + ) + +# From here on, we can use Python 3 features, but the syntax must remain +# Python 2 compatible. + +import runpy # noqa: E402 +from importlib.machinery import PathFinder # noqa: E402 +from os.path import dirname # noqa: E402 + +PIP_SOURCES_ROOT = dirname(dirname(__file__)) + + +class PipImportRedirectingFinder: + @classmethod + def find_spec(self, fullname, path=None, target=None): # type: ignore + if fullname != "pip": + return None + + spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) + assert spec, (PIP_SOURCES_ROOT, fullname) + return spec + + +sys.meta_path.insert(0, PipImportRedirectingFinder()) + +assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" +runpy.run_module("pip", run_name="__main__", alter_sys=True) diff --git a/web/lib/python3.11/site-packages/pip/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..2c0086c3 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/__pycache__/__main__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 00000000..038aabd5 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/__pycache__/__main__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/__pycache__/__pip-runner__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/__pycache__/__pip-runner__.cpython-311.pyc new file mode 100644 index 00000000..7be5f7e3 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/__pycache__/__pip-runner__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__init__.py b/web/lib/python3.11/site-packages/pip/_internal/__init__.py new file mode 100644 index 00000000..6afb5c62 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/__init__.py @@ -0,0 +1,19 @@ +from typing import List, Optional + +import pip._internal.utils.inject_securetransport # noqa +from pip._internal.utils import _log + +# init_logging() must be called before any call to logging.getLogger() +# which happens at import of most modules. +_log.init_logging() + + +def main(args: (Optional[List[str]]) = None) -> int: + """This is preserved for old console scripts that may still be referencing + it. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..65586f15 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/build_env.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/build_env.cpython-311.pyc new file mode 100644 index 00000000..90aba4e3 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/build_env.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/cache.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/cache.cpython-311.pyc new file mode 100644 index 00000000..ddac6f78 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/cache.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/configuration.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/configuration.cpython-311.pyc new file mode 100644 index 00000000..2053ff93 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/configuration.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/exceptions.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 00000000..35ae9563 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/exceptions.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/main.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/main.cpython-311.pyc new file mode 100644 index 00000000..30a0c573 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/main.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/pyproject.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/pyproject.cpython-311.pyc new file mode 100644 index 00000000..4f05e50e Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/pyproject.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-311.pyc new file mode 100644 index 00000000..bc34da56 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-311.pyc new file mode 100644 index 00000000..53639bd8 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/build_env.py b/web/lib/python3.11/site-packages/pip/_internal/build_env.py new file mode 100644 index 00000000..cc2b38ba --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/build_env.py @@ -0,0 +1,310 @@ +"""Build Environment used for isolation during sdist building +""" + +import logging +import os +import pathlib +import site +import sys +import textwrap +from collections import OrderedDict +from sysconfig import get_paths +from types import TracebackType +from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type + +from pip._vendor.certifi import where +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.version import Version + +from pip import __file__ as pip_location +from pip._internal.cli.spinners import open_spinner +from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib +from pip._internal.metadata import get_default_environment, get_environment +from pip._internal.utils.subprocess import call_subprocess +from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + +logger = logging.getLogger(__name__) + + +class _Prefix: + def __init__(self, path: str) -> None: + self.path = path + self.setup = False + self.bin_dir = get_paths( + "nt" if os.name == "nt" else "posix_prefix", + vars={"base": path, "platbase": path}, + )["scripts"] + self.lib_dirs = get_prefixed_libs(path) + + +def get_runnable_pip() -> str: + """Get a file to pass to a Python executable, to run the currently-running pip. + + This is used to run a pip subprocess, for installing requirements into the build + environment. + """ + source = pathlib.Path(pip_location).resolve().parent + + if not source.is_dir(): + # This would happen if someone is using pip from inside a zip file. In that + # case, we can use that directly. + return str(source) + + return os.fsdecode(source / "__pip-runner__.py") + + +def _get_system_sitepackages() -> Set[str]: + """Get system site packages + + Usually from site.getsitepackages, + but fallback on `get_purelib()/get_platlib()` if unavailable + (e.g. in a virtualenv created by virtualenv<20) + + Returns normalized set of strings. + """ + if hasattr(site, "getsitepackages"): + system_sites = site.getsitepackages() + else: + # virtualenv < 20 overwrites site.py without getsitepackages + # fallback on get_purelib/get_platlib. + # this is known to miss things, but shouldn't in the cases + # where getsitepackages() has been removed (inside a virtualenv) + system_sites = [get_purelib(), get_platlib()] + return {os.path.normcase(path) for path in system_sites} + + +class BuildEnvironment: + """Creates and manages an isolated environment to install build deps""" + + def __init__(self) -> None: + temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True) + + self._prefixes = OrderedDict( + (name, _Prefix(os.path.join(temp_dir.path, name))) + for name in ("normal", "overlay") + ) + + self._bin_dirs: List[str] = [] + self._lib_dirs: List[str] = [] + for prefix in reversed(list(self._prefixes.values())): + self._bin_dirs.append(prefix.bin_dir) + self._lib_dirs.extend(prefix.lib_dirs) + + # Customize site to: + # - ensure .pth files are honored + # - prevent access to system site packages + system_sites = _get_system_sitepackages() + + self._site_dir = os.path.join(temp_dir.path, "site") + if not os.path.exists(self._site_dir): + os.mkdir(self._site_dir) + with open( + os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8" + ) as fp: + fp.write( + textwrap.dedent( + """ + import os, site, sys + + # First, drop system-sites related paths. + original_sys_path = sys.path[:] + known_paths = set() + for path in {system_sites!r}: + site.addsitedir(path, known_paths=known_paths) + system_paths = set( + os.path.normcase(path) + for path in sys.path[len(original_sys_path):] + ) + original_sys_path = [ + path for path in original_sys_path + if os.path.normcase(path) not in system_paths + ] + sys.path = original_sys_path + + # Second, add lib directories. + # ensuring .pth file are processed. + for path in {lib_dirs!r}: + assert not path in sys.path + site.addsitedir(path) + """ + ).format(system_sites=system_sites, lib_dirs=self._lib_dirs) + ) + + def __enter__(self) -> None: + self._save_env = { + name: os.environ.get(name, None) + for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH") + } + + path = self._bin_dirs[:] + old_path = self._save_env["PATH"] + if old_path: + path.extend(old_path.split(os.pathsep)) + + pythonpath = [self._site_dir] + + os.environ.update( + { + "PATH": os.pathsep.join(path), + "PYTHONNOUSERSITE": "1", + "PYTHONPATH": os.pathsep.join(pythonpath), + } + ) + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + for varname, old_value in self._save_env.items(): + if old_value is None: + os.environ.pop(varname, None) + else: + os.environ[varname] = old_value + + def check_requirements( + self, reqs: Iterable[str] + ) -> Tuple[Set[Tuple[str, str]], Set[str]]: + """Return 2 sets: + - conflicting requirements: set of (installed, wanted) reqs tuples + - missing requirements: set of reqs + """ + missing = set() + conflicting = set() + if reqs: + env = ( + get_environment(self._lib_dirs) + if hasattr(self, "_lib_dirs") + else get_default_environment() + ) + for req_str in reqs: + req = Requirement(req_str) + # We're explicitly evaluating with an empty extra value, since build + # environments are not provided any mechanism to select specific extras. + if req.marker is not None and not req.marker.evaluate({"extra": ""}): + continue + dist = env.get_distribution(req.name) + if not dist: + missing.add(req_str) + continue + if isinstance(dist.version, Version): + installed_req_str = f"{req.name}=={dist.version}" + else: + installed_req_str = f"{req.name}==={dist.version}" + if not req.specifier.contains(dist.version, prereleases=True): + conflicting.add((installed_req_str, req_str)) + # FIXME: Consider direct URL? + return conflicting, missing + + def install_requirements( + self, + finder: "PackageFinder", + requirements: Iterable[str], + prefix_as_string: str, + *, + kind: str, + ) -> None: + prefix = self._prefixes[prefix_as_string] + assert not prefix.setup + prefix.setup = True + if not requirements: + return + self._install_requirements( + get_runnable_pip(), + finder, + requirements, + prefix, + kind=kind, + ) + + @staticmethod + def _install_requirements( + pip_runnable: str, + finder: "PackageFinder", + requirements: Iterable[str], + prefix: _Prefix, + *, + kind: str, + ) -> None: + args: List[str] = [ + sys.executable, + pip_runnable, + "install", + "--ignore-installed", + "--no-user", + "--prefix", + prefix.path, + "--no-warn-script-location", + ] + if logger.getEffectiveLevel() <= logging.DEBUG: + args.append("-v") + for format_control in ("no_binary", "only_binary"): + formats = getattr(finder.format_control, format_control) + args.extend( + ( + "--" + format_control.replace("_", "-"), + ",".join(sorted(formats or {":none:"})), + ) + ) + + index_urls = finder.index_urls + if index_urls: + args.extend(["-i", index_urls[0]]) + for extra_index in index_urls[1:]: + args.extend(["--extra-index-url", extra_index]) + else: + args.append("--no-index") + for link in finder.find_links: + args.extend(["--find-links", link]) + + for host in finder.trusted_hosts: + args.extend(["--trusted-host", host]) + if finder.allow_all_prereleases: + args.append("--pre") + if finder.prefer_binary: + args.append("--prefer-binary") + args.append("--") + args.extend(requirements) + extra_environ = {"_PIP_STANDALONE_CERT": where()} + with open_spinner(f"Installing {kind}") as spinner: + call_subprocess( + args, + command_desc=f"pip subprocess to install {kind}", + spinner=spinner, + extra_environ=extra_environ, + ) + + +class NoOpBuildEnvironment(BuildEnvironment): + """A no-op drop-in replacement for BuildEnvironment""" + + def __init__(self) -> None: + pass + + def __enter__(self) -> None: + pass + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + pass + + def cleanup(self) -> None: + pass + + def install_requirements( + self, + finder: "PackageFinder", + requirements: Iterable[str], + prefix_as_string: str, + *, + kind: str, + ) -> None: + raise NotImplementedError() diff --git a/web/lib/python3.11/site-packages/pip/_internal/cache.py b/web/lib/python3.11/site-packages/pip/_internal/cache.py new file mode 100644 index 00000000..c53b7f02 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cache.py @@ -0,0 +1,293 @@ +"""Cache Management +""" + +import hashlib +import json +import logging +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Set + +from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.exceptions import InvalidWheelFilename +from pip._internal.models.direct_url import DirectUrl +from pip._internal.models.format_control import FormatControl +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds +from pip._internal.utils.urls import path_to_url + +logger = logging.getLogger(__name__) + +ORIGIN_JSON_NAME = "origin.json" + + +def _hash_dict(d: Dict[str, str]) -> str: + """Return a stable sha224 of a dictionary.""" + s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + return hashlib.sha224(s.encode("ascii")).hexdigest() + + +class Cache: + """An abstract class - provides cache directories for data from links + + + :param cache_dir: The root of the cache. + :param format_control: An object of FormatControl class to limit + binaries being read from the cache. + :param allowed_formats: which formats of files the cache should store. + ('binary' and 'source' are the only allowed values) + """ + + def __init__( + self, cache_dir: str, format_control: FormatControl, allowed_formats: Set[str] + ) -> None: + super().__init__() + assert not cache_dir or os.path.isabs(cache_dir) + self.cache_dir = cache_dir or None + self.format_control = format_control + self.allowed_formats = allowed_formats + + _valid_formats = {"source", "binary"} + assert self.allowed_formats.union(_valid_formats) == _valid_formats + + def _get_cache_path_parts(self, link: Link) -> List[str]: + """Get parts of part that must be os.path.joined with cache_dir""" + + # We want to generate an url to use as our cache key, we don't want to + # just re-use the URL because it might have other items in the fragment + # and we don't care about those. + key_parts = {"url": link.url_without_fragment} + if link.hash_name is not None and link.hash is not None: + key_parts[link.hash_name] = link.hash + if link.subdirectory_fragment: + key_parts["subdirectory"] = link.subdirectory_fragment + + # Include interpreter name, major and minor version in cache key + # to cope with ill-behaved sdists that build a different wheel + # depending on the python version their setup.py is being run on, + # and don't encode the difference in compatibility tags. + # https://github.com/pypa/pip/issues/7296 + key_parts["interpreter_name"] = interpreter_name() + key_parts["interpreter_version"] = interpreter_version() + + # Encode our key url with sha224, we'll use this because it has similar + # security properties to sha256, but with a shorter total output (and + # thus less secure). However the differences don't make a lot of + # difference for our use case here. + hashed = _hash_dict(key_parts) + + # We want to nest the directories some to prevent having a ton of top + # level directories where we might run out of sub directories on some + # FS. + parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] + + return parts + + def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]: + can_not_cache = not self.cache_dir or not canonical_package_name or not link + if can_not_cache: + return [] + + formats = self.format_control.get_allowed_formats(canonical_package_name) + if not self.allowed_formats.intersection(formats): + return [] + + candidates = [] + path = self.get_path_for_link(link) + if os.path.isdir(path): + for candidate in os.listdir(path): + candidates.append((candidate, path)) + return candidates + + def get_path_for_link(self, link: Link) -> str: + """Return a directory to store cached items in for link.""" + raise NotImplementedError() + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + """Returns a link to a cached item if it exists, otherwise returns the + passed link. + """ + raise NotImplementedError() + + +class SimpleWheelCache(Cache): + """A cache of wheels for future installs.""" + + def __init__(self, cache_dir: str, format_control: FormatControl) -> None: + super().__init__(cache_dir, format_control, {"binary"}) + + def get_path_for_link(self, link: Link) -> str: + """Return a directory to store cached wheels for link + + Because there are M wheels for any one sdist, we provide a directory + to cache them in, and then consult that directory when looking up + cache hits. + + We only insert things into the cache if they have plausible version + numbers, so that we don't contaminate the cache with things that were + not unique. E.g. ./package might have dozens of installs done for it + and build a version of 0.0...and if we built and cached a wheel, we'd + end up using the same wheel even if the source has been edited. + + :param link: The link of the sdist for which this will cache wheels. + """ + parts = self._get_cache_path_parts(link) + assert self.cache_dir + # Store wheels within the root cache_dir + return os.path.join(self.cache_dir, "wheels", *parts) + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + candidates = [] + + if not package_name: + return link + + canonical_package_name = canonicalize_name(package_name) + for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name): + try: + wheel = Wheel(wheel_name) + except InvalidWheelFilename: + continue + if canonicalize_name(wheel.name) != canonical_package_name: + logger.debug( + "Ignoring cached wheel %s for %s as it " + "does not match the expected distribution name %s.", + wheel_name, + link, + package_name, + ) + continue + if not wheel.supported(supported_tags): + # Built for a different python/arch/etc + continue + candidates.append( + ( + wheel.support_index_min(supported_tags), + wheel_name, + wheel_dir, + ) + ) + + if not candidates: + return link + + _, wheel_name, wheel_dir = min(candidates) + return Link(path_to_url(os.path.join(wheel_dir, wheel_name))) + + +class EphemWheelCache(SimpleWheelCache): + """A SimpleWheelCache that creates it's own temporary cache directory""" + + def __init__(self, format_control: FormatControl) -> None: + self._temp_dir = TempDirectory( + kind=tempdir_kinds.EPHEM_WHEEL_CACHE, + globally_managed=True, + ) + + super().__init__(self._temp_dir.path, format_control) + + +class CacheEntry: + def __init__( + self, + link: Link, + persistent: bool, + ): + self.link = link + self.persistent = persistent + self.origin: Optional[DirectUrl] = None + origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME + if origin_direct_url_path.exists(): + self.origin = DirectUrl.from_json(origin_direct_url_path.read_text()) + + +class WheelCache(Cache): + """Wraps EphemWheelCache and SimpleWheelCache into a single Cache + + This Cache allows for gracefully degradation, using the ephem wheel cache + when a certain link is not found in the simple wheel cache first. + """ + + def __init__( + self, cache_dir: str, format_control: Optional[FormatControl] = None + ) -> None: + if format_control is None: + format_control = FormatControl() + super().__init__(cache_dir, format_control, {"binary"}) + self._wheel_cache = SimpleWheelCache(cache_dir, format_control) + self._ephem_cache = EphemWheelCache(format_control) + + def get_path_for_link(self, link: Link) -> str: + return self._wheel_cache.get_path_for_link(link) + + def get_ephem_path_for_link(self, link: Link) -> str: + return self._ephem_cache.get_path_for_link(link) + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + cache_entry = self.get_cache_entry(link, package_name, supported_tags) + if cache_entry is None: + return link + return cache_entry.link + + def get_cache_entry( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Optional[CacheEntry]: + """Returns a CacheEntry with a link to a cached item if it exists or + None. The cache entry indicates if the item was found in the persistent + or ephemeral cache. + """ + retval = self._wheel_cache.get( + link=link, + package_name=package_name, + supported_tags=supported_tags, + ) + if retval is not link: + return CacheEntry(retval, persistent=True) + + retval = self._ephem_cache.get( + link=link, + package_name=package_name, + supported_tags=supported_tags, + ) + if retval is not link: + return CacheEntry(retval, persistent=False) + + return None + + @staticmethod + def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None: + origin_path = Path(cache_dir) / ORIGIN_JSON_NAME + if origin_path.is_file(): + origin = DirectUrl.from_json(origin_path.read_text()) + # TODO: use DirectUrl.equivalent when https://github.com/pypa/pip/pull/10564 + # is merged. + if origin.url != download_info.url: + logger.warning( + "Origin URL %s in cache entry %s does not match download URL %s. " + "This is likely a pip bug or a cache corruption issue.", + origin.url, + cache_dir, + download_info.url, + ) + origin_path.write_text(download_info.to_json(), encoding="utf-8") diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__init__.py b/web/lib/python3.11/site-packages/pip/_internal/cli/__init__.py new file mode 100644 index 00000000..e589bb91 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/__init__.py @@ -0,0 +1,4 @@ +"""Subpackage containing all of pip's command line interface related code +""" + +# This file intentionally does not import submodules diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..a0bfd738 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-311.pyc new file mode 100644 index 00000000..abf604f5 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-311.pyc new file mode 100644 index 00000000..04e7e621 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-311.pyc new file mode 100644 index 00000000..5bd71b18 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-311.pyc new file mode 100644 index 00000000..29eed3f5 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main.cpython-311.pyc new file mode 100644 index 00000000..795163a7 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-311.pyc new file mode 100644 index 00000000..afde0a2a Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/parser.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/parser.cpython-311.pyc new file mode 100644 index 00000000..9d121460 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/parser.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-311.pyc new file mode 100644 index 00000000..bad8d05a Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-311.pyc new file mode 100644 index 00000000..096021a4 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-311.pyc new file mode 100644 index 00000000..e714f6f2 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-311.pyc new file mode 100644 index 00000000..c4f2572c Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/autocompletion.py b/web/lib/python3.11/site-packages/pip/_internal/cli/autocompletion.py new file mode 100644 index 00000000..226fe84d --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/autocompletion.py @@ -0,0 +1,171 @@ +"""Logic that powers autocompletion installed by ``pip completion``. +""" + +import optparse +import os +import sys +from itertools import chain +from typing import Any, Iterable, List, Optional + +from pip._internal.cli.main_parser import create_main_parser +from pip._internal.commands import commands_dict, create_command +from pip._internal.metadata import get_default_environment + + +def autocomplete() -> None: + """Entry Point for completion of main and subcommand options.""" + # Don't complete if user hasn't sourced bash_completion file. + if "PIP_AUTO_COMPLETE" not in os.environ: + return + cwords = os.environ["COMP_WORDS"].split()[1:] + cword = int(os.environ["COMP_CWORD"]) + try: + current = cwords[cword - 1] + except IndexError: + current = "" + + parser = create_main_parser() + subcommands = list(commands_dict) + options = [] + + # subcommand + subcommand_name: Optional[str] = None + for word in cwords: + if word in subcommands: + subcommand_name = word + break + # subcommand options + if subcommand_name is not None: + # special case: 'help' subcommand has no options + if subcommand_name == "help": + sys.exit(1) + # special case: list locally installed dists for show and uninstall + should_list_installed = not current.startswith("-") and subcommand_name in [ + "show", + "uninstall", + ] + if should_list_installed: + env = get_default_environment() + lc = current.lower() + installed = [ + dist.canonical_name + for dist in env.iter_installed_distributions(local_only=True) + if dist.canonical_name.startswith(lc) + and dist.canonical_name not in cwords[1:] + ] + # if there are no dists installed, fall back to option completion + if installed: + for dist in installed: + print(dist) + sys.exit(1) + + should_list_installables = ( + not current.startswith("-") and subcommand_name == "install" + ) + if should_list_installables: + for path in auto_complete_paths(current, "path"): + print(path) + sys.exit(1) + + subcommand = create_command(subcommand_name) + + for opt in subcommand.parser.option_list_all: + if opt.help != optparse.SUPPRESS_HELP: + for opt_str in opt._long_opts + opt._short_opts: + options.append((opt_str, opt.nargs)) + + # filter out previously specified options from available options + prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]] + options = [(x, v) for (x, v) in options if x not in prev_opts] + # filter options by current input + options = [(k, v) for k, v in options if k.startswith(current)] + # get completion type given cwords and available subcommand options + completion_type = get_path_completion_type( + cwords, + cword, + subcommand.parser.option_list_all, + ) + # get completion files and directories if ``completion_type`` is + # `` ``, `` `` or `` `` + if completion_type: + paths = auto_complete_paths(current, completion_type) + options = [(path, 0) for path in paths] + for option in options: + opt_label = option[0] + # append '=' to options which require args + if option[1] and option[0][:2] == "--": + opt_label += "=" + print(opt_label) + else: + # show main parser options only when necessary + + opts = [i.option_list for i in parser.option_groups] + opts.append(parser.option_list) + flattened_opts = chain.from_iterable(opts) + if current.startswith("-"): + for opt in flattened_opts: + if opt.help != optparse.SUPPRESS_HELP: + subcommands += opt._long_opts + opt._short_opts + else: + # get completion type given cwords and all available options + completion_type = get_path_completion_type(cwords, cword, flattened_opts) + if completion_type: + subcommands = list(auto_complete_paths(current, completion_type)) + + print(" ".join([x for x in subcommands if x.startswith(current)])) + sys.exit(1) + + +def get_path_completion_type( + cwords: List[str], cword: int, opts: Iterable[Any] +) -> Optional[str]: + """Get the type of path completion (``file``, ``dir``, ``path`` or None) + + :param cwords: same as the environmental variable ``COMP_WORDS`` + :param cword: same as the environmental variable ``COMP_CWORD`` + :param opts: The available options to check + :return: path completion type (``file``, ``dir``, ``path`` or None) + """ + if cword < 2 or not cwords[cword - 2].startswith("-"): + return None + for opt in opts: + if opt.help == optparse.SUPPRESS_HELP: + continue + for o in str(opt).split("/"): + if cwords[cword - 2].split("=")[0] == o: + if not opt.metavar or any( + x in ("path", "file", "dir") for x in opt.metavar.split("/") + ): + return opt.metavar + return None + + +def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]: + """If ``completion_type`` is ``file`` or ``path``, list all regular files + and directories starting with ``current``; otherwise only list directories + starting with ``current``. + + :param current: The word to be completed + :param completion_type: path completion type(``file``, ``path`` or ``dir``) + :return: A generator of regular files and/or directories + """ + directory, filename = os.path.split(current) + current_path = os.path.abspath(directory) + # Don't complete paths if they can't be accessed + if not os.access(current_path, os.R_OK): + return + filename = os.path.normcase(filename) + # list all files that start with ``filename`` + file_list = ( + x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename) + ) + for f in file_list: + opt = os.path.join(current_path, f) + comp_file = os.path.normcase(os.path.join(directory, f)) + # complete regular files when there is not `` `` after option + # complete directories when there is `` ``, `` `` or + # `` ``after option + if completion_type != "dir" and os.path.isfile(opt): + yield comp_file + elif os.path.isdir(opt): + yield os.path.join(comp_file, "") diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/base_command.py b/web/lib/python3.11/site-packages/pip/_internal/cli/base_command.py new file mode 100644 index 00000000..5bd7e67e --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/base_command.py @@ -0,0 +1,216 @@ +"""Base Command class, and related routines""" + +import functools +import logging +import logging.config +import optparse +import os +import sys +import traceback +from optparse import Values +from typing import Any, Callable, List, Optional, Tuple + +from pip._vendor.rich import traceback as rich_traceback + +from pip._internal.cli import cmdoptions +from pip._internal.cli.command_context import CommandContextMixIn +from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter +from pip._internal.cli.status_codes import ( + ERROR, + PREVIOUS_BUILD_DIR_ERROR, + UNKNOWN_ERROR, + VIRTUALENV_NOT_FOUND, +) +from pip._internal.exceptions import ( + BadCommand, + CommandError, + DiagnosticPipError, + InstallationError, + NetworkConnectionError, + PreviousBuildDirError, + UninstallationError, +) +from pip._internal.utils.filesystem import check_path_owner +from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging +from pip._internal.utils.misc import get_prog, normalize_path +from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry +from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry +from pip._internal.utils.virtualenv import running_under_virtualenv + +__all__ = ["Command"] + +logger = logging.getLogger(__name__) + + +class Command(CommandContextMixIn): + usage: str = "" + ignore_require_venv: bool = False + + def __init__(self, name: str, summary: str, isolated: bool = False) -> None: + super().__init__() + + self.name = name + self.summary = summary + self.parser = ConfigOptionParser( + usage=self.usage, + prog=f"{get_prog()} {name}", + formatter=UpdatingDefaultsHelpFormatter(), + add_help_option=False, + name=name, + description=self.__doc__, + isolated=isolated, + ) + + self.tempdir_registry: Optional[TempDirRegistry] = None + + # Commands should add options to this option group + optgroup_name = f"{self.name.capitalize()} Options" + self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) + + # Add the general options + gen_opts = cmdoptions.make_option_group( + cmdoptions.general_group, + self.parser, + ) + self.parser.add_option_group(gen_opts) + + self.add_options() + + def add_options(self) -> None: + pass + + def handle_pip_version_check(self, options: Values) -> None: + """ + This is a no-op so that commands by default do not do the pip version + check. + """ + # Make sure we do the pip version check if the index_group options + # are present. + assert not hasattr(options, "no_index") + + def run(self, options: Values, args: List[str]) -> int: + raise NotImplementedError + + def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]: + # factored out for testability + return self.parser.parse_args(args) + + def main(self, args: List[str]) -> int: + try: + with self.main_context(): + return self._main(args) + finally: + logging.shutdown() + + def _main(self, args: List[str]) -> int: + # We must initialize this before the tempdir manager, otherwise the + # configuration would not be accessible by the time we clean up the + # tempdir manager. + self.tempdir_registry = self.enter_context(tempdir_registry()) + # Intentionally set as early as possible so globally-managed temporary + # directories are available to the rest of the code. + self.enter_context(global_tempdir_manager()) + + options, args = self.parse_args(args) + + # Set verbosity so that it can be used elsewhere. + self.verbosity = options.verbose - options.quiet + + level_number = setup_logging( + verbosity=self.verbosity, + no_color=options.no_color, + user_log_file=options.log, + ) + + # TODO: Try to get these passing down from the command? + # without resorting to os.environ to hold these. + # This also affects isolated builds and it should. + + if options.no_input: + os.environ["PIP_NO_INPUT"] = "1" + + if options.exists_action: + os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action) + + if options.require_venv and not self.ignore_require_venv: + # If a venv is required check if it can really be found + if not running_under_virtualenv(): + logger.critical("Could not find an activated virtualenv (required).") + sys.exit(VIRTUALENV_NOT_FOUND) + + if options.cache_dir: + options.cache_dir = normalize_path(options.cache_dir) + if not check_path_owner(options.cache_dir): + logger.warning( + "The directory '%s' or its parent directory is not owned " + "or is not writable by the current user. The cache " + "has been disabled. Check the permissions and owner of " + "that directory. If executing pip with sudo, you should " + "use sudo's -H flag.", + options.cache_dir, + ) + options.cache_dir = None + + def intercepts_unhandled_exc( + run_func: Callable[..., int] + ) -> Callable[..., int]: + @functools.wraps(run_func) + def exc_logging_wrapper(*args: Any) -> int: + try: + status = run_func(*args) + assert isinstance(status, int) + return status + except DiagnosticPipError as exc: + logger.error("[present-rich] %s", exc) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except PreviousBuildDirError as exc: + logger.critical(str(exc)) + logger.debug("Exception information:", exc_info=True) + + return PREVIOUS_BUILD_DIR_ERROR + except ( + InstallationError, + UninstallationError, + BadCommand, + NetworkConnectionError, + ) as exc: + logger.critical(str(exc)) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except CommandError as exc: + logger.critical("%s", exc) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except BrokenStdoutLoggingError: + # Bypass our logger and write any remaining messages to + # stderr because stdout no longer works. + print("ERROR: Pipe to stdout was broken", file=sys.stderr) + if level_number <= logging.DEBUG: + traceback.print_exc(file=sys.stderr) + + return ERROR + except KeyboardInterrupt: + logger.critical("Operation cancelled by user") + logger.debug("Exception information:", exc_info=True) + + return ERROR + except BaseException: + logger.critical("Exception:", exc_info=True) + + return UNKNOWN_ERROR + + return exc_logging_wrapper + + try: + if not options.debug_mode: + run = intercepts_unhandled_exc(self.run) + else: + run = self.run + rich_traceback.install(show_locals=True) + return run(options, args) + finally: + self.handle_pip_version_check(options) diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/cmdoptions.py b/web/lib/python3.11/site-packages/pip/_internal/cli/cmdoptions.py new file mode 100644 index 00000000..b4e2560d --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/cmdoptions.py @@ -0,0 +1,1049 @@ +""" +shared options and groups + +The principle here is to define options once, but *not* instantiate them +globally. One reason being that options with action='append' can carry state +between parses. pip parses general options twice internally, and shouldn't +pass on state. To be consistent, all options will follow this design. +""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import importlib.util +import logging +import os +import textwrap +from functools import partial +from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values +from textwrap import dedent +from typing import Any, Callable, Dict, Optional, Tuple + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli.parser import ConfigOptionParser +from pip._internal.exceptions import CommandError +from pip._internal.locations import USER_CACHE_DIR, get_src_prefix +from pip._internal.models.format_control import FormatControl +from pip._internal.models.index import PyPI +from pip._internal.models.target_python import TargetPython +from pip._internal.utils.hashes import STRONG_HASHES +from pip._internal.utils.misc import strtobool + +logger = logging.getLogger(__name__) + + +def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: + """ + Raise an option parsing error using parser.error(). + + Args: + parser: an OptionParser instance. + option: an Option instance. + msg: the error text. + """ + msg = f"{option} error: {msg}" + msg = textwrap.fill(" ".join(msg.split())) + parser.error(msg) + + +def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: + """ + Return an OptionGroup object + group -- assumed to be dict with 'name' and 'options' keys + parser -- an optparse Parser + """ + option_group = OptionGroup(parser, group["name"]) + for option in group["options"]: + option_group.add_option(option()) + return option_group + + +def check_dist_restriction(options: Values, check_target: bool = False) -> None: + """Function for determining if custom platform options are allowed. + + :param options: The OptionParser options. + :param check_target: Whether or not to check if --target is being used. + """ + dist_restriction_set = any( + [ + options.python_version, + options.platforms, + options.abis, + options.implementation, + ] + ) + + binary_only = FormatControl(set(), {":all:"}) + sdist_dependencies_allowed = ( + options.format_control != binary_only and not options.ignore_dependencies + ) + + # Installations or downloads using dist restrictions must not combine + # source distributions and dist-specific wheels, as they are not + # guaranteed to be locally compatible. + if dist_restriction_set and sdist_dependencies_allowed: + raise CommandError( + "When restricting platform and interpreter constraints using " + "--python-version, --platform, --abi, or --implementation, " + "either --no-deps must be set, or --only-binary=:all: must be " + "set and --no-binary must not be set (or must be set to " + ":none:)." + ) + + if check_target: + if dist_restriction_set and not options.target_dir: + raise CommandError( + "Can not use any platform or abi specific options unless " + "installing via '--target'" + ) + + +def _path_option_check(option: Option, opt: str, value: str) -> str: + return os.path.expanduser(value) + + +def _package_name_option_check(option: Option, opt: str, value: str) -> str: + return canonicalize_name(value) + + +class PipOption(Option): + TYPES = Option.TYPES + ("path", "package_name") + TYPE_CHECKER = Option.TYPE_CHECKER.copy() + TYPE_CHECKER["package_name"] = _package_name_option_check + TYPE_CHECKER["path"] = _path_option_check + + +########### +# options # +########### + +help_: Callable[..., Option] = partial( + Option, + "-h", + "--help", + dest="help", + action="help", + help="Show help.", +) + +debug_mode: Callable[..., Option] = partial( + Option, + "--debug", + dest="debug_mode", + action="store_true", + default=False, + help=( + "Let unhandled exceptions propagate outside the main subroutine, " + "instead of logging them to stderr." + ), +) + +isolated_mode: Callable[..., Option] = partial( + Option, + "--isolated", + dest="isolated_mode", + action="store_true", + default=False, + help=( + "Run pip in an isolated mode, ignoring environment variables and user " + "configuration." + ), +) + +require_virtualenv: Callable[..., Option] = partial( + Option, + "--require-virtualenv", + "--require-venv", + dest="require_venv", + action="store_true", + default=False, + help=( + "Allow pip to only run in a virtual environment; " + "exit with an error otherwise." + ), +) + +python: Callable[..., Option] = partial( + Option, + "--python", + dest="python", + help="Run pip with the specified Python interpreter.", +) + +verbose: Callable[..., Option] = partial( + Option, + "-v", + "--verbose", + dest="verbose", + action="count", + default=0, + help="Give more output. Option is additive, and can be used up to 3 times.", +) + +no_color: Callable[..., Option] = partial( + Option, + "--no-color", + dest="no_color", + action="store_true", + default=False, + help="Suppress colored output.", +) + +version: Callable[..., Option] = partial( + Option, + "-V", + "--version", + dest="version", + action="store_true", + help="Show version and exit.", +) + +quiet: Callable[..., Option] = partial( + Option, + "-q", + "--quiet", + dest="quiet", + action="count", + default=0, + help=( + "Give less output. Option is additive, and can be used up to 3" + " times (corresponding to WARNING, ERROR, and CRITICAL logging" + " levels)." + ), +) + +progress_bar: Callable[..., Option] = partial( + Option, + "--progress-bar", + dest="progress_bar", + type="choice", + choices=["on", "off"], + default="on", + help="Specify whether the progress bar should be used [on, off] (default: on)", +) + +log: Callable[..., Option] = partial( + PipOption, + "--log", + "--log-file", + "--local-log", + dest="log", + metavar="path", + type="path", + help="Path to a verbose appending log.", +) + +no_input: Callable[..., Option] = partial( + Option, + # Don't ask for input + "--no-input", + dest="no_input", + action="store_true", + default=False, + help="Disable prompting for input.", +) + +proxy: Callable[..., Option] = partial( + Option, + "--proxy", + dest="proxy", + type="str", + default="", + help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.", +) + +retries: Callable[..., Option] = partial( + Option, + "--retries", + dest="retries", + type="int", + default=5, + help="Maximum number of retries each connection should attempt " + "(default %default times).", +) + +timeout: Callable[..., Option] = partial( + Option, + "--timeout", + "--default-timeout", + metavar="sec", + dest="timeout", + type="float", + default=15, + help="Set the socket timeout (default %default seconds).", +) + + +def exists_action() -> Option: + return Option( + # Option when path already exist + "--exists-action", + dest="exists_action", + type="choice", + choices=["s", "i", "w", "b", "a"], + default=[], + action="append", + metavar="action", + help="Default action when a path already exists: " + "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", + ) + + +cert: Callable[..., Option] = partial( + PipOption, + "--cert", + dest="cert", + type="path", + metavar="path", + help=( + "Path to PEM-encoded CA certificate bundle. " + "If provided, overrides the default. " + "See 'SSL Certificate Verification' in pip documentation " + "for more information." + ), +) + +client_cert: Callable[..., Option] = partial( + PipOption, + "--client-cert", + dest="client_cert", + type="path", + default=None, + metavar="path", + help="Path to SSL client certificate, a single file containing the " + "private key and the certificate in PEM format.", +) + +index_url: Callable[..., Option] = partial( + Option, + "-i", + "--index-url", + "--pypi-url", + dest="index_url", + metavar="URL", + default=PyPI.simple_url, + help="Base URL of the Python Package Index (default %default). " + "This should point to a repository compliant with PEP 503 " + "(the simple repository API) or a local directory laid out " + "in the same format.", +) + + +def extra_index_url() -> Option: + return Option( + "--extra-index-url", + dest="extra_index_urls", + metavar="URL", + action="append", + default=[], + help="Extra URLs of package indexes to use in addition to " + "--index-url. Should follow the same rules as " + "--index-url.", + ) + + +no_index: Callable[..., Option] = partial( + Option, + "--no-index", + dest="no_index", + action="store_true", + default=False, + help="Ignore package index (only looking at --find-links URLs instead).", +) + + +def find_links() -> Option: + return Option( + "-f", + "--find-links", + dest="find_links", + action="append", + default=[], + metavar="url", + help="If a URL or path to an html file, then parse for links to " + "archives such as sdist (.tar.gz) or wheel (.whl) files. " + "If a local path or file:// URL that's a directory, " + "then look for archives in the directory listing. " + "Links to VCS project URLs are not supported.", + ) + + +def trusted_host() -> Option: + return Option( + "--trusted-host", + dest="trusted_hosts", + action="append", + metavar="HOSTNAME", + default=[], + help="Mark this host or host:port pair as trusted, even though it " + "does not have valid or any HTTPS.", + ) + + +def constraints() -> Option: + return Option( + "-c", + "--constraint", + dest="constraints", + action="append", + default=[], + metavar="file", + help="Constrain versions using the given constraints file. " + "This option can be used multiple times.", + ) + + +def requirements() -> Option: + return Option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help="Install from the given requirements file. " + "This option can be used multiple times.", + ) + + +def editable() -> Option: + return Option( + "-e", + "--editable", + dest="editables", + action="append", + default=[], + metavar="path/url", + help=( + "Install a project in editable mode (i.e. setuptools " + '"develop mode") from a local project path or a VCS url.' + ), + ) + + +def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: + value = os.path.abspath(value) + setattr(parser.values, option.dest, value) + + +src: Callable[..., Option] = partial( + PipOption, + "--src", + "--source", + "--source-dir", + "--source-directory", + dest="src_dir", + type="path", + metavar="dir", + default=get_src_prefix(), + action="callback", + callback=_handle_src, + help="Directory to check out editable projects into. " + 'The default in a virtualenv is " /src". ' + 'The default for global installs is " /src".', +) + + +def _get_format_control(values: Values, option: Option) -> Any: + """Get a format_control object.""" + return getattr(values, option.dest) + + +def _handle_no_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.no_binary, + existing.only_binary, + ) + + +def _handle_only_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.only_binary, + existing.no_binary, + ) + + +def no_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--no-binary", + dest="format_control", + action="callback", + callback=_handle_no_binary, + type="str", + default=format_control, + help="Do not use binary packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all binary packages, ":none:" to empty the set (notice ' + "the colons), or one or more package names with commas between " + "them (no colons). Note that some packages are tricky to compile " + "and may fail to install when this option is used on them.", + ) + + +def only_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--only-binary", + dest="format_control", + action="callback", + callback=_handle_only_binary, + type="str", + default=format_control, + help="Do not use source packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all source packages, ":none:" to empty the set, or one ' + "or more package names with commas between them. Packages " + "without binary distributions will fail to install when this " + "option is used on them.", + ) + + +platforms: Callable[..., Option] = partial( + Option, + "--platform", + dest="platforms", + metavar="platform", + action="append", + default=None, + help=( + "Only use wheels compatible with . Defaults to the " + "platform of the running system. Use this option multiple times to " + "specify multiple platforms supported by the target interpreter." + ), +) + + +# This was made a separate function for unit-testing purposes. +def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]: + """ + Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. + + :return: A 2-tuple (version_info, error_msg), where `error_msg` is + non-None if and only if there was a parsing error. + """ + if not value: + # The empty string is the same as not providing a value. + return (None, None) + + parts = value.split(".") + if len(parts) > 3: + return ((), "at most three version parts are allowed") + + if len(parts) == 1: + # Then we are in the case of "3" or "37". + value = parts[0] + if len(value) > 1: + parts = [value[0], value[1:]] + + try: + version_info = tuple(int(part) for part in parts) + except ValueError: + return ((), "each version part must be an integer") + + return (version_info, None) + + +def _handle_python_version( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """ + Handle a provided --python-version value. + """ + version_info, error_msg = _convert_python_version(value) + if error_msg is not None: + msg = "invalid --python-version value: {!r}: {}".format( + value, + error_msg, + ) + raise_option_error(parser, option=option, msg=msg) + + parser.values.python_version = version_info + + +python_version: Callable[..., Option] = partial( + Option, + "--python-version", + dest="python_version", + metavar="python_version", + action="callback", + callback=_handle_python_version, + type="str", + default=None, + help=dedent( + """\ + The Python interpreter version to use for wheel and "Requires-Python" + compatibility checks. Defaults to a version derived from the running + interpreter. The version can be specified using up to three dot-separated + integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor + version can also be given as a string without dots (e.g. "37" for 3.7.0). + """ + ), +) + + +implementation: Callable[..., Option] = partial( + Option, + "--implementation", + dest="implementation", + metavar="implementation", + default=None, + help=( + "Only use wheels compatible with Python " + "implementation , e.g. 'pp', 'jy', 'cp', " + " or 'ip'. If not specified, then the current " + "interpreter implementation is used. Use 'py' to force " + "implementation-agnostic wheels." + ), +) + + +abis: Callable[..., Option] = partial( + Option, + "--abi", + dest="abis", + metavar="abi", + action="append", + default=None, + help=( + "Only use wheels compatible with Python abi , e.g. 'pypy_41'. " + "If not specified, then the current interpreter abi tag is used. " + "Use this option multiple times to specify multiple abis supported " + "by the target interpreter. Generally you will need to specify " + "--implementation, --platform, and --python-version when using this " + "option." + ), +) + + +def add_target_python_options(cmd_opts: OptionGroup) -> None: + cmd_opts.add_option(platforms()) + cmd_opts.add_option(python_version()) + cmd_opts.add_option(implementation()) + cmd_opts.add_option(abis()) + + +def make_target_python(options: Values) -> TargetPython: + target_python = TargetPython( + platforms=options.platforms, + py_version_info=options.python_version, + abis=options.abis, + implementation=options.implementation, + ) + + return target_python + + +def prefer_binary() -> Option: + return Option( + "--prefer-binary", + dest="prefer_binary", + action="store_true", + default=False, + help="Prefer older binary packages over newer source packages.", + ) + + +cache_dir: Callable[..., Option] = partial( + PipOption, + "--cache-dir", + dest="cache_dir", + default=USER_CACHE_DIR, + metavar="dir", + type="path", + help="Store the cache data in .", +) + + +def _handle_no_cache_dir( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-cache-dir option. + + This is an optparse.Option callback for the --no-cache-dir option. + """ + # The value argument will be None if --no-cache-dir is passed via the + # command-line, since the option doesn't accept arguments. However, + # the value can be non-None if the option is triggered e.g. by an + # environment variable, like PIP_NO_CACHE_DIR=true. + if value is not None: + # Then parse the string value to get argument error-checking. + try: + strtobool(value) + except ValueError as exc: + raise_option_error(parser, option=option, msg=str(exc)) + + # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() + # converted to 0 (like "false" or "no") caused cache_dir to be disabled + # rather than enabled (logic would say the latter). Thus, we disable + # the cache directory not just on values that parse to True, but (for + # backwards compatibility reasons) also on values that parse to False. + # In other words, always set it to False if the option is provided in + # some (valid) form. + parser.values.cache_dir = False + + +no_cache: Callable[..., Option] = partial( + Option, + "--no-cache-dir", + dest="cache_dir", + action="callback", + callback=_handle_no_cache_dir, + help="Disable the cache.", +) + +no_deps: Callable[..., Option] = partial( + Option, + "--no-deps", + "--no-dependencies", + dest="ignore_dependencies", + action="store_true", + default=False, + help="Don't install package dependencies.", +) + +ignore_requires_python: Callable[..., Option] = partial( + Option, + "--ignore-requires-python", + dest="ignore_requires_python", + action="store_true", + help="Ignore the Requires-Python information.", +) + +no_build_isolation: Callable[..., Option] = partial( + Option, + "--no-build-isolation", + dest="build_isolation", + action="store_false", + default=True, + help="Disable isolation when building a modern source distribution. " + "Build dependencies specified by PEP 518 must be already installed " + "if this option is used.", +) + +check_build_deps: Callable[..., Option] = partial( + Option, + "--check-build-dependencies", + dest="check_build_deps", + action="store_true", + default=False, + help="Check the build dependencies when PEP517 is used.", +) + + +def _handle_no_use_pep517( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-use-pep517 option. + + This is an optparse.Option callback for the no_use_pep517 option. + """ + # Since --no-use-pep517 doesn't accept arguments, the value argument + # will be None if --no-use-pep517 is passed via the command-line. + # However, the value can be non-None if the option is triggered e.g. + # by an environment variable, for example "PIP_NO_USE_PEP517=true". + if value is not None: + msg = """A value was passed for --no-use-pep517, + probably using either the PIP_NO_USE_PEP517 environment variable + or the "no-use-pep517" config file option. Use an appropriate value + of the PIP_USE_PEP517 environment variable or the "use-pep517" + config file option instead. + """ + raise_option_error(parser, option=option, msg=msg) + + # If user doesn't wish to use pep517, we check if setuptools is installed + # and raise error if it is not. + if not importlib.util.find_spec("setuptools"): + msg = "It is not possible to use --no-use-pep517 without setuptools installed." + raise_option_error(parser, option=option, msg=msg) + + # Otherwise, --no-use-pep517 was passed via the command-line. + parser.values.use_pep517 = False + + +use_pep517: Any = partial( + Option, + "--use-pep517", + dest="use_pep517", + action="store_true", + default=None, + help="Use PEP 517 for building source distributions " + "(use --no-use-pep517 to force legacy behaviour).", +) + +no_use_pep517: Any = partial( + Option, + "--no-use-pep517", + dest="use_pep517", + action="callback", + callback=_handle_no_use_pep517, + default=None, + help=SUPPRESS_HELP, +) + + +def _handle_config_settings( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + key, sep, val = value.partition("=") + if sep != "=": + parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") # noqa + dest = getattr(parser.values, option.dest) + if dest is None: + dest = {} + setattr(parser.values, option.dest, dest) + dest[key] = val + + +config_settings: Callable[..., Option] = partial( + Option, + "--config-settings", + dest="config_settings", + type=str, + action="callback", + callback=_handle_config_settings, + metavar="settings", + help="Configuration settings to be passed to the PEP 517 build backend. " + "Settings take the form KEY=VALUE. Use multiple --config-settings options " + "to pass multiple keys to the backend.", +) + +install_options: Callable[..., Option] = partial( + Option, + "--install-option", + dest="install_options", + action="append", + metavar="options", + help="Extra arguments to be supplied to the setup.py install " + 'command (use like --install-option="--install-scripts=/usr/local/' + 'bin"). Use multiple --install-option options to pass multiple ' + "options to setup.py install. If you are using an option with a " + "directory path, be sure to use absolute path.", +) + +build_options: Callable[..., Option] = partial( + Option, + "--build-option", + dest="build_options", + metavar="options", + action="append", + help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", +) + +global_options: Callable[..., Option] = partial( + Option, + "--global-option", + dest="global_options", + action="append", + metavar="options", + help="Extra global options to be supplied to the setup.py " + "call before the install or bdist_wheel command.", +) + +no_clean: Callable[..., Option] = partial( + Option, + "--no-clean", + action="store_true", + default=False, + help="Don't clean up build directories.", +) + +pre: Callable[..., Option] = partial( + Option, + "--pre", + action="store_true", + default=False, + help="Include pre-release and development versions. By default, " + "pip only finds stable versions.", +) + +disable_pip_version_check: Callable[..., Option] = partial( + Option, + "--disable-pip-version-check", + dest="disable_pip_version_check", + action="store_true", + default=False, + help="Don't periodically check PyPI to determine whether a new version " + "of pip is available for download. Implied with --no-index.", +) + +root_user_action: Callable[..., Option] = partial( + Option, + "--root-user-action", + dest="root_user_action", + default="warn", + choices=["warn", "ignore"], + help="Action if pip is run as a root user. By default, a warning message is shown.", +) + + +def _handle_merge_hash( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """Given a value spelled "algo:digest", append the digest to a list + pointed to in a dict by the algo name.""" + if not parser.values.hashes: + parser.values.hashes = {} + try: + algo, digest = value.split(":", 1) + except ValueError: + parser.error( + "Arguments to {} must be a hash name " # noqa + "followed by a value, like --hash=sha256:" + "abcde...".format(opt_str) + ) + if algo not in STRONG_HASHES: + parser.error( + "Allowed hash algorithms for {} are {}.".format( # noqa + opt_str, ", ".join(STRONG_HASHES) + ) + ) + parser.values.hashes.setdefault(algo, []).append(digest) + + +hash: Callable[..., Option] = partial( + Option, + "--hash", + # Hash values eventually end up in InstallRequirement.hashes due to + # __dict__ copying in process_line(). + dest="hashes", + action="callback", + callback=_handle_merge_hash, + type="string", + help="Verify that the package's archive matches this " + "hash before installing. Example: --hash=sha256:abcdef...", +) + + +require_hashes: Callable[..., Option] = partial( + Option, + "--require-hashes", + dest="require_hashes", + action="store_true", + default=False, + help="Require a hash to check each requirement against, for " + "repeatable installs. This option is implied when any package in a " + "requirements file has a --hash option.", +) + + +list_path: Callable[..., Option] = partial( + PipOption, + "--path", + dest="path", + type="path", + action="append", + help="Restrict to the specified installation path for listing " + "packages (can be used multiple times).", +) + + +def check_list_path_option(options: Values) -> None: + if options.path and (options.user or options.local): + raise CommandError("Cannot combine '--path' with '--user' or '--local'") + + +list_exclude: Callable[..., Option] = partial( + PipOption, + "--exclude", + dest="excludes", + action="append", + metavar="package", + type="package_name", + help="Exclude specified package from the output", +) + + +no_python_version_warning: Callable[..., Option] = partial( + Option, + "--no-python-version-warning", + dest="no_python_version_warning", + action="store_true", + default=False, + help="Silence deprecation warnings for upcoming unsupported Pythons.", +) + + +use_new_feature: Callable[..., Option] = partial( + Option, + "--use-feature", + dest="features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "fast-deps", + "truststore", + "no-binary-enable-wheel-cache", + ], + help="Enable new functionality, that may be backward incompatible.", +) + +use_deprecated_feature: Callable[..., Option] = partial( + Option, + "--use-deprecated", + dest="deprecated_features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "legacy-resolver", + ], + help=("Enable deprecated functionality, that will be removed in the future."), +) + + +########## +# groups # +########## + +general_group: Dict[str, Any] = { + "name": "General Options", + "options": [ + help_, + debug_mode, + isolated_mode, + require_virtualenv, + python, + verbose, + version, + quiet, + log, + no_input, + proxy, + retries, + timeout, + exists_action, + trusted_host, + cert, + client_cert, + cache_dir, + no_cache, + disable_pip_version_check, + no_color, + no_python_version_warning, + use_new_feature, + use_deprecated_feature, + ], +} + +index_group: Dict[str, Any] = { + "name": "Package Index Options", + "options": [ + index_url, + extra_index_url, + no_index, + find_links, + ], +} diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/command_context.py b/web/lib/python3.11/site-packages/pip/_internal/cli/command_context.py new file mode 100644 index 00000000..139995ac --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/command_context.py @@ -0,0 +1,27 @@ +from contextlib import ExitStack, contextmanager +from typing import ContextManager, Generator, TypeVar + +_T = TypeVar("_T", covariant=True) + + +class CommandContextMixIn: + def __init__(self) -> None: + super().__init__() + self._in_main_context = False + self._main_context = ExitStack() + + @contextmanager + def main_context(self) -> Generator[None, None, None]: + assert not self._in_main_context + + self._in_main_context = True + try: + with self._main_context: + yield + finally: + self._in_main_context = False + + def enter_context(self, context_provider: ContextManager[_T]) -> _T: + assert self._in_main_context + + return self._main_context.enter_context(context_provider) diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/main.py b/web/lib/python3.11/site-packages/pip/_internal/cli/main.py new file mode 100644 index 00000000..0e312215 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/main.py @@ -0,0 +1,70 @@ +"""Primary application entrypoint. +""" +import locale +import logging +import os +import sys +from typing import List, Optional + +from pip._internal.cli.autocompletion import autocomplete +from pip._internal.cli.main_parser import parse_command +from pip._internal.commands import create_command +from pip._internal.exceptions import PipError +from pip._internal.utils import deprecation + +logger = logging.getLogger(__name__) + + +# Do not import and use main() directly! Using it directly is actively +# discouraged by pip's maintainers. The name, location and behavior of +# this function is subject to change, so calling it directly is not +# portable across different pip versions. + +# In addition, running pip in-process is unsupported and unsafe. This is +# elaborated in detail at +# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program. +# That document also provides suggestions that should work for nearly +# all users that are considering importing and using main() directly. + +# However, we know that certain users will still want to invoke pip +# in-process. If you understand and accept the implications of using pip +# in an unsupported manner, the best approach is to use runpy to avoid +# depending on the exact location of this entry point. + +# The following example shows how to use runpy to invoke pip in that +# case: +# +# sys.argv = ["pip", your, args, here] +# runpy.run_module("pip", run_name="__main__") +# +# Note that this will exit the process after running, unlike a direct +# call to main. As it is not safe to do any processing after calling +# main, this should not be an issue in practice. + + +def main(args: Optional[List[str]] = None) -> int: + if args is None: + args = sys.argv[1:] + + # Configure our deprecation warnings to be sent through loggers + deprecation.install_warning_logger() + + autocomplete() + + try: + cmd_name, cmd_args = parse_command(args) + except PipError as exc: + sys.stderr.write(f"ERROR: {exc}") + sys.stderr.write(os.linesep) + sys.exit(1) + + # Needed for locale.getpreferredencoding(False) to work + # in pip._internal.utils.encoding.auto_decode + try: + locale.setlocale(locale.LC_ALL, "") + except locale.Error as e: + # setlocale can apparently crash if locale are uninitialized + logger.debug("Ignoring error %s when setting locale", e) + command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) + + return command.main(cmd_args) diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/main_parser.py b/web/lib/python3.11/site-packages/pip/_internal/cli/main_parser.py new file mode 100644 index 00000000..5ade356b --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/main_parser.py @@ -0,0 +1,134 @@ +"""A single place for constructing and exposing the main parser +""" + +import os +import subprocess +import sys +from typing import List, Optional, Tuple + +from pip._internal.build_env import get_runnable_pip +from pip._internal.cli import cmdoptions +from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter +from pip._internal.commands import commands_dict, get_similar_commands +from pip._internal.exceptions import CommandError +from pip._internal.utils.misc import get_pip_version, get_prog + +__all__ = ["create_main_parser", "parse_command"] + + +def create_main_parser() -> ConfigOptionParser: + """Creates and returns the main parser for pip's CLI""" + + parser = ConfigOptionParser( + usage="\n%prog [options]", + add_help_option=False, + formatter=UpdatingDefaultsHelpFormatter(), + name="global", + prog=get_prog(), + ) + parser.disable_interspersed_args() + + parser.version = get_pip_version() + + # add the general options + gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) + parser.add_option_group(gen_opts) + + # so the help formatter knows + parser.main = True # type: ignore + + # create command listing for description + description = [""] + [ + f"{name:27} {command_info.summary}" + for name, command_info in commands_dict.items() + ] + parser.description = "\n".join(description) + + return parser + + +def identify_python_interpreter(python: str) -> Optional[str]: + # If the named file exists, use it. + # If it's a directory, assume it's a virtual environment and + # look for the environment's Python executable. + if os.path.exists(python): + if os.path.isdir(python): + # bin/python for Unix, Scripts/python.exe for Windows + # Try both in case of odd cases like cygwin. + for exe in ("bin/python", "Scripts/python.exe"): + py = os.path.join(python, exe) + if os.path.exists(py): + return py + else: + return python + + # Could not find the interpreter specified + return None + + +def parse_command(args: List[str]) -> Tuple[str, List[str]]: + parser = create_main_parser() + + # Note: parser calls disable_interspersed_args(), so the result of this + # call is to split the initial args into the general options before the + # subcommand and everything else. + # For example: + # args: ['--timeout=5', 'install', '--user', 'INITools'] + # general_options: ['--timeout==5'] + # args_else: ['install', '--user', 'INITools'] + general_options, args_else = parser.parse_args(args) + + # --python + if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: + # Re-invoke pip using the specified Python interpreter + interpreter = identify_python_interpreter(general_options.python) + if interpreter is None: + raise CommandError( + f"Could not locate Python interpreter {general_options.python}" + ) + + pip_cmd = [ + interpreter, + get_runnable_pip(), + ] + pip_cmd.extend(args) + + # Set a flag so the child doesn't re-invoke itself, causing + # an infinite loop. + os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1" + returncode = 0 + try: + proc = subprocess.run(pip_cmd) + returncode = proc.returncode + except (subprocess.SubprocessError, OSError) as exc: + raise CommandError(f"Failed to run pip under {interpreter}: {exc}") + sys.exit(returncode) + + # --version + if general_options.version: + sys.stdout.write(parser.version) + sys.stdout.write(os.linesep) + sys.exit() + + # pip || pip help -> print_help() + if not args_else or (args_else[0] == "help" and len(args_else) == 1): + parser.print_help() + sys.exit() + + # the subcommand name + cmd_name = args_else[0] + + if cmd_name not in commands_dict: + guess = get_similar_commands(cmd_name) + + msg = [f'unknown command "{cmd_name}"'] + if guess: + msg.append(f'maybe you meant "{guess}"') + + raise CommandError(" - ".join(msg)) + + # all the args without the subcommand + cmd_args = args[:] + cmd_args.remove(cmd_name) + + return cmd_name, cmd_args diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/parser.py b/web/lib/python3.11/site-packages/pip/_internal/cli/parser.py new file mode 100644 index 00000000..c762cf27 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/parser.py @@ -0,0 +1,294 @@ +"""Base option parser setup""" + +import logging +import optparse +import shutil +import sys +import textwrap +from contextlib import suppress +from typing import Any, Dict, Generator, List, Tuple + +from pip._internal.cli.status_codes import UNKNOWN_ERROR +from pip._internal.configuration import Configuration, ConfigurationError +from pip._internal.utils.misc import redact_auth_from_url, strtobool + +logger = logging.getLogger(__name__) + + +class PrettyHelpFormatter(optparse.IndentedHelpFormatter): + """A prettier/less verbose help formatter for optparse.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + # help position must be aligned with __init__.parseopts.description + kwargs["max_help_position"] = 30 + kwargs["indent_increment"] = 1 + kwargs["width"] = shutil.get_terminal_size()[0] - 2 + super().__init__(*args, **kwargs) + + def format_option_strings(self, option: optparse.Option) -> str: + return self._format_option_strings(option) + + def _format_option_strings( + self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", " + ) -> str: + """ + Return a comma-separated list of option strings and metavars. + + :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') + :param mvarfmt: metavar format string + :param optsep: separator + """ + opts = [] + + if option._short_opts: + opts.append(option._short_opts[0]) + if option._long_opts: + opts.append(option._long_opts[0]) + if len(opts) > 1: + opts.insert(1, optsep) + + if option.takes_value(): + assert option.dest is not None + metavar = option.metavar or option.dest.lower() + opts.append(mvarfmt.format(metavar.lower())) + + return "".join(opts) + + def format_heading(self, heading: str) -> str: + if heading == "Options": + return "" + return heading + ":\n" + + def format_usage(self, usage: str) -> str: + """ + Ensure there is only one newline between usage and the first heading + if there is no description. + """ + msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) + return msg + + def format_description(self, description: str) -> str: + # leave full control over description to us + if description: + if hasattr(self.parser, "main"): + label = "Commands" + else: + label = "Description" + # some doc strings have initial newlines, some don't + description = description.lstrip("\n") + # some doc strings have final newlines and spaces, some don't + description = description.rstrip() + # dedent, then reindent + description = self.indent_lines(textwrap.dedent(description), " ") + description = f"{label}:\n{description}\n" + return description + else: + return "" + + def format_epilog(self, epilog: str) -> str: + # leave full control over epilog to us + if epilog: + return epilog + else: + return "" + + def indent_lines(self, text: str, indent: str) -> str: + new_lines = [indent + line for line in text.split("\n")] + return "\n".join(new_lines) + + +class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): + """Custom help formatter for use in ConfigOptionParser. + + This is updates the defaults before expanding them, allowing + them to show up correctly in the help listing. + + Also redact auth from url type options + """ + + def expand_default(self, option: optparse.Option) -> str: + default_values = None + if self.parser is not None: + assert isinstance(self.parser, ConfigOptionParser) + self.parser._update_defaults(self.parser.defaults) + assert option.dest is not None + default_values = self.parser.defaults.get(option.dest) + help_text = super().expand_default(option) + + if default_values and option.metavar == "URL": + if isinstance(default_values, str): + default_values = [default_values] + + # If its not a list, we should abort and just return the help text + if not isinstance(default_values, list): + default_values = [] + + for val in default_values: + help_text = help_text.replace(val, redact_auth_from_url(val)) + + return help_text + + +class CustomOptionParser(optparse.OptionParser): + def insert_option_group( + self, idx: int, *args: Any, **kwargs: Any + ) -> optparse.OptionGroup: + """Insert an OptionGroup at a given position.""" + group = self.add_option_group(*args, **kwargs) + + self.option_groups.pop() + self.option_groups.insert(idx, group) + + return group + + @property + def option_list_all(self) -> List[optparse.Option]: + """Get a list of all options, including those in option groups.""" + res = self.option_list[:] + for i in self.option_groups: + res.extend(i.option_list) + + return res + + +class ConfigOptionParser(CustomOptionParser): + """Custom option parser which updates its defaults by checking the + configuration files and environmental variables""" + + def __init__( + self, + *args: Any, + name: str, + isolated: bool = False, + **kwargs: Any, + ) -> None: + self.name = name + self.config = Configuration(isolated) + + assert self.name + super().__init__(*args, **kwargs) + + def check_default(self, option: optparse.Option, key: str, val: Any) -> Any: + try: + return option.check_value(key, val) + except optparse.OptionValueError as exc: + print(f"An error occurred during configuration: {exc}") + sys.exit(3) + + def _get_ordered_configuration_items( + self, + ) -> Generator[Tuple[str, Any], None, None]: + # Configuration gives keys in an unordered manner. Order them. + override_order = ["global", self.name, ":env:"] + + # Pool the options into different groups + section_items: Dict[str, List[Tuple[str, Any]]] = { + name: [] for name in override_order + } + for section_key, val in self.config.items(): + # ignore empty values + if not val: + logger.debug( + "Ignoring configuration key '%s' as it's value is empty.", + section_key, + ) + continue + + section, key = section_key.split(".", 1) + if section in override_order: + section_items[section].append((key, val)) + + # Yield each group in their override order + for section in override_order: + for key, val in section_items[section]: + yield key, val + + def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]: + """Updates the given defaults with values from the config files and + the environ. Does a little special handling for certain types of + options (lists).""" + + # Accumulate complex default state. + self.values = optparse.Values(self.defaults) + late_eval = set() + # Then set the options with those values + for key, val in self._get_ordered_configuration_items(): + # '--' because configuration supports only long names + option = self.get_option("--" + key) + + # Ignore options not present in this parser. E.g. non-globals put + # in [global] by users that want them to apply to all applicable + # commands. + if option is None: + continue + + assert option.dest is not None + + if option.action in ("store_true", "store_false"): + try: + val = strtobool(val) + except ValueError: + self.error( + "{} is not a valid value for {} option, " # noqa + "please specify a boolean value like yes/no, " + "true/false or 1/0 instead.".format(val, key) + ) + elif option.action == "count": + with suppress(ValueError): + val = strtobool(val) + with suppress(ValueError): + val = int(val) + if not isinstance(val, int) or val < 0: + self.error( + "{} is not a valid value for {} option, " # noqa + "please instead specify either a non-negative integer " + "or a boolean value like yes/no or false/true " + "which is equivalent to 1/0.".format(val, key) + ) + elif option.action == "append": + val = val.split() + val = [self.check_default(option, key, v) for v in val] + elif option.action == "callback": + assert option.callback is not None + late_eval.add(option.dest) + opt_str = option.get_opt_string() + val = option.convert_value(opt_str, val) + # From take_action + args = option.callback_args or () + kwargs = option.callback_kwargs or {} + option.callback(option, opt_str, val, self, *args, **kwargs) + else: + val = self.check_default(option, key, val) + + defaults[option.dest] = val + + for key in late_eval: + defaults[key] = getattr(self.values, key) + self.values = None + return defaults + + def get_default_values(self) -> optparse.Values: + """Overriding to make updating the defaults after instantiation of + the option parser possible, _update_defaults() does the dirty work.""" + if not self.process_default_values: + # Old, pre-Optik 1.5 behaviour. + return optparse.Values(self.defaults) + + # Load the configuration, or error out in case of an error + try: + self.config.load() + except ConfigurationError as err: + self.exit(UNKNOWN_ERROR, str(err)) + + defaults = self._update_defaults(self.defaults.copy()) # ours + for option in self._get_all_options(): + assert option.dest is not None + default = defaults.get(option.dest) + if isinstance(default, str): + opt_str = option.get_opt_string() + defaults[option.dest] = option.check_value(opt_str, default) + return optparse.Values(defaults) + + def error(self, msg: str) -> None: + self.print_usage(sys.stderr) + self.exit(UNKNOWN_ERROR, f"{msg}\n") diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/progress_bars.py b/web/lib/python3.11/site-packages/pip/_internal/cli/progress_bars.py new file mode 100644 index 00000000..0ad14031 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/progress_bars.py @@ -0,0 +1,68 @@ +import functools +from typing import Callable, Generator, Iterable, Iterator, Optional, Tuple + +from pip._vendor.rich.progress import ( + BarColumn, + DownloadColumn, + FileSizeColumn, + Progress, + ProgressColumn, + SpinnerColumn, + TextColumn, + TimeElapsedColumn, + TimeRemainingColumn, + TransferSpeedColumn, +) + +from pip._internal.utils.logging import get_indentation + +DownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]] + + +def _rich_progress_bar( + iterable: Iterable[bytes], + *, + bar_type: str, + size: int, +) -> Generator[bytes, None, None]: + assert bar_type == "on", "This should only be used in the default mode." + + if not size: + total = float("inf") + columns: Tuple[ProgressColumn, ...] = ( + TextColumn("[progress.description]{task.description}"), + SpinnerColumn("line", speed=1.5), + FileSizeColumn(), + TransferSpeedColumn(), + TimeElapsedColumn(), + ) + else: + total = size + columns = ( + TextColumn("[progress.description]{task.description}"), + BarColumn(), + DownloadColumn(), + TransferSpeedColumn(), + TextColumn("eta"), + TimeRemainingColumn(), + ) + + progress = Progress(*columns, refresh_per_second=30) + task_id = progress.add_task(" " * (get_indentation() + 2), total=total) + with progress: + for chunk in iterable: + yield chunk + progress.update(task_id, advance=len(chunk)) + + +def get_download_progress_renderer( + *, bar_type: str, size: Optional[int] = None +) -> DownloadProgressRenderer: + """Get an object that can be used to render the download progress. + + Returns a callable, that takes an iterable to "wrap". + """ + if bar_type == "on": + return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size) + else: + return iter # no-op, when passed an iterator diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/req_command.py b/web/lib/python3.11/site-packages/pip/_internal/cli/req_command.py new file mode 100644 index 00000000..1044809f --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/req_command.py @@ -0,0 +1,502 @@ +"""Contains the Command base classes that depend on PipSession. + +The classes in this module are in a separate module so the commands not +needing download / PackageFinder capability don't unnecessarily import the +PackageFinder machinery and all its vendored dependencies, etc. +""" + +import logging +import os +import sys +from functools import partial +from optparse import Values +from typing import TYPE_CHECKING, Any, List, Optional, Tuple + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.command_context import CommandContextMixIn +from pip._internal.exceptions import CommandError, PreviousBuildDirError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.network.session import PipSession +from pip._internal.operations.build.build_tracker import BuildTracker +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.constructors import ( + install_req_from_editable, + install_req_from_line, + install_req_from_parsed_requirement, + install_req_from_req_string, +) +from pip._internal.req.req_file import parse_requirements +from pip._internal.req.req_install import InstallRequirement +from pip._internal.resolution.base import BaseResolver +from pip._internal.self_outdated_check import pip_self_version_check +from pip._internal.utils.temp_dir import ( + TempDirectory, + TempDirectoryTypeRegistry, + tempdir_kinds, +) +from pip._internal.utils.virtualenv import running_under_virtualenv + +if TYPE_CHECKING: + from ssl import SSLContext + +logger = logging.getLogger(__name__) + + +def _create_truststore_ssl_context() -> Optional["SSLContext"]: + if sys.version_info < (3, 10): + raise CommandError("The truststore feature is only available for Python 3.10+") + + try: + import ssl + except ImportError: + logger.warning("Disabling truststore since ssl support is missing") + return None + + try: + import truststore + except ImportError: + raise CommandError( + "To use the truststore feature, 'truststore' must be installed into " + "pip's current environment." + ) + + return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + + +class SessionCommandMixin(CommandContextMixIn): + + """ + A class mixin for command classes needing _build_session(). + """ + + def __init__(self) -> None: + super().__init__() + self._session: Optional[PipSession] = None + + @classmethod + def _get_index_urls(cls, options: Values) -> Optional[List[str]]: + """Return a list of index urls from user-provided options.""" + index_urls = [] + if not getattr(options, "no_index", False): + url = getattr(options, "index_url", None) + if url: + index_urls.append(url) + urls = getattr(options, "extra_index_urls", None) + if urls: + index_urls.extend(urls) + # Return None rather than an empty list + return index_urls or None + + def get_default_session(self, options: Values) -> PipSession: + """Get a default-managed session.""" + if self._session is None: + self._session = self.enter_context(self._build_session(options)) + # there's no type annotation on requests.Session, so it's + # automatically ContextManager[Any] and self._session becomes Any, + # then https://github.com/python/mypy/issues/7696 kicks in + assert self._session is not None + return self._session + + def _build_session( + self, + options: Values, + retries: Optional[int] = None, + timeout: Optional[int] = None, + fallback_to_certifi: bool = False, + ) -> PipSession: + cache_dir = options.cache_dir + assert not cache_dir or os.path.isabs(cache_dir) + + if "truststore" in options.features_enabled: + try: + ssl_context = _create_truststore_ssl_context() + except Exception: + if not fallback_to_certifi: + raise + ssl_context = None + else: + ssl_context = None + + session = PipSession( + cache=os.path.join(cache_dir, "http") if cache_dir else None, + retries=retries if retries is not None else options.retries, + trusted_hosts=options.trusted_hosts, + index_urls=self._get_index_urls(options), + ssl_context=ssl_context, + ) + + # Handle custom ca-bundles from the user + if options.cert: + session.verify = options.cert + + # Handle SSL client certificate + if options.client_cert: + session.cert = options.client_cert + + # Handle timeouts + if options.timeout or timeout: + session.timeout = timeout if timeout is not None else options.timeout + + # Handle configured proxies + if options.proxy: + session.proxies = { + "http": options.proxy, + "https": options.proxy, + } + + # Determine if we can prompt the user for authentication or not + session.auth.prompting = not options.no_input + + return session + + +class IndexGroupCommand(Command, SessionCommandMixin): + + """ + Abstract base class for commands with the index_group options. + + This also corresponds to the commands that permit the pip version check. + """ + + def handle_pip_version_check(self, options: Values) -> None: + """ + Do the pip version check if not disabled. + + This overrides the default behavior of not doing the check. + """ + # Make sure the index_group options are present. + assert hasattr(options, "no_index") + + if options.disable_pip_version_check or options.no_index: + return + + # Otherwise, check if we're using the latest version of pip available. + session = self._build_session( + options, + retries=0, + timeout=min(5, options.timeout), + # This is set to ensure the function does not fail when truststore is + # specified in use-feature but cannot be loaded. This usually raises a + # CommandError and shows a nice user-facing error, but this function is not + # called in that try-except block. + fallback_to_certifi=True, + ) + with session: + pip_self_version_check(session, options) + + +KEEPABLE_TEMPDIR_TYPES = [ + tempdir_kinds.BUILD_ENV, + tempdir_kinds.EPHEM_WHEEL_CACHE, + tempdir_kinds.REQ_BUILD, +] + + +def warn_if_run_as_root() -> None: + """Output a warning for sudo users on Unix. + + In a virtual environment, sudo pip still writes to virtualenv. + On Windows, users may run pip as Administrator without issues. + This warning only applies to Unix root users outside of virtualenv. + """ + if running_under_virtualenv(): + return + if not hasattr(os, "getuid"): + return + # On Windows, there are no "system managed" Python packages. Installing as + # Administrator via pip is the correct way of updating system environments. + # + # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform + # checks: https://mypy.readthedocs.io/en/stable/common_issues.html + if sys.platform == "win32" or sys.platform == "cygwin": + return + + if os.getuid() != 0: + return + + logger.warning( + "Running pip as the 'root' user can result in broken permissions and " + "conflicting behaviour with the system package manager. " + "It is recommended to use a virtual environment instead: " + "https://pip.pypa.io/warnings/venv" + ) + + +def with_cleanup(func: Any) -> Any: + """Decorator for common logic related to managing temporary + directories. + """ + + def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None: + for t in KEEPABLE_TEMPDIR_TYPES: + registry.set_delete(t, False) + + def wrapper( + self: RequirementCommand, options: Values, args: List[Any] + ) -> Optional[int]: + assert self.tempdir_registry is not None + if options.no_clean: + configure_tempdir_registry(self.tempdir_registry) + + try: + return func(self, options, args) + except PreviousBuildDirError: + # This kind of conflict can occur when the user passes an explicit + # build directory with a pre-existing folder. In that case we do + # not want to accidentally remove it. + configure_tempdir_registry(self.tempdir_registry) + raise + + return wrapper + + +class RequirementCommand(IndexGroupCommand): + def __init__(self, *args: Any, **kw: Any) -> None: + super().__init__(*args, **kw) + + self.cmd_opts.add_option(cmdoptions.no_clean()) + + @staticmethod + def determine_resolver_variant(options: Values) -> str: + """Determines which resolver should be used, based on the given options.""" + if "legacy-resolver" in options.deprecated_features_enabled: + return "legacy" + + return "2020-resolver" + + @classmethod + def make_requirement_preparer( + cls, + temp_build_dir: TempDirectory, + options: Values, + build_tracker: BuildTracker, + session: PipSession, + finder: PackageFinder, + use_user_site: bool, + download_dir: Optional[str] = None, + verbosity: int = 0, + ) -> RequirementPreparer: + """ + Create a RequirementPreparer instance for the given parameters. + """ + temp_build_dir_path = temp_build_dir.path + assert temp_build_dir_path is not None + + resolver_variant = cls.determine_resolver_variant(options) + if resolver_variant == "2020-resolver": + lazy_wheel = "fast-deps" in options.features_enabled + if lazy_wheel: + logger.warning( + "pip is using lazily downloaded wheels using HTTP " + "range requests to obtain dependency information. " + "This experimental feature is enabled through " + "--use-feature=fast-deps and it is not ready for " + "production." + ) + else: + lazy_wheel = False + if "fast-deps" in options.features_enabled: + logger.warning( + "fast-deps has no effect when used with the legacy resolver." + ) + + return RequirementPreparer( + build_dir=temp_build_dir_path, + src_dir=options.src_dir, + download_dir=download_dir, + build_isolation=options.build_isolation, + check_build_deps=options.check_build_deps, + build_tracker=build_tracker, + session=session, + progress_bar=options.progress_bar, + finder=finder, + require_hashes=options.require_hashes, + use_user_site=use_user_site, + lazy_wheel=lazy_wheel, + verbosity=verbosity, + ) + + @classmethod + def make_resolver( + cls, + preparer: RequirementPreparer, + finder: PackageFinder, + options: Values, + wheel_cache: Optional[WheelCache] = None, + use_user_site: bool = False, + ignore_installed: bool = True, + ignore_requires_python: bool = False, + force_reinstall: bool = False, + upgrade_strategy: str = "to-satisfy-only", + use_pep517: Optional[bool] = None, + py_version_info: Optional[Tuple[int, ...]] = None, + ) -> BaseResolver: + """ + Create a Resolver instance for the given parameters. + """ + make_install_req = partial( + install_req_from_req_string, + isolated=options.isolated_mode, + use_pep517=use_pep517, + config_settings=getattr(options, "config_settings", None), + ) + resolver_variant = cls.determine_resolver_variant(options) + # The long import name and duplicated invocation is needed to convince + # Mypy into correctly typechecking. Otherwise it would complain the + # "Resolver" class being redefined. + if resolver_variant == "2020-resolver": + import pip._internal.resolution.resolvelib.resolver + + return pip._internal.resolution.resolvelib.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + import pip._internal.resolution.legacy.resolver + + return pip._internal.resolution.legacy.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + + def get_requirements( + self, + args: List[str], + options: Values, + finder: PackageFinder, + session: PipSession, + ) -> List[InstallRequirement]: + """ + Parse command-line arguments into the corresponding requirements. + """ + requirements: List[InstallRequirement] = [] + for filename in options.constraints: + for parsed_req in parse_requirements( + filename, + constraint=True, + finder=finder, + options=options, + session=session, + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + user_supplied=False, + ) + requirements.append(req_to_add) + + for req in args: + req_to_add = install_req_from_line( + req, + None, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + for req in options.editables: + req_to_add = install_req_from_editable( + req, + user_supplied=True, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + # NOTE: options.require_hashes may be set if --require-hashes is True + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, finder=finder, options=options, session=session + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + ) + requirements.append(req_to_add) + + # If any requirement has hash options, enable hash checking. + if any(req.has_hash_options for req in requirements): + options.require_hashes = True + + if not (args or options.editables or options.requirements): + opts = {"name": self.name} + if options.find_links: + raise CommandError( + "You must give at least one requirement to {name} " + '(maybe you meant "pip {name} {links}"?)'.format( + **dict(opts, links=" ".join(options.find_links)) + ) + ) + else: + raise CommandError( + "You must give at least one requirement to {name} " + '(see "pip help {name}")'.format(**opts) + ) + + return requirements + + @staticmethod + def trace_basic_info(finder: PackageFinder) -> None: + """ + Trace basic information about the provided objects. + """ + # Display where finder is looking for packages + search_scope = finder.search_scope + locations = search_scope.get_formatted_locations() + if locations: + logger.info(locations) + + def _build_package_finder( + self, + options: Values, + session: PipSession, + target_python: Optional[TargetPython] = None, + ignore_requires_python: Optional[bool] = None, + ) -> PackageFinder: + """ + Create a package finder appropriate to this requirement command. + + :param ignore_requires_python: Whether to ignore incompatible + "Requires-Python" values in links. Defaults to False. + """ + link_collector = LinkCollector.create(session, options=options) + selection_prefs = SelectionPreferences( + allow_yanked=True, + format_control=options.format_control, + allow_all_prereleases=options.pre, + prefer_binary=options.prefer_binary, + ignore_requires_python=ignore_requires_python, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + target_python=target_python, + ) diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/spinners.py b/web/lib/python3.11/site-packages/pip/_internal/cli/spinners.py new file mode 100644 index 00000000..cf2b976f --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/spinners.py @@ -0,0 +1,159 @@ +import contextlib +import itertools +import logging +import sys +import time +from typing import IO, Generator, Optional + +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.logging import get_indentation + +logger = logging.getLogger(__name__) + + +class SpinnerInterface: + def spin(self) -> None: + raise NotImplementedError() + + def finish(self, final_status: str) -> None: + raise NotImplementedError() + + +class InteractiveSpinner(SpinnerInterface): + def __init__( + self, + message: str, + file: Optional[IO[str]] = None, + spin_chars: str = "-\\|/", + # Empirically, 8 updates/second looks nice + min_update_interval_seconds: float = 0.125, + ): + self._message = message + if file is None: + file = sys.stdout + self._file = file + self._rate_limiter = RateLimiter(min_update_interval_seconds) + self._finished = False + + self._spin_cycle = itertools.cycle(spin_chars) + + self._file.write(" " * get_indentation() + self._message + " ... ") + self._width = 0 + + def _write(self, status: str) -> None: + assert not self._finished + # Erase what we wrote before by backspacing to the beginning, writing + # spaces to overwrite the old text, and then backspacing again + backup = "\b" * self._width + self._file.write(backup + " " * self._width + backup) + # Now we have a blank slate to add our status + self._file.write(status) + self._width = len(status) + self._file.flush() + self._rate_limiter.reset() + + def spin(self) -> None: + if self._finished: + return + if not self._rate_limiter.ready(): + return + self._write(next(self._spin_cycle)) + + def finish(self, final_status: str) -> None: + if self._finished: + return + self._write(final_status) + self._file.write("\n") + self._file.flush() + self._finished = True + + +# Used for dumb terminals, non-interactive installs (no tty), etc. +# We still print updates occasionally (once every 60 seconds by default) to +# act as a keep-alive for systems like Travis-CI that take lack-of-output as +# an indication that a task has frozen. +class NonInteractiveSpinner(SpinnerInterface): + def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None: + self._message = message + self._finished = False + self._rate_limiter = RateLimiter(min_update_interval_seconds) + self._update("started") + + def _update(self, status: str) -> None: + assert not self._finished + self._rate_limiter.reset() + logger.info("%s: %s", self._message, status) + + def spin(self) -> None: + if self._finished: + return + if not self._rate_limiter.ready(): + return + self._update("still running...") + + def finish(self, final_status: str) -> None: + if self._finished: + return + self._update(f"finished with status '{final_status}'") + self._finished = True + + +class RateLimiter: + def __init__(self, min_update_interval_seconds: float) -> None: + self._min_update_interval_seconds = min_update_interval_seconds + self._last_update: float = 0 + + def ready(self) -> bool: + now = time.time() + delta = now - self._last_update + return delta >= self._min_update_interval_seconds + + def reset(self) -> None: + self._last_update = time.time() + + +@contextlib.contextmanager +def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]: + # Interactive spinner goes directly to sys.stdout rather than being routed + # through the logging system, but it acts like it has level INFO, + # i.e. it's only displayed if we're at level INFO or better. + # Non-interactive spinner goes through the logging system, so it is always + # in sync with logging configuration. + if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO: + spinner: SpinnerInterface = InteractiveSpinner(message) + else: + spinner = NonInteractiveSpinner(message) + try: + with hidden_cursor(sys.stdout): + yield spinner + except KeyboardInterrupt: + spinner.finish("canceled") + raise + except Exception: + spinner.finish("error") + raise + else: + spinner.finish("done") + + +HIDE_CURSOR = "\x1b[?25l" +SHOW_CURSOR = "\x1b[?25h" + + +@contextlib.contextmanager +def hidden_cursor(file: IO[str]) -> Generator[None, None, None]: + # The Windows terminal does not support the hide/show cursor ANSI codes, + # even via colorama. So don't even try. + if WINDOWS: + yield + # We don't want to clutter the output with control characters if we're + # writing to a file, or if the user is running with --quiet. + # See https://github.com/pypa/pip/issues/3418 + elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO: + yield + else: + file.write(HIDE_CURSOR) + try: + yield + finally: + file.write(SHOW_CURSOR) diff --git a/web/lib/python3.11/site-packages/pip/_internal/cli/status_codes.py b/web/lib/python3.11/site-packages/pip/_internal/cli/status_codes.py new file mode 100644 index 00000000..5e29502c --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/cli/status_codes.py @@ -0,0 +1,6 @@ +SUCCESS = 0 +ERROR = 1 +UNKNOWN_ERROR = 2 +VIRTUALENV_NOT_FOUND = 3 +PREVIOUS_BUILD_DIR_ERROR = 4 +NO_MATCHES_FOUND = 23 diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__init__.py b/web/lib/python3.11/site-packages/pip/_internal/commands/__init__.py new file mode 100644 index 00000000..858a4101 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/__init__.py @@ -0,0 +1,132 @@ +""" +Package containing all pip commands +""" + +import importlib +from collections import namedtuple +from typing import Any, Dict, Optional + +from pip._internal.cli.base_command import Command + +CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary") + +# This dictionary does a bunch of heavy lifting for help output: +# - Enables avoiding additional (costly) imports for presenting `--help`. +# - The ordering matters for help display. +# +# Even though the module path starts with the same "pip._internal.commands" +# prefix, the full path makes testing easier (specifically when modifying +# `commands_dict` in test setup / teardown). +commands_dict: Dict[str, CommandInfo] = { + "install": CommandInfo( + "pip._internal.commands.install", + "InstallCommand", + "Install packages.", + ), + "download": CommandInfo( + "pip._internal.commands.download", + "DownloadCommand", + "Download packages.", + ), + "uninstall": CommandInfo( + "pip._internal.commands.uninstall", + "UninstallCommand", + "Uninstall packages.", + ), + "freeze": CommandInfo( + "pip._internal.commands.freeze", + "FreezeCommand", + "Output installed packages in requirements format.", + ), + "inspect": CommandInfo( + "pip._internal.commands.inspect", + "InspectCommand", + "Inspect the python environment.", + ), + "list": CommandInfo( + "pip._internal.commands.list", + "ListCommand", + "List installed packages.", + ), + "show": CommandInfo( + "pip._internal.commands.show", + "ShowCommand", + "Show information about installed packages.", + ), + "check": CommandInfo( + "pip._internal.commands.check", + "CheckCommand", + "Verify installed packages have compatible dependencies.", + ), + "config": CommandInfo( + "pip._internal.commands.configuration", + "ConfigurationCommand", + "Manage local and global configuration.", + ), + "search": CommandInfo( + "pip._internal.commands.search", + "SearchCommand", + "Search PyPI for packages.", + ), + "cache": CommandInfo( + "pip._internal.commands.cache", + "CacheCommand", + "Inspect and manage pip's wheel cache.", + ), + "index": CommandInfo( + "pip._internal.commands.index", + "IndexCommand", + "Inspect information available from package indexes.", + ), + "wheel": CommandInfo( + "pip._internal.commands.wheel", + "WheelCommand", + "Build wheels from your requirements.", + ), + "hash": CommandInfo( + "pip._internal.commands.hash", + "HashCommand", + "Compute hashes of package archives.", + ), + "completion": CommandInfo( + "pip._internal.commands.completion", + "CompletionCommand", + "A helper command used for command completion.", + ), + "debug": CommandInfo( + "pip._internal.commands.debug", + "DebugCommand", + "Show information useful for debugging.", + ), + "help": CommandInfo( + "pip._internal.commands.help", + "HelpCommand", + "Show help for commands.", + ), +} + + +def create_command(name: str, **kwargs: Any) -> Command: + """ + Create an instance of the Command class with the given name. + """ + module_path, class_name, summary = commands_dict[name] + module = importlib.import_module(module_path) + command_class = getattr(module, class_name) + command = command_class(name=name, summary=summary, **kwargs) + + return command + + +def get_similar_commands(name: str) -> Optional[str]: + """Command name auto-correct.""" + from difflib import get_close_matches + + name = name.lower() + + close_commands = get_close_matches(name, commands_dict.keys()) + + if close_commands: + return close_commands[0] + else: + return None diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..f2a76bd4 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/cache.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/cache.cpython-311.pyc new file mode 100644 index 00000000..86e55c44 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/cache.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/check.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/check.cpython-311.pyc new file mode 100644 index 00000000..3600f115 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/check.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/completion.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/completion.cpython-311.pyc new file mode 100644 index 00000000..66db4a8c Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/completion.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-311.pyc new file mode 100644 index 00000000..de7bc4e7 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/debug.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/debug.cpython-311.pyc new file mode 100644 index 00000000..e91e337c Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/debug.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/download.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/download.cpython-311.pyc new file mode 100644 index 00000000..590b4335 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/download.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-311.pyc new file mode 100644 index 00000000..8478b25a Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/hash.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/hash.cpython-311.pyc new file mode 100644 index 00000000..68a2cdd0 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/hash.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/help.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/help.cpython-311.pyc new file mode 100644 index 00000000..bc1314cb Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/help.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/index.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/index.cpython-311.pyc new file mode 100644 index 00000000..197f8642 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/index.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-311.pyc new file mode 100644 index 00000000..2ff3d4b1 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/install.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/install.cpython-311.pyc new file mode 100644 index 00000000..169fa0b2 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/install.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/list.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/list.cpython-311.pyc new file mode 100644 index 00000000..c0ead171 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/list.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/search.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/search.cpython-311.pyc new file mode 100644 index 00000000..e0e22659 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/search.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/show.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/show.cpython-311.pyc new file mode 100644 index 00000000..0e26644d Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/show.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-311.pyc new file mode 100644 index 00000000..d9914002 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-311.pyc new file mode 100644 index 00000000..291e2525 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/cache.py b/web/lib/python3.11/site-packages/pip/_internal/commands/cache.py new file mode 100644 index 00000000..c5f03302 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/cache.py @@ -0,0 +1,223 @@ +import os +import textwrap +from optparse import Values +from typing import Any, List + +import pip._internal.utils.filesystem as filesystem +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.exceptions import CommandError, PipError +from pip._internal.utils.logging import getLogger + +logger = getLogger(__name__) + + +class CacheCommand(Command): + """ + Inspect and manage pip's wheel cache. + + Subcommands: + + - dir: Show the cache directory. + - info: Show information about the cache. + - list: List filenames of packages stored in the cache. + - remove: Remove one or more package from the cache. + - purge: Remove all items from the cache. + + `` `` can be a glob expression or a package name. + """ + + ignore_require_venv = True + usage = """ + %prog dir + %prog info + %prog list [ ] [--format=[human, abspath]] + %prog remove + %prog purge + """ + + def add_options(self) -> None: + + self.cmd_opts.add_option( + "--format", + action="store", + dest="list_format", + default="human", + choices=("human", "abspath"), + help="Select the output format among: human (default) or abspath", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "dir": self.get_cache_dir, + "info": self.get_cache_info, + "list": self.list_cache_items, + "remove": self.remove_cache_items, + "purge": self.purge_cache, + } + + if not options.cache_dir: + logger.error("pip cache commands can not function since cache is disabled.") + return ERROR + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def get_cache_dir(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + logger.info(options.cache_dir) + + def get_cache_info(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + num_http_files = len(self._find_http_files(options)) + num_packages = len(self._find_wheels(options, "*")) + + http_cache_location = self._cache_dir(options, "http") + wheels_cache_location = self._cache_dir(options, "wheels") + http_cache_size = filesystem.format_directory_size(http_cache_location) + wheels_cache_size = filesystem.format_directory_size(wheels_cache_location) + + message = ( + textwrap.dedent( + """ + Package index page cache location: {http_cache_location} + Package index page cache size: {http_cache_size} + Number of HTTP files: {num_http_files} + Locally built wheels location: {wheels_cache_location} + Locally built wheels size: {wheels_cache_size} + Number of locally built wheels: {package_count} + """ + ) + .format( + http_cache_location=http_cache_location, + http_cache_size=http_cache_size, + num_http_files=num_http_files, + wheels_cache_location=wheels_cache_location, + package_count=num_packages, + wheels_cache_size=wheels_cache_size, + ) + .strip() + ) + + logger.info(message) + + def list_cache_items(self, options: Values, args: List[Any]) -> None: + if len(args) > 1: + raise CommandError("Too many arguments") + + if args: + pattern = args[0] + else: + pattern = "*" + + files = self._find_wheels(options, pattern) + if options.list_format == "human": + self.format_for_human(files) + else: + self.format_for_abspath(files) + + def format_for_human(self, files: List[str]) -> None: + if not files: + logger.info("No locally built wheels cached.") + return + + results = [] + for filename in files: + wheel = os.path.basename(filename) + size = filesystem.format_file_size(filename) + results.append(f" - {wheel} ({size})") + logger.info("Cache contents:\n") + logger.info("\n".join(sorted(results))) + + def format_for_abspath(self, files: List[str]) -> None: + if not files: + return + + results = [] + for filename in files: + results.append(filename) + + logger.info("\n".join(sorted(results))) + + def remove_cache_items(self, options: Values, args: List[Any]) -> None: + if len(args) > 1: + raise CommandError("Too many arguments") + + if not args: + raise CommandError("Please provide a pattern") + + files = self._find_wheels(options, args[0]) + + no_matching_msg = "No matching packages" + if args[0] == "*": + # Only fetch http files if no specific pattern given + files += self._find_http_files(options) + else: + # Add the pattern to the log message + no_matching_msg += ' for pattern "{}"'.format(args[0]) + + if not files: + logger.warning(no_matching_msg) + + for filename in files: + os.unlink(filename) + logger.verbose("Removed %s", filename) + logger.info("Files removed: %s", len(files)) + + def purge_cache(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + return self.remove_cache_items(options, ["*"]) + + def _cache_dir(self, options: Values, subdir: str) -> str: + return os.path.join(options.cache_dir, subdir) + + def _find_http_files(self, options: Values) -> List[str]: + http_dir = self._cache_dir(options, "http") + return filesystem.find_files(http_dir, "*") + + def _find_wheels(self, options: Values, pattern: str) -> List[str]: + wheel_dir = self._cache_dir(options, "wheels") + + # The wheel filename format, as specified in PEP 427, is: + # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl + # + # Additionally, non-alphanumeric values in the distribution are + # normalized to underscores (_), meaning hyphens can never occur + # before `-{version}`. + # + # Given that information: + # - If the pattern we're given contains a hyphen (-), the user is + # providing at least the version. Thus, we can just append `*.whl` + # to match the rest of it. + # - If the pattern we're given doesn't contain a hyphen (-), the + # user is only providing the name. Thus, we append `-*.whl` to + # match the hyphen before the version, followed by anything else. + # + # PEP 427: https://www.python.org/dev/peps/pep-0427/ + pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl") + + return filesystem.find_files(wheel_dir, pattern) diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/check.py b/web/lib/python3.11/site-packages/pip/_internal/commands/check.py new file mode 100644 index 00000000..3864220b --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/check.py @@ -0,0 +1,53 @@ +import logging +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.operations.check import ( + check_package_set, + create_package_set_from_installed, +) +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class CheckCommand(Command): + """Verify installed packages have compatible dependencies.""" + + usage = """ + %prog [options]""" + + def run(self, options: Values, args: List[str]) -> int: + + package_set, parsing_probs = create_package_set_from_installed() + missing, conflicting = check_package_set(package_set) + + for project_name in missing: + version = package_set[project_name].version + for dependency in missing[project_name]: + write_output( + "%s %s requires %s, which is not installed.", + project_name, + version, + dependency[0], + ) + + for project_name in conflicting: + version = package_set[project_name].version + for dep_name, dep_version, req in conflicting[project_name]: + write_output( + "%s %s has requirement %s, but you have %s %s.", + project_name, + version, + req, + dep_name, + dep_version, + ) + + if missing or conflicting or parsing_probs: + return ERROR + else: + write_output("No broken requirements found.") + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/completion.py b/web/lib/python3.11/site-packages/pip/_internal/commands/completion.py new file mode 100644 index 00000000..deaa3089 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/completion.py @@ -0,0 +1,126 @@ +import sys +import textwrap +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.utils.misc import get_prog + +BASE_COMPLETION = """ +# pip {shell} completion start{script}# pip {shell} completion end +""" + +COMPLETION_SCRIPTS = { + "bash": """ + _pip_completion() + {{ + COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\ + COMP_CWORD=$COMP_CWORD \\ + PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) + }} + complete -o default -F _pip_completion {prog} + """, + "zsh": """ + function _pip_completion {{ + local words cword + read -Ac words + read -cn cword + reply=( $( COMP_WORDS="$words[*]" \\ + COMP_CWORD=$(( cword-1 )) \\ + PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null )) + }} + compctl -K _pip_completion {prog} + """, + "fish": """ + function __fish_complete_pip + set -lx COMP_WORDS (commandline -o) "" + set -lx COMP_CWORD ( \\ + math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\ + ) + set -lx PIP_AUTO_COMPLETE 1 + string split \\ -- (eval $COMP_WORDS[1]) + end + complete -fa "(__fish_complete_pip)" -c {prog} + """, + "powershell": """ + if ((Test-Path Function:\\TabExpansion) -and -not ` + (Test-Path Function:\\_pip_completeBackup)) {{ + Rename-Item Function:\\TabExpansion _pip_completeBackup + }} + function TabExpansion($line, $lastWord) {{ + $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart() + if ($lastBlock.StartsWith("{prog} ")) {{ + $Env:COMP_WORDS=$lastBlock + $Env:COMP_CWORD=$lastBlock.Split().Length - 1 + $Env:PIP_AUTO_COMPLETE=1 + (& {prog}).Split() + Remove-Item Env:COMP_WORDS + Remove-Item Env:COMP_CWORD + Remove-Item Env:PIP_AUTO_COMPLETE + }} + elseif (Test-Path Function:\\_pip_completeBackup) {{ + # Fall back on existing tab expansion + _pip_completeBackup $line $lastWord + }} + }} + """, +} + + +class CompletionCommand(Command): + """A helper command to be used for command completion.""" + + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--bash", + "-b", + action="store_const", + const="bash", + dest="shell", + help="Emit completion code for bash", + ) + self.cmd_opts.add_option( + "--zsh", + "-z", + action="store_const", + const="zsh", + dest="shell", + help="Emit completion code for zsh", + ) + self.cmd_opts.add_option( + "--fish", + "-f", + action="store_const", + const="fish", + dest="shell", + help="Emit completion code for fish", + ) + self.cmd_opts.add_option( + "--powershell", + "-p", + action="store_const", + const="powershell", + dest="shell", + help="Emit completion code for powershell", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + """Prints the completion code of the given shell""" + shells = COMPLETION_SCRIPTS.keys() + shell_options = ["--" + shell for shell in sorted(shells)] + if options.shell in shells: + script = textwrap.dedent( + COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog()) + ) + print(BASE_COMPLETION.format(script=script, shell=options.shell)) + return SUCCESS + else: + sys.stderr.write( + "ERROR: You must pass {}\n".format(" or ".join(shell_options)) + ) + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/configuration.py b/web/lib/python3.11/site-packages/pip/_internal/commands/configuration.py new file mode 100644 index 00000000..84b134e4 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/configuration.py @@ -0,0 +1,282 @@ +import logging +import os +import subprocess +from optparse import Values +from typing import Any, List, Optional + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.configuration import ( + Configuration, + Kind, + get_configuration_files, + kinds, +) +from pip._internal.exceptions import PipError +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import get_prog, write_output + +logger = logging.getLogger(__name__) + + +class ConfigurationCommand(Command): + """ + Manage local and global configuration. + + Subcommands: + + - list: List the active configuration (or from the file specified) + - edit: Edit the configuration file in an editor + - get: Get the value associated with command.option + - set: Set the command.option=value + - unset: Unset the value associated with command.option + - debug: List the configuration files and values defined under them + + Configuration keys should be dot separated command and option name, + with the special prefix "global" affecting any command. For example, + "pip config set global.index-url https://example.org/" would configure + the index url for all commands, but "pip config set download.timeout 10" + would configure a 10 second timeout only for "pip download" commands. + + If none of --user, --global and --site are passed, a virtual + environment configuration file is used if one is active and the file + exists. Otherwise, all modifications happen to the user file by + default. + """ + + ignore_require_venv = True + usage = """ + %prog [ ] list + %prog [ ] [--editor ] edit + + %prog [ ] get command.option + %prog [ ] set command.option value + %prog [ ] unset command.option + %prog [ ] debug + """ + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--editor", + dest="editor", + action="store", + default=None, + help=( + "Editor to use to edit the file. Uses VISUAL or EDITOR " + "environment variables if not provided." + ), + ) + + self.cmd_opts.add_option( + "--global", + dest="global_file", + action="store_true", + default=False, + help="Use the system-wide configuration file only", + ) + + self.cmd_opts.add_option( + "--user", + dest="user_file", + action="store_true", + default=False, + help="Use the user configuration file only", + ) + + self.cmd_opts.add_option( + "--site", + dest="site_file", + action="store_true", + default=False, + help="Use the current environment configuration file only", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "list": self.list_values, + "edit": self.open_in_editor, + "get": self.get_name, + "set": self.set_name_value, + "unset": self.unset_name, + "debug": self.list_config_values, + } + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Determine which configuration files are to be loaded + # Depends on whether the command is modifying. + try: + load_only = self._determine_file( + options, need_value=(action in ["get", "set", "unset", "edit"]) + ) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + # Load a new configuration + self.configuration = Configuration( + isolated=options.isolated_mode, load_only=load_only + ) + self.configuration.load() + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]: + file_options = [ + key + for key, value in ( + (kinds.USER, options.user_file), + (kinds.GLOBAL, options.global_file), + (kinds.SITE, options.site_file), + ) + if value + ] + + if not file_options: + if not need_value: + return None + # Default to user, unless there's a site file. + elif any( + os.path.exists(site_config_file) + for site_config_file in get_configuration_files()[kinds.SITE] + ): + return kinds.SITE + else: + return kinds.USER + elif len(file_options) == 1: + return file_options[0] + + raise PipError( + "Need exactly one file to operate upon " + "(--user, --site, --global) to perform." + ) + + def list_values(self, options: Values, args: List[str]) -> None: + self._get_n_args(args, "list", n=0) + + for key, value in sorted(self.configuration.items()): + write_output("%s=%r", key, value) + + def get_name(self, options: Values, args: List[str]) -> None: + key = self._get_n_args(args, "get [name]", n=1) + value = self.configuration.get_value(key) + + write_output("%s", value) + + def set_name_value(self, options: Values, args: List[str]) -> None: + key, value = self._get_n_args(args, "set [name] [value]", n=2) + self.configuration.set_value(key, value) + + self._save_configuration() + + def unset_name(self, options: Values, args: List[str]) -> None: + key = self._get_n_args(args, "unset [name]", n=1) + self.configuration.unset_value(key) + + self._save_configuration() + + def list_config_values(self, options: Values, args: List[str]) -> None: + """List config key-value pairs across different config files""" + self._get_n_args(args, "debug", n=0) + + self.print_env_var_values() + # Iterate over config files and print if they exist, and the + # key-value pairs present in them if they do + for variant, files in sorted(self.configuration.iter_config_files()): + write_output("%s:", variant) + for fname in files: + with indent_log(): + file_exists = os.path.exists(fname) + write_output("%s, exists: %r", fname, file_exists) + if file_exists: + self.print_config_file_values(variant) + + def print_config_file_values(self, variant: Kind) -> None: + """Get key-value pairs from the file of a variant""" + for name, value in self.configuration.get_values_in_config(variant).items(): + with indent_log(): + write_output("%s: %s", name, value) + + def print_env_var_values(self) -> None: + """Get key-values pairs present as environment variables""" + write_output("%s:", "env_var") + with indent_log(): + for key, value in sorted(self.configuration.get_environ_vars()): + env_var = f"PIP_{key.upper()}" + write_output("%s=%r", env_var, value) + + def open_in_editor(self, options: Values, args: List[str]) -> None: + editor = self._determine_editor(options) + + fname = self.configuration.get_file_to_edit() + if fname is None: + raise PipError("Could not determine appropriate file.") + elif '"' in fname: + # This shouldn't happen, unless we see a username like that. + # If that happens, we'd appreciate a pull request fixing this. + raise PipError( + f'Can not open an editor for a file name containing "\n{fname}' + ) + + try: + subprocess.check_call(f'{editor} "{fname}"', shell=True) + except FileNotFoundError as e: + if not e.filename: + e.filename = editor + raise + except subprocess.CalledProcessError as e: + raise PipError( + "Editor Subprocess exited with exit code {}".format(e.returncode) + ) + + def _get_n_args(self, args: List[str], example: str, n: int) -> Any: + """Helper to make sure the command got the right number of arguments""" + if len(args) != n: + msg = ( + "Got unexpected number of arguments, expected {}. " + '(example: "{} config {}")' + ).format(n, get_prog(), example) + raise PipError(msg) + + if n == 1: + return args[0] + else: + return args + + def _save_configuration(self) -> None: + # We successfully ran a modifying command. Need to save the + # configuration. + try: + self.configuration.save() + except Exception: + logger.exception( + "Unable to save configuration. Please report this as a bug." + ) + raise PipError("Internal Error.") + + def _determine_editor(self, options: Values) -> str: + if options.editor is not None: + return options.editor + elif "VISUAL" in os.environ: + return os.environ["VISUAL"] + elif "EDITOR" in os.environ: + return os.environ["EDITOR"] + else: + raise PipError("Could not determine editor to use.") diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/debug.py b/web/lib/python3.11/site-packages/pip/_internal/commands/debug.py new file mode 100644 index 00000000..6fad1fe8 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/debug.py @@ -0,0 +1,199 @@ +import importlib.resources +import locale +import logging +import os +import sys +from optparse import Values +from types import ModuleType +from typing import Any, Dict, List, Optional + +import pip._vendor +from pip._vendor.certifi import where +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.configuration import Configuration +from pip._internal.metadata import get_environment +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import get_pip_version + +logger = logging.getLogger(__name__) + + +def show_value(name: str, value: Any) -> None: + logger.info("%s: %s", name, value) + + +def show_sys_implementation() -> None: + logger.info("sys.implementation:") + implementation_name = sys.implementation.name + with indent_log(): + show_value("name", implementation_name) + + +def create_vendor_txt_map() -> Dict[str, str]: + with importlib.resources.open_text("pip._vendor", "vendor.txt") as f: + # Purge non version specifying lines. + # Also, remove any space prefix or suffixes (including comments). + lines = [ + line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line + ] + + # Transform into "module" -> version dict. + return dict(line.split("==", 1) for line in lines) + + +def get_module_from_module_name(module_name: str) -> ModuleType: + # Module name can be uppercase in vendor.txt for some reason... + module_name = module_name.lower() + # PATCH: setuptools is actually only pkg_resources. + if module_name == "setuptools": + module_name = "pkg_resources" + + __import__(f"pip._vendor.{module_name}", globals(), locals(), level=0) + return getattr(pip._vendor, module_name) + + +def get_vendor_version_from_module(module_name: str) -> Optional[str]: + module = get_module_from_module_name(module_name) + version = getattr(module, "__version__", None) + + if not version: + # Try to find version in debundled module info. + assert module.__file__ is not None + env = get_environment([os.path.dirname(module.__file__)]) + dist = env.get_distribution(module_name) + if dist: + version = str(dist.version) + + return version + + +def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None: + """Log the actual version and print extra info if there is + a conflict or if the actual version could not be imported. + """ + for module_name, expected_version in vendor_txt_versions.items(): + extra_message = "" + actual_version = get_vendor_version_from_module(module_name) + if not actual_version: + extra_message = ( + " (Unable to locate actual module version, using" + " vendor.txt specified version)" + ) + actual_version = expected_version + elif parse_version(actual_version) != parse_version(expected_version): + extra_message = ( + " (CONFLICT: vendor.txt suggests version should" + " be {})".format(expected_version) + ) + logger.info("%s==%s%s", module_name, actual_version, extra_message) + + +def show_vendor_versions() -> None: + logger.info("vendored library versions:") + + vendor_txt_versions = create_vendor_txt_map() + with indent_log(): + show_actual_vendor_versions(vendor_txt_versions) + + +def show_tags(options: Values) -> None: + tag_limit = 10 + + target_python = make_target_python(options) + tags = target_python.get_tags() + + # Display the target options that were explicitly provided. + formatted_target = target_python.format_given() + suffix = "" + if formatted_target: + suffix = f" (target: {formatted_target})" + + msg = "Compatible tags: {}{}".format(len(tags), suffix) + logger.info(msg) + + if options.verbose < 1 and len(tags) > tag_limit: + tags_limited = True + tags = tags[:tag_limit] + else: + tags_limited = False + + with indent_log(): + for tag in tags: + logger.info(str(tag)) + + if tags_limited: + msg = ( + "...\n[First {tag_limit} tags shown. Pass --verbose to show all.]" + ).format(tag_limit=tag_limit) + logger.info(msg) + + +def ca_bundle_info(config: Configuration) -> str: + levels = set() + for key, _ in config.items(): + levels.add(key.split(".")[0]) + + if not levels: + return "Not specified" + + levels_that_override_global = ["install", "wheel", "download"] + global_overriding_level = [ + level for level in levels if level in levels_that_override_global + ] + if not global_overriding_level: + return "global" + + if "global" in levels: + levels.remove("global") + return ", ".join(levels) + + +class DebugCommand(Command): + """ + Display debug information. + """ + + usage = """ + %prog """ + ignore_require_venv = True + + def add_options(self) -> None: + cmdoptions.add_target_python_options(self.cmd_opts) + self.parser.insert_option_group(0, self.cmd_opts) + self.parser.config.load() + + def run(self, options: Values, args: List[str]) -> int: + logger.warning( + "This command is only meant for debugging. " + "Do not use this with automation for parsing and getting these " + "details, since the output and options of this command may " + "change without notice." + ) + show_value("pip version", get_pip_version()) + show_value("sys.version", sys.version) + show_value("sys.executable", sys.executable) + show_value("sys.getdefaultencoding", sys.getdefaultencoding()) + show_value("sys.getfilesystemencoding", sys.getfilesystemencoding()) + show_value( + "locale.getpreferredencoding", + locale.getpreferredencoding(), + ) + show_value("sys.platform", sys.platform) + show_sys_implementation() + + show_value("'cert' config value", ca_bundle_info(self.parser.config)) + show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE")) + show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE")) + show_value("pip._vendor.certifi.where()", where()) + show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) + + show_vendor_versions() + + show_tags(options) + + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/download.py b/web/lib/python3.11/site-packages/pip/_internal/commands/download.py new file mode 100644 index 00000000..4132e089 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/download.py @@ -0,0 +1,149 @@ +import logging +import os +from optparse import Values +from typing import List + +from pip._internal.cli import cmdoptions +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.req_command import RequirementCommand, with_cleanup +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.req.req_install import ( + LegacySetupPyOptionsCheckMode, + check_legacy_setup_py_options, +) +from pip._internal.utils.misc import ensure_dir, normalize_path, write_output +from pip._internal.utils.temp_dir import TempDirectory + +logger = logging.getLogger(__name__) + + +class DownloadCommand(RequirementCommand): + """ + Download packages from: + + - PyPI (and other indexes) using requirement specifiers. + - VCS project urls. + - Local project directories. + - Local or remote source archives. + + pip also supports downloading from "requirements files", which provide + an easy way to specify a whole environment to be downloaded. + """ + + usage = """ + %prog [options] [package-index-options] ... + %prog [options] -r [package-index-options] ... + %prog [options] ... + %prog [options] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.global_options()) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.src()) + self.cmd_opts.add_option(cmdoptions.pre()) + self.cmd_opts.add_option(cmdoptions.require_hashes()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + + self.cmd_opts.add_option( + "-d", + "--dest", + "--destination-dir", + "--destination-directory", + dest="download_dir", + metavar="dir", + default=os.curdir, + help="Download packages into .", + ) + + cmdoptions.add_target_python_options(self.cmd_opts) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + + options.ignore_installed = True + # editable doesn't really make sense for `pip download`, but the bowels + # of the RequirementSet code require that property. + options.editables = [] + + cmdoptions.check_dist_restriction(options) + + options.download_dir = normalize_path(options.download_dir) + ensure_dir(options.download_dir) + + session = self.get_default_session(options) + + target_python = make_target_python(options) + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="download", + globally_managed=True, + ) + + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options( + options, reqs, LegacySetupPyOptionsCheckMode.DOWNLOAD + ) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + download_dir=options.download_dir, + use_user_site=False, + verbosity=self.verbosity, + ) + + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + ignore_requires_python=options.ignore_requires_python, + use_pep517=options.use_pep517, + py_version_info=options.python_version, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve(reqs, check_supported_wheels=True) + + downloaded: List[str] = [] + for req in requirement_set.requirements.values(): + if req.satisfied_by is None: + assert req.name is not None + preparer.save_linked_requirement(req) + downloaded.append(req.name) + if downloaded: + write_output("Successfully downloaded %s", " ".join(downloaded)) + + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/freeze.py b/web/lib/python3.11/site-packages/pip/_internal/commands/freeze.py new file mode 100644 index 00000000..5fa6d39b --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/freeze.py @@ -0,0 +1,97 @@ +import sys +from optparse import Values +from typing import List + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.operations.freeze import freeze +from pip._internal.utils.compat import stdlib_pkgs + +DEV_PKGS = {"pip", "setuptools", "distribute", "wheel"} + + +class FreezeCommand(Command): + """ + Output installed packages in requirements format. + + packages are listed in a case-insensitive sorted order. + """ + + usage = """ + %prog [options]""" + log_streams = ("ext://sys.stderr", "ext://sys.stderr") + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help=( + "Use the order in the given requirements file and its " + "comments when generating output. This option can be " + "used multiple times." + ), + ) + self.cmd_opts.add_option( + "-l", + "--local", + dest="local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not output " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.cmd_opts.add_option( + "--all", + dest="freeze_all", + action="store_true", + help=( + "Do not skip these packages in the output:" + " {}".format(", ".join(DEV_PKGS)) + ), + ) + self.cmd_opts.add_option( + "--exclude-editable", + dest="exclude_editable", + action="store_true", + help="Exclude editable package from output.", + ) + self.cmd_opts.add_option(cmdoptions.list_exclude()) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + skip = set(stdlib_pkgs) + if not options.freeze_all: + skip.update(DEV_PKGS) + + if options.excludes: + skip.update(options.excludes) + + cmdoptions.check_list_path_option(options) + + for line in freeze( + requirement=options.requirements, + local_only=options.local, + user_only=options.user, + paths=options.path, + isolated=options.isolated_mode, + skip=skip, + exclude_editable=options.exclude_editable, + ): + sys.stdout.write(line + "\n") + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/hash.py b/web/lib/python3.11/site-packages/pip/_internal/commands/hash.py new file mode 100644 index 00000000..042dac81 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/hash.py @@ -0,0 +1,59 @@ +import hashlib +import logging +import sys +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES +from pip._internal.utils.misc import read_chunks, write_output + +logger = logging.getLogger(__name__) + + +class HashCommand(Command): + """ + Compute a hash of a local package archive. + + These can be used with --hash in a requirements file to do repeatable + installs. + """ + + usage = "%prog [options] ..." + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-a", + "--algorithm", + dest="algorithm", + choices=STRONG_HASHES, + action="store", + default=FAVORITE_HASH, + help="The hash algorithm to use: one of {}".format( + ", ".join(STRONG_HASHES) + ), + ) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + self.parser.print_usage(sys.stderr) + return ERROR + + algorithm = options.algorithm + for path in args: + write_output( + "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm) + ) + return SUCCESS + + +def _hash_of_file(path: str, algorithm: str) -> str: + """Return the hash digest of a file.""" + with open(path, "rb") as archive: + hash = hashlib.new(algorithm) + for chunk in read_chunks(archive): + hash.update(chunk) + return hash.hexdigest() diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/help.py b/web/lib/python3.11/site-packages/pip/_internal/commands/help.py new file mode 100644 index 00000000..62066318 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/help.py @@ -0,0 +1,41 @@ +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError + + +class HelpCommand(Command): + """Show help for commands""" + + usage = """ + %prog """ + ignore_require_venv = True + + def run(self, options: Values, args: List[str]) -> int: + from pip._internal.commands import ( + commands_dict, + create_command, + get_similar_commands, + ) + + try: + # 'pip help' with no args is handled by pip.__init__.parseopt() + cmd_name = args[0] # the command we need help for + except IndexError: + return SUCCESS + + if cmd_name not in commands_dict: + guess = get_similar_commands(cmd_name) + + msg = [f'unknown command "{cmd_name}"'] + if guess: + msg.append(f'maybe you meant "{guess}"') + + raise CommandError(" - ".join(msg)) + + command = create_command(cmd_name) + command.parser.print_help() + + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/index.py b/web/lib/python3.11/site-packages/pip/_internal/commands/index.py new file mode 100644 index 00000000..b4bf0ac0 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/index.py @@ -0,0 +1,138 @@ +import logging +from optparse import Values +from typing import Any, Iterable, List, Optional, Union + +from pip._vendor.packaging.version import LegacyVersion, Version + +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import IndexGroupCommand +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.commands.search import print_dist_installation_info +from pip._internal.exceptions import CommandError, DistributionNotFound, PipError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.network.session import PipSession +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class IndexCommand(IndexGroupCommand): + """ + Inspect information available from package indexes. + """ + + usage = """ + %prog versions + """ + + def add_options(self) -> None: + cmdoptions.add_target_python_options(self.cmd_opts) + + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.pre()) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "versions": self.get_available_package_versions, + } + + logger.warning( + "pip index is currently an experimental command. " + "It may be removed/changed in a future release " + "without prior warning." + ) + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def _build_package_finder( + self, + options: Values, + session: PipSession, + target_python: Optional[TargetPython] = None, + ignore_requires_python: Optional[bool] = None, + ) -> PackageFinder: + """ + Create a package finder appropriate to the index command. + """ + link_collector = LinkCollector.create(session, options=options) + + # Pass allow_yanked=False to ignore yanked versions. + selection_prefs = SelectionPreferences( + allow_yanked=False, + allow_all_prereleases=options.pre, + ignore_requires_python=ignore_requires_python, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + target_python=target_python, + ) + + def get_available_package_versions(self, options: Values, args: List[Any]) -> None: + if len(args) != 1: + raise CommandError("You need to specify exactly one argument") + + target_python = cmdoptions.make_target_python(options) + query = args[0] + + with self._build_session(options) as session: + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + + versions: Iterable[Union[LegacyVersion, Version]] = ( + candidate.version for candidate in finder.find_all_candidates(query) + ) + + if not options.pre: + # Remove prereleases + versions = ( + version for version in versions if not version.is_prerelease + ) + versions = set(versions) + + if not versions: + raise DistributionNotFound( + "No matching distribution found for {}".format(query) + ) + + formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)] + latest = formatted_versions[0] + + write_output("{} ({})".format(query, latest)) + write_output("Available versions: {}".format(", ".join(formatted_versions))) + print_dist_installation_info(query, latest) diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/inspect.py b/web/lib/python3.11/site-packages/pip/_internal/commands/inspect.py new file mode 100644 index 00000000..a4e35993 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/inspect.py @@ -0,0 +1,97 @@ +import logging +from optparse import Values +from typing import Any, Dict, List + +from pip._vendor.packaging.markers import default_environment +from pip._vendor.rich import print_json + +from pip import __version__ +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.metadata import BaseDistribution, get_environment +from pip._internal.utils.compat import stdlib_pkgs +from pip._internal.utils.urls import path_to_url + +logger = logging.getLogger(__name__) + + +class InspectCommand(Command): + """ + Inspect the content of a Python environment and produce a report in JSON format. + """ + + ignore_require_venv = True + usage = """ + %prog [options]""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not list " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + logger.warning( + "pip inspect is currently an experimental command. " + "The output format may change in a future release without prior warning." + ) + + cmdoptions.check_list_path_option(options) + dists = get_environment(options.path).iter_installed_distributions( + local_only=options.local, + user_only=options.user, + skip=set(stdlib_pkgs), + ) + output = { + "version": "0", + "pip_version": __version__, + "installed": [self._dist_to_dict(dist) for dist in dists], + "environment": default_environment(), + # TODO tags? scheme? + } + print_json(data=output) + return SUCCESS + + def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]: + res: Dict[str, Any] = { + "metadata": dist.metadata_dict, + "metadata_location": dist.info_location, + } + # direct_url. Note that we don't have download_info (as in the installation + # report) since it is not recorded in installed metadata. + direct_url = dist.direct_url + if direct_url is not None: + res["direct_url"] = direct_url.to_dict() + else: + # Emulate direct_url for legacy editable installs. + editable_project_location = dist.editable_project_location + if editable_project_location is not None: + res["direct_url"] = { + "url": path_to_url(editable_project_location), + "dir_info": { + "editable": True, + }, + } + # installer + installer = dist.installer + if dist.installer: + res["installer"] = installer + # requested + if dist.installed_with_dist_info: + res["requested"] = dist.requested + return res diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/install.py b/web/lib/python3.11/site-packages/pip/_internal/commands/install.py new file mode 100644 index 00000000..e081c27d --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/install.py @@ -0,0 +1,860 @@ +import errno +import json +import operator +import os +import shutil +import site +from optparse import SUPPRESS_HELP, Values +from typing import Iterable, List, Optional + +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.rich import print_json + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.req_command import ( + RequirementCommand, + warn_if_run_as_root, + with_cleanup, +) +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.exceptions import CommandError, InstallationError +from pip._internal.locations import get_scheme +from pip._internal.metadata import get_environment +from pip._internal.models.format_control import FormatControl +from pip._internal.models.installation_report import InstallationReport +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.operations.check import ConflictDetails, check_install_conflicts +from pip._internal.req import install_given_reqs +from pip._internal.req.req_install import ( + InstallRequirement, + LegacySetupPyOptionsCheckMode, + check_legacy_setup_py_options, +) +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.deprecation import ( + LegacyInstallReasonFailedBdistWheel, + deprecated, +) +from pip._internal.utils.distutils_args import parse_distutils_args +from pip._internal.utils.filesystem import test_writable_dir +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import ( + ensure_dir, + get_pip_version, + protect_pip_from_modification_on_windows, + write_output, +) +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.utils.virtualenv import ( + running_under_virtualenv, + virtualenv_no_global, +) +from pip._internal.wheel_builder import ( + BdistWheelAllowedPredicate, + build, + should_build_for_install_command, +) + +logger = getLogger(__name__) + + +def get_check_bdist_wheel_allowed( + format_control: FormatControl, +) -> BdistWheelAllowedPredicate: + def check_binary_allowed(req: InstallRequirement) -> bool: + canonical_name = canonicalize_name(req.name or "") + allowed_formats = format_control.get_allowed_formats(canonical_name) + return "binary" in allowed_formats + + return check_binary_allowed + + +class InstallCommand(RequirementCommand): + """ + Install packages from: + + - PyPI (and other indexes) using requirement specifiers. + - VCS project urls. + - Local project directories. + - Local or remote source archives. + + pip also supports installing from "requirements files", which provide + an easy way to specify a whole environment to be installed. + """ + + usage = """ + %prog [options] [package-index-options] ... + %prog [options] -r [package-index-options] ... + %prog [options] [-e] ... + %prog [options] [-e] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.pre()) + + self.cmd_opts.add_option(cmdoptions.editable()) + self.cmd_opts.add_option( + "--dry-run", + action="store_true", + dest="dry_run", + default=False, + help=( + "Don't actually install anything, just print what would be. " + "Can be used in combination with --ignore-installed " + "to 'resolve' the requirements." + ), + ) + self.cmd_opts.add_option( + "-t", + "--target", + dest="target_dir", + metavar="dir", + default=None, + help=( + "Install packages into . " + "By default this will not replace existing files/folders in " + " . Use --upgrade to replace existing packages in " + "with new versions." + ), + ) + cmdoptions.add_target_python_options(self.cmd_opts) + + self.cmd_opts.add_option( + "--user", + dest="use_user_site", + action="store_true", + help=( + "Install to the Python user install directory for your " + "platform. Typically ~/.local/, or %APPDATA%\\Python on " + "Windows. (See the Python documentation for site.USER_BASE " + "for full details.)" + ), + ) + self.cmd_opts.add_option( + "--no-user", + dest="use_user_site", + action="store_false", + help=SUPPRESS_HELP, + ) + self.cmd_opts.add_option( + "--root", + dest="root_path", + metavar="dir", + default=None, + help="Install everything relative to this alternate root directory.", + ) + self.cmd_opts.add_option( + "--prefix", + dest="prefix_path", + metavar="dir", + default=None, + help=( + "Installation prefix where lib, bin and other top-level " + "folders are placed" + ), + ) + + self.cmd_opts.add_option(cmdoptions.src()) + + self.cmd_opts.add_option( + "-U", + "--upgrade", + dest="upgrade", + action="store_true", + help=( + "Upgrade all specified packages to the newest available " + "version. The handling of dependencies depends on the " + "upgrade-strategy used." + ), + ) + + self.cmd_opts.add_option( + "--upgrade-strategy", + dest="upgrade_strategy", + default="only-if-needed", + choices=["only-if-needed", "eager"], + help=( + "Determines how dependency upgrading should be handled " + "[default: %default]. " + '"eager" - dependencies are upgraded regardless of ' + "whether the currently installed version satisfies the " + "requirements of the upgraded package(s). " + '"only-if-needed" - are upgraded only when they do not ' + "satisfy the requirements of the upgraded package(s)." + ), + ) + + self.cmd_opts.add_option( + "--force-reinstall", + dest="force_reinstall", + action="store_true", + help="Reinstall all packages even if they are already up-to-date.", + ) + + self.cmd_opts.add_option( + "-I", + "--ignore-installed", + dest="ignore_installed", + action="store_true", + help=( + "Ignore the installed packages, overwriting them. " + "This can break your system if the existing package " + "is of a different version or was installed " + "with a different package manager!" + ), + ) + + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + + self.cmd_opts.add_option(cmdoptions.config_settings()) + self.cmd_opts.add_option(cmdoptions.install_options()) + self.cmd_opts.add_option(cmdoptions.global_options()) + + self.cmd_opts.add_option( + "--compile", + action="store_true", + dest="compile", + default=True, + help="Compile Python source files to bytecode", + ) + + self.cmd_opts.add_option( + "--no-compile", + action="store_false", + dest="compile", + help="Do not compile Python source files to bytecode", + ) + + self.cmd_opts.add_option( + "--no-warn-script-location", + action="store_false", + dest="warn_script_location", + default=True, + help="Do not warn when installing scripts outside PATH", + ) + self.cmd_opts.add_option( + "--no-warn-conflicts", + action="store_false", + dest="warn_about_conflicts", + default=True, + help="Do not warn about broken dependencies", + ) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.require_hashes()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + self.cmd_opts.add_option(cmdoptions.root_user_action()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + self.cmd_opts.add_option( + "--report", + dest="json_report_file", + metavar="file", + default=None, + help=( + "Generate a JSON file describing what pip did to install " + "the provided requirements. " + "Can be used in combination with --dry-run and --ignore-installed " + "to 'resolve' the requirements. " + "When - is used as file name it writes to stdout. " + "When writing to stdout, please combine with the --quiet option " + "to avoid mixing pip logging output with JSON output." + ), + ) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + if options.use_user_site and options.target_dir is not None: + raise CommandError("Can not combine '--user' and '--target'") + + upgrade_strategy = "to-satisfy-only" + if options.upgrade: + upgrade_strategy = options.upgrade_strategy + + cmdoptions.check_dist_restriction(options, check_target=True) + + install_options = options.install_options or [] + + logger.verbose("Using %s", get_pip_version()) + options.use_user_site = decide_user_install( + options.use_user_site, + prefix_path=options.prefix_path, + target_dir=options.target_dir, + root_path=options.root_path, + isolated_mode=options.isolated_mode, + ) + + target_temp_dir: Optional[TempDirectory] = None + target_temp_dir_path: Optional[str] = None + if options.target_dir: + options.ignore_installed = True + options.target_dir = os.path.abspath(options.target_dir) + if ( + # fmt: off + os.path.exists(options.target_dir) and + not os.path.isdir(options.target_dir) + # fmt: on + ): + raise CommandError( + "Target path exists but is not a directory, will not continue." + ) + + # Create a target directory for using with the target option + target_temp_dir = TempDirectory(kind="target") + target_temp_dir_path = target_temp_dir.path + self.enter_context(target_temp_dir) + + global_options = options.global_options or [] + + session = self.get_default_session(options) + + target_python = make_target_python(options) + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="install", + globally_managed=True, + ) + + try: + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options( + options, reqs, LegacySetupPyOptionsCheckMode.INSTALL + ) + + if "no-binary-enable-wheel-cache" in options.features_enabled: + # TODO: remove format_control from WheelCache when the deprecation cycle + # is over + wheel_cache = WheelCache(options.cache_dir) + else: + if options.format_control.no_binary: + deprecated( + reason=( + "--no-binary currently disables reading from " + "the cache of locally built wheels. In the future " + "--no-binary will not influence the wheel cache." + ), + replacement="to use the --no-cache-dir option", + feature_flag="no-binary-enable-wheel-cache", + issue=11453, + gone_in="23.1", + ) + wheel_cache = WheelCache(options.cache_dir, options.format_control) + + # Only when installing is it permitted to use PEP 660. + # In other circumstances (pip wheel, pip download) we generate + # regular (i.e. non editable) metadata and wheels. + for req in reqs: + req.permit_editable_wheels = True + + reject_location_related_install_options(reqs, options.install_options) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + use_user_site=options.use_user_site, + verbosity=self.verbosity, + ) + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + wheel_cache=wheel_cache, + use_user_site=options.use_user_site, + ignore_installed=options.ignore_installed, + ignore_requires_python=options.ignore_requires_python, + force_reinstall=options.force_reinstall, + upgrade_strategy=upgrade_strategy, + use_pep517=options.use_pep517, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve( + reqs, check_supported_wheels=not options.target_dir + ) + + if options.json_report_file: + logger.warning( + "--report is currently an experimental option. " + "The output format may change in a future release " + "without prior warning." + ) + + report = InstallationReport(requirement_set.requirements_to_install) + if options.json_report_file == "-": + print_json(data=report.to_dict()) + else: + with open(options.json_report_file, "w", encoding="utf-8") as f: + json.dump(report.to_dict(), f, indent=2, ensure_ascii=False) + + if options.dry_run: + would_install_items = sorted( + (r.metadata["name"], r.metadata["version"]) + for r in requirement_set.requirements_to_install + ) + if would_install_items: + write_output( + "Would install %s", + " ".join("-".join(item) for item in would_install_items), + ) + return SUCCESS + + try: + pip_req = requirement_set.get_requirement("pip") + except KeyError: + modifying_pip = False + else: + # If we're not replacing an already installed pip, + # we're not modifying it. + modifying_pip = pip_req.satisfied_by is None + protect_pip_from_modification_on_windows(modifying_pip=modifying_pip) + + check_bdist_wheel_allowed = get_check_bdist_wheel_allowed( + finder.format_control + ) + + reqs_to_build = [ + r + for r in requirement_set.requirements.values() + if should_build_for_install_command(r, check_bdist_wheel_allowed) + ] + + _, build_failures = build( + reqs_to_build, + wheel_cache=wheel_cache, + verify=True, + build_options=[], + global_options=global_options, + ) + + # If we're using PEP 517, we cannot do a legacy setup.py install + # so we fail here. + pep517_build_failure_names: List[str] = [ + r.name for r in build_failures if r.use_pep517 # type: ignore + ] + if pep517_build_failure_names: + raise InstallationError( + "Could not build wheels for {}, which is required to " + "install pyproject.toml-based projects".format( + ", ".join(pep517_build_failure_names) + ) + ) + + # For now, we just warn about failures building legacy + # requirements, as we'll fall through to a setup.py install for + # those. + for r in build_failures: + if not r.use_pep517: + r.legacy_install_reason = LegacyInstallReasonFailedBdistWheel + + to_install = resolver.get_installation_order(requirement_set) + + # Check for conflicts in the package set we're installing. + conflicts: Optional[ConflictDetails] = None + should_warn_about_conflicts = ( + not options.ignore_dependencies and options.warn_about_conflicts + ) + if should_warn_about_conflicts: + conflicts = self._determine_conflicts(to_install) + + # Don't warn about script install locations if + # --target or --prefix has been specified + warn_script_location = options.warn_script_location + if options.target_dir or options.prefix_path: + warn_script_location = False + + installed = install_given_reqs( + to_install, + install_options, + global_options, + root=options.root_path, + home=target_temp_dir_path, + prefix=options.prefix_path, + warn_script_location=warn_script_location, + use_user_site=options.use_user_site, + pycompile=options.compile, + ) + + lib_locations = get_lib_location_guesses( + user=options.use_user_site, + home=target_temp_dir_path, + root=options.root_path, + prefix=options.prefix_path, + isolated=options.isolated_mode, + ) + env = get_environment(lib_locations) + + installed.sort(key=operator.attrgetter("name")) + items = [] + for result in installed: + item = result.name + try: + installed_dist = env.get_distribution(item) + if installed_dist is not None: + item = f"{item}-{installed_dist.version}" + except Exception: + pass + items.append(item) + + if conflicts is not None: + self._warn_about_conflicts( + conflicts, + resolver_variant=self.determine_resolver_variant(options), + ) + + installed_desc = " ".join(items) + if installed_desc: + write_output( + "Successfully installed %s", + installed_desc, + ) + except OSError as error: + show_traceback = self.verbosity >= 1 + + message = create_os_error_message( + error, + show_traceback, + options.use_user_site, + ) + logger.error(message, exc_info=show_traceback) # noqa + + return ERROR + + if options.target_dir: + assert target_temp_dir + self._handle_target_dir( + options.target_dir, target_temp_dir, options.upgrade + ) + if options.root_user_action == "warn": + warn_if_run_as_root() + return SUCCESS + + def _handle_target_dir( + self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool + ) -> None: + ensure_dir(target_dir) + + # Checking both purelib and platlib directories for installed + # packages to be moved to target directory + lib_dir_list = [] + + # Checking both purelib and platlib directories for installed + # packages to be moved to target directory + scheme = get_scheme("", home=target_temp_dir.path) + purelib_dir = scheme.purelib + platlib_dir = scheme.platlib + data_dir = scheme.data + + if os.path.exists(purelib_dir): + lib_dir_list.append(purelib_dir) + if os.path.exists(platlib_dir) and platlib_dir != purelib_dir: + lib_dir_list.append(platlib_dir) + if os.path.exists(data_dir): + lib_dir_list.append(data_dir) + + for lib_dir in lib_dir_list: + for item in os.listdir(lib_dir): + if lib_dir == data_dir: + ddir = os.path.join(data_dir, item) + if any(s.startswith(ddir) for s in lib_dir_list[:-1]): + continue + target_item_dir = os.path.join(target_dir, item) + if os.path.exists(target_item_dir): + if not upgrade: + logger.warning( + "Target directory %s already exists. Specify " + "--upgrade to force replacement.", + target_item_dir, + ) + continue + if os.path.islink(target_item_dir): + logger.warning( + "Target directory %s already exists and is " + "a link. pip will not automatically replace " + "links, please remove if replacement is " + "desired.", + target_item_dir, + ) + continue + if os.path.isdir(target_item_dir): + shutil.rmtree(target_item_dir) + else: + os.remove(target_item_dir) + + shutil.move(os.path.join(lib_dir, item), target_item_dir) + + def _determine_conflicts( + self, to_install: List[InstallRequirement] + ) -> Optional[ConflictDetails]: + try: + return check_install_conflicts(to_install) + except Exception: + logger.exception( + "Error while checking for conflicts. Please file an issue on " + "pip's issue tracker: https://github.com/pypa/pip/issues/new" + ) + return None + + def _warn_about_conflicts( + self, conflict_details: ConflictDetails, resolver_variant: str + ) -> None: + package_set, (missing, conflicting) = conflict_details + if not missing and not conflicting: + return + + parts: List[str] = [] + if resolver_variant == "legacy": + parts.append( + "pip's legacy dependency resolver does not consider dependency " + "conflicts when selecting packages. This behaviour is the " + "source of the following dependency conflicts." + ) + else: + assert resolver_variant == "2020-resolver" + parts.append( + "pip's dependency resolver does not currently take into account " + "all the packages that are installed. This behaviour is the " + "source of the following dependency conflicts." + ) + + # NOTE: There is some duplication here, with commands/check.py + for project_name in missing: + version = package_set[project_name][0] + for dependency in missing[project_name]: + message = ( + "{name} {version} requires {requirement}, " + "which is not installed." + ).format( + name=project_name, + version=version, + requirement=dependency[1], + ) + parts.append(message) + + for project_name in conflicting: + version = package_set[project_name][0] + for dep_name, dep_version, req in conflicting[project_name]: + message = ( + "{name} {version} requires {requirement}, but {you} have " + "{dep_name} {dep_version} which is incompatible." + ).format( + name=project_name, + version=version, + requirement=req, + dep_name=dep_name, + dep_version=dep_version, + you=("you" if resolver_variant == "2020-resolver" else "you'll"), + ) + parts.append(message) + + logger.critical("\n".join(parts)) + + +def get_lib_location_guesses( + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + isolated: bool = False, + prefix: Optional[str] = None, +) -> List[str]: + scheme = get_scheme( + "", + user=user, + home=home, + root=root, + isolated=isolated, + prefix=prefix, + ) + return [scheme.purelib, scheme.platlib] + + +def site_packages_writable(root: Optional[str], isolated: bool) -> bool: + return all( + test_writable_dir(d) + for d in set(get_lib_location_guesses(root=root, isolated=isolated)) + ) + + +def decide_user_install( + use_user_site: Optional[bool], + prefix_path: Optional[str] = None, + target_dir: Optional[str] = None, + root_path: Optional[str] = None, + isolated_mode: bool = False, +) -> bool: + """Determine whether to do a user install based on the input options. + + If use_user_site is False, no additional checks are done. + If use_user_site is True, it is checked for compatibility with other + options. + If use_user_site is None, the default behaviour depends on the environment, + which is provided by the other arguments. + """ + # In some cases (config from tox), use_user_site can be set to an integer + # rather than a bool, which 'use_user_site is False' wouldn't catch. + if (use_user_site is not None) and (not use_user_site): + logger.debug("Non-user install by explicit request") + return False + + if use_user_site: + if prefix_path: + raise CommandError( + "Can not combine '--user' and '--prefix' as they imply " + "different installation locations" + ) + if virtualenv_no_global(): + raise InstallationError( + "Can not perform a '--user' install. User site-packages " + "are not visible in this virtualenv." + ) + logger.debug("User install by explicit request") + return True + + # If we are here, user installs have not been explicitly requested/avoided + assert use_user_site is None + + # user install incompatible with --prefix/--target + if prefix_path or target_dir: + logger.debug("Non-user install due to --prefix or --target option") + return False + + # If user installs are not enabled, choose a non-user install + if not site.ENABLE_USER_SITE: + logger.debug("Non-user install because user site-packages disabled") + return False + + # If we have permission for a non-user install, do that, + # otherwise do a user install. + if site_packages_writable(root=root_path, isolated=isolated_mode): + logger.debug("Non-user install because site-packages writeable") + return False + + logger.info( + "Defaulting to user installation because normal site-packages " + "is not writeable" + ) + return True + + +def reject_location_related_install_options( + requirements: List[InstallRequirement], options: Optional[List[str]] +) -> None: + """If any location-changing --install-option arguments were passed for + requirements or on the command-line, then show a deprecation warning. + """ + + def format_options(option_names: Iterable[str]) -> List[str]: + return ["--{}".format(name.replace("_", "-")) for name in option_names] + + offenders = [] + + for requirement in requirements: + install_options = requirement.install_options + location_options = parse_distutils_args(install_options) + if location_options: + offenders.append( + "{!r} from {}".format( + format_options(location_options.keys()), requirement + ) + ) + + if options: + location_options = parse_distutils_args(options) + if location_options: + offenders.append( + "{!r} from command line".format(format_options(location_options.keys())) + ) + + if not offenders: + return + + raise CommandError( + "Location-changing options found in --install-option: {}." + " This is unsupported, use pip-level options like --user," + " --prefix, --root, and --target instead.".format("; ".join(offenders)) + ) + + +def create_os_error_message( + error: OSError, show_traceback: bool, using_user_site: bool +) -> str: + """Format an error message for an OSError + + It may occur anytime during the execution of the install command. + """ + parts = [] + + # Mention the error if we are not going to show a traceback + parts.append("Could not install packages due to an OSError") + if not show_traceback: + parts.append(": ") + parts.append(str(error)) + else: + parts.append(".") + + # Spilt the error indication from a helper message (if any) + parts[-1] += "\n" + + # Suggest useful actions to the user: + # (1) using user site-packages or (2) verifying the permissions + if error.errno == errno.EACCES: + user_option_part = "Consider using the `--user` option" + permissions_part = "Check the permissions" + + if not running_under_virtualenv() and not using_user_site: + parts.extend( + [ + user_option_part, + " or ", + permissions_part.lower(), + ] + ) + else: + parts.append(permissions_part) + parts.append(".\n") + + # Suggest the user to enable Long Paths if path length is + # more than 260 + if ( + WINDOWS + and error.errno == errno.ENOENT + and error.filename + and len(error.filename) > 260 + ): + parts.append( + "HINT: This error might have occurred since " + "this system does not have Windows Long Path " + "support enabled. You can find information on " + "how to enable this at " + "https://pip.pypa.io/warnings/enable-long-paths\n" + ) + + return "".join(parts).strip() + "\n" diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/list.py b/web/lib/python3.11/site-packages/pip/_internal/commands/list.py new file mode 100644 index 00000000..8e1426db --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/list.py @@ -0,0 +1,365 @@ +import json +import logging +from optparse import Values +from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import IndexGroupCommand +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution, get_environment +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.network.session import PipSession +from pip._internal.utils.compat import stdlib_pkgs +from pip._internal.utils.misc import tabulate, write_output + +if TYPE_CHECKING: + from pip._internal.metadata.base import DistributionVersion + + class _DistWithLatestInfo(BaseDistribution): + """Give the distribution object a couple of extra fields. + + These will be populated during ``get_outdated()``. This is dirty but + makes the rest of the code much cleaner. + """ + + latest_version: DistributionVersion + latest_filetype: str + + _ProcessedDists = Sequence[_DistWithLatestInfo] + + +logger = logging.getLogger(__name__) + + +class ListCommand(IndexGroupCommand): + """ + List installed packages, including editables. + + Packages are listed in a case-insensitive sorted order. + """ + + ignore_require_venv = True + usage = """ + %prog [options]""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-o", + "--outdated", + action="store_true", + default=False, + help="List outdated packages", + ) + self.cmd_opts.add_option( + "-u", + "--uptodate", + action="store_true", + default=False, + help="List uptodate packages", + ) + self.cmd_opts.add_option( + "-e", + "--editable", + action="store_true", + default=False, + help="List editable projects.", + ) + self.cmd_opts.add_option( + "-l", + "--local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not list " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.cmd_opts.add_option( + "--pre", + action="store_true", + default=False, + help=( + "Include pre-release and development versions. By default, " + "pip only finds stable versions." + ), + ) + + self.cmd_opts.add_option( + "--format", + action="store", + dest="list_format", + default="columns", + choices=("columns", "freeze", "json"), + help="Select the output format among: columns (default), freeze, or json", + ) + + self.cmd_opts.add_option( + "--not-required", + action="store_true", + dest="not_required", + help="List packages that are not dependencies of installed packages.", + ) + + self.cmd_opts.add_option( + "--exclude-editable", + action="store_false", + dest="include_editable", + help="Exclude editable package from output.", + ) + self.cmd_opts.add_option( + "--include-editable", + action="store_true", + dest="include_editable", + help="Include editable package from output.", + default=True, + ) + self.cmd_opts.add_option(cmdoptions.list_exclude()) + index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + def _build_package_finder( + self, options: Values, session: PipSession + ) -> PackageFinder: + """ + Create a package finder appropriate to this list command. + """ + link_collector = LinkCollector.create(session, options=options) + + # Pass allow_yanked=False to ignore yanked versions. + selection_prefs = SelectionPreferences( + allow_yanked=False, + allow_all_prereleases=options.pre, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + ) + + def run(self, options: Values, args: List[str]) -> int: + if options.outdated and options.uptodate: + raise CommandError("Options --outdated and --uptodate cannot be combined.") + + if options.outdated and options.list_format == "freeze": + raise CommandError( + "List format 'freeze' can not be used with the --outdated option." + ) + + cmdoptions.check_list_path_option(options) + + skip = set(stdlib_pkgs) + if options.excludes: + skip.update(canonicalize_name(n) for n in options.excludes) + + packages: "_ProcessedDists" = [ + cast("_DistWithLatestInfo", d) + for d in get_environment(options.path).iter_installed_distributions( + local_only=options.local, + user_only=options.user, + editables_only=options.editable, + include_editables=options.include_editable, + skip=skip, + ) + ] + + # get_not_required must be called firstly in order to find and + # filter out all dependencies correctly. Otherwise a package + # can't be identified as requirement because some parent packages + # could be filtered out before. + if options.not_required: + packages = self.get_not_required(packages, options) + + if options.outdated: + packages = self.get_outdated(packages, options) + elif options.uptodate: + packages = self.get_uptodate(packages, options) + + self.output_package_listing(packages, options) + return SUCCESS + + def get_outdated( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + return [ + dist + for dist in self.iter_packages_latest_infos(packages, options) + if dist.latest_version > dist.version + ] + + def get_uptodate( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + return [ + dist + for dist in self.iter_packages_latest_infos(packages, options) + if dist.latest_version == dist.version + ] + + def get_not_required( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + dep_keys = { + canonicalize_name(dep.name) + for dist in packages + for dep in (dist.iter_dependencies() or ()) + } + + # Create a set to remove duplicate packages, and cast it to a list + # to keep the return type consistent with get_outdated and + # get_uptodate + return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys}) + + def iter_packages_latest_infos( + self, packages: "_ProcessedDists", options: Values + ) -> Generator["_DistWithLatestInfo", None, None]: + with self._build_session(options) as session: + finder = self._build_package_finder(options, session) + + def latest_info( + dist: "_DistWithLatestInfo", + ) -> Optional["_DistWithLatestInfo"]: + all_candidates = finder.find_all_candidates(dist.canonical_name) + if not options.pre: + # Remove prereleases + all_candidates = [ + candidate + for candidate in all_candidates + if not candidate.version.is_prerelease + ] + + evaluator = finder.make_candidate_evaluator( + project_name=dist.canonical_name, + ) + best_candidate = evaluator.sort_best_candidate(all_candidates) + if best_candidate is None: + return None + + remote_version = best_candidate.version + if best_candidate.link.is_wheel: + typ = "wheel" + else: + typ = "sdist" + dist.latest_version = remote_version + dist.latest_filetype = typ + return dist + + for dist in map(latest_info, packages): + if dist is not None: + yield dist + + def output_package_listing( + self, packages: "_ProcessedDists", options: Values + ) -> None: + packages = sorted( + packages, + key=lambda dist: dist.canonical_name, + ) + if options.list_format == "columns" and packages: + data, header = format_for_columns(packages, options) + self.output_package_listing_columns(data, header) + elif options.list_format == "freeze": + for dist in packages: + if options.verbose >= 1: + write_output( + "%s==%s (%s)", dist.raw_name, dist.version, dist.location + ) + else: + write_output("%s==%s", dist.raw_name, dist.version) + elif options.list_format == "json": + write_output(format_for_json(packages, options)) + + def output_package_listing_columns( + self, data: List[List[str]], header: List[str] + ) -> None: + # insert the header first: we need to know the size of column names + if len(data) > 0: + data.insert(0, header) + + pkg_strings, sizes = tabulate(data) + + # Create and add a separator. + if len(data) > 0: + pkg_strings.insert(1, " ".join(map(lambda x: "-" * x, sizes))) + + for val in pkg_strings: + write_output(val) + + +def format_for_columns( + pkgs: "_ProcessedDists", options: Values +) -> Tuple[List[List[str]], List[str]]: + """ + Convert the package data into something usable + by output_package_listing_columns. + """ + header = ["Package", "Version"] + + running_outdated = options.outdated + if running_outdated: + header.extend(["Latest", "Type"]) + + has_editables = any(x.editable for x in pkgs) + if has_editables: + header.append("Editable project location") + + if options.verbose >= 1: + header.append("Location") + if options.verbose >= 1: + header.append("Installer") + + data = [] + for proj in pkgs: + # if we're working on the 'outdated' list, separate out the + # latest_version and type + row = [proj.raw_name, str(proj.version)] + + if running_outdated: + row.append(str(proj.latest_version)) + row.append(proj.latest_filetype) + + if has_editables: + row.append(proj.editable_project_location or "") + + if options.verbose >= 1: + row.append(proj.location or "") + if options.verbose >= 1: + row.append(proj.installer) + + data.append(row) + + return data, header + + +def format_for_json(packages: "_ProcessedDists", options: Values) -> str: + data = [] + for dist in packages: + info = { + "name": dist.raw_name, + "version": str(dist.version), + } + if options.verbose >= 1: + info["location"] = dist.location or "" + info["installer"] = dist.installer + if options.outdated: + info["latest_version"] = str(dist.latest_version) + info["latest_filetype"] = dist.latest_filetype + editable_project_location = dist.editable_project_location + if editable_project_location: + info["editable_project_location"] = editable_project_location + data.append(info) + return json.dumps(data) diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/search.py b/web/lib/python3.11/site-packages/pip/_internal/commands/search.py new file mode 100644 index 00000000..03ed925b --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/search.py @@ -0,0 +1,174 @@ +import logging +import shutil +import sys +import textwrap +import xmlrpc.client +from collections import OrderedDict +from optparse import Values +from typing import TYPE_CHECKING, Dict, List, Optional + +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.cli.base_command import Command +from pip._internal.cli.req_command import SessionCommandMixin +from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.metadata import get_default_environment +from pip._internal.models.index import PyPI +from pip._internal.network.xmlrpc import PipXmlrpcTransport +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import write_output + +if TYPE_CHECKING: + from typing import TypedDict + + class TransformedHit(TypedDict): + name: str + summary: str + versions: List[str] + + +logger = logging.getLogger(__name__) + + +class SearchCommand(Command, SessionCommandMixin): + """Search for PyPI packages whose name or summary contains .""" + + usage = """ + %prog [options] """ + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-i", + "--index", + dest="index", + metavar="URL", + default=PyPI.pypi_url, + help="Base URL of Python Package Index (default %default)", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + raise CommandError("Missing required argument (search query).") + query = args + pypi_hits = self.search(query, options) + hits = transform_hits(pypi_hits) + + terminal_width = None + if sys.stdout.isatty(): + terminal_width = shutil.get_terminal_size()[0] + + print_results(hits, terminal_width=terminal_width) + if pypi_hits: + return SUCCESS + return NO_MATCHES_FOUND + + def search(self, query: List[str], options: Values) -> List[Dict[str, str]]: + index_url = options.index + + session = self.get_default_session(options) + + transport = PipXmlrpcTransport(index_url, session) + pypi = xmlrpc.client.ServerProxy(index_url, transport) + try: + hits = pypi.search({"name": query, "summary": query}, "or") + except xmlrpc.client.Fault as fault: + message = "XMLRPC request failed [code: {code}]\n{string}".format( + code=fault.faultCode, + string=fault.faultString, + ) + raise CommandError(message) + assert isinstance(hits, list) + return hits + + +def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]: + """ + The list from pypi is really a list of versions. We want a list of + packages with the list of versions stored inline. This converts the + list from pypi into one we can use. + """ + packages: Dict[str, "TransformedHit"] = OrderedDict() + for hit in hits: + name = hit["name"] + summary = hit["summary"] + version = hit["version"] + + if name not in packages.keys(): + packages[name] = { + "name": name, + "summary": summary, + "versions": [version], + } + else: + packages[name]["versions"].append(version) + + # if this is the highest version, replace summary and score + if version == highest_version(packages[name]["versions"]): + packages[name]["summary"] = summary + + return list(packages.values()) + + +def print_dist_installation_info(name: str, latest: str) -> None: + env = get_default_environment() + dist = env.get_distribution(name) + if dist is not None: + with indent_log(): + if dist.version == latest: + write_output("INSTALLED: %s (latest)", dist.version) + else: + write_output("INSTALLED: %s", dist.version) + if parse_version(latest).pre: + write_output( + "LATEST: %s (pre-release; install" + " with `pip install --pre`)", + latest, + ) + else: + write_output("LATEST: %s", latest) + + +def print_results( + hits: List["TransformedHit"], + name_column_width: Optional[int] = None, + terminal_width: Optional[int] = None, +) -> None: + if not hits: + return + if name_column_width is None: + name_column_width = ( + max( + [ + len(hit["name"]) + len(highest_version(hit.get("versions", ["-"]))) + for hit in hits + ] + ) + + 4 + ) + + for hit in hits: + name = hit["name"] + summary = hit["summary"] or "" + latest = highest_version(hit.get("versions", ["-"])) + if terminal_width is not None: + target_width = terminal_width - name_column_width - 5 + if target_width > 10: + # wrap and indent summary to fit terminal + summary_lines = textwrap.wrap(summary, target_width) + summary = ("\n" + " " * (name_column_width + 3)).join(summary_lines) + + name_latest = f"{name} ({latest})" + line = f"{name_latest:{name_column_width}} - {summary}" + try: + write_output(line) + print_dist_installation_info(name, latest) + except UnicodeEncodeError: + pass + + +def highest_version(versions: List[str]) -> str: + return max(versions, key=parse_version) diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/show.py b/web/lib/python3.11/site-packages/pip/_internal/commands/show.py new file mode 100644 index 00000000..212167c9 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/show.py @@ -0,0 +1,183 @@ +import logging +from optparse import Values +from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.metadata import BaseDistribution, get_default_environment +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class ShowCommand(Command): + """ + Show information about one or more installed packages. + + The output is in RFC-compliant mail header format. + """ + + usage = """ + %prog [options] ...""" + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-f", + "--files", + dest="files", + action="store_true", + default=False, + help="Show the full list of installed files for each package.", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + logger.warning("ERROR: Please provide a package name or names.") + return ERROR + query = args + + results = search_packages_info(query) + if not print_results( + results, list_files=options.files, verbose=options.verbose + ): + return ERROR + return SUCCESS + + +class _PackageInfo(NamedTuple): + name: str + version: str + location: str + requires: List[str] + required_by: List[str] + installer: str + metadata_version: str + classifiers: List[str] + summary: str + homepage: str + project_urls: List[str] + author: str + author_email: str + license: str + entry_points: List[str] + files: Optional[List[str]] + + +def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]: + """ + Gather details from installed distributions. Print distribution name, + version, location, and installed files. Installed files requires a + pip generated 'installed-files.txt' in the distributions '.egg-info' + directory. + """ + env = get_default_environment() + + installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()} + query_names = [canonicalize_name(name) for name in query] + missing = sorted( + [name for name, pkg in zip(query, query_names) if pkg not in installed] + ) + if missing: + logger.warning("Package(s) not found: %s", ", ".join(missing)) + + def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]: + return ( + dist.metadata["Name"] or "UNKNOWN" + for dist in installed.values() + if current_dist.canonical_name + in {canonicalize_name(d.name) for d in dist.iter_dependencies()} + ) + + for query_name in query_names: + try: + dist = installed[query_name] + except KeyError: + continue + + requires = sorted((req.name for req in dist.iter_dependencies()), key=str.lower) + required_by = sorted(_get_requiring_packages(dist), key=str.lower) + + try: + entry_points_text = dist.read_text("entry_points.txt") + entry_points = entry_points_text.splitlines(keepends=False) + except FileNotFoundError: + entry_points = [] + + files_iter = dist.iter_declared_entries() + if files_iter is None: + files: Optional[List[str]] = None + else: + files = sorted(files_iter) + + metadata = dist.metadata + + yield _PackageInfo( + name=dist.raw_name, + version=str(dist.version), + location=dist.location or "", + requires=requires, + required_by=required_by, + installer=dist.installer, + metadata_version=dist.metadata_version or "", + classifiers=metadata.get_all("Classifier", []), + summary=metadata.get("Summary", ""), + homepage=metadata.get("Home-page", ""), + project_urls=metadata.get_all("Project-URL", []), + author=metadata.get("Author", ""), + author_email=metadata.get("Author-email", ""), + license=metadata.get("License", ""), + entry_points=entry_points, + files=files, + ) + + +def print_results( + distributions: Iterable[_PackageInfo], + list_files: bool, + verbose: bool, +) -> bool: + """ + Print the information from installed distributions found. + """ + results_printed = False + for i, dist in enumerate(distributions): + results_printed = True + if i > 0: + write_output("---") + + write_output("Name: %s", dist.name) + write_output("Version: %s", dist.version) + write_output("Summary: %s", dist.summary) + write_output("Home-page: %s", dist.homepage) + write_output("Author: %s", dist.author) + write_output("Author-email: %s", dist.author_email) + write_output("License: %s", dist.license) + write_output("Location: %s", dist.location) + write_output("Requires: %s", ", ".join(dist.requires)) + write_output("Required-by: %s", ", ".join(dist.required_by)) + + if verbose: + write_output("Metadata-Version: %s", dist.metadata_version) + write_output("Installer: %s", dist.installer) + write_output("Classifiers:") + for classifier in dist.classifiers: + write_output(" %s", classifier) + write_output("Entry-points:") + for entry in dist.entry_points: + write_output(" %s", entry.strip()) + write_output("Project-URLs:") + for project_url in dist.project_urls: + write_output(" %s", project_url) + if list_files: + write_output("Files:") + if dist.files is None: + write_output("Cannot locate RECORD or installed-files.txt") + else: + for line in dist.files: + write_output(" %s", line.strip()) + return results_printed diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/uninstall.py b/web/lib/python3.11/site-packages/pip/_internal/commands/uninstall.py new file mode 100644 index 00000000..dea8077e --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/uninstall.py @@ -0,0 +1,106 @@ +import logging +from optparse import Values +from typing import List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.req_command import SessionCommandMixin, warn_if_run_as_root +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import InstallationError +from pip._internal.req import parse_requirements +from pip._internal.req.constructors import ( + install_req_from_line, + install_req_from_parsed_requirement, +) +from pip._internal.utils.misc import protect_pip_from_modification_on_windows + +logger = logging.getLogger(__name__) + + +class UninstallCommand(Command, SessionCommandMixin): + """ + Uninstall packages. + + pip is able to uninstall most installed packages. Known exceptions are: + + - Pure distutils packages installed with ``python setup.py install``, which + leave behind no metadata to determine what files were installed. + - Script wrappers installed by ``python setup.py develop``. + """ + + usage = """ + %prog [options] ... + %prog [options] -r ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help=( + "Uninstall all the packages listed in the given requirements " + "file. This option can be used multiple times." + ), + ) + self.cmd_opts.add_option( + "-y", + "--yes", + dest="yes", + action="store_true", + help="Don't ask for confirmation of uninstall deletions.", + ) + self.cmd_opts.add_option(cmdoptions.root_user_action()) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + session = self.get_default_session(options) + + reqs_to_uninstall = {} + for name in args: + req = install_req_from_line( + name, + isolated=options.isolated_mode, + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + else: + logger.warning( + "Invalid requirement: %r ignored -" + " the uninstall command expects named" + " requirements.", + name, + ) + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, options=options, session=session + ): + req = install_req_from_parsed_requirement( + parsed_req, isolated=options.isolated_mode + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + if not reqs_to_uninstall: + raise InstallationError( + f"You must give at least one requirement to {self.name} (see " + f'"pip help {self.name}")' + ) + + protect_pip_from_modification_on_windows( + modifying_pip="pip" in reqs_to_uninstall + ) + + for req in reqs_to_uninstall.values(): + uninstall_pathset = req.uninstall( + auto_confirm=options.yes, + verbose=self.verbosity > 0, + ) + if uninstall_pathset: + uninstall_pathset.commit() + if options.root_user_action == "warn": + warn_if_run_as_root() + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/commands/wheel.py b/web/lib/python3.11/site-packages/pip/_internal/commands/wheel.py new file mode 100644 index 00000000..1afbd562 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/commands/wheel.py @@ -0,0 +1,203 @@ +import logging +import os +import shutil +from optparse import Values +from typing import List + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import RequirementCommand, with_cleanup +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.req.req_install import ( + InstallRequirement, + LegacySetupPyOptionsCheckMode, + check_legacy_setup_py_options, +) +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.misc import ensure_dir, normalize_path +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.wheel_builder import build, should_build_for_wheel_command + +logger = logging.getLogger(__name__) + + +class WheelCommand(RequirementCommand): + """ + Build Wheel archives for your requirements and dependencies. + + Wheel is a built-package format, and offers the advantage of not + recompiling your software during every install. For more details, see the + wheel docs: https://wheel.readthedocs.io/en/latest/ + + 'pip wheel' uses the build system interface as described here: + https://pip.pypa.io/en/stable/reference/build-system/ + + """ + + usage = """ + %prog [options] ... + %prog [options] -r ... + %prog [options] [-e] ... + %prog [options] [-e] ... + %prog [options] ...""" + + def add_options(self) -> None: + + self.cmd_opts.add_option( + "-w", + "--wheel-dir", + dest="wheel_dir", + metavar="dir", + default=os.curdir, + help=( + "Build wheels into , where the default is the " + "current working directory." + ), + ) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.editable()) + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.src()) + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + + self.cmd_opts.add_option( + "--no-verify", + dest="no_verify", + action="store_true", + default=False, + help="Don't verify if built wheel is valid.", + ) + + self.cmd_opts.add_option(cmdoptions.config_settings()) + self.cmd_opts.add_option(cmdoptions.build_options()) + self.cmd_opts.add_option(cmdoptions.global_options()) + + self.cmd_opts.add_option( + "--pre", + action="store_true", + default=False, + help=( + "Include pre-release and development versions. By default, " + "pip only finds stable versions." + ), + ) + + self.cmd_opts.add_option(cmdoptions.require_hashes()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + session = self.get_default_session(options) + + finder = self._build_package_finder(options, session) + wheel_cache = WheelCache(options.cache_dir, options.format_control) + + options.wheel_dir = normalize_path(options.wheel_dir) + ensure_dir(options.wheel_dir) + + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="wheel", + globally_managed=True, + ) + + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options( + options, reqs, LegacySetupPyOptionsCheckMode.WHEEL + ) + + if "no-binary-enable-wheel-cache" in options.features_enabled: + # TODO: remove format_control from WheelCache when the deprecation cycle + # is over + wheel_cache = WheelCache(options.cache_dir) + else: + if options.format_control.no_binary: + deprecated( + reason=( + "--no-binary currently disables reading from " + "the cache of locally built wheels. In the future " + "--no-binary will not influence the wheel cache." + ), + replacement="to use the --no-cache-dir option", + feature_flag="no-binary-enable-wheel-cache", + issue=11453, + gone_in="23.1", + ) + wheel_cache = WheelCache(options.cache_dir, options.format_control) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + download_dir=options.wheel_dir, + use_user_site=False, + verbosity=self.verbosity, + ) + + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + wheel_cache=wheel_cache, + ignore_requires_python=options.ignore_requires_python, + use_pep517=options.use_pep517, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve(reqs, check_supported_wheels=True) + + reqs_to_build: List[InstallRequirement] = [] + for req in requirement_set.requirements.values(): + if req.is_wheel: + preparer.save_linked_requirement(req) + elif should_build_for_wheel_command(req): + reqs_to_build.append(req) + + # build wheels + build_successes, build_failures = build( + reqs_to_build, + wheel_cache=wheel_cache, + verify=(not options.no_verify), + build_options=options.build_options or [], + global_options=options.global_options or [], + ) + for req in build_successes: + assert req.link and req.link.is_wheel + assert req.local_file_path + # copy from cache to target directory + try: + shutil.copy(req.local_file_path, options.wheel_dir) + except OSError as e: + logger.warning( + "Building wheel for %s failed: %s", + req.name, + e, + ) + build_failures.append(req) + if len(build_failures) != 0: + raise CommandError("Failed to build one or more wheels") + + return SUCCESS diff --git a/web/lib/python3.11/site-packages/pip/_internal/configuration.py b/web/lib/python3.11/site-packages/pip/_internal/configuration.py new file mode 100644 index 00000000..8fd46c9b --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/configuration.py @@ -0,0 +1,374 @@ +"""Configuration management setup + +Some terminology: +- name + As written in config files. +- value + Value associated with a name +- key + Name combined with it's section (section.name) +- variant + A single word describing where the configuration key-value pair came from +""" + +import configparser +import locale +import os +import sys +from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple + +from pip._internal.exceptions import ( + ConfigurationError, + ConfigurationFileCouldNotBeLoaded, +) +from pip._internal.utils import appdirs +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import ensure_dir, enum + +RawConfigParser = configparser.RawConfigParser # Shorthand +Kind = NewType("Kind", str) + +CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf" +ENV_NAMES_IGNORED = "version", "help" + +# The kinds of configurations there are. +kinds = enum( + USER="user", # User Specific + GLOBAL="global", # System Wide + SITE="site", # [Virtual] Environment Specific + ENV="env", # from PIP_CONFIG_FILE + ENV_VAR="env-var", # from Environment Variables +) +OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR +VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE + +logger = getLogger(__name__) + + +# NOTE: Maybe use the optionx attribute to normalize keynames. +def _normalize_name(name: str) -> str: + """Make a name consistent regardless of source (environment or file)""" + name = name.lower().replace("_", "-") + if name.startswith("--"): + name = name[2:] # only prefer long opts + return name + + +def _disassemble_key(name: str) -> List[str]: + if "." not in name: + error_message = ( + "Key does not contain dot separated section and key. " + "Perhaps you wanted to use 'global.{}' instead?" + ).format(name) + raise ConfigurationError(error_message) + return name.split(".", 1) + + +def get_configuration_files() -> Dict[Kind, List[str]]: + global_config_files = [ + os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip") + ] + + site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME) + legacy_config_file = os.path.join( + os.path.expanduser("~"), + "pip" if WINDOWS else ".pip", + CONFIG_BASENAME, + ) + new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME) + return { + kinds.GLOBAL: global_config_files, + kinds.SITE: [site_config_file], + kinds.USER: [legacy_config_file, new_config_file], + } + + +class Configuration: + """Handles management of configuration. + + Provides an interface to accessing and managing configuration files. + + This class converts provides an API that takes "section.key-name" style + keys and stores the value associated with it as "key-name" under the + section "section". + + This allows for a clean interface wherein the both the section and the + key-name are preserved in an easy to manage form in the configuration files + and the data stored is also nice. + """ + + def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None: + super().__init__() + + if load_only is not None and load_only not in VALID_LOAD_ONLY: + raise ConfigurationError( + "Got invalid value for load_only - should be one of {}".format( + ", ".join(map(repr, VALID_LOAD_ONLY)) + ) + ) + self.isolated = isolated + self.load_only = load_only + + # Because we keep track of where we got the data from + self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = { + variant: [] for variant in OVERRIDE_ORDER + } + self._config: Dict[Kind, Dict[str, Any]] = { + variant: {} for variant in OVERRIDE_ORDER + } + self._modified_parsers: List[Tuple[str, RawConfigParser]] = [] + + def load(self) -> None: + """Loads configuration from configuration files and environment""" + self._load_config_files() + if not self.isolated: + self._load_environment_vars() + + def get_file_to_edit(self) -> Optional[str]: + """Returns the file with highest priority in configuration""" + assert self.load_only is not None, "Need to be specified a file to be editing" + + try: + return self._get_parser_to_modify()[0] + except IndexError: + return None + + def items(self) -> Iterable[Tuple[str, Any]]: + """Returns key-value pairs like dict.items() representing the loaded + configuration + """ + return self._dictionary.items() + + def get_value(self, key: str) -> Any: + """Get a value from the configuration.""" + orig_key = key + key = _normalize_name(key) + try: + return self._dictionary[key] + except KeyError: + # disassembling triggers a more useful error message than simply + # "No such key" in the case that the key isn't in the form command.option + _disassemble_key(key) + raise ConfigurationError(f"No such key - {orig_key}") + + def set_value(self, key: str, value: Any) -> None: + """Modify a value in the configuration.""" + key = _normalize_name(key) + self._ensure_have_load_only() + + assert self.load_only + fname, parser = self._get_parser_to_modify() + + if parser is not None: + section, name = _disassemble_key(key) + + # Modify the parser and the configuration + if not parser.has_section(section): + parser.add_section(section) + parser.set(section, name, value) + + self._config[self.load_only][key] = value + self._mark_as_modified(fname, parser) + + def unset_value(self, key: str) -> None: + """Unset a value in the configuration.""" + orig_key = key + key = _normalize_name(key) + self._ensure_have_load_only() + + assert self.load_only + if key not in self._config[self.load_only]: + raise ConfigurationError(f"No such key - {orig_key}") + + fname, parser = self._get_parser_to_modify() + + if parser is not None: + section, name = _disassemble_key(key) + if not ( + parser.has_section(section) and parser.remove_option(section, name) + ): + # The option was not removed. + raise ConfigurationError( + "Fatal Internal error [id=1]. Please report as a bug." + ) + + # The section may be empty after the option was removed. + if not parser.items(section): + parser.remove_section(section) + self._mark_as_modified(fname, parser) + + del self._config[self.load_only][key] + + def save(self) -> None: + """Save the current in-memory state.""" + self._ensure_have_load_only() + + for fname, parser in self._modified_parsers: + logger.info("Writing to %s", fname) + + # Ensure directory exists. + ensure_dir(os.path.dirname(fname)) + + with open(fname, "w") as f: + parser.write(f) + + # + # Private routines + # + + def _ensure_have_load_only(self) -> None: + if self.load_only is None: + raise ConfigurationError("Needed a specific file to be modifying.") + logger.debug("Will be working with %s variant only", self.load_only) + + @property + def _dictionary(self) -> Dict[str, Any]: + """A dictionary representing the loaded configuration.""" + # NOTE: Dictionaries are not populated if not loaded. So, conditionals + # are not needed here. + retval = {} + + for variant in OVERRIDE_ORDER: + retval.update(self._config[variant]) + + return retval + + def _load_config_files(self) -> None: + """Loads configuration from configuration files""" + config_files = dict(self.iter_config_files()) + if config_files[kinds.ENV][0:1] == [os.devnull]: + logger.debug( + "Skipping loading configuration files due to " + "environment's PIP_CONFIG_FILE being os.devnull" + ) + return + + for variant, files in config_files.items(): + for fname in files: + # If there's specific variant set in `load_only`, load only + # that variant, not the others. + if self.load_only is not None and variant != self.load_only: + logger.debug("Skipping file '%s' (variant: %s)", fname, variant) + continue + + parser = self._load_file(variant, fname) + + # Keeping track of the parsers used + self._parsers[variant].append((fname, parser)) + + def _load_file(self, variant: Kind, fname: str) -> RawConfigParser: + logger.verbose("For variant '%s', will try loading '%s'", variant, fname) + parser = self._construct_parser(fname) + + for section in parser.sections(): + items = parser.items(section) + self._config[variant].update(self._normalized_keys(section, items)) + + return parser + + def _construct_parser(self, fname: str) -> RawConfigParser: + parser = configparser.RawConfigParser() + # If there is no such file, don't bother reading it but create the + # parser anyway, to hold the data. + # Doing this is useful when modifying and saving files, where we don't + # need to construct a parser. + if os.path.exists(fname): + locale_encoding = locale.getpreferredencoding(False) + try: + parser.read(fname, encoding=locale_encoding) + except UnicodeDecodeError: + # See https://github.com/pypa/pip/issues/4963 + raise ConfigurationFileCouldNotBeLoaded( + reason=f"contains invalid {locale_encoding} characters", + fname=fname, + ) + except configparser.Error as error: + # See https://github.com/pypa/pip/issues/4893 + raise ConfigurationFileCouldNotBeLoaded(error=error) + return parser + + def _load_environment_vars(self) -> None: + """Loads configuration from environment variables""" + self._config[kinds.ENV_VAR].update( + self._normalized_keys(":env:", self.get_environ_vars()) + ) + + def _normalized_keys( + self, section: str, items: Iterable[Tuple[str, Any]] + ) -> Dict[str, Any]: + """Normalizes items to construct a dictionary with normalized keys. + + This routine is where the names become keys and are made the same + regardless of source - configuration files or environment. + """ + normalized = {} + for name, val in items: + key = section + "." + _normalize_name(name) + normalized[key] = val + return normalized + + def get_environ_vars(self) -> Iterable[Tuple[str, str]]: + """Returns a generator with all environmental vars with prefix PIP_""" + for key, val in os.environ.items(): + if key.startswith("PIP_"): + name = key[4:].lower() + if name not in ENV_NAMES_IGNORED: + yield name, val + + # XXX: This is patched in the tests. + def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]: + """Yields variant and configuration files associated with it. + + This should be treated like items of a dictionary. + """ + # SMELL: Move the conditions out of this function + + # environment variables have the lowest priority + config_file = os.environ.get("PIP_CONFIG_FILE", None) + if config_file is not None: + yield kinds.ENV, [config_file] + else: + yield kinds.ENV, [] + + config_files = get_configuration_files() + + # at the base we have any global configuration + yield kinds.GLOBAL, config_files[kinds.GLOBAL] + + # per-user configuration next + should_load_user_config = not self.isolated and not ( + config_file and os.path.exists(config_file) + ) + if should_load_user_config: + # The legacy config file is overridden by the new config file + yield kinds.USER, config_files[kinds.USER] + + # finally virtualenv configuration first trumping others + yield kinds.SITE, config_files[kinds.SITE] + + def get_values_in_config(self, variant: Kind) -> Dict[str, Any]: + """Get values present in a config file""" + return self._config[variant] + + def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]: + # Determine which parser to modify + assert self.load_only + parsers = self._parsers[self.load_only] + if not parsers: + # This should not happen if everything works correctly. + raise ConfigurationError( + "Fatal Internal error [id=2]. Please report as a bug." + ) + + # Use the highest priority parser. + return parsers[-1] + + # XXX: This is patched in the tests. + def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None: + file_parser_tuple = (fname, parser) + if file_parser_tuple not in self._modified_parsers: + self._modified_parsers.append(file_parser_tuple) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self._dictionary!r})" diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__init__.py b/web/lib/python3.11/site-packages/pip/_internal/distributions/__init__.py new file mode 100644 index 00000000..9a89a838 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/distributions/__init__.py @@ -0,0 +1,21 @@ +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.distributions.sdist import SourceDistribution +from pip._internal.distributions.wheel import WheelDistribution +from pip._internal.req.req_install import InstallRequirement + + +def make_distribution_for_install_requirement( + install_req: InstallRequirement, +) -> AbstractDistribution: + """Returns a Distribution for the given InstallRequirement""" + # Editable requirements will always be source distributions. They use the + # legacy logic until we create a modern standard for them. + if install_req.editable: + return SourceDistribution(install_req) + + # If it's a wheel, it's a WheelDistribution + if install_req.is_wheel: + return WheelDistribution(install_req) + + # Otherwise, a SourceDistribution + return SourceDistribution(install_req) diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..91314fcf Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/base.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/base.cpython-311.pyc new file mode 100644 index 00000000..dfad2632 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/base.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-311.pyc new file mode 100644 index 00000000..cf3b5cb2 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-311.pyc new file mode 100644 index 00000000..45a7d7b3 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-311.pyc new file mode 100644 index 00000000..228faaa6 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/base.py b/web/lib/python3.11/site-packages/pip/_internal/distributions/base.py new file mode 100644 index 00000000..75ce2dc9 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/distributions/base.py @@ -0,0 +1,39 @@ +import abc + +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata.base import BaseDistribution +from pip._internal.req import InstallRequirement + + +class AbstractDistribution(metaclass=abc.ABCMeta): + """A base class for handling installable artifacts. + + The requirements for anything installable are as follows: + + - we must be able to determine the requirement name + (or we can't correctly handle the non-upgrade case). + + - for packages with setup requirements, we must also be able + to determine their requirements without installing additional + packages (for the same reason as run-time dependencies) + + - we must be able to create a Distribution object exposing the + above metadata. + """ + + def __init__(self, req: InstallRequirement) -> None: + super().__init__() + self.req = req + + @abc.abstractmethod + def get_metadata_distribution(self) -> BaseDistribution: + raise NotImplementedError() + + @abc.abstractmethod + def prepare_distribution_metadata( + self, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, + ) -> None: + raise NotImplementedError() diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/installed.py b/web/lib/python3.11/site-packages/pip/_internal/distributions/installed.py new file mode 100644 index 00000000..edb38aa1 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/distributions/installed.py @@ -0,0 +1,23 @@ +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution + + +class InstalledDistribution(AbstractDistribution): + """Represents an installed package. + + This does not need any preparation as the required information has already + been computed. + """ + + def get_metadata_distribution(self) -> BaseDistribution: + assert self.req.satisfied_by is not None, "not actually installed" + return self.req.satisfied_by + + def prepare_distribution_metadata( + self, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, + ) -> None: + pass diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/sdist.py b/web/lib/python3.11/site-packages/pip/_internal/distributions/sdist.py new file mode 100644 index 00000000..4c256479 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/distributions/sdist.py @@ -0,0 +1,150 @@ +import logging +from typing import Iterable, Set, Tuple + +from pip._internal.build_env import BuildEnvironment +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.exceptions import InstallationError +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution +from pip._internal.utils.subprocess import runner_with_spinner_message + +logger = logging.getLogger(__name__) + + +class SourceDistribution(AbstractDistribution): + """Represents a source distribution. + + The preparation step for these needs metadata for the packages to be + generated, either using PEP 517 or using the legacy `setup.py egg_info`. + """ + + def get_metadata_distribution(self) -> BaseDistribution: + return self.req.get_dist() + + def prepare_distribution_metadata( + self, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, + ) -> None: + # Load pyproject.toml, to determine whether PEP 517 is to be used + self.req.load_pyproject_toml() + + # Set up the build isolation, if this requirement should be isolated + should_isolate = self.req.use_pep517 and build_isolation + if should_isolate: + # Setup an isolated environment and install the build backend static + # requirements in it. + self._prepare_build_backend(finder) + # Check that if the requirement is editable, it either supports PEP 660 or + # has a setup.py or a setup.cfg. This cannot be done earlier because we need + # to setup the build backend to verify it supports build_editable, nor can + # it be done later, because we want to avoid installing build requirements + # needlessly. Doing it here also works around setuptools generating + # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory + # without setup.py nor setup.cfg. + self.req.isolated_editable_sanity_check() + # Install the dynamic build requirements. + self._install_build_reqs(finder) + # Check if the current environment provides build dependencies + should_check_deps = self.req.use_pep517 and check_build_deps + if should_check_deps: + pyproject_requires = self.req.pyproject_requires + assert pyproject_requires is not None + conflicting, missing = self.req.build_env.check_requirements( + pyproject_requires + ) + if conflicting: + self._raise_conflicts("the backend dependencies", conflicting) + if missing: + self._raise_missing_reqs(missing) + self.req.prepare_metadata() + + def _prepare_build_backend(self, finder: PackageFinder) -> None: + # Isolate in a BuildEnvironment and install the build-time + # requirements. + pyproject_requires = self.req.pyproject_requires + assert pyproject_requires is not None + + self.req.build_env = BuildEnvironment() + self.req.build_env.install_requirements( + finder, pyproject_requires, "overlay", kind="build dependencies" + ) + conflicting, missing = self.req.build_env.check_requirements( + self.req.requirements_to_check + ) + if conflicting: + self._raise_conflicts("PEP 517/518 supported requirements", conflicting) + if missing: + logger.warning( + "Missing build requirements in pyproject.toml for %s.", + self.req, + ) + logger.warning( + "The project does not specify a build backend, and " + "pip cannot fall back to setuptools without %s.", + " and ".join(map(repr, sorted(missing))), + ) + + def _get_build_requires_wheel(self) -> Iterable[str]: + with self.req.build_env: + runner = runner_with_spinner_message("Getting requirements to build wheel") + backend = self.req.pep517_backend + assert backend is not None + with backend.subprocess_runner(runner): + return backend.get_requires_for_build_wheel() + + def _get_build_requires_editable(self) -> Iterable[str]: + with self.req.build_env: + runner = runner_with_spinner_message( + "Getting requirements to build editable" + ) + backend = self.req.pep517_backend + assert backend is not None + with backend.subprocess_runner(runner): + return backend.get_requires_for_build_editable() + + def _install_build_reqs(self, finder: PackageFinder) -> None: + # Install any extra build dependencies that the backend requests. + # This must be done in a second pass, as the pyproject.toml + # dependencies must be installed before we can call the backend. + if ( + self.req.editable + and self.req.permit_editable_wheels + and self.req.supports_pyproject_editable() + ): + build_reqs = self._get_build_requires_editable() + else: + build_reqs = self._get_build_requires_wheel() + conflicting, missing = self.req.build_env.check_requirements(build_reqs) + if conflicting: + self._raise_conflicts("the backend dependencies", conflicting) + self.req.build_env.install_requirements( + finder, missing, "normal", kind="backend dependencies" + ) + + def _raise_conflicts( + self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]] + ) -> None: + format_string = ( + "Some build dependencies for {requirement} " + "conflict with {conflicting_with}: {description}." + ) + error_message = format_string.format( + requirement=self.req, + conflicting_with=conflicting_with, + description=", ".join( + f"{installed} is incompatible with {wanted}" + for installed, wanted in sorted(conflicting_reqs) + ), + ) + raise InstallationError(error_message) + + def _raise_missing_reqs(self, missing: Set[str]) -> None: + format_string = ( + "Some build dependencies for {requirement} are missing: {missing}." + ) + error_message = format_string.format( + requirement=self.req, missing=", ".join(map(repr, sorted(missing))) + ) + raise InstallationError(error_message) diff --git a/web/lib/python3.11/site-packages/pip/_internal/distributions/wheel.py b/web/lib/python3.11/site-packages/pip/_internal/distributions/wheel.py new file mode 100644 index 00000000..03aac775 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/distributions/wheel.py @@ -0,0 +1,34 @@ +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import ( + BaseDistribution, + FilesystemWheel, + get_wheel_distribution, +) + + +class WheelDistribution(AbstractDistribution): + """Represents a wheel distribution. + + This does not need any preparation as wheels can be directly unpacked. + """ + + def get_metadata_distribution(self) -> BaseDistribution: + """Loads the metadata from the wheel file into memory and returns a + Distribution that uses it, not relying on the wheel file or + requirement. + """ + assert self.req.local_file_path, "Set as part of preparation during download" + assert self.req.name, "Wheels are never unnamed" + wheel = FilesystemWheel(self.req.local_file_path) + return get_wheel_distribution(wheel, canonicalize_name(self.req.name)) + + def prepare_distribution_metadata( + self, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, + ) -> None: + pass diff --git a/web/lib/python3.11/site-packages/pip/_internal/exceptions.py b/web/lib/python3.11/site-packages/pip/_internal/exceptions.py new file mode 100644 index 00000000..2ab1f591 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/exceptions.py @@ -0,0 +1,660 @@ +"""Exceptions used throughout package. + +This module MUST NOT try to import from anything within `pip._internal` to +operate. This is expected to be importable from any/all files within the +subpackage and, thus, should not depend on them. +""" + +import configparser +import re +from itertools import chain, groupby, repeat +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +from pip._vendor.requests.models import Request, Response +from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult +from pip._vendor.rich.markup import escape +from pip._vendor.rich.text import Text + +if TYPE_CHECKING: + from hashlib import _Hash + from typing import Literal + + from pip._internal.metadata import BaseDistribution + from pip._internal.req.req_install import InstallRequirement + + +# +# Scaffolding +# +def _is_kebab_case(s: str) -> bool: + return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None + + +def _prefix_with_indent( + s: Union[Text, str], + console: Console, + *, + prefix: str, + indent: str, +) -> Text: + if isinstance(s, Text): + text = s + else: + text = console.render_str(s) + + return console.render_str(prefix, overflow="ignore") + console.render_str( + f"\n{indent}", overflow="ignore" + ).join(text.split(allow_blank=True)) + + +class PipError(Exception): + """The base pip error.""" + + +class DiagnosticPipError(PipError): + """An error, that presents diagnostic information to the user. + + This contains a bunch of logic, to enable pretty presentation of our error + messages. Each error gets a unique reference. Each error can also include + additional context, a hint and/or a note -- which are presented with the + main error message in a consistent style. + + This is adapted from the error output styling in `sphinx-theme-builder`. + """ + + reference: str + + def __init__( + self, + *, + kind: 'Literal["error", "warning"]' = "error", + reference: Optional[str] = None, + message: Union[str, Text], + context: Optional[Union[str, Text]], + hint_stmt: Optional[Union[str, Text]], + note_stmt: Optional[Union[str, Text]] = None, + link: Optional[str] = None, + ) -> None: + # Ensure a proper reference is provided. + if reference is None: + assert hasattr(self, "reference"), "error reference not provided!" + reference = self.reference + assert _is_kebab_case(reference), "error reference must be kebab-case!" + + self.kind = kind + self.reference = reference + + self.message = message + self.context = context + + self.note_stmt = note_stmt + self.hint_stmt = hint_stmt + + self.link = link + + super().__init__(f"<{self.__class__.__name__}: {self.reference}>") + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__}(" + f"reference={self.reference!r}, " + f"message={self.message!r}, " + f"context={self.context!r}, " + f"note_stmt={self.note_stmt!r}, " + f"hint_stmt={self.hint_stmt!r}" + ")>" + ) + + def __rich_console__( + self, + console: Console, + options: ConsoleOptions, + ) -> RenderResult: + colour = "red" if self.kind == "error" else "yellow" + + yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]" + yield "" + + if not options.ascii_only: + # Present the main message, with relevant context indented. + if self.context is not None: + yield _prefix_with_indent( + self.message, + console, + prefix=f"[{colour}]×[/] ", + indent=f"[{colour}]│[/] ", + ) + yield _prefix_with_indent( + self.context, + console, + prefix=f"[{colour}]╰─>[/] ", + indent=f"[{colour}] [/] ", + ) + else: + yield _prefix_with_indent( + self.message, + console, + prefix="[red]×[/] ", + indent=" ", + ) + else: + yield self.message + if self.context is not None: + yield "" + yield self.context + + if self.note_stmt is not None or self.hint_stmt is not None: + yield "" + + if self.note_stmt is not None: + yield _prefix_with_indent( + self.note_stmt, + console, + prefix="[magenta bold]note[/]: ", + indent=" ", + ) + if self.hint_stmt is not None: + yield _prefix_with_indent( + self.hint_stmt, + console, + prefix="[cyan bold]hint[/]: ", + indent=" ", + ) + + if self.link is not None: + yield "" + yield f"Link: {self.link}" + + +# +# Actual Errors +# +class ConfigurationError(PipError): + """General exception in configuration""" + + +class InstallationError(PipError): + """General exception during installation""" + + +class UninstallationError(PipError): + """General exception during uninstallation""" + + +class MissingPyProjectBuildRequires(DiagnosticPipError): + """Raised when pyproject.toml has `build-system`, but no `build-system.requires`.""" + + reference = "missing-pyproject-build-system-requires" + + def __init__(self, *, package: str) -> None: + super().__init__( + message=f"Can not process {escape(package)}", + context=Text( + "This package has an invalid pyproject.toml file.\n" + "The [build-system] table is missing the mandatory `requires` key." + ), + note_stmt="This is an issue with the package mentioned above, not pip.", + hint_stmt=Text("See PEP 518 for the detailed specification."), + ) + + +class InvalidPyProjectBuildRequires(DiagnosticPipError): + """Raised when pyproject.toml an invalid `build-system.requires`.""" + + reference = "invalid-pyproject-build-system-requires" + + def __init__(self, *, package: str, reason: str) -> None: + super().__init__( + message=f"Can not process {escape(package)}", + context=Text( + "This package has an invalid `build-system.requires` key in " + f"pyproject.toml.\n{reason}" + ), + note_stmt="This is an issue with the package mentioned above, not pip.", + hint_stmt=Text("See PEP 518 for the detailed specification."), + ) + + +class NoneMetadataError(PipError): + """Raised when accessing a Distribution's "METADATA" or "PKG-INFO". + + This signifies an inconsistency, when the Distribution claims to have + the metadata file (if not, raise ``FileNotFoundError`` instead), but is + not actually able to produce its content. This may be due to permission + errors. + """ + + def __init__( + self, + dist: "BaseDistribution", + metadata_name: str, + ) -> None: + """ + :param dist: A Distribution object. + :param metadata_name: The name of the metadata being accessed + (can be "METADATA" or "PKG-INFO"). + """ + self.dist = dist + self.metadata_name = metadata_name + + def __str__(self) -> str: + # Use `dist` in the error message because its stringification + # includes more information, like the version and location. + return "None {} metadata found for distribution: {}".format( + self.metadata_name, + self.dist, + ) + + +class UserInstallationInvalid(InstallationError): + """A --user install is requested on an environment without user site.""" + + def __str__(self) -> str: + return "User base directory is not specified" + + +class InvalidSchemeCombination(InstallationError): + def __str__(self) -> str: + before = ", ".join(str(a) for a in self.args[:-1]) + return f"Cannot set {before} and {self.args[-1]} together" + + +class DistributionNotFound(InstallationError): + """Raised when a distribution cannot be found to satisfy a requirement""" + + +class RequirementsFileParseError(InstallationError): + """Raised when a general error occurs parsing a requirements file line.""" + + +class BestVersionAlreadyInstalled(PipError): + """Raised when the most up-to-date version of a package is already + installed.""" + + +class BadCommand(PipError): + """Raised when virtualenv or a command is not found""" + + +class CommandError(PipError): + """Raised when there is an error in command-line arguments""" + + +class PreviousBuildDirError(PipError): + """Raised when there's a previous conflicting build directory""" + + +class NetworkConnectionError(PipError): + """HTTP connection error""" + + def __init__( + self, + error_msg: str, + response: Optional[Response] = None, + request: Optional[Request] = None, + ) -> None: + """ + Initialize NetworkConnectionError with `request` and `response` + objects. + """ + self.response = response + self.request = request + self.error_msg = error_msg + if ( + self.response is not None + and not self.request + and hasattr(response, "request") + ): + self.request = self.response.request + super().__init__(error_msg, response, request) + + def __str__(self) -> str: + return str(self.error_msg) + + +class InvalidWheelFilename(InstallationError): + """Invalid wheel filename.""" + + +class UnsupportedWheel(InstallationError): + """Unsupported wheel.""" + + +class InvalidWheel(InstallationError): + """Invalid (e.g. corrupt) wheel.""" + + def __init__(self, location: str, name: str): + self.location = location + self.name = name + + def __str__(self) -> str: + return f"Wheel '{self.name}' located at {self.location} is invalid." + + +class MetadataInconsistent(InstallationError): + """Built metadata contains inconsistent information. + + This is raised when the metadata contains values (e.g. name and version) + that do not match the information previously obtained from sdist filename, + user-supplied ``#egg=`` value, or an install requirement name. + """ + + def __init__( + self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str + ) -> None: + self.ireq = ireq + self.field = field + self.f_val = f_val + self.m_val = m_val + + def __str__(self) -> str: + return ( + f"Requested {self.ireq} has inconsistent {self.field}: " + f"expected {self.f_val!r}, but metadata has {self.m_val!r}" + ) + + +class LegacyInstallFailure(DiagnosticPipError): + """Error occurred while executing `setup.py install`""" + + reference = "legacy-install-failure" + + def __init__(self, package_details: str) -> None: + super().__init__( + message="Encountered error while trying to install package.", + context=package_details, + hint_stmt="See above for output from the failure.", + note_stmt="This is an issue with the package mentioned above, not pip.", + ) + + +class InstallationSubprocessError(DiagnosticPipError, InstallationError): + """A subprocess call failed.""" + + reference = "subprocess-exited-with-error" + + def __init__( + self, + *, + command_description: str, + exit_code: int, + output_lines: Optional[List[str]], + ) -> None: + if output_lines is None: + output_prompt = Text("See above for output.") + else: + output_prompt = ( + Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n") + + Text("".join(output_lines)) + + Text.from_markup(R"[red]\[end of output][/]") + ) + + super().__init__( + message=( + f"[green]{escape(command_description)}[/] did not run successfully.\n" + f"exit code: {exit_code}" + ), + context=output_prompt, + hint_stmt=None, + note_stmt=( + "This error originates from a subprocess, and is likely not a " + "problem with pip." + ), + ) + + self.command_description = command_description + self.exit_code = exit_code + + def __str__(self) -> str: + return f"{self.command_description} exited with {self.exit_code}" + + +class MetadataGenerationFailed(InstallationSubprocessError, InstallationError): + reference = "metadata-generation-failed" + + def __init__( + self, + *, + package_details: str, + ) -> None: + super(InstallationSubprocessError, self).__init__( + message="Encountered error while generating package metadata.", + context=escape(package_details), + hint_stmt="See above for details.", + note_stmt="This is an issue with the package mentioned above, not pip.", + ) + + def __str__(self) -> str: + return "metadata generation failed" + + +class HashErrors(InstallationError): + """Multiple HashError instances rolled into one for reporting""" + + def __init__(self) -> None: + self.errors: List["HashError"] = [] + + def append(self, error: "HashError") -> None: + self.errors.append(error) + + def __str__(self) -> str: + lines = [] + self.errors.sort(key=lambda e: e.order) + for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__): + lines.append(cls.head) + lines.extend(e.body() for e in errors_of_cls) + if lines: + return "\n".join(lines) + return "" + + def __bool__(self) -> bool: + return bool(self.errors) + + +class HashError(InstallationError): + """ + A failure to verify a package against known-good hashes + + :cvar order: An int sorting hash exception classes by difficulty of + recovery (lower being harder), so the user doesn't bother fretting + about unpinned packages when he has deeper issues, like VCS + dependencies, to deal with. Also keeps error reports in a + deterministic order. + :cvar head: A section heading for display above potentially many + exceptions of this kind + :ivar req: The InstallRequirement that triggered this error. This is + pasted on after the exception is instantiated, because it's not + typically available earlier. + + """ + + req: Optional["InstallRequirement"] = None + head = "" + order: int = -1 + + def body(self) -> str: + """Return a summary of me for display under the heading. + + This default implementation simply prints a description of the + triggering requirement. + + :param req: The InstallRequirement that provoked this error, with + its link already populated by the resolver's _populate_link(). + + """ + return f" {self._requirement_name()}" + + def __str__(self) -> str: + return f"{self.head}\n{self.body()}" + + def _requirement_name(self) -> str: + """Return a description of the requirement that triggered me. + + This default implementation returns long description of the req, with + line numbers + + """ + return str(self.req) if self.req else "unknown package" + + +class VcsHashUnsupported(HashError): + """A hash was provided for a version-control-system-based requirement, but + we don't have a method for hashing those.""" + + order = 0 + head = ( + "Can't verify hashes for these requirements because we don't " + "have a way to hash version control repositories:" + ) + + +class DirectoryUrlHashUnsupported(HashError): + """A hash was provided for a version-control-system-based requirement, but + we don't have a method for hashing those.""" + + order = 1 + head = ( + "Can't verify hashes for these file:// requirements because they " + "point to directories:" + ) + + +class HashMissing(HashError): + """A hash was needed for a requirement but is absent.""" + + order = 2 + head = ( + "Hashes are required in --require-hashes mode, but they are " + "missing from some requirements. Here is a list of those " + "requirements along with the hashes their downloaded archives " + "actually had. Add lines like these to your requirements files to " + "prevent tampering. (If you did not enable --require-hashes " + "manually, note that it turns on automatically when any package " + "has a hash.)" + ) + + def __init__(self, gotten_hash: str) -> None: + """ + :param gotten_hash: The hash of the (possibly malicious) archive we + just downloaded + """ + self.gotten_hash = gotten_hash + + def body(self) -> str: + # Dodge circular import. + from pip._internal.utils.hashes import FAVORITE_HASH + + package = None + if self.req: + # In the case of URL-based requirements, display the original URL + # seen in the requirements file rather than the package name, + # so the output can be directly copied into the requirements file. + package = ( + self.req.original_link + if self.req.original_link + # In case someone feeds something downright stupid + # to InstallRequirement's constructor. + else getattr(self.req, "req", None) + ) + return " {} --hash={}:{}".format( + package or "unknown package", FAVORITE_HASH, self.gotten_hash + ) + + +class HashUnpinned(HashError): + """A requirement had a hash specified but was not pinned to a specific + version.""" + + order = 3 + head = ( + "In --require-hashes mode, all requirements must have their " + "versions pinned with ==. These do not:" + ) + + +class HashMismatch(HashError): + """ + Distribution file hash values don't match. + + :ivar package_name: The name of the package that triggered the hash + mismatch. Feel free to write to this after the exception is raise to + improve its error message. + + """ + + order = 4 + head = ( + "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS " + "FILE. If you have updated the package versions, please update " + "the hashes. Otherwise, examine the package contents carefully; " + "someone may have tampered with them." + ) + + def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None: + """ + :param allowed: A dict of algorithm names pointing to lists of allowed + hex digests + :param gots: A dict of algorithm names pointing to hashes we + actually got from the files under suspicion + """ + self.allowed = allowed + self.gots = gots + + def body(self) -> str: + return " {}:\n{}".format(self._requirement_name(), self._hash_comparison()) + + def _hash_comparison(self) -> str: + """ + Return a comparison of actual and expected hash values. + + Example:: + + Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde + or 123451234512345123451234512345123451234512345 + Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef + + """ + + def hash_then_or(hash_name: str) -> "chain[str]": + # For now, all the decent hashes have 6-char names, so we can get + # away with hard-coding space literals. + return chain([hash_name], repeat(" or")) + + lines: List[str] = [] + for hash_name, expecteds in self.allowed.items(): + prefix = hash_then_or(hash_name) + lines.extend( + (" Expected {} {}".format(next(prefix), e)) for e in expecteds + ) + lines.append( + " Got {}\n".format(self.gots[hash_name].hexdigest()) + ) + return "\n".join(lines) + + +class UnsupportedPythonVersion(InstallationError): + """Unsupported python version according to Requires-Python package + metadata.""" + + +class ConfigurationFileCouldNotBeLoaded(ConfigurationError): + """When there are errors while loading a configuration file""" + + def __init__( + self, + reason: str = "could not be loaded", + fname: Optional[str] = None, + error: Optional[configparser.Error] = None, + ) -> None: + super().__init__(error) + self.reason = reason + self.fname = fname + self.error = error + + def __str__(self) -> str: + if self.fname is not None: + message_part = f" in {self.fname}." + else: + assert self.error is not None + message_part = f".\n{self.error}\n" + return f"Configuration file {self.reason}{message_part}" diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/__init__.py b/web/lib/python3.11/site-packages/pip/_internal/index/__init__.py new file mode 100644 index 00000000..7a17b7b3 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/index/__init__.py @@ -0,0 +1,2 @@ +"""Index interaction code +""" diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/__init__.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 00000000..8585a50c Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/__init__.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/collector.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/collector.cpython-311.pyc new file mode 100644 index 00000000..6a1d650a Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/collector.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-311.pyc new file mode 100644 index 00000000..1ae0dc50 Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/sources.cpython-311.pyc b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/sources.cpython-311.pyc new file mode 100644 index 00000000..846a101a Binary files /dev/null and b/web/lib/python3.11/site-packages/pip/_internal/index/__pycache__/sources.cpython-311.pyc differ diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/collector.py b/web/lib/python3.11/site-packages/pip/_internal/index/collector.py new file mode 100644 index 00000000..0120610c --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/index/collector.py @@ -0,0 +1,505 @@ +""" +The main purpose of this module is to expose LinkCollector.collect_sources(). +""" + +import collections +import email.message +import functools +import itertools +import json +import logging +import os +import urllib.parse +import urllib.request +from html.parser import HTMLParser +from optparse import Values +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + Iterable, + List, + MutableMapping, + NamedTuple, + Optional, + Sequence, + Tuple, + Union, +) + +from pip._vendor import requests +from pip._vendor.requests import Response +from pip._vendor.requests.exceptions import RetryError, SSLError + +from pip._internal.exceptions import NetworkConnectionError +from pip._internal.models.link import Link +from pip._internal.models.search_scope import SearchScope +from pip._internal.network.session import PipSession +from pip._internal.network.utils import raise_for_status +from pip._internal.utils.filetypes import is_archive_file +from pip._internal.utils.misc import redact_auth_from_url +from pip._internal.vcs import vcs + +from .sources import CandidatesFromPage, LinkSource, build_source + +if TYPE_CHECKING: + from typing import Protocol +else: + Protocol = object + +logger = logging.getLogger(__name__) + +ResponseHeaders = MutableMapping[str, str] + + +def _match_vcs_scheme(url: str) -> Optional[str]: + """Look for VCS schemes in the URL. + + Returns the matched VCS scheme, or None if there's no match. + """ + for scheme in vcs.schemes: + if url.lower().startswith(scheme) and url[len(scheme)] in "+:": + return scheme + return None + + +class _NotAPIContent(Exception): + def __init__(self, content_type: str, request_desc: str) -> None: + super().__init__(content_type, request_desc) + self.content_type = content_type + self.request_desc = request_desc + + +def _ensure_api_header(response: Response) -> None: + """ + Check the Content-Type header to ensure the response contains a Simple + API Response. + + Raises `_NotAPIContent` if the content type is not a valid content-type. + """ + content_type = response.headers.get("Content-Type", "Unknown") + + content_type_l = content_type.lower() + if content_type_l.startswith( + ( + "text/html", + "application/vnd.pypi.simple.v1+html", + "application/vnd.pypi.simple.v1+json", + ) + ): + return + + raise _NotAPIContent(content_type, response.request.method) + + +class _NotHTTP(Exception): + pass + + +def _ensure_api_response(url: str, session: PipSession) -> None: + """ + Send a HEAD request to the URL, and ensure the response contains a simple + API Response. + + Raises `_NotHTTP` if the URL is not available for a HEAD request, or + `_NotAPIContent` if the content type is not a valid content type. + """ + scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) + if scheme not in {"http", "https"}: + raise _NotHTTP() + + resp = session.head(url, allow_redirects=True) + raise_for_status(resp) + + _ensure_api_header(resp) + + +def _get_simple_response(url: str, session: PipSession) -> Response: + """Access an Simple API response with GET, and return the response. + + This consists of three parts: + + 1. If the URL looks suspiciously like an archive, send a HEAD first to + check the Content-Type is HTML or Simple API, to avoid downloading a + large file. Raise `_NotHTTP` if the content type cannot be determined, or + `_NotAPIContent` if it is not HTML or a Simple API. + 2. Actually perform the request. Raise HTTP exceptions on network failures. + 3. Check the Content-Type header to make sure we got a Simple API response, + and raise `_NotAPIContent` otherwise. + """ + if is_archive_file(Link(url).filename): + _ensure_api_response(url, session=session) + + logger.debug("Getting page %s", redact_auth_from_url(url)) + + resp = session.get( + url, + headers={ + "Accept": ", ".join( + [ + "application/vnd.pypi.simple.v1+json", + "application/vnd.pypi.simple.v1+html; q=0.1", + "text/html; q=0.01", + ] + ), + # We don't want to blindly returned cached data for + # /simple/, because authors generally expecting that + # twine upload && pip install will function, but if + # they've done a pip install in the last ~10 minutes + # it won't. Thus by setting this to zero we will not + # blindly use any cached data, however the benefit of + # using max-age=0 instead of no-cache, is that we will + # still support conditional requests, so we will still + # minimize traffic sent in cases where the page hasn't + # changed at all, we will just always incur the round + # trip for the conditional GET now instead of only + # once per 10 minutes. + # For more information, please see pypa/pip#5670. + "Cache-Control": "max-age=0", + }, + ) + raise_for_status(resp) + + # The check for archives above only works if the url ends with + # something that looks like an archive. However that is not a + # requirement of an url. Unless we issue a HEAD request on every + # url we cannot know ahead of time for sure if something is a + # Simple API response or not. However we can check after we've + # downloaded it. + _ensure_api_header(resp) + + logger.debug( + "Fetched page %s as %s", + redact_auth_from_url(url), + resp.headers.get("Content-Type", "Unknown"), + ) + + return resp + + +def _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]: + """Determine if we have any encoding information in our headers.""" + if headers and "Content-Type" in headers: + m = email.message.Message() + m["content-type"] = headers["Content-Type"] + charset = m.get_param("charset") + if charset: + return str(charset) + return None + + +class CacheablePageContent: + def __init__(self, page: "IndexContent") -> None: + assert page.cache_link_parsing + self.page = page + + def __eq__(self, other: object) -> bool: + return isinstance(other, type(self)) and self.page.url == other.page.url + + def __hash__(self) -> int: + return hash(self.page.url) + + +class ParseLinks(Protocol): + def __call__(self, page: "IndexContent") -> Iterable[Link]: + ... + + +def with_cached_index_content(fn: ParseLinks) -> ParseLinks: + """ + Given a function that parses an Iterable[Link] from an IndexContent, cache the + function's result (keyed by CacheablePageContent), unless the IndexContent + `page` has `page.cache_link_parsing == False`. + """ + + @functools.lru_cache(maxsize=None) + def wrapper(cacheable_page: CacheablePageContent) -> List[Link]: + return list(fn(cacheable_page.page)) + + @functools.wraps(fn) + def wrapper_wrapper(page: "IndexContent") -> List[Link]: + if page.cache_link_parsing: + return wrapper(CacheablePageContent(page)) + return list(fn(page)) + + return wrapper_wrapper + + +@with_cached_index_content +def parse_links(page: "IndexContent") -> Iterable[Link]: + """ + Parse a Simple API's Index Content, and yield its anchor elements as Link objects. + """ + + content_type_l = page.content_type.lower() + if content_type_l.startswith("application/vnd.pypi.simple.v1+json"): + data = json.loads(page.content) + for file in data.get("files", []): + link = Link.from_json(file, page.url) + if link is None: + continue + yield link + return + + parser = HTMLLinkParser(page.url) + encoding = page.encoding or "utf-8" + parser.feed(page.content.decode(encoding)) + + url = page.url + base_url = parser.base_url or url + for anchor in parser.anchors: + link = Link.from_element(anchor, page_url=url, base_url=base_url) + if link is None: + continue + yield link + + +class IndexContent: + """Represents one response (or page), along with its URL""" + + def __init__( + self, + content: bytes, + content_type: str, + encoding: Optional[str], + url: str, + cache_link_parsing: bool = True, + ) -> None: + """ + :param encoding: the encoding to decode the given content. + :param url: the URL from which the HTML was downloaded. + :param cache_link_parsing: whether links parsed from this page's url + should be cached. PyPI index urls should + have this set to False, for example. + """ + self.content = content + self.content_type = content_type + self.encoding = encoding + self.url = url + self.cache_link_parsing = cache_link_parsing + + def __str__(self) -> str: + return redact_auth_from_url(self.url) + + +class HTMLLinkParser(HTMLParser): + """ + HTMLParser that keeps the first base HREF and a list of all anchor + elements' attributes. + """ + + def __init__(self, url: str) -> None: + super().__init__(convert_charrefs=True) + + self.url: str = url + self.base_url: Optional[str] = None + self.anchors: List[Dict[str, Optional[str]]] = [] + + def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: + if tag == "base" and self.base_url is None: + href = self.get_href(attrs) + if href is not None: + self.base_url = href + elif tag == "a": + self.anchors.append(dict(attrs)) + + def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]: + for name, value in attrs: + if name == "href": + return value + return None + + +def _handle_get_simple_fail( + link: Link, + reason: Union[str, Exception], + meth: Optional[Callable[..., None]] = None, +) -> None: + if meth is None: + meth = logger.debug + meth("Could not fetch URL %s: %s - skipping", link, reason) + + +def _make_index_content( + response: Response, cache_link_parsing: bool = True +) -> IndexContent: + encoding = _get_encoding_from_headers(response.headers) + return IndexContent( + response.content, + response.headers["Content-Type"], + encoding=encoding, + url=response.url, + cache_link_parsing=cache_link_parsing, + ) + + +def _get_index_content(link: Link, *, session: PipSession) -> Optional["IndexContent"]: + url = link.url.split("#", 1)[0] + + # Check for VCS schemes that do not support lookup as web pages. + vcs_scheme = _match_vcs_scheme(url) + if vcs_scheme: + logger.warning( + "Cannot look at %s URL %s because it does not support lookup as web pages.", + vcs_scheme, + link, + ) + return None + + # Tack index.html onto file:// URLs that point to directories + scheme, _, path, _, _, _ = urllib.parse.urlparse(url) + if scheme == "file" and os.path.isdir(urllib.request.url2pathname(path)): + # add trailing slash if not present so urljoin doesn't trim + # final segment + if not url.endswith("/"): + url += "/" + # TODO: In the future, it would be nice if pip supported PEP 691 + # style respones in the file:// URLs, however there's no + # standard file extension for application/vnd.pypi.simple.v1+json + # so we'll need to come up with something on our own. + url = urllib.parse.urljoin(url, "index.html") + logger.debug(" file: URL is directory, getting %s", url) + + try: + resp = _get_simple_response(url, session=session) + except _NotHTTP: + logger.warning( + "Skipping page %s because it looks like an archive, and cannot " + "be checked by a HTTP HEAD request.", + link, + ) + except _NotAPIContent as exc: + logger.warning( + "Skipping page %s because the %s request got Content-Type: %s. " + "The only supported Content-Types are application/vnd.pypi.simple.v1+json, " + "application/vnd.pypi.simple.v1+html, and text/html", + link, + exc.request_desc, + exc.content_type, + ) + except NetworkConnectionError as exc: + _handle_get_simple_fail(link, exc) + except RetryError as exc: + _handle_get_simple_fail(link, exc) + except SSLError as exc: + reason = "There was a problem confirming the ssl certificate: " + reason += str(exc) + _handle_get_simple_fail(link, reason, meth=logger.info) + except requests.ConnectionError as exc: + _handle_get_simple_fail(link, f"connection error: {exc}") + except requests.Timeout: + _handle_get_simple_fail(link, "timed out") + else: + return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing) + return None + + +class CollectedSources(NamedTuple): + find_links: Sequence[Optional[LinkSource]] + index_urls: Sequence[Optional[LinkSource]] + + +class LinkCollector: + + """ + Responsible for collecting Link objects from all configured locations, + making network requests as needed. + + The class's main method is its collect_sources() method. + """ + + def __init__( + self, + session: PipSession, + search_scope: SearchScope, + ) -> None: + self.search_scope = search_scope + self.session = session + + @classmethod + def create( + cls, + session: PipSession, + options: Values, + suppress_no_index: bool = False, + ) -> "LinkCollector": + """ + :param session: The Session to use to make requests. + :param suppress_no_index: Whether to ignore the --no-index option + when constructing the SearchScope object. + """ + index_urls = [options.index_url] + options.extra_index_urls + if options.no_index and not suppress_no_index: + logger.debug( + "Ignoring indexes: %s", + ",".join(redact_auth_from_url(url) for url in index_urls), + ) + index_urls = [] + + # Make sure find_links is a list before passing to create(). + find_links = options.find_links or [] + + search_scope = SearchScope.create( + find_links=find_links, + index_urls=index_urls, + no_index=options.no_index, + ) + link_collector = LinkCollector( + session=session, + search_scope=search_scope, + ) + return link_collector + + @property + def find_links(self) -> List[str]: + return self.search_scope.find_links + + def fetch_response(self, location: Link) -> Optional[IndexContent]: + """ + Fetch an HTML page containing package links. + """ + return _get_index_content(location, session=self.session) + + def collect_sources( + self, + project_name: str, + candidates_from_page: CandidatesFromPage, + ) -> CollectedSources: + # The OrderedDict calls deduplicate sources by URL. + index_url_sources = collections.OrderedDict( + build_source( + loc, + candidates_from_page=candidates_from_page, + page_validator=self.session.is_secure_origin, + expand_dir=False, + cache_link_parsing=False, + ) + for loc in self.search_scope.get_index_urls_locations(project_name) + ).values() + find_links_sources = collections.OrderedDict( + build_source( + loc, + candidates_from_page=candidates_from_page, + page_validator=self.session.is_secure_origin, + expand_dir=True, + cache_link_parsing=True, + ) + for loc in self.find_links + ).values() + + if logger.isEnabledFor(logging.DEBUG): + lines = [ + f"* {s.link}" + for s in itertools.chain(find_links_sources, index_url_sources) + if s is not None and s.link is not None + ] + lines = [ + f"{len(lines)} location(s) to search " + f"for versions of {project_name}:" + ] + lines + logger.debug("\n".join(lines)) + + return CollectedSources( + find_links=list(find_links_sources), + index_urls=list(index_url_sources), + ) diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/package_finder.py b/web/lib/python3.11/site-packages/pip/_internal/index/package_finder.py new file mode 100644 index 00000000..9bf247f0 --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/index/package_finder.py @@ -0,0 +1,1025 @@ +"""Routines related to PyPI, indexes""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import enum +import functools +import itertools +import logging +import re +from typing import FrozenSet, Iterable, List, Optional, Set, Tuple, Union + +from pip._vendor.packaging import specifiers +from pip._vendor.packaging.tags import Tag +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.packaging.version import _BaseVersion +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.exceptions import ( + BestVersionAlreadyInstalled, + DistributionNotFound, + InvalidWheelFilename, + UnsupportedWheel, +) +from pip._internal.index.collector import LinkCollector, parse_links +from pip._internal.models.candidate import InstallationCandidate +from pip._internal.models.format_control import FormatControl +from pip._internal.models.link import Link +from pip._internal.models.search_scope import SearchScope +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.models.wheel import Wheel +from pip._internal.req import InstallRequirement +from pip._internal.utils._log import getLogger +from pip._internal.utils.filetypes import WHEEL_EXTENSION +from pip._internal.utils.hashes import Hashes +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import build_netloc +from pip._internal.utils.packaging import check_requires_python +from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS + +__all__ = ["FormatControl", "BestCandidateResult", "PackageFinder"] + + +logger = getLogger(__name__) + +BuildTag = Union[Tuple[()], Tuple[int, str]] +CandidateSortingKey = Tuple[int, int, int, _BaseVersion, Optional[int], BuildTag] + + +def _check_link_requires_python( + link: Link, + version_info: Tuple[int, int, int], + ignore_requires_python: bool = False, +) -> bool: + """ + Return whether the given Python version is compatible with a link's + "Requires-Python" value. + + :param version_info: A 3-tuple of ints representing the Python + major-minor-micro version to check. + :param ignore_requires_python: Whether to ignore the "Requires-Python" + value if the given Python version isn't compatible. + """ + try: + is_compatible = check_requires_python( + link.requires_python, + version_info=version_info, + ) + except specifiers.InvalidSpecifier: + logger.debug( + "Ignoring invalid Requires-Python (%r) for link: %s", + link.requires_python, + link, + ) + else: + if not is_compatible: + version = ".".join(map(str, version_info)) + if not ignore_requires_python: + logger.verbose( + "Link requires a different Python (%s not in: %r): %s", + version, + link.requires_python, + link, + ) + return False + + logger.debug( + "Ignoring failed Requires-Python check (%s not in: %r) for link: %s", + version, + link.requires_python, + link, + ) + + return True + + +class LinkType(enum.Enum): + candidate = enum.auto() + different_project = enum.auto() + yanked = enum.auto() + format_unsupported = enum.auto() + format_invalid = enum.auto() + platform_mismatch = enum.auto() + requires_python_mismatch = enum.auto() + + +class LinkEvaluator: + + """ + Responsible for evaluating links for a particular project. + """ + + _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$") + + # Don't include an allow_yanked default value to make sure each call + # site considers whether yanked releases are allowed. This also causes + # that decision to be made explicit in the calling code, which helps + # people when reading the code. + def __init__( + self, + project_name: str, + canonical_name: str, + formats: FrozenSet[str], + target_python: TargetPython, + allow_yanked: bool, + ignore_requires_python: Optional[bool] = None, + ) -> None: + """ + :param project_name: The user supplied package name. + :param canonical_name: The canonical package name. + :param formats: The formats allowed for this package. Should be a set + with 'binary' or 'source' or both in it. + :param target_python: The target Python interpreter to use when + evaluating link compatibility. This is used, for example, to + check wheel compatibility, as well as when checking the Python + version, e.g. the Python version embedded in a link filename + (or egg fragment) and against an HTML link's optional PEP 503 + "data-requires-python" attribute. + :param allow_yanked: Whether files marked as yanked (in the sense + of PEP 592) are permitted to be candidates for install. + :param ignore_requires_python: Whether to ignore incompatible + PEP 503 "data-requires-python" values in HTML links. Defaults + to False. + """ + if ignore_requires_python is None: + ignore_requires_python = False + + self._allow_yanked = allow_yanked + self._canonical_name = canonical_name + self._ignore_requires_python = ignore_requires_python + self._formats = formats + self._target_python = target_python + + self.project_name = project_name + + def evaluate_link(self, link: Link) -> Tuple[LinkType, str]: + """ + Determine whether a link is a candidate for installation. + + :return: A tuple (result, detail), where *result* is an enum + representing whether the evaluation found a candidate, or the reason + why one is not found. If a candidate is found, *detail* will be the + candidate's version string; if one is not found, it contains the + reason the link fails to qualify. + """ + version = None + if link.is_yanked and not self._allow_yanked: + reason = link.yanked_reason or " " + return (LinkType.yanked, f"yanked for reason: {reason}") + + if link.egg_fragment: + egg_info = link.egg_fragment + ext = link.ext + else: + egg_info, ext = link.splitext() + if not ext: + return (LinkType.format_unsupported, "not a file") + if ext not in SUPPORTED_EXTENSIONS: + return ( + LinkType.format_unsupported, + f"unsupported archive format: {ext}", + ) + if "binary" not in self._formats and ext == WHEEL_EXTENSION: + reason = f"No binaries permitted for {self.project_name}" + return (LinkType.format_unsupported, reason) + if "macosx10" in link.path and ext == ".zip": + return (LinkType.format_unsupported, "macosx10 one") + if ext == WHEEL_EXTENSION: + try: + wheel = Wheel(link.filename) + except InvalidWheelFilename: + return ( + LinkType.format_invalid, + "invalid wheel filename", + ) + if canonicalize_name(wheel.name) != self._canonical_name: + reason = f"wrong project name (not {self.project_name})" + return (LinkType.different_project, reason) + + supported_tags = self._target_python.get_tags() + if not wheel.supported(supported_tags): + # Include the wheel's tags in the reason string to + # simplify troubleshooting compatibility issues. + file_tags = ", ".join(wheel.get_formatted_file_tags()) + reason = ( + f"none of the wheel's tags ({file_tags}) are compatible " + f"(run pip debug --verbose to show compatible tags)" + ) + return (LinkType.platform_mismatch, reason) + + version = wheel.version + + # This should be up by the self.ok_binary check, but see issue 2700. + if "source" not in self._formats and ext != WHEEL_EXTENSION: + reason = f"No sources permitted for {self.project_name}" + return (LinkType.format_unsupported, reason) + + if not version: + version = _extract_version_from_fragment( + egg_info, + self._canonical_name, + ) + if not version: + reason = f"Missing project version for {self.project_name}" + return (LinkType.format_invalid, reason) + + match = self._py_version_re.search(version) + if match: + version = version[: match.start()] + py_version = match.group(1) + if py_version != self._target_python.py_version: + return ( + LinkType.platform_mismatch, + "Python version is incorrect", + ) + + supports_python = _check_link_requires_python( + link, + version_info=self._target_python.py_version_info, + ignore_requires_python=self._ignore_requires_python, + ) + if not supports_python: + reason = f"{version} Requires-Python {link.requires_python}" + return (LinkType.requires_python_mismatch, reason) + + logger.debug("Found link %s, version: %s", link, version) + + return (LinkType.candidate, version) + + +def filter_unallowed_hashes( + candidates: List[InstallationCandidate], + hashes: Hashes, + project_name: str, +) -> List[InstallationCandidate]: + """ + Filter out candidates whose hashes aren't allowed, and return a new + list of candidates. + + If at least one candidate has an allowed hash, then all candidates with + either an allowed hash or no hash specified are returned. Otherwise, + the given candidates are returned. + + Including the candidates with no hash specified when there is a match + allows a warning to be logged if there is a more preferred candidate + with no hash specified. Returning all candidates in the case of no + matches lets pip report the hash of the candidate that would otherwise + have been installed (e.g. permitting the user to more easily update + their requirements file with the desired hash). + """ + if not hashes: + logger.debug( + "Given no hashes to check %s links for project %r: " + "discarding no candidates", + len(candidates), + project_name, + ) + # Make sure we're not returning back the given value. + return list(candidates) + + matches_or_no_digest = [] + # Collect the non-matches for logging purposes. + non_matches = [] + match_count = 0 + for candidate in candidates: + link = candidate.link + if not link.has_hash: + pass + elif link.is_hash_allowed(hashes=hashes): + match_count += 1 + else: + non_matches.append(candidate) + continue + + matches_or_no_digest.append(candidate) + + if match_count: + filtered = matches_or_no_digest + else: + # Make sure we're not returning back the given value. + filtered = list(candidates) + + if len(filtered) == len(candidates): + discard_message = "discarding no candidates" + else: + discard_message = "discarding {} non-matches:\n {}".format( + len(non_matches), + "\n ".join(str(candidate.link) for candidate in non_matches), + ) + + logger.debug( + "Checked %s links for project %r against %s hashes " + "(%s matches, %s no digest): %s", + len(candidates), + project_name, + hashes.digest_count, + match_count, + len(matches_or_no_digest) - match_count, + discard_message, + ) + + return filtered + + +class CandidatePreferences: + + """ + Encapsulates some of the preferences for filtering and sorting + InstallationCandidate objects. + """ + + def __init__( + self, + prefer_binary: bool = False, + allow_all_prereleases: bool = False, + ) -> None: + """ + :param allow_all_prereleases: Whether to allow all pre-releases. + """ + self.allow_all_prereleases = allow_all_prereleases + self.prefer_binary = prefer_binary + + +class BestCandidateResult: + """A collection of candidates, returned by `PackageFinder.find_best_candidate`. + + This class is only intended to be instantiated by CandidateEvaluator's + `compute_best_candidate()` method. + """ + + def __init__( + self, + candidates: List[InstallationCandidate], + applicable_candidates: List[InstallationCandidate], + best_candidate: Optional[InstallationCandidate], + ) -> None: + """ + :param candidates: A sequence of all available candidates found. + :param applicable_candidates: The applicable candidates. + :param best_candidate: The most preferred candidate found, or None + if no applicable candidates were found. + """ + assert set(applicable_candidates) <= set(candidates) + + if best_candidate is None: + assert not applicable_candidates + else: + assert best_candidate in applicable_candidates + + self._applicable_candidates = applicable_candidates + self._candidates = candidates + + self.best_candidate = best_candidate + + def iter_all(self) -> Iterable[InstallationCandidate]: + """Iterate through all candidates.""" + return iter(self._candidates) + + def iter_applicable(self) -> Iterable[InstallationCandidate]: + """Iterate through the applicable candidates.""" + return iter(self._applicable_candidates) + + +class CandidateEvaluator: + + """ + Responsible for filtering and sorting candidates for installation based + on what tags are valid. + """ + + @classmethod + def create( + cls, + project_name: str, + target_python: Optional[TargetPython] = None, + prefer_binary: bool = False, + allow_all_prereleases: bool = False, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> "CandidateEvaluator": + """Create a CandidateEvaluator object. + + :param target_python: The target Python interpreter to use when + checking compatibility. If None (the default), a TargetPython + object will be constructed from the running Python. + :param specifier: An optional object implementing `filter` + (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable + versions. + :param hashes: An optional collection of allowed hashes. + """ + if target_python is None: + target_python = TargetPython() + if specifier is None: + specifier = specifiers.SpecifierSet() + + supported_tags = target_python.get_tags() + + return cls( + project_name=project_name, + supported_tags=supported_tags, + specifier=specifier, + prefer_binary=prefer_binary, + allow_all_prereleases=allow_all_prereleases, + hashes=hashes, + ) + + def __init__( + self, + project_name: str, + supported_tags: List[Tag], + specifier: specifiers.BaseSpecifier, + prefer_binary: bool = False, + allow_all_prereleases: bool = False, + hashes: Optional[Hashes] = None, + ) -> None: + """ + :param supported_tags: The PEP 425 tags supported by the target + Python in order of preference (most preferred first). + """ + self._allow_all_prereleases = allow_all_prereleases + self._hashes = hashes + self._prefer_binary = prefer_binary + self._project_name = project_name + self._specifier = specifier + self._supported_tags = supported_tags + # Since the index of the tag in the _supported_tags list is used + # as a priority, precompute a map from tag to index/priority to be + # used in wheel.find_most_preferred_tag. + self._wheel_tag_preferences = { + tag: idx for idx, tag in enumerate(supported_tags) + } + + def get_applicable_candidates( + self, + candidates: List[InstallationCandidate], + ) -> List[InstallationCandidate]: + """ + Return the applicable candidates from a list of candidates. + """ + # Using None infers from the specifier instead. + allow_prereleases = self._allow_all_prereleases or None + specifier = self._specifier + versions = { + str(v) + for v in specifier.filter( + # We turn the version object into a str here because otherwise + # when we're debundled but setuptools isn't, Python will see + # packaging.version.Version and + # pkg_resources._vendor.packaging.version.Version as different + # types. This way we'll use a str as a common data interchange + # format. If we stop using the pkg_resources provided specifier + # and start using our own, we can drop the cast to str(). + (str(c.version) for c in candidates), + prereleases=allow_prereleases, + ) + } + + # Again, converting version to str to deal with debundling. + applicable_candidates = [c for c in candidates if str(c.version) in versions] + + filtered_applicable_candidates = filter_unallowed_hashes( + candidates=applicable_candidates, + hashes=self._hashes, + project_name=self._project_name, + ) + + return sorted(filtered_applicable_candidates, key=self._sort_key) + + def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey: + """ + Function to pass as the `key` argument to a call to sorted() to sort + InstallationCandidates by preference. + + Returns a tuple such that tuples sorting as greater using Python's + default comparison operator are more preferred. + + The preference is as follows: + + First and foremost, candidates with allowed (matching) hashes are + always preferred over candidates without matching hashes. This is + because e.g. if the only candidate with an allowed hash is yanked, + we still want to use that candidate. + + Second, excepting hash considerations, candidates that have been + yanked (in the sense of PEP 592) are always less preferred than + candidates that haven't been yanked. Then: + + If not finding wheels, they are sorted by version only. + If finding wheels, then the sort order is by version, then: + 1. existing installs + 2. wheels ordered via Wheel.support_index_min(self._supported_tags) + 3. source archives + If prefer_binary was set, then all wheels are sorted above sources. + + Note: it was considered to embed this logic into the Link + comparison operators, but then different sdist links + with the same version, would have to be considered equal + """ + valid_tags = self._supported_tags + support_num = len(valid_tags) + build_tag: BuildTag = () + binary_preference = 0 + link = candidate.link + if link.is_wheel: + # can raise InvalidWheelFilename + wheel = Wheel(link.filename) + try: + pri = -( + wheel.find_most_preferred_tag( + valid_tags, self._wheel_tag_preferences + ) + ) + except ValueError: + raise UnsupportedWheel( + "{} is not a supported wheel for this platform. It " + "can't be sorted.".format(wheel.filename) + ) + if self._prefer_binary: + binary_preference = 1 + if wheel.build_tag is not None: + match = re.match(r"^(\d+)(.*)$", wheel.build_tag) + build_tag_groups = match.groups() + build_tag = (int(build_tag_groups[0]), build_tag_groups[1]) + else: # sdist + pri = -(support_num) + has_allowed_hash = int(link.is_hash_allowed(self._hashes)) + yank_value = -1 * int(link.is_yanked) # -1 for yanked. + return ( + has_allowed_hash, + yank_value, + binary_preference, + candidate.version, + pri, + build_tag, + ) + + def sort_best_candidate( + self, + candidates: List[InstallationCandidate], + ) -> Optional[InstallationCandidate]: + """ + Return the best candidate per the instance's sort order, or None if + no candidate is acceptable. + """ + if not candidates: + return None + best_candidate = max(candidates, key=self._sort_key) + return best_candidate + + def compute_best_candidate( + self, + candidates: List[InstallationCandidate], + ) -> BestCandidateResult: + """ + Compute and return a `BestCandidateResult` instance. + """ + applicable_candidates = self.get_applicable_candidates(candidates) + + best_candidate = self.sort_best_candidate(applicable_candidates) + + return BestCandidateResult( + candidates, + applicable_candidates=applicable_candidates, + best_candidate=best_candidate, + ) + + +class PackageFinder: + """This finds packages. + + This is meant to match easy_install's technique for looking for + packages, by reading pages and looking for appropriate links. + """ + + def __init__( + self, + link_collector: LinkCollector, + target_python: TargetPython, + allow_yanked: bool, + format_control: Optional[FormatControl] = None, + candidate_prefs: Optional[CandidatePreferences] = None, + ignore_requires_python: Optional[bool] = None, + ) -> None: + """ + This constructor is primarily meant to be used by the create() class + method and from tests. + + :param format_control: A FormatControl object, used to control + the selection of source packages / binary packages when consulting + the index and links. + :param candidate_prefs: Options to use when creating a + CandidateEvaluator object. + """ + if candidate_prefs is None: + candidate_prefs = CandidatePreferences() + + format_control = format_control or FormatControl(set(), set()) + + self._allow_yanked = allow_yanked + self._candidate_prefs = candidate_prefs + self._ignore_requires_python = ignore_requires_python + self._link_collector = link_collector + self._target_python = target_python + + self.format_control = format_control + + # These are boring links that have already been logged somehow. + self._logged_links: Set[Tuple[Link, LinkType, str]] = set() + + # Don't include an allow_yanked default value to make sure each call + # site considers whether yanked releases are allowed. This also causes + # that decision to be made explicit in the calling code, which helps + # people when reading the code. + @classmethod + def create( + cls, + link_collector: LinkCollector, + selection_prefs: SelectionPreferences, + target_python: Optional[TargetPython] = None, + ) -> "PackageFinder": + """Create a PackageFinder. + + :param selection_prefs: The candidate selection preferences, as a + SelectionPreferences object. + :param target_python: The target Python interpreter to use when + checking compatibility. If None (the default), a TargetPython + object will be constructed from the running Python. + """ + if target_python is None: + target_python = TargetPython() + + candidate_prefs = CandidatePreferences( + prefer_binary=selection_prefs.prefer_binary, + allow_all_prereleases=selection_prefs.allow_all_prereleases, + ) + + return cls( + candidate_prefs=candidate_prefs, + link_collector=link_collector, + target_python=target_python, + allow_yanked=selection_prefs.allow_yanked, + format_control=selection_prefs.format_control, + ignore_requires_python=selection_prefs.ignore_requires_python, + ) + + @property + def target_python(self) -> TargetPython: + return self._target_python + + @property + def search_scope(self) -> SearchScope: + return self._link_collector.search_scope + + @search_scope.setter + def search_scope(self, search_scope: SearchScope) -> None: + self._link_collector.search_scope = search_scope + + @property + def find_links(self) -> List[str]: + return self._link_collector.find_links + + @property + def index_urls(self) -> List[str]: + return self.search_scope.index_urls + + @property + def trusted_hosts(self) -> Iterable[str]: + for host_port in self._link_collector.session.pip_trusted_origins: + yield build_netloc(*host_port) + + @property + def allow_all_prereleases(self) -> bool: + return self._candidate_prefs.allow_all_prereleases + + def set_allow_all_prereleases(self) -> None: + self._candidate_prefs.allow_all_prereleases = True + + @property + def prefer_binary(self) -> bool: + return self._candidate_prefs.prefer_binary + + def set_prefer_binary(self) -> None: + self._candidate_prefs.prefer_binary = True + + def requires_python_skipped_reasons(self) -> List[str]: + reasons = { + detail + for _, result, detail in self._logged_links + if result == LinkType.requires_python_mismatch + } + return sorted(reasons) + + def make_link_evaluator(self, project_name: str) -> LinkEvaluator: + canonical_name = canonicalize_name(project_name) + formats = self.format_control.get_allowed_formats(canonical_name) + + return LinkEvaluator( + project_name=project_name, + canonical_name=canonical_name, + formats=formats, + target_python=self._target_python, + allow_yanked=self._allow_yanked, + ignore_requires_python=self._ignore_requires_python, + ) + + def _sort_links(self, links: Iterable[Link]) -> List[Link]: + """ + Returns elements of links in order, non-egg links first, egg links + second, while eliminating duplicates + """ + eggs, no_eggs = [], [] + seen: Set[Link] = set() + for link in links: + if link not in seen: + seen.add(link) + if link.egg_fragment: + eggs.append(link) + else: + no_eggs.append(link) + return no_eggs + eggs + + def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None: + entry = (link, result, detail) + if entry not in self._logged_links: + # Put the link at the end so the reason is more visible and because + # the link string is usually very long. + logger.debug("Skipping link: %s: %s", detail, link) + self._logged_links.add(entry) + + def get_install_candidate( + self, link_evaluator: LinkEvaluator, link: Link + ) -> Optional[InstallationCandidate]: + """ + If the link is a candidate for install, convert it to an + InstallationCandidate and return it. Otherwise, return None. + """ + result, detail = link_evaluator.evaluate_link(link) + if result != LinkType.candidate: + self._log_skipped_link(link, result, detail) + return None + + return InstallationCandidate( + name=link_evaluator.project_name, + link=link, + version=detail, + ) + + def evaluate_links( + self, link_evaluator: LinkEvaluator, links: Iterable[Link] + ) -> List[InstallationCandidate]: + """ + Convert links that are candidates to InstallationCandidate objects. + """ + candidates = [] + for link in self._sort_links(links): + candidate = self.get_install_candidate(link_evaluator, link) + if candidate is not None: + candidates.append(candidate) + + return candidates + + def process_project_url( + self, project_url: Link, link_evaluator: LinkEvaluator + ) -> List[InstallationCandidate]: + logger.debug( + "Fetching project page and analyzing links: %s", + project_url, + ) + index_response = self._link_collector.fetch_response(project_url) + if index_response is None: + return [] + + page_links = list(parse_links(index_response)) + + with indent_log(): + package_links = self.evaluate_links( + link_evaluator, + links=page_links, + ) + + return package_links + + @functools.lru_cache(maxsize=None) + def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]: + """Find all available InstallationCandidate for project_name + + This checks index_urls and find_links. + All versions found are returned as an InstallationCandidate list. + + See LinkEvaluator.evaluate_link() for details on which files + are accepted. + """ + link_evaluator = self.make_link_evaluator(project_name) + + collected_sources = self._link_collector.collect_sources( + project_name=project_name, + candidates_from_page=functools.partial( + self.process_project_url, + link_evaluator=link_evaluator, + ), + ) + + page_candidates_it = itertools.chain.from_iterable( + source.page_candidates() + for sources in collected_sources + for source in sources + if source is not None + ) + page_candidates = list(page_candidates_it) + + file_links_it = itertools.chain.from_iterable( + source.file_links() + for sources in collected_sources + for source in sources + if source is not None + ) + file_candidates = self.evaluate_links( + link_evaluator, + sorted(file_links_it, reverse=True), + ) + + if logger.isEnabledFor(logging.DEBUG) and file_candidates: + paths = [] + for candidate in file_candidates: + assert candidate.link.url # we need to have a URL + try: + paths.append(candidate.link.file_path) + except Exception: + paths.append(candidate.link.url) # it's not a local file + + logger.debug("Local files found: %s", ", ".join(paths)) + + # This is an intentional priority ordering + return file_candidates + page_candidates + + def make_candidate_evaluator( + self, + project_name: str, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> CandidateEvaluator: + """Create a CandidateEvaluator object to use.""" + candidate_prefs = self._candidate_prefs + return CandidateEvaluator.create( + project_name=project_name, + target_python=self._target_python, + prefer_binary=candidate_prefs.prefer_binary, + allow_all_prereleases=candidate_prefs.allow_all_prereleases, + specifier=specifier, + hashes=hashes, + ) + + @functools.lru_cache(maxsize=None) + def find_best_candidate( + self, + project_name: str, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> BestCandidateResult: + """Find matches for the given project and specifier. + + :param specifier: An optional object implementing `filter` + (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable + versions. + + :return: A `BestCandidateResult` instance. + """ + candidates = self.find_all_candidates(project_name) + candidate_evaluator = self.make_candidate_evaluator( + project_name=project_name, + specifier=specifier, + hashes=hashes, + ) + return candidate_evaluator.compute_best_candidate(candidates) + + def find_requirement( + self, req: InstallRequirement, upgrade: bool + ) -> Optional[InstallationCandidate]: + """Try to find a Link matching req + + Expects req, an InstallRequirement and upgrade, a boolean + Returns a InstallationCandidate if found, + Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise + """ + hashes = req.hashes(trust_internet=False) + best_candidate_result = self.find_best_candidate( + req.name, + specifier=req.specifier, + hashes=hashes, + ) + best_candidate = best_candidate_result.best_candidate + + installed_version: Optional[_BaseVersion] = None + if req.satisfied_by is not None: + installed_version = req.satisfied_by.version + + def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str: + # This repeated parse_version and str() conversion is needed to + # handle different vendoring sources from pip and pkg_resources. + # If we stop using the pkg_resources provided specifier and start + # using our own, we can drop the cast to str(). + return ( + ", ".join( + sorted( + {str(c.version) for c in cand_iter}, + key=parse_version, + ) + ) + or "none" + ) + + if installed_version is None and best_candidate is None: + logger.critical( + "Could not find a version that satisfies the requirement %s " + "(from versions: %s)", + req, + _format_versions(best_candidate_result.iter_all()), + ) + + raise DistributionNotFound( + "No matching distribution found for {}".format(req) + ) + + best_installed = False + if installed_version and ( + best_candidate is None or best_candidate.version <= installed_version + ): + best_installed = True + + if not upgrade and installed_version is not None: + if best_installed: + logger.debug( + "Existing installed version (%s) is most up-to-date and " + "satisfies requirement", + installed_version, + ) + else: + logger.debug( + "Existing installed version (%s) satisfies requirement " + "(most up-to-date version is %s)", + installed_version, + best_candidate.version, + ) + return None + + if best_installed: + # We have an existing version, and its the best version + logger.debug( + "Installed version (%s) is most up-to-date (past versions: %s)", + installed_version, + _format_versions(best_candidate_result.iter_applicable()), + ) + raise BestVersionAlreadyInstalled + + logger.debug( + "Using version %s (newest of versions: %s)", + best_candidate.version, + _format_versions(best_candidate_result.iter_applicable()), + ) + return best_candidate + + +def _find_name_version_sep(fragment: str, canonical_name: str) -> int: + """Find the separator's index based on the package's canonical name. + + :param fragment: A + filename "fragment" (stem) or + egg fragment. + :param canonical_name: The package's canonical name. + + This function is needed since the canonicalized name does not necessarily + have the same length as the egg info's name part. An example:: + + >>> fragment = 'foo__bar-1.0' + >>> canonical_name = 'foo-bar' + >>> _find_name_version_sep(fragment, canonical_name) + 8 + """ + # Project name and version must be separated by one single dash. Find all + # occurrences of dashes; if the string in front of it matches the canonical + # name, this is the one separating the name and version parts. + for i, c in enumerate(fragment): + if c != "-": + continue + if canonicalize_name(fragment[:i]) == canonical_name: + return i + raise ValueError(f"{fragment} does not match {canonical_name}") + + +def _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]: + """Parse the version string from a + filename + "fragment" (stem) or egg fragment. + + :param fragment: The string to parse. E.g. foo-2.1 + :param canonical_name: The canonicalized name of the package this + belongs to. + """ + try: + version_start = _find_name_version_sep(fragment, canonical_name) + 1 + except ValueError: + return None + version = fragment[version_start:] + if not version: + return None + return version diff --git a/web/lib/python3.11/site-packages/pip/_internal/index/sources.py b/web/lib/python3.11/site-packages/pip/_internal/index/sources.py new file mode 100644 index 00000000..eec3f12f --- /dev/null +++ b/web/lib/python3.11/site-packages/pip/_internal/index/sources.py @@ -0,0 +1,224 @@ +import logging +import mimetypes +import os +import pathlib +from typing import Callable, Iterable, Optional, Tuple + +from pip._internal.models.candidate import InstallationCandidate +from pip._internal.models.link import Link +from pip._internal.utils.urls import path_to_url, url_to_path +from pip._internal.vcs import is_url + +logger = logging.getLogger(__name__) + +FoundCandidates = Iterable[InstallationCandidate] +FoundLinks = Iterable[Link] +CandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]] +PageValidator = Callable[[Link], bool] + + +class LinkSource: + @property + def link(self) -> Optional[Link]: + """Returns the underlying link, if there's one.""" + raise NotImplementedError() + + def page_candidates(self) -> FoundCandidates: + """Candidates found by parsing an archive listing HTML file.""" + raise NotImplementedError() + + def file_links(self) -> FoundLinks: + """Links found by specifying archives directly.""" + raise NotImplementedError() + + +def _is_html_file(file_url: str) -> bool: + return mimetypes.guess_type(file_url, strict=False)[0] == "text/html" + + +class _FlatDirectorySource(LinkSource): + """Link source specified by ``--find-links= ``. + + This looks the content of the directory, and returns: + + * ``page_candidates``: Links listed on each HTML file in the directory. + * ``file_candidates``: Archives in the directory. + """ + + def __init__( + self, + candidates_from_page: CandidatesFromPage, + path: str, + ) -> None: + self._candidates_from_page = candidates_from_page + self._path = pathlib.Path(os.path.realpath(path)) + + @property + def link(self) -> Optional[Link]: + return None + + def page_candidates(self) -> FoundCandidates: + for path in self._path.iterdir(): + url = path_to_url(str(path)) + if not _is_html_file(url): + continue + yield from self._candidates_from_page(Link(url)) + + def file_links(self) -> FoundLinks: + for path in self._path.iterdir(): + url = path_to_url(str(path)) + if _is_html_file(url): + continue + yield Link(url) + + +class _LocalFileSource(LinkSource): + """``--find-links= `` or ``--[extra-]index-url=