From c4abc31e51223633978c72217fe193a8880fa702 Mon Sep 17 00:00:00 2001 From: Pradyun Gedam Date: Thu, 18 Sep 2025 16:10:31 +0100 Subject: [PATCH 1/2] Append to `.gitignore` instead of overwriting it Help ensure that the `.gitignore` file is not destroyed, if an environment is created in a directory that already exists. --- Lib/test/test_venv.py | 14 ++++++++++++++ Lib/venv/__init__.py | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 3c18c9c2900ad7..a2e9cabffb70cb 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -787,6 +787,20 @@ def test_scm_ignore_files_git(self): file_lines = self.get_text_file_contents('.gitignore').splitlines() self.assertIn('*', file_lines) + @requireVenvCreate + def test_scm_ignore_files_git_appends_to_existing_file(self): + """Test that an existing .gitignore file is appended to.""" + gitignore_path = self.get_env_file('.gitignore') + with open(gitignore_path, 'w', encoding='utf-8') as fp: + fp.write("# Existing comment\n") + + self.run_with_capture(venv.create, self.env_dir, + scm_ignore_files={'git'}) + + file_lines = self.get_text_file_contents('.gitignore').splitlines() + self.assertIn('# Existing comment', file_lines) + self.assertIn('*', file_lines) + @requireVenvCreate def test_create_scm_ignore_files_multiple(self): """ diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index dc9c5991df7e1c..a5d688776a3fd1 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -293,8 +293,8 @@ def create_git_ignore_file(self, context): ignored by git. """ gitignore_path = os.path.join(context.env_dir, '.gitignore') - with open(gitignore_path, 'w', encoding='utf-8') as file: - file.write('# Created by venv; ' + with open(gitignore_path, 'a', encoding='utf-8') as file: + file.write('# Added by venv; ' 'see https://docs.python.org/3/library/venv.html\n') file.write('*\n') From ec8e80db1816a6723600b267c980cf6413ce7489 Mon Sep 17 00:00:00 2001 From: Pradyun Gedam Date: Thu, 18 Sep 2025 16:14:02 +0100 Subject: [PATCH 2/2] Add news entry --- .../next/Library/2025-09-18-16-13-54.gh-issue-135604.pSPFfp.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2025-09-18-16-13-54.gh-issue-135604.pSPFfp.rst diff --git a/Misc/NEWS.d/next/Library/2025-09-18-16-13-54.gh-issue-135604.pSPFfp.rst b/Misc/NEWS.d/next/Library/2025-09-18-16-13-54.gh-issue-135604.pSPFfp.rst new file mode 100644 index 00000000000000..1f08b1d4121f5e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-09-18-16-13-54.gh-issue-135604.pSPFfp.rst @@ -0,0 +1 @@ +Change ``venv`` to append ``*`` to ``.gitignore`` instead of overwriting it.