We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Make our downstream integration tests re-runnable
Currently our downstream tests both clone a git repository into the venv created by nox. Due to how the setup is written the nox session will fail when run a second time due to the repository already existing. It would be nice to be able to run:

`$ nox -rs downstream_requests` over and over without needing to reclone the repository or manually configure the test setup.

I think checking that the repository exists and if so not applying the git patches and continuing as normal would work okay for this case?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `noxfile.py`
Content:
```
1 import os
2 import shutil
3 import subprocess
4 import sys
5 
6 import nox
7 
8 SOURCE_FILES = [
9     "docs/",
10     "dummyserver/",
11     "src/",
12     "test/",
13     "noxfile.py",
14     "setup.py",
15 ]
16 
17 
18 def tests_impl(
19     session: nox.Session,
20     extras: str = "socks,secure,brotli,zstd",
21     byte_string_comparisons: bool = True,
22 ) -> None:
23     # Install deps and the package itself.
24     session.install("-r", "dev-requirements.txt")
25     session.install(f".[{extras}]")
26 
27     # Show the pip version.
28     session.run("pip", "--version")
29     # Print the Python version and bytesize.
30     session.run("python", "--version")
31     session.run("python", "-c", "import struct; print(struct.calcsize('P') * 8)")
32     # Print OpenSSL information.
33     session.run("python", "-m", "OpenSSL.debug")
34 
35     memray_supported = True
36     if sys.implementation.name != "cpython" or sys.version_info < (3, 8):
37         memray_supported = False  # pytest-memray requires CPython 3.8+
38     elif sys.platform == "win32":
39         memray_supported = False
40 
41     # Inspired from https://hynek.me/articles/ditch-codecov-python/
42     # We use parallel mode and then combine in a later CI step
43     session.run(
44         "python",
45         *(("-bb",) if byte_string_comparisons else ()),
46         "-m",
47         "coverage",
48         "run",
49         "--parallel-mode",
50         "-m",
51         "pytest",
52         *("--memray", "--hide-memray-summary") if memray_supported else (),
53         "-v",
54         "-ra",
55         f"--color={'yes' if 'GITHUB_ACTIONS' in os.environ else 'auto'}",
56         "--tb=native",
57         "--no-success-flaky-report",
58         *(session.posargs or ("test/",)),
59         env={"PYTHONWARNINGS": "always::DeprecationWarning"},
60     )
61 
62 
63 @nox.session(python=["3.7", "3.8", "3.9", "3.10", "3.11", "pypy"])
64 def test(session: nox.Session) -> None:
65     tests_impl(session)
66 
67 
68 @nox.session(python=["2.7"])
69 def unsupported_setup_py(session: nox.Session) -> None:
70     # Can't check both returncode and output with session.run
71     process = subprocess.run(
72         ["python", "setup.py", "install"],
73         env={**session.env},
74         text=True,
75         capture_output=True,
76     )
77     assert process.returncode == 1
78     print(process.stderr)
79     assert "Please use `python -m pip install .` instead." in process.stderr
80 
81 
82 @nox.session(python=["3"])
83 def test_brotlipy(session: nox.Session) -> None:
84     """Check that if 'brotlipy' is installed instead of 'brotli' or
85     'brotlicffi' that we still don't blow up.
86     """
87     session.install("brotlipy")
88     tests_impl(session, extras="socks,secure", byte_string_comparisons=False)
89 
90 
91 def git_clone(session: nox.Session, git_url: str) -> None:
92     session.run("git", "clone", "--depth", "1", git_url, external=True)
93 
94 
95 @nox.session()
96 def downstream_botocore(session: nox.Session) -> None:
97     root = os.getcwd()
98     tmp_dir = session.create_tmp()
99 
100     session.cd(tmp_dir)
101     git_clone(session, "https://github.com/boto/botocore")
102     session.chdir("botocore")
103     for patch in [
104         "0001-Mark-100-Continue-tests-as-failing.patch",
105         "0002-Stop-relying-on-removed-DEFAULT_CIPHERS.patch",
106     ]:
107         session.run("git", "apply", f"{root}/ci/{patch}", external=True)
108     session.run("git", "rev-parse", "HEAD", external=True)
109     session.run("python", "scripts/ci/install")
110 
111     session.cd(root)
112     session.install(".", silent=False)
113     session.cd(f"{tmp_dir}/botocore")
114 
115     session.run("python", "-c", "import urllib3; print(urllib3.__version__)")
116     session.run("python", "scripts/ci/run-tests")
117 
118 
119 @nox.session()
120 def downstream_requests(session: nox.Session) -> None:
121     root = os.getcwd()
122     tmp_dir = session.create_tmp()
123 
124     session.cd(tmp_dir)
125     git_clone(session, "https://github.com/psf/requests")
126     session.chdir("requests")
127     session.run(
128         "git", "apply", f"{root}/ci/0003-requests-removed-warnings.patch", external=True
129     )
130     session.run(
131         "git", "apply", f"{root}/ci/0004-requests-chunked-requests.patch", external=True
132     )
133     session.run("git", "rev-parse", "HEAD", external=True)
134     session.install(".[socks]", silent=False)
135     session.install("-r", "requirements-dev.txt", silent=False)
136 
137     session.cd(root)
138     session.install(".", silent=False)
139     session.cd(f"{tmp_dir}/requests")
140 
141     session.run("python", "-c", "import urllib3; print(urllib3.__version__)")
142     session.run("pytest", "tests")
143 
144 
145 @nox.session()
146 def format(session: nox.Session) -> None:
147     """Run code formatters."""
148     lint(session)
149 
150 
151 @nox.session
152 def lint(session: nox.Session) -> None:
153     session.install("pre-commit")
154     session.run("pre-commit", "run", "--all-files")
155 
156     mypy(session)
157 
158 
159 @nox.session(python="3.8")
160 def mypy(session: nox.Session) -> None:
161     """Run mypy."""
162     session.install("-r", "mypy-requirements.txt")
163     session.run("mypy", "--version")
164     session.run(
165         "mypy",
166         "dummyserver",
167         "noxfile.py",
168         "src/urllib3",
169         "test",
170     )
171 
172 
173 @nox.session
174 def docs(session: nox.Session) -> None:
175     session.install("-r", "docs/requirements.txt")
176     session.install(".[socks,secure,brotli,zstd]")
177 
178     session.chdir("docs")
179     if os.path.exists("_build"):
180         shutil.rmtree("_build")
181     session.run("sphinx-build", "-b", "html", "-W", ".", "_build/html")
182
```
--- 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/noxfile.py b/noxfile.py
--- a/noxfile.py
+++ b/noxfile.py
@@ -89,7 +89,21 @@
 
 
 def git_clone(session: nox.Session, git_url: str) -> None:
-    session.run("git", "clone", "--depth", "1", git_url, external=True)
+    """We either clone the target repository or if already exist
+    simply reset the state and pull.
+    """
+    expected_directory = git_url.split("/")[-1]
+
+    if expected_directory.endswith(".git"):
+        expected_directory = expected_directory[:-4]
+
+    if not os.path.isdir(expected_directory):
+        session.run("git", "clone", "--depth", "1", git_url, external=True)
+    else:
+        session.run(
+            "git", "-C", expected_directory, "reset", "--hard", "HEAD", external=True
+        )
+        session.run("git", "-C", expected_directory, "pull", external=True)
 
 
 @nox.session()

{"golden_diff": "diff --git a/noxfile.py b/noxfile.py\n--- a/noxfile.py\n+++ b/noxfile.py\n@@ -89,7 +89,21 @@\n \n \n def git_clone(session: nox.Session, git_url: str) -> None:\n-    session.run(\"git\", \"clone\", \"--depth\", \"1\", git_url, external=True)\n+    \"\"\"We either clone the target repository or if already exist\n+    simply reset the state and pull.\n+    \"\"\"\n+    expected_directory = git_url.split(\"/\")[-1]\n+\n+    if expected_directory.endswith(\".git\"):\n+        expected_directory = expected_directory[:-4]\n+\n+    if not os.path.isdir(expected_directory):\n+        session.run(\"git\", \"clone\", \"--depth\", \"1\", git_url, external=True)\n+    else:\n+        session.run(\n+            \"git\", \"-C\", expected_directory, \"reset\", \"--hard\", \"HEAD\", external=True\n+        )\n+        session.run(\"git\", \"-C\", expected_directory, \"pull\", external=True)\n \n \n @nox.session()\n", "issue": "Make our downstream integration tests re-runnable\nCurrently our downstream tests both clone a git repository into the venv created by nox. Due to how the setup is written the nox session will fail when run a second time due to the repository already existing. It would be nice to be able to run:\r\n\r\n`$ nox -rs downstream_requests` over and over without needing to reclone the repository or manually configure the test setup.\r\n\r\nI think checking that the repository exists and if so not applying the git patches and continuing as normal would work okay for this case?\n", "before_files": [{"content": "import os\nimport shutil\nimport subprocess\nimport sys\n\nimport nox\n\nSOURCE_FILES = [\n    \"docs/\",\n    \"dummyserver/\",\n    \"src/\",\n    \"test/\",\n    \"noxfile.py\",\n    \"setup.py\",\n]\n\n\ndef tests_impl(\n    session: nox.Session,\n    extras: str = \"socks,secure,brotli,zstd\",\n    byte_string_comparisons: bool = True,\n) -> None:\n    # Install deps and the package itself.\n    session.install(\"-r\", \"dev-requirements.txt\")\n    session.install(f\".[{extras}]\")\n\n    # Show the pip version.\n    session.run(\"pip\", \"--version\")\n    # Print the Python version and bytesize.\n    session.run(\"python\", \"--version\")\n    session.run(\"python\", \"-c\", \"import struct; print(struct.calcsize('P') * 8)\")\n    # Print OpenSSL information.\n    session.run(\"python\", \"-m\", \"OpenSSL.debug\")\n\n    memray_supported = True\n    if sys.implementation.name != \"cpython\" or sys.version_info < (3, 8):\n        memray_supported = False  # pytest-memray requires CPython 3.8+\n    elif sys.platform == \"win32\":\n        memray_supported = False\n\n    # Inspired from https://hynek.me/articles/ditch-codecov-python/\n    # We use parallel mode and then combine in a later CI step\n    session.run(\n        \"python\",\n        *((\"-bb\",) if byte_string_comparisons else ()),\n        \"-m\",\n        \"coverage\",\n        \"run\",\n        \"--parallel-mode\",\n        \"-m\",\n        \"pytest\",\n        *(\"--memray\", \"--hide-memray-summary\") if memray_supported else (),\n        \"-v\",\n        \"-ra\",\n        f\"--color={'yes' if 'GITHUB_ACTIONS' in os.environ else 'auto'}\",\n        \"--tb=native\",\n        \"--no-success-flaky-report\",\n        *(session.posargs or (\"test/\",)),\n        env={\"PYTHONWARNINGS\": \"always::DeprecationWarning\"},\n    )\n\n\n@nox.session(python=[\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\", \"pypy\"])\ndef test(session: nox.Session) -> None:\n    tests_impl(session)\n\n\n@nox.session(python=[\"2.7\"])\ndef unsupported_setup_py(session: nox.Session) -> None:\n    # Can't check both returncode and output with session.run\n    process = subprocess.run(\n        [\"python\", \"setup.py\", \"install\"],\n        env={**session.env},\n        text=True,\n        capture_output=True,\n    )\n    assert process.returncode == 1\n    print(process.stderr)\n    assert \"Please use `python -m pip install .` instead.\" in process.stderr\n\n\n@nox.session(python=[\"3\"])\ndef test_brotlipy(session: nox.Session) -> None:\n    \"\"\"Check that if 'brotlipy' is installed instead of 'brotli' or\n    'brotlicffi' that we still don't blow up.\n    \"\"\"\n    session.install(\"brotlipy\")\n    tests_impl(session, extras=\"socks,secure\", byte_string_comparisons=False)\n\n\ndef git_clone(session: nox.Session, git_url: str) -> None:\n    session.run(\"git\", \"clone\", \"--depth\", \"1\", git_url, external=True)\n\n\n@nox.session()\ndef downstream_botocore(session: nox.Session) -> None:\n    root = os.getcwd()\n    tmp_dir = session.create_tmp()\n\n    session.cd(tmp_dir)\n    git_clone(session, \"https://github.com/boto/botocore\")\n    session.chdir(\"botocore\")\n    for patch in [\n        \"0001-Mark-100-Continue-tests-as-failing.patch\",\n        \"0002-Stop-relying-on-removed-DEFAULT_CIPHERS.patch\",\n    ]:\n        session.run(\"git\", \"apply\", f\"{root}/ci/{patch}\", external=True)\n    session.run(\"git\", \"rev-parse\", \"HEAD\", external=True)\n    session.run(\"python\", \"scripts/ci/install\")\n\n    session.cd(root)\n    session.install(\".\", silent=False)\n    session.cd(f\"{tmp_dir}/botocore\")\n\n    session.run(\"python\", \"-c\", \"import urllib3; print(urllib3.__version__)\")\n    session.run(\"python\", \"scripts/ci/run-tests\")\n\n\n@nox.session()\ndef downstream_requests(session: nox.Session) -> None:\n    root = os.getcwd()\n    tmp_dir = session.create_tmp()\n\n    session.cd(tmp_dir)\n    git_clone(session, \"https://github.com/psf/requests\")\n    session.chdir(\"requests\")\n    session.run(\n        \"git\", \"apply\", f\"{root}/ci/0003-requests-removed-warnings.patch\", external=True\n    )\n    session.run(\n        \"git\", \"apply\", f\"{root}/ci/0004-requests-chunked-requests.patch\", external=True\n    )\n    session.run(\"git\", \"rev-parse\", \"HEAD\", external=True)\n    session.install(\".[socks]\", silent=False)\n    session.install(\"-r\", \"requirements-dev.txt\", silent=False)\n\n    session.cd(root)\n    session.install(\".\", silent=False)\n    session.cd(f\"{tmp_dir}/requests\")\n\n    session.run(\"python\", \"-c\", \"import urllib3; print(urllib3.__version__)\")\n    session.run(\"pytest\", \"tests\")\n\n\n@nox.session()\ndef format(session: nox.Session) -> None:\n    \"\"\"Run code formatters.\"\"\"\n    lint(session)\n\n\n@nox.session\ndef lint(session: nox.Session) -> None:\n    session.install(\"pre-commit\")\n    session.run(\"pre-commit\", \"run\", \"--all-files\")\n\n    mypy(session)\n\n\n@nox.session(python=\"3.8\")\ndef mypy(session: nox.Session) -> None:\n    \"\"\"Run mypy.\"\"\"\n    session.install(\"-r\", \"mypy-requirements.txt\")\n    session.run(\"mypy\", \"--version\")\n    session.run(\n        \"mypy\",\n        \"dummyserver\",\n        \"noxfile.py\",\n        \"src/urllib3\",\n        \"test\",\n    )\n\n\n@nox.session\ndef docs(session: nox.Session) -> None:\n    session.install(\"-r\", \"docs/requirements.txt\")\n    session.install(\".[socks,secure,brotli,zstd]\")\n\n    session.chdir(\"docs\")\n    if os.path.exists(\"_build\"):\n        shutil.rmtree(\"_build\")\n    session.run(\"sphinx-build\", \"-b\", \"html\", \"-W\", \".\", \"_build/html\")\n", "path": "noxfile.py"}], "after_files": [{"content": "import os\nimport shutil\nimport subprocess\nimport sys\n\nimport nox\n\nSOURCE_FILES = [\n    \"docs/\",\n    \"dummyserver/\",\n    \"src/\",\n    \"test/\",\n    \"noxfile.py\",\n    \"setup.py\",\n]\n\n\ndef tests_impl(\n    session: nox.Session,\n    extras: str = \"socks,secure,brotli,zstd\",\n    byte_string_comparisons: bool = True,\n) -> None:\n    # Install deps and the package itself.\n    session.install(\"-r\", \"dev-requirements.txt\")\n    session.install(f\".[{extras}]\")\n\n    # Show the pip version.\n    session.run(\"pip\", \"--version\")\n    # Print the Python version and bytesize.\n    session.run(\"python\", \"--version\")\n    session.run(\"python\", \"-c\", \"import struct; print(struct.calcsize('P') * 8)\")\n    # Print OpenSSL information.\n    session.run(\"python\", \"-m\", \"OpenSSL.debug\")\n\n    memray_supported = True\n    if sys.implementation.name != \"cpython\" or sys.version_info < (3, 8):\n        memray_supported = False  # pytest-memray requires CPython 3.8+\n    elif sys.platform == \"win32\":\n        memray_supported = False\n\n    # Inspired from https://hynek.me/articles/ditch-codecov-python/\n    # We use parallel mode and then combine in a later CI step\n    session.run(\n        \"python\",\n        *((\"-bb\",) if byte_string_comparisons else ()),\n        \"-m\",\n        \"coverage\",\n        \"run\",\n        \"--parallel-mode\",\n        \"-m\",\n        \"pytest\",\n        *(\"--memray\", \"--hide-memray-summary\") if memray_supported else (),\n        \"-v\",\n        \"-ra\",\n        f\"--color={'yes' if 'GITHUB_ACTIONS' in os.environ else 'auto'}\",\n        \"--tb=native\",\n        \"--no-success-flaky-report\",\n        *(session.posargs or (\"test/\",)),\n        env={\"PYTHONWARNINGS\": \"always::DeprecationWarning\"},\n    )\n\n\n@nox.session(python=[\"3.7\", \"3.8\", \"3.9\", \"3.10\", \"3.11\", \"pypy\"])\ndef test(session: nox.Session) -> None:\n    tests_impl(session)\n\n\n@nox.session(python=[\"2.7\"])\ndef unsupported_setup_py(session: nox.Session) -> None:\n    # Can't check both returncode and output with session.run\n    process = subprocess.run(\n        [\"python\", \"setup.py\", \"install\"],\n        env={**session.env},\n        text=True,\n        capture_output=True,\n    )\n    assert process.returncode == 1\n    print(process.stderr)\n    assert \"Please use `python -m pip install .` instead.\" in process.stderr\n\n\n@nox.session(python=[\"3\"])\ndef test_brotlipy(session: nox.Session) -> None:\n    \"\"\"Check that if 'brotlipy' is installed instead of 'brotli' or\n    'brotlicffi' that we still don't blow up.\n    \"\"\"\n    session.install(\"brotlipy\")\n    tests_impl(session, extras=\"socks,secure\", byte_string_comparisons=False)\n\n\ndef git_clone(session: nox.Session, git_url: str) -> None:\n    \"\"\"We either clone the target repository or if already exist\n    simply reset the state and pull.\n    \"\"\"\n    expected_directory = git_url.split(\"/\")[-1]\n\n    if expected_directory.endswith(\".git\"):\n        expected_directory = expected_directory[:-4]\n\n    if not os.path.isdir(expected_directory):\n        session.run(\"git\", \"clone\", \"--depth\", \"1\", git_url, external=True)\n    else:\n        session.run(\n            \"git\", \"-C\", expected_directory, \"reset\", \"--hard\", \"HEAD\", external=True\n        )\n        session.run(\"git\", \"-C\", expected_directory, \"pull\", external=True)\n\n\n@nox.session()\ndef downstream_botocore(session: nox.Session) -> None:\n    root = os.getcwd()\n    tmp_dir = session.create_tmp()\n\n    session.cd(tmp_dir)\n    git_clone(session, \"https://github.com/boto/botocore\")\n    session.chdir(\"botocore\")\n    for patch in [\n        \"0001-Mark-100-Continue-tests-as-failing.patch\",\n        \"0002-Stop-relying-on-removed-DEFAULT_CIPHERS.patch\",\n    ]:\n        session.run(\"git\", \"apply\", f\"{root}/ci/{patch}\", external=True)\n    session.run(\"git\", \"rev-parse\", \"HEAD\", external=True)\n    session.run(\"python\", \"scripts/ci/install\")\n\n    session.cd(root)\n    session.install(\".\", silent=False)\n    session.cd(f\"{tmp_dir}/botocore\")\n\n    session.run(\"python\", \"-c\", \"import urllib3; print(urllib3.__version__)\")\n    session.run(\"python\", \"scripts/ci/run-tests\")\n\n\n@nox.session()\ndef downstream_requests(session: nox.Session) -> None:\n    root = os.getcwd()\n    tmp_dir = session.create_tmp()\n\n    session.cd(tmp_dir)\n    git_clone(session, \"https://github.com/psf/requests\")\n    session.chdir(\"requests\")\n    session.run(\n        \"git\", \"apply\", f\"{root}/ci/0003-requests-removed-warnings.patch\", external=True\n    )\n    session.run(\n        \"git\", \"apply\", f\"{root}/ci/0004-requests-chunked-requests.patch\", external=True\n    )\n    session.run(\"git\", \"rev-parse\", \"HEAD\", external=True)\n    session.install(\".[socks]\", silent=False)\n    session.install(\"-r\", \"requirements-dev.txt\", silent=False)\n\n    session.cd(root)\n    session.install(\".\", silent=False)\n    session.cd(f\"{tmp_dir}/requests\")\n\n    session.run(\"python\", \"-c\", \"import urllib3; print(urllib3.__version__)\")\n    session.run(\"pytest\", \"tests\")\n\n\n@nox.session()\ndef format(session: nox.Session) -> None:\n    \"\"\"Run code formatters.\"\"\"\n    lint(session)\n\n\n@nox.session\ndef lint(session: nox.Session) -> None:\n    session.install(\"pre-commit\")\n    session.run(\"pre-commit\", \"run\", \"--all-files\")\n\n    mypy(session)\n\n\n@nox.session(python=\"3.8\")\ndef mypy(session: nox.Session) -> None:\n    \"\"\"Run mypy.\"\"\"\n    session.install(\"-r\", \"mypy-requirements.txt\")\n    session.run(\"mypy\", \"--version\")\n    session.run(\n        \"mypy\",\n        \"dummyserver\",\n        \"noxfile.py\",\n        \"src/urllib3\",\n        \"test\",\n    )\n\n\n@nox.session\ndef docs(session: nox.Session) -> None:\n    session.install(\"-r\", \"docs/requirements.txt\")\n    session.install(\".[socks,secure,brotli,zstd]\")\n\n    session.chdir(\"docs\")\n    if os.path.exists(\"_build\"):\n        shutil.rmtree(\"_build\")\n    session.run(\"sphinx-build\", \"-b\", \"html\", \"-W\", \".\", \"_build/html\")\n", "path": "noxfile.py"}]}