From e50046688f734f65f452de9b8feb10189efd7c1b Mon Sep 17 00:00:00 2001 From: Martin Lambertsen Date: Sun, 8 Jan 2023 23:49:07 +0100 Subject: [PATCH] Fix some resource leaks by open file handles --- git/repo/base.py | 9 +++++++-- git/repo/fun.py | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/git/repo/base.py b/git/repo/base.py index 4a3704c0b..30f71b0c8 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -9,6 +9,9 @@ import re import shlex import warnings + +from pathlib import Path + from gitdb.db.loose import LooseObjectDB from gitdb.exc import BadObject @@ -268,7 +271,7 @@ def __init__( pass try: - common_dir = open(osp.join(self.git_dir, "commondir"), "rt").readlines()[0].strip() + common_dir = (Path(self.git_dir) / "commondir").read_text().splitlines()[0].strip() self._common_dir = osp.join(self.git_dir, common_dir) except OSError: self._common_dir = "" @@ -1385,4 +1388,6 @@ def currently_rebasing_on(self) -> Commit | None: rebase_head_file = osp.join(self.git_dir, "REBASE_HEAD") if not osp.isfile(rebase_head_file): return None - return self.commit(open(rebase_head_file, "rt").readline().strip()) + with open(rebase_head_file, "rt") as f: + content = f.readline().strip() + return self.commit(content) diff --git a/git/repo/fun.py b/git/repo/fun.py index 2ca2e3d6f..ae35aa81e 100644 --- a/git/repo/fun.py +++ b/git/repo/fun.py @@ -2,6 +2,7 @@ from __future__ import annotations import os import stat +from pathlib import Path from string import digits from git.exc import WorkTreeRepositoryUnsupported @@ -83,7 +84,7 @@ def find_worktree_git_dir(dotgit: "PathLike") -> Optional[str]: return None try: - lines = open(dotgit, "r").readlines() + lines = Path(dotgit).read_text().splitlines() for key, value in [line.strip().split(": ") for line in lines]: if key == "gitdir": return value