We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Custom repository doesn't have precedence over PyPI
<!--
  Hi there! Thank you for discovering and submitting an issue.

  Before you submit this; let's make sure of a few things.
  Please make sure the following boxes are ticked if they are correct.
  If not, please try and fulfill these first.
-->

<!-- Checked checkbox should look like this: [x] -->
- [x] I am on the [latest](https://github.com/python-poetry/poetry/releases/latest) Poetry version.
- [x] I have searched the [issues](https://github.com/python-poetry/poetry/issues) of this repo and believe that this is not a duplicate.
- [x] If an exception occurs when executing a command, I executed it again in debug mode (`-vvv` option).

<!--
  Once those are done, if you're able to fill in the following list with your information,
  it'd be very helpful to whoever handles the issue.
-->

- **OS version and name**: macOS Mojave 10.14.6
- **Poetry version**: 1.1.3
- **Link of a [Gist](https://gist.github.com/) with the contents of your pyproject.toml file**:
```toml
[[tool.poetry.source]]
name = 'foobar'
url = 'http://repository.intranet.foobar.com/artifactory/api/pypi/pypi-virtual/simple'

[build-system]
requires = ["poetry_core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
```

## Issue
In docs we can read:
> Any custom repository will have precedence over PyPI.

In the above example, `foobar` is a proxy repo incl. both internal packages and the public ones from PyPI. Running `poetry install` should cause a creation of `poetry.lock`, where all the packages have `foobar` in their `source` field. However, it's completely opposite - none of the packages has a `source` field, which means all of them are downloaded directly from PyPI.

When I add `default = true` to the above `source` element, which means PyPI is disabled, everything works properly - generated `poetry.lock` includes `foobar` as a `source` for all packages and installation doesn't break, so it's not a problem with repository itself.

It's especially frustrating when you want to use `poetry export` (for any reason), because then the final `requirements.txt` doesn't include neither `--index-url` nor `--extra-index-url` (it seems it depends on the actually used sources, not the `pyproject.toml` content).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `poetry/factory.py`
Content:
```
1 from __future__ import absolute_import
2 from __future__ import unicode_literals
3 
4 from typing import Dict
5 from typing import Optional
6 
7 from clikit.api.io.io import IO
8 
9 from poetry.core.factory import Factory as BaseFactory
10 from poetry.core.toml.file import TOMLFile
11 
12 from .config.config import Config
13 from .config.file_config_source import FileConfigSource
14 from .io.null_io import NullIO
15 from .locations import CONFIG_DIR
16 from .packages.locker import Locker
17 from .poetry import Poetry
18 from .repositories.pypi_repository import PyPiRepository
19 from .utils._compat import Path
20 
21 
22 class Factory(BaseFactory):
23     """
24     Factory class to create various elements needed by Poetry.
25     """
26 
27     def create_poetry(
28         self, cwd=None, io=None
29     ):  # type: (Optional[Path], Optional[IO]) -> Poetry
30         if io is None:
31             io = NullIO()
32 
33         base_poetry = super(Factory, self).create_poetry(cwd)
34 
35         locker = Locker(
36             base_poetry.file.parent / "poetry.lock", base_poetry.local_config
37         )
38 
39         # Loading global configuration
40         config = self.create_config(io)
41 
42         # Loading local configuration
43         local_config_file = TOMLFile(base_poetry.file.parent / "poetry.toml")
44         if local_config_file.exists():
45             if io.is_debug():
46                 io.write_line(
47                     "Loading configuration file {}".format(local_config_file.path)
48                 )
49 
50             config.merge(local_config_file.read())
51 
52         # Load local sources
53         repositories = {}
54         existing_repositories = config.get("repositories", {})
55         for source in base_poetry.pyproject.poetry_config.get("source", []):
56             name = source.get("name")
57             url = source.get("url")
58             if name and url:
59                 if name not in existing_repositories:
60                     repositories[name] = {"url": url}
61 
62         config.merge({"repositories": repositories})
63 
64         poetry = Poetry(
65             base_poetry.file.path,
66             base_poetry.local_config,
67             base_poetry.package,
68             locker,
69             config,
70         )
71 
72         # Configuring sources
73         sources = poetry.local_config.get("source", [])
74         for source in sources:
75             repository = self.create_legacy_repository(source, config)
76             is_default = source.get("default", False)
77             is_secondary = source.get("secondary", False)
78             if io.is_debug():
79                 message = "Adding repository {} ({})".format(
80                     repository.name, repository.url
81                 )
82                 if is_default:
83                     message += " and setting it as the default one"
84                 elif is_secondary:
85                     message += " and setting it as secondary"
86 
87                 io.write_line(message)
88 
89             poetry.pool.add_repository(repository, is_default, secondary=is_secondary)
90 
91         # Always put PyPI last to prefer private repositories
92         # but only if we have no other default source
93         if not poetry.pool.has_default():
94             has_sources = bool(sources)
95             poetry.pool.add_repository(PyPiRepository(), not has_sources, has_sources)
96         else:
97             if io.is_debug():
98                 io.write_line("Deactivating the PyPI repository")
99 
100         return poetry
101 
102     @classmethod
103     def create_config(cls, io=None):  # type: (Optional[IO]) -> Config
104         if io is None:
105             io = NullIO()
106 
107         config = Config()
108         # Load global config
109         config_file = TOMLFile(Path(CONFIG_DIR) / "config.toml")
110         if config_file.exists():
111             if io.is_debug():
112                 io.write_line(
113                     "<debug>Loading configuration file {}</debug>".format(
114                         config_file.path
115                     )
116                 )
117 
118             config.merge(config_file.read())
119 
120         config.set_config_source(FileConfigSource(config_file))
121 
122         # Load global auth config
123         auth_config_file = TOMLFile(Path(CONFIG_DIR) / "auth.toml")
124         if auth_config_file.exists():
125             if io.is_debug():
126                 io.write_line(
127                     "<debug>Loading configuration file {}</debug>".format(
128                         auth_config_file.path
129                     )
130                 )
131 
132             config.merge(auth_config_file.read())
133 
134         config.set_auth_config_source(FileConfigSource(auth_config_file))
135 
136         return config
137 
138     def create_legacy_repository(
139         self, source, auth_config
140     ):  # type: (Dict[str, str], Config) -> LegacyRepository
141         from .repositories.legacy_repository import LegacyRepository
142         from .utils.helpers import get_cert
143         from .utils.helpers import get_client_cert
144 
145         if "url" in source:
146             # PyPI-like repository
147             if "name" not in source:
148                 raise RuntimeError("Missing [name] in source.")
149         else:
150             raise RuntimeError("Unsupported source specified")
151 
152         name = source["name"]
153         url = source["url"]
154 
155         return LegacyRepository(
156             name,
157             url,
158             config=auth_config,
159             cert=get_cert(auth_config, name),
160             client_cert=get_client_cert(auth_config, name),
161         )
162
```

Path: `poetry/repositories/pool.py`
Content:
```
1 from typing import TYPE_CHECKING
2 from typing import Dict
3 from typing import List
4 from typing import Optional
5 
6 from .base_repository import BaseRepository
7 from .exceptions import PackageNotFound
8 from .repository import Repository
9 
10 
11 if TYPE_CHECKING:
12     from poetry.core.packages import Package
13 
14 
15 class Pool(BaseRepository):
16     def __init__(
17         self, repositories=None, ignore_repository_names=False
18     ):  # type: (Optional[List[Repository]], bool) -> None
19         if repositories is None:
20             repositories = []
21 
22         self._lookup = {}  # type: Dict[str, int]
23         self._repositories = []  # type: List[Repository]
24         self._default = False
25         self._secondary_start_idx = None
26 
27         for repository in repositories:
28             self.add_repository(repository)
29 
30         self._ignore_repository_names = ignore_repository_names
31 
32         super(Pool, self).__init__()
33 
34     @property
35     def repositories(self):  # type: () -> List[Repository]
36         return self._repositories
37 
38     def has_default(self):  # type: () -> bool
39         return self._default
40 
41     def has_repository(self, name):  # type: (str) -> bool
42         name = name.lower() if name is not None else None
43 
44         return name in self._lookup
45 
46     def repository(self, name):  # type: (str) -> Repository
47         if name is not None:
48             name = name.lower()
49 
50         if name in self._lookup:
51             return self._repositories[self._lookup[name]]
52 
53         raise ValueError('Repository "{}" does not exist.'.format(name))
54 
55     def add_repository(
56         self, repository, default=False, secondary=False
57     ):  # type: (Repository, bool, bool) -> Pool
58         """
59         Adds a repository to the pool.
60         """
61         repository_name = (
62             repository.name.lower() if repository.name is not None else None
63         )
64         if default:
65             if self.has_default():
66                 raise ValueError("Only one repository can be the default")
67 
68             self._default = True
69             self._repositories.insert(0, repository)
70             for name in self._lookup:
71                 self._lookup[name] += 1
72 
73             if self._secondary_start_idx is not None:
74                 self._secondary_start_idx += 1
75 
76             self._lookup[repository_name] = 0
77         elif secondary:
78             if self._secondary_start_idx is None:
79                 self._secondary_start_idx = len(self._repositories)
80 
81             self._repositories.append(repository)
82             self._lookup[repository_name] = len(self._repositories) - 1
83         else:
84             if self._secondary_start_idx is None:
85                 self._repositories.append(repository)
86                 self._lookup[repository_name] = len(self._repositories) - 1
87             else:
88                 self._repositories.insert(self._secondary_start_idx, repository)
89 
90                 for name, idx in self._lookup.items():
91                     if idx < self._secondary_start_idx:
92                         continue
93 
94                     self._lookup[name] += 1
95 
96                 self._lookup[repository_name] = self._secondary_start_idx
97                 self._secondary_start_idx += 1
98 
99         return self
100 
101     def remove_repository(self, repository_name):  # type: (str) -> Pool
102         if repository_name is not None:
103             repository_name = repository_name.lower()
104 
105         idx = self._lookup.get(repository_name)
106         if idx is not None:
107             del self._repositories[idx]
108 
109         return self
110 
111     def has_package(self, package):
112         raise NotImplementedError()
113 
114     def package(
115         self, name, version, extras=None, repository=None
116     ):  # type: (str, str, List[str], str) -> Package
117         if repository is not None:
118             repository = repository.lower()
119 
120         if (
121             repository is not None
122             and repository not in self._lookup
123             and not self._ignore_repository_names
124         ):
125             raise ValueError('Repository "{}" does not exist.'.format(repository))
126 
127         if repository is not None and not self._ignore_repository_names:
128             try:
129                 return self.repository(repository).package(name, version, extras=extras)
130             except PackageNotFound:
131                 pass
132         else:
133             for idx, repo in enumerate(self._repositories):
134                 try:
135                     package = repo.package(name, version, extras=extras)
136                 except PackageNotFound:
137                     continue
138 
139                 if package:
140                     self._packages.append(package)
141 
142                     return package
143 
144         raise PackageNotFound("Package {} ({}) not found.".format(name, version))
145 
146     def find_packages(
147         self, dependency,
148     ):
149         repository = dependency.source_name
150         if repository is not None:
151             repository = repository.lower()
152 
153         if (
154             repository is not None
155             and repository not in self._lookup
156             and not self._ignore_repository_names
157         ):
158             raise ValueError('Repository "{}" does not exist.'.format(repository))
159 
160         if repository is not None and not self._ignore_repository_names:
161             return self.repository(repository).find_packages(dependency)
162 
163         packages = []
164         for repo in self._repositories:
165             packages += repo.find_packages(dependency)
166 
167         return packages
168 
169     def search(self, query):
170         from .legacy_repository import LegacyRepository
171 
172         results = []
173         for repository in self._repositories:
174             if isinstance(repository, LegacyRepository):
175                 continue
176 
177             results += repository.search(query)
178 
179         return results
180
```
--- END FILES ---

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

Here is an example:

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

```

diff --git a/poetry/factory.py b/poetry/factory.py
--- a/poetry/factory.py
+++ b/poetry/factory.py
@@ -88,14 +88,15 @@
 
             poetry.pool.add_repository(repository, is_default, secondary=is_secondary)
 
-        # Always put PyPI last to prefer private repositories
-        # but only if we have no other default source
-        if not poetry.pool.has_default():
-            has_sources = bool(sources)
-            poetry.pool.add_repository(PyPiRepository(), not has_sources, has_sources)
-        else:
+        # Put PyPI last to prefer private repositories
+        # unless we have no default source AND no primary sources
+        # (default = false, secondary = false)
+        if poetry.pool.has_default():
             if io.is_debug():
                 io.write_line("Deactivating the PyPI repository")
+        else:
+            default = not poetry.pool.has_primary_repositories()
+            poetry.pool.add_repository(PyPiRepository(), default, not default)
 
         return poetry
 
diff --git a/poetry/repositories/pool.py b/poetry/repositories/pool.py
--- a/poetry/repositories/pool.py
+++ b/poetry/repositories/pool.py
@@ -22,6 +22,7 @@
         self._lookup = {}  # type: Dict[str, int]
         self._repositories = []  # type: List[Repository]
         self._default = False
+        self._has_primary_repositories = False
         self._secondary_start_idx = None
 
         for repository in repositories:
@@ -38,6 +39,9 @@
     def has_default(self):  # type: () -> bool
         return self._default
 
+    def has_primary_repositories(self):  # type: () -> bool
+        return self._has_primary_repositories
+
     def has_repository(self, name):  # type: (str) -> bool
         name = name.lower() if name is not None else None
 
@@ -81,6 +85,7 @@
             self._repositories.append(repository)
             self._lookup[repository_name] = len(self._repositories) - 1
         else:
+            self._has_primary_repositories = True
             if self._secondary_start_idx is None:
                 self._repositories.append(repository)
                 self._lookup[repository_name] = len(self._repositories) - 1

{"golden_diff": "diff --git a/poetry/factory.py b/poetry/factory.py\n--- a/poetry/factory.py\n+++ b/poetry/factory.py\n@@ -88,14 +88,15 @@\n \n             poetry.pool.add_repository(repository, is_default, secondary=is_secondary)\n \n-        # Always put PyPI last to prefer private repositories\n-        # but only if we have no other default source\n-        if not poetry.pool.has_default():\n-            has_sources = bool(sources)\n-            poetry.pool.add_repository(PyPiRepository(), not has_sources, has_sources)\n-        else:\n+        # Put PyPI last to prefer private repositories\n+        # unless we have no default source AND no primary sources\n+        # (default = false, secondary = false)\n+        if poetry.pool.has_default():\n             if io.is_debug():\n                 io.write_line(\"Deactivating the PyPI repository\")\n+        else:\n+            default = not poetry.pool.has_primary_repositories()\n+            poetry.pool.add_repository(PyPiRepository(), default, not default)\n \n         return poetry\n \ndiff --git a/poetry/repositories/pool.py b/poetry/repositories/pool.py\n--- a/poetry/repositories/pool.py\n+++ b/poetry/repositories/pool.py\n@@ -22,6 +22,7 @@\n         self._lookup = {}  # type: Dict[str, int]\n         self._repositories = []  # type: List[Repository]\n         self._default = False\n+        self._has_primary_repositories = False\n         self._secondary_start_idx = None\n \n         for repository in repositories:\n@@ -38,6 +39,9 @@\n     def has_default(self):  # type: () -> bool\n         return self._default\n \n+    def has_primary_repositories(self):  # type: () -> bool\n+        return self._has_primary_repositories\n+\n     def has_repository(self, name):  # type: (str) -> bool\n         name = name.lower() if name is not None else None\n \n@@ -81,6 +85,7 @@\n             self._repositories.append(repository)\n             self._lookup[repository_name] = len(self._repositories) - 1\n         else:\n+            self._has_primary_repositories = True\n             if self._secondary_start_idx is None:\n                 self._repositories.append(repository)\n                 self._lookup[repository_name] = len(self._repositories) - 1\n", "issue": "Custom repository doesn't have precedence over PyPI\n<!--\r\n  Hi there! Thank you for discovering and submitting an issue.\r\n\r\n  Before you submit this; let's make sure of a few things.\r\n  Please make sure the following boxes are ticked if they are correct.\r\n  If not, please try and fulfill these first.\r\n-->\r\n\r\n<!-- Checked checkbox should look like this: [x] -->\r\n- [x] I am on the [latest](https://github.com/python-poetry/poetry/releases/latest) Poetry version.\r\n- [x] I have searched the [issues](https://github.com/python-poetry/poetry/issues) of this repo and believe that this is not a duplicate.\r\n- [x] If an exception occurs when executing a command, I executed it again in debug mode (`-vvv` option).\r\n\r\n<!--\r\n  Once those are done, if you're able to fill in the following list with your information,\r\n  it'd be very helpful to whoever handles the issue.\r\n-->\r\n\r\n- **OS version and name**: macOS Mojave 10.14.6\r\n- **Poetry version**: 1.1.3\r\n- **Link of a [Gist](https://gist.github.com/) with the contents of your pyproject.toml file**:\r\n```toml\r\n[[tool.poetry.source]]\r\nname = 'foobar'\r\nurl = 'http://repository.intranet.foobar.com/artifactory/api/pypi/pypi-virtual/simple'\r\n\r\n[build-system]\r\nrequires = [\"poetry_core>=1.0.0\"]\r\nbuild-backend = \"poetry.core.masonry.api\"\r\n```\r\n\r\n## Issue\r\nIn docs we can read:\r\n> Any custom repository will have precedence over PyPI.\r\n\r\nIn the above example, `foobar` is a proxy repo incl. both internal packages and the public ones from PyPI. Running `poetry install` should cause a creation of `poetry.lock`, where all the packages have `foobar` in their `source` field. However, it's completely opposite - none of the packages has a `source` field, which means all of them are downloaded directly from PyPI.\r\n\r\nWhen I add `default = true` to the above `source` element, which means PyPI is disabled, everything works properly - generated `poetry.lock` includes `foobar` as a `source` for all packages and installation doesn't break, so it's not a problem with repository itself.\r\n\r\nIt's especially frustrating when you want to use `poetry export` (for any reason), because then the final `requirements.txt` doesn't include neither `--index-url` nor `--extra-index-url` (it seems it depends on the actually used sources, not the `pyproject.toml` content).\n", "before_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom typing import Dict\nfrom typing import Optional\n\nfrom clikit.api.io.io import IO\n\nfrom poetry.core.factory import Factory as BaseFactory\nfrom poetry.core.toml.file import TOMLFile\n\nfrom .config.config import Config\nfrom .config.file_config_source import FileConfigSource\nfrom .io.null_io import NullIO\nfrom .locations import CONFIG_DIR\nfrom .packages.locker import Locker\nfrom .poetry import Poetry\nfrom .repositories.pypi_repository import PyPiRepository\nfrom .utils._compat import Path\n\n\nclass Factory(BaseFactory):\n    \"\"\"\n    Factory class to create various elements needed by Poetry.\n    \"\"\"\n\n    def create_poetry(\n        self, cwd=None, io=None\n    ):  # type: (Optional[Path], Optional[IO]) -> Poetry\n        if io is None:\n            io = NullIO()\n\n        base_poetry = super(Factory, self).create_poetry(cwd)\n\n        locker = Locker(\n            base_poetry.file.parent / \"poetry.lock\", base_poetry.local_config\n        )\n\n        # Loading global configuration\n        config = self.create_config(io)\n\n        # Loading local configuration\n        local_config_file = TOMLFile(base_poetry.file.parent / \"poetry.toml\")\n        if local_config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"Loading configuration file {}\".format(local_config_file.path)\n                )\n\n            config.merge(local_config_file.read())\n\n        # Load local sources\n        repositories = {}\n        existing_repositories = config.get(\"repositories\", {})\n        for source in base_poetry.pyproject.poetry_config.get(\"source\", []):\n            name = source.get(\"name\")\n            url = source.get(\"url\")\n            if name and url:\n                if name not in existing_repositories:\n                    repositories[name] = {\"url\": url}\n\n        config.merge({\"repositories\": repositories})\n\n        poetry = Poetry(\n            base_poetry.file.path,\n            base_poetry.local_config,\n            base_poetry.package,\n            locker,\n            config,\n        )\n\n        # Configuring sources\n        sources = poetry.local_config.get(\"source\", [])\n        for source in sources:\n            repository = self.create_legacy_repository(source, config)\n            is_default = source.get(\"default\", False)\n            is_secondary = source.get(\"secondary\", False)\n            if io.is_debug():\n                message = \"Adding repository {} ({})\".format(\n                    repository.name, repository.url\n                )\n                if is_default:\n                    message += \" and setting it as the default one\"\n                elif is_secondary:\n                    message += \" and setting it as secondary\"\n\n                io.write_line(message)\n\n            poetry.pool.add_repository(repository, is_default, secondary=is_secondary)\n\n        # Always put PyPI last to prefer private repositories\n        # but only if we have no other default source\n        if not poetry.pool.has_default():\n            has_sources = bool(sources)\n            poetry.pool.add_repository(PyPiRepository(), not has_sources, has_sources)\n        else:\n            if io.is_debug():\n                io.write_line(\"Deactivating the PyPI repository\")\n\n        return poetry\n\n    @classmethod\n    def create_config(cls, io=None):  # type: (Optional[IO]) -> Config\n        if io is None:\n            io = NullIO()\n\n        config = Config()\n        # Load global config\n        config_file = TOMLFile(Path(CONFIG_DIR) / \"config.toml\")\n        if config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"<debug>Loading configuration file {}</debug>\".format(\n                        config_file.path\n                    )\n                )\n\n            config.merge(config_file.read())\n\n        config.set_config_source(FileConfigSource(config_file))\n\n        # Load global auth config\n        auth_config_file = TOMLFile(Path(CONFIG_DIR) / \"auth.toml\")\n        if auth_config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"<debug>Loading configuration file {}</debug>\".format(\n                        auth_config_file.path\n                    )\n                )\n\n            config.merge(auth_config_file.read())\n\n        config.set_auth_config_source(FileConfigSource(auth_config_file))\n\n        return config\n\n    def create_legacy_repository(\n        self, source, auth_config\n    ):  # type: (Dict[str, str], Config) -> LegacyRepository\n        from .repositories.legacy_repository import LegacyRepository\n        from .utils.helpers import get_cert\n        from .utils.helpers import get_client_cert\n\n        if \"url\" in source:\n            # PyPI-like repository\n            if \"name\" not in source:\n                raise RuntimeError(\"Missing [name] in source.\")\n        else:\n            raise RuntimeError(\"Unsupported source specified\")\n\n        name = source[\"name\"]\n        url = source[\"url\"]\n\n        return LegacyRepository(\n            name,\n            url,\n            config=auth_config,\n            cert=get_cert(auth_config, name),\n            client_cert=get_client_cert(auth_config, name),\n        )\n", "path": "poetry/factory.py"}, {"content": "from typing import TYPE_CHECKING\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nfrom .base_repository import BaseRepository\nfrom .exceptions import PackageNotFound\nfrom .repository import Repository\n\n\nif TYPE_CHECKING:\n    from poetry.core.packages import Package\n\n\nclass Pool(BaseRepository):\n    def __init__(\n        self, repositories=None, ignore_repository_names=False\n    ):  # type: (Optional[List[Repository]], bool) -> None\n        if repositories is None:\n            repositories = []\n\n        self._lookup = {}  # type: Dict[str, int]\n        self._repositories = []  # type: List[Repository]\n        self._default = False\n        self._secondary_start_idx = None\n\n        for repository in repositories:\n            self.add_repository(repository)\n\n        self._ignore_repository_names = ignore_repository_names\n\n        super(Pool, self).__init__()\n\n    @property\n    def repositories(self):  # type: () -> List[Repository]\n        return self._repositories\n\n    def has_default(self):  # type: () -> bool\n        return self._default\n\n    def has_repository(self, name):  # type: (str) -> bool\n        name = name.lower() if name is not None else None\n\n        return name in self._lookup\n\n    def repository(self, name):  # type: (str) -> Repository\n        if name is not None:\n            name = name.lower()\n\n        if name in self._lookup:\n            return self._repositories[self._lookup[name]]\n\n        raise ValueError('Repository \"{}\" does not exist.'.format(name))\n\n    def add_repository(\n        self, repository, default=False, secondary=False\n    ):  # type: (Repository, bool, bool) -> Pool\n        \"\"\"\n        Adds a repository to the pool.\n        \"\"\"\n        repository_name = (\n            repository.name.lower() if repository.name is not None else None\n        )\n        if default:\n            if self.has_default():\n                raise ValueError(\"Only one repository can be the default\")\n\n            self._default = True\n            self._repositories.insert(0, repository)\n            for name in self._lookup:\n                self._lookup[name] += 1\n\n            if self._secondary_start_idx is not None:\n                self._secondary_start_idx += 1\n\n            self._lookup[repository_name] = 0\n        elif secondary:\n            if self._secondary_start_idx is None:\n                self._secondary_start_idx = len(self._repositories)\n\n            self._repositories.append(repository)\n            self._lookup[repository_name] = len(self._repositories) - 1\n        else:\n            if self._secondary_start_idx is None:\n                self._repositories.append(repository)\n                self._lookup[repository_name] = len(self._repositories) - 1\n            else:\n                self._repositories.insert(self._secondary_start_idx, repository)\n\n                for name, idx in self._lookup.items():\n                    if idx < self._secondary_start_idx:\n                        continue\n\n                    self._lookup[name] += 1\n\n                self._lookup[repository_name] = self._secondary_start_idx\n                self._secondary_start_idx += 1\n\n        return self\n\n    def remove_repository(self, repository_name):  # type: (str) -> Pool\n        if repository_name is not None:\n            repository_name = repository_name.lower()\n\n        idx = self._lookup.get(repository_name)\n        if idx is not None:\n            del self._repositories[idx]\n\n        return self\n\n    def has_package(self, package):\n        raise NotImplementedError()\n\n    def package(\n        self, name, version, extras=None, repository=None\n    ):  # type: (str, str, List[str], str) -> Package\n        if repository is not None:\n            repository = repository.lower()\n\n        if (\n            repository is not None\n            and repository not in self._lookup\n            and not self._ignore_repository_names\n        ):\n            raise ValueError('Repository \"{}\" does not exist.'.format(repository))\n\n        if repository is not None and not self._ignore_repository_names:\n            try:\n                return self.repository(repository).package(name, version, extras=extras)\n            except PackageNotFound:\n                pass\n        else:\n            for idx, repo in enumerate(self._repositories):\n                try:\n                    package = repo.package(name, version, extras=extras)\n                except PackageNotFound:\n                    continue\n\n                if package:\n                    self._packages.append(package)\n\n                    return package\n\n        raise PackageNotFound(\"Package {} ({}) not found.\".format(name, version))\n\n    def find_packages(\n        self, dependency,\n    ):\n        repository = dependency.source_name\n        if repository is not None:\n            repository = repository.lower()\n\n        if (\n            repository is not None\n            and repository not in self._lookup\n            and not self._ignore_repository_names\n        ):\n            raise ValueError('Repository \"{}\" does not exist.'.format(repository))\n\n        if repository is not None and not self._ignore_repository_names:\n            return self.repository(repository).find_packages(dependency)\n\n        packages = []\n        for repo in self._repositories:\n            packages += repo.find_packages(dependency)\n\n        return packages\n\n    def search(self, query):\n        from .legacy_repository import LegacyRepository\n\n        results = []\n        for repository in self._repositories:\n            if isinstance(repository, LegacyRepository):\n                continue\n\n            results += repository.search(query)\n\n        return results\n", "path": "poetry/repositories/pool.py"}], "after_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom typing import Dict\nfrom typing import Optional\n\nfrom clikit.api.io.io import IO\n\nfrom poetry.core.factory import Factory as BaseFactory\nfrom poetry.core.toml.file import TOMLFile\n\nfrom .config.config import Config\nfrom .config.file_config_source import FileConfigSource\nfrom .io.null_io import NullIO\nfrom .locations import CONFIG_DIR\nfrom .packages.locker import Locker\nfrom .poetry import Poetry\nfrom .repositories.pypi_repository import PyPiRepository\nfrom .utils._compat import Path\n\n\nclass Factory(BaseFactory):\n    \"\"\"\n    Factory class to create various elements needed by Poetry.\n    \"\"\"\n\n    def create_poetry(\n        self, cwd=None, io=None\n    ):  # type: (Optional[Path], Optional[IO]) -> Poetry\n        if io is None:\n            io = NullIO()\n\n        base_poetry = super(Factory, self).create_poetry(cwd)\n\n        locker = Locker(\n            base_poetry.file.parent / \"poetry.lock\", base_poetry.local_config\n        )\n\n        # Loading global configuration\n        config = self.create_config(io)\n\n        # Loading local configuration\n        local_config_file = TOMLFile(base_poetry.file.parent / \"poetry.toml\")\n        if local_config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"Loading configuration file {}\".format(local_config_file.path)\n                )\n\n            config.merge(local_config_file.read())\n\n        # Load local sources\n        repositories = {}\n        existing_repositories = config.get(\"repositories\", {})\n        for source in base_poetry.pyproject.poetry_config.get(\"source\", []):\n            name = source.get(\"name\")\n            url = source.get(\"url\")\n            if name and url:\n                if name not in existing_repositories:\n                    repositories[name] = {\"url\": url}\n\n        config.merge({\"repositories\": repositories})\n\n        poetry = Poetry(\n            base_poetry.file.path,\n            base_poetry.local_config,\n            base_poetry.package,\n            locker,\n            config,\n        )\n\n        # Configuring sources\n        sources = poetry.local_config.get(\"source\", [])\n        for source in sources:\n            repository = self.create_legacy_repository(source, config)\n            is_default = source.get(\"default\", False)\n            is_secondary = source.get(\"secondary\", False)\n            if io.is_debug():\n                message = \"Adding repository {} ({})\".format(\n                    repository.name, repository.url\n                )\n                if is_default:\n                    message += \" and setting it as the default one\"\n                elif is_secondary:\n                    message += \" and setting it as secondary\"\n\n                io.write_line(message)\n\n            poetry.pool.add_repository(repository, is_default, secondary=is_secondary)\n\n        # Put PyPI last to prefer private repositories\n        # unless we have no default source AND no primary sources\n        # (default = false, secondary = false)\n        if poetry.pool.has_default():\n            if io.is_debug():\n                io.write_line(\"Deactivating the PyPI repository\")\n        else:\n            default = not poetry.pool.has_primary_repositories()\n            poetry.pool.add_repository(PyPiRepository(), default, not default)\n\n        return poetry\n\n    @classmethod\n    def create_config(cls, io=None):  # type: (Optional[IO]) -> Config\n        if io is None:\n            io = NullIO()\n\n        config = Config()\n        # Load global config\n        config_file = TOMLFile(Path(CONFIG_DIR) / \"config.toml\")\n        if config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"<debug>Loading configuration file {}</debug>\".format(\n                        config_file.path\n                    )\n                )\n\n            config.merge(config_file.read())\n\n        config.set_config_source(FileConfigSource(config_file))\n\n        # Load global auth config\n        auth_config_file = TOMLFile(Path(CONFIG_DIR) / \"auth.toml\")\n        if auth_config_file.exists():\n            if io.is_debug():\n                io.write_line(\n                    \"<debug>Loading configuration file {}</debug>\".format(\n                        auth_config_file.path\n                    )\n                )\n\n            config.merge(auth_config_file.read())\n\n        config.set_auth_config_source(FileConfigSource(auth_config_file))\n\n        return config\n\n    def create_legacy_repository(\n        self, source, auth_config\n    ):  # type: (Dict[str, str], Config) -> LegacyRepository\n        from .repositories.legacy_repository import LegacyRepository\n        from .utils.helpers import get_cert\n        from .utils.helpers import get_client_cert\n\n        if \"url\" in source:\n            # PyPI-like repository\n            if \"name\" not in source:\n                raise RuntimeError(\"Missing [name] in source.\")\n        else:\n            raise RuntimeError(\"Unsupported source specified\")\n\n        name = source[\"name\"]\n        url = source[\"url\"]\n\n        return LegacyRepository(\n            name,\n            url,\n            config=auth_config,\n            cert=get_cert(auth_config, name),\n            client_cert=get_client_cert(auth_config, name),\n        )\n", "path": "poetry/factory.py"}, {"content": "from typing import TYPE_CHECKING\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\n\nfrom .base_repository import BaseRepository\nfrom .exceptions import PackageNotFound\nfrom .repository import Repository\n\n\nif TYPE_CHECKING:\n    from poetry.core.packages import Package\n\n\nclass Pool(BaseRepository):\n    def __init__(\n        self, repositories=None, ignore_repository_names=False\n    ):  # type: (Optional[List[Repository]], bool) -> None\n        if repositories is None:\n            repositories = []\n\n        self._lookup = {}  # type: Dict[str, int]\n        self._repositories = []  # type: List[Repository]\n        self._default = False\n        self._has_primary_repositories = False\n        self._secondary_start_idx = None\n\n        for repository in repositories:\n            self.add_repository(repository)\n\n        self._ignore_repository_names = ignore_repository_names\n\n        super(Pool, self).__init__()\n\n    @property\n    def repositories(self):  # type: () -> List[Repository]\n        return self._repositories\n\n    def has_default(self):  # type: () -> bool\n        return self._default\n\n    def has_primary_repositories(self):  # type: () -> bool\n        return self._has_primary_repositories\n\n    def has_repository(self, name):  # type: (str) -> bool\n        name = name.lower() if name is not None else None\n\n        return name in self._lookup\n\n    def repository(self, name):  # type: (str) -> Repository\n        if name is not None:\n            name = name.lower()\n\n        if name in self._lookup:\n            return self._repositories[self._lookup[name]]\n\n        raise ValueError('Repository \"{}\" does not exist.'.format(name))\n\n    def add_repository(\n        self, repository, default=False, secondary=False\n    ):  # type: (Repository, bool, bool) -> Pool\n        \"\"\"\n        Adds a repository to the pool.\n        \"\"\"\n        repository_name = (\n            repository.name.lower() if repository.name is not None else None\n        )\n        if default:\n            if self.has_default():\n                raise ValueError(\"Only one repository can be the default\")\n\n            self._default = True\n            self._repositories.insert(0, repository)\n            for name in self._lookup:\n                self._lookup[name] += 1\n\n            if self._secondary_start_idx is not None:\n                self._secondary_start_idx += 1\n\n            self._lookup[repository_name] = 0\n        elif secondary:\n            if self._secondary_start_idx is None:\n                self._secondary_start_idx = len(self._repositories)\n\n            self._repositories.append(repository)\n            self._lookup[repository_name] = len(self._repositories) - 1\n        else:\n            self._has_primary_repositories = True\n            if self._secondary_start_idx is None:\n                self._repositories.append(repository)\n                self._lookup[repository_name] = len(self._repositories) - 1\n            else:\n                self._repositories.insert(self._secondary_start_idx, repository)\n\n                for name, idx in self._lookup.items():\n                    if idx < self._secondary_start_idx:\n                        continue\n\n                    self._lookup[name] += 1\n\n                self._lookup[repository_name] = self._secondary_start_idx\n                self._secondary_start_idx += 1\n\n        return self\n\n    def remove_repository(self, repository_name):  # type: (str) -> Pool\n        if repository_name is not None:\n            repository_name = repository_name.lower()\n\n        idx = self._lookup.get(repository_name)\n        if idx is not None:\n            del self._repositories[idx]\n\n        return self\n\n    def has_package(self, package):\n        raise NotImplementedError()\n\n    def package(\n        self, name, version, extras=None, repository=None\n    ):  # type: (str, str, List[str], str) -> Package\n        if repository is not None:\n            repository = repository.lower()\n\n        if (\n            repository is not None\n            and repository not in self._lookup\n            and not self._ignore_repository_names\n        ):\n            raise ValueError('Repository \"{}\" does not exist.'.format(repository))\n\n        if repository is not None and not self._ignore_repository_names:\n            try:\n                return self.repository(repository).package(name, version, extras=extras)\n            except PackageNotFound:\n                pass\n        else:\n            for idx, repo in enumerate(self._repositories):\n                try:\n                    package = repo.package(name, version, extras=extras)\n                except PackageNotFound:\n                    continue\n\n                if package:\n                    self._packages.append(package)\n\n                    return package\n\n        raise PackageNotFound(\"Package {} ({}) not found.\".format(name, version))\n\n    def find_packages(\n        self, dependency,\n    ):\n        repository = dependency.source_name\n        if repository is not None:\n            repository = repository.lower()\n\n        if (\n            repository is not None\n            and repository not in self._lookup\n            and not self._ignore_repository_names\n        ):\n            raise ValueError('Repository \"{}\" does not exist.'.format(repository))\n\n        if repository is not None and not self._ignore_repository_names:\n            return self.repository(repository).find_packages(dependency)\n\n        packages = []\n        for repo in self._repositories:\n            packages += repo.find_packages(dependency)\n\n        return packages\n\n    def search(self, query):\n        from .legacy_repository import LegacyRepository\n\n        results = []\n        for repository in self._repositories:\n            if isinstance(repository, LegacyRepository):\n                continue\n\n            results += repository.search(query)\n\n        return results\n", "path": "poetry/repositories/pool.py"}]}