Skip to content

Don't suppress messages when logging is not configured #1813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions git/cmd.py
Original file line number Diff line number Diff line change
@@ -81,8 +81,7 @@
"strip_newline_in_stdout",
}

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
_logger = logging.getLogger(__name__)

__all__ = ("Git",)

@@ -146,7 +145,7 @@ def pump_stream(
handler(line)

except Exception as ex:
log.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")
_logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text.
if "I/O operation on closed file" not in str(ex):
# Only reraise if the error was not due to the stream closing
raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex
@@ -600,7 +599,7 @@ def _terminate(self) -> None:
self.status = self._status_code_if_terminate or proc.poll()
return
except OSError as ex:
log.info("Ignored error after process had died: %r", ex)
_logger.info("Ignored error after process had died: %r", ex)

# It can be that nothing really exists anymore...
if os is None or getattr(os, "kill", None) is None:
@@ -613,7 +612,7 @@ def _terminate(self) -> None:

self.status = self._status_code_if_terminate or status
except OSError as ex:
log.info("Ignored error after process had died: %r", ex)
_logger.info("Ignored error after process had died: %r", ex)
# END exception handling

def __del__(self) -> None:
@@ -654,7 +653,7 @@ def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> byte

if status != 0:
errstr = read_all_from_possibly_closed_stream(p_stderr)
log.debug("AutoInterrupt wait stderr: %r" % (errstr,))
_logger.debug("AutoInterrupt wait stderr: %r" % (errstr,))
raise GitCommandError(remove_password_if_present(self.args), status, errstr)
return status

@@ -1018,7 +1017,7 @@ def execute(
# Remove password for the command if present.
redacted_command = remove_password_if_present(command)
if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process):
log.info(" ".join(redacted_command))
_logger.info(" ".join(redacted_command))

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text.

# Allow the user to have the command executed in their working dir.
try:
@@ -1055,7 +1054,7 @@ def execute(
stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb")
if shell is None:
shell = self.USE_SHELL
log.debug(
_logger.debug(
"Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)",
redacted_command,
cwd,
@@ -1167,17 +1166,17 @@ def as_text(stdout_value: Union[bytes, str]) -> str:
# END as_text

if stderr_value:
log.info(
_logger.info(
"%s -> %d; stdout: '%s'; stderr: '%s'",
cmdstr,
status,
as_text(stdout_value),
safe_decode(stderr_value),
)
elif stdout_value:
log.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
_logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text.
else:
log.info("%s -> %d", cmdstr, status)
_logger.info("%s -> %d", cmdstr, status)

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text.
# END handle debug printing

if with_exceptions and status != 0:
9 changes: 3 additions & 6 deletions git/config.py
Original file line number Diff line number Diff line change
@@ -60,10 +60,7 @@

__all__ = ("GitConfigParser", "SectionConstraint")


log = logging.getLogger("git.config")
log.addHandler(logging.NullHandler())

_logger = logging.getLogger(__name__)

CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository")
"""The configuration level of a configuration file."""
@@ -412,7 +409,7 @@ def release(self) -> None:
try:
self.write()
except IOError:
log.error("Exception during destruction of GitConfigParser", exc_info=True)
_logger.error("Exception during destruction of GitConfigParser", exc_info=True)
except ReferenceError:
# This happens in Python 3... and usually means that some state cannot be
# written as the sections dict cannot be iterated. This usually happens when
@@ -712,7 +709,7 @@ def write(self) -> None:
# END assert multiple files

if self._has_includes():
log.debug(
_logger.debug(
"Skipping write-back of configuration file as include files were merged in."
+ "Set merge_includes=False to prevent this."
)
9 changes: 4 additions & 5 deletions git/objects/commit.py
Original file line number Diff line number Diff line change
@@ -52,8 +52,7 @@

# ------------------------------------------------------------------------

log = logging.getLogger("git.objects.commit")
log.addHandler(logging.NullHandler())
_logger = logging.getLogger(__name__)

__all__ = ("Commit",)

@@ -767,7 +766,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
self.author_tz_offset,
) = parse_actor_and_date(author_line.decode(self.encoding, "replace"))
except UnicodeDecodeError:
log.error(
_logger.error(
"Failed to decode author line '%s' using encoding %s",
author_line,
self.encoding,
@@ -781,7 +780,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
self.committer_tz_offset,
) = parse_actor_and_date(committer_line.decode(self.encoding, "replace"))
except UnicodeDecodeError:
log.error(
_logger.error(
"Failed to decode committer line '%s' using encoding %s",
committer_line,
self.encoding,
@@ -795,7 +794,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
try:
self.message = self.message.decode(self.encoding, "replace")
except UnicodeDecodeError:
log.error(
_logger.error(
"Failed to decode message '%s' using encoding %s",
self.message,
self.encoding,
18 changes: 8 additions & 10 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
@@ -40,6 +40,7 @@


# typing ----------------------------------------------------------------------

from typing import Callable, Dict, Mapping, Sequence, TYPE_CHECKING, cast
from typing import Any, Iterator, Union

@@ -50,14 +51,11 @@
from git.repo import Repo
from git.refs import Head


# -----------------------------------------------------------------------------

__all__ = ["Submodule", "UpdateProgress"]


log = logging.getLogger("git.objects.submodule.base")
log.addHandler(logging.NullHandler())
_logger = logging.getLogger(__name__)


class UpdateProgress(RemoteProgress):
@@ -731,7 +729,7 @@ def update(
)
mrepo.head.reference.set_tracking_branch(remote_branch)
except (IndexError, InvalidGitRepositoryError):
log.warning("Failed to checkout tracking branch %s", self.branch_path)
_logger.warning("Failed to checkout tracking branch %s", self.branch_path)
# END handle tracking branch

# NOTE: Have to write the repo config file as well, otherwise the
@@ -761,14 +759,14 @@ def update(
binsha = rcommit.binsha
hexsha = rcommit.hexsha
else:
log.error(
_logger.error(
"%s a tracking branch was not set for local branch '%s'",
msg_base,
mrepo.head.reference,
)
# END handle remote ref
else:
log.error("%s there was no local tracking branch", msg_base)
_logger.error("%s there was no local tracking branch", msg_base)
# END handle detached head
# END handle to_latest_revision option

@@ -786,15 +784,15 @@ def update(
if force:
msg = "Will force checkout or reset on local branch that is possibly in the future of"
msg += " the commit it will be checked out to, effectively 'forgetting' new commits"
log.debug(msg)
_logger.debug(msg)
else:
msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits"
msg %= (
is_detached and "checkout" or "reset",
mrepo.head,
mrepo,
)
log.info(msg)
_logger.info(msg)
may_reset = False
# END handle force
# END handle if we are in the future
@@ -834,7 +832,7 @@ def update(
except Exception as err:
if not keep_going:
raise
log.error(str(err))
_logger.error(str(err))
# END handle keep_going

# HANDLE RECURSION
7 changes: 3 additions & 4 deletions git/objects/submodule/root.py
Original file line number Diff line number Diff line change
@@ -22,8 +22,7 @@

__all__ = ["RootModule", "RootUpdateProgress"]

log = logging.getLogger("git.objects.submodule.root")
log.addHandler(logging.NullHandler())
_logger = logging.getLogger(__name__)


class RootUpdateProgress(UpdateProgress):
@@ -321,7 +320,7 @@ def update(
# this way, it will be checked out in the next step.
# This will change the submodule relative to us, so
# the user will be able to commit the change easily.
log.warning(
_logger.warning(
"Current sha %s was not contained in the tracking\
branch at the new remote, setting it the the remote's tracking branch",
sm.hexsha,
@@ -393,7 +392,7 @@ def update(
except Exception as err:
if not keep_going:
raise
log.error(str(err))
_logger.error(str(err))
# END handle keep_going

# FINALLY UPDATE ALL ACTUAL SUBMODULES
19 changes: 8 additions & 11 deletions git/remote.py
Original file line number Diff line number Diff line change
@@ -64,10 +64,7 @@

# -------------------------------------------------------------


log = logging.getLogger("git.remote")
log.addHandler(logging.NullHandler())

_logger = logging.getLogger(__name__)

__all__ = ("RemoteProgress", "PushInfo", "FetchInfo", "Remote")

@@ -857,7 +854,7 @@ def _get_fetch_info_from_stderr(
stderr_text = progress.error_lines and "\n".join(progress.error_lines) or ""
proc.wait(stderr=stderr_text)
if stderr_text:
log.warning("Error lines received while fetching: %s", stderr_text)
_logger.warning("Error lines received while fetching: %s", stderr_text)

for line in progress.other_lines:
line = force_text(line)
@@ -878,9 +875,9 @@ def _get_fetch_info_from_stderr(
msg += "length of progress lines %i should be equal to lines in FETCH_HEAD file %i\n"
msg += "Will ignore extra progress lines or fetch head lines."
msg %= (l_fil, l_fhi)
log.debug(msg)
log.debug(b"info lines: " + str(fetch_info_lines).encode("UTF-8"))
log.debug(b"head info: " + str(fetch_head_info).encode("UTF-8"))
_logger.debug(msg)
_logger.debug(b"info lines: " + str(fetch_info_lines).encode("UTF-8"))
_logger.debug(b"head info: " + str(fetch_head_info).encode("UTF-8"))
if l_fil < l_fhi:
fetch_head_info = fetch_head_info[:l_fil]
else:
@@ -892,8 +889,8 @@ def _get_fetch_info_from_stderr(
try:
output.append(FetchInfo._from_line(self.repo, err_line, fetch_line))
except ValueError as exc:
log.debug("Caught error while parsing line: %s", exc)
log.warning("Git informed while fetching: %s", err_line.strip())
_logger.debug("Caught error while parsing line: %s", exc)
_logger.warning("Git informed while fetching: %s", err_line.strip())
return output

def _get_push_info(
@@ -935,7 +932,7 @@ def stdout_handler(line: str) -> None:
if not output:
raise
elif stderr_text:
log.warning("Error lines received while fetching: %s", stderr_text)
_logger.warning("Error lines received while fetching: %s", stderr_text)
output.error = e

return output
8 changes: 4 additions & 4 deletions git/repo/base.py
Original file line number Diff line number Diff line change
@@ -89,7 +89,7 @@

# -----------------------------------------------------------

log = logging.getLogger(__name__)
_logger = logging.getLogger(__name__)

__all__ = ("Repo",)

@@ -772,7 +772,7 @@ def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> boo
if object_info.type == object_type.encode():
return True
else:
log.debug(
_logger.debug(
"Commit hash points to an object of type '%s'. Requested were objects of type '%s'",
object_info.type.decode(),
object_type,
@@ -781,7 +781,7 @@ def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> boo
else:
return True
except BadObject:
log.debug("Commit hash is invalid.")
_logger.debug("Commit hash is invalid.")
return False

def _get_daemon_export(self) -> bool:
@@ -1298,7 +1298,7 @@ def _clone(
cmdline = getattr(proc, "args", "")
cmdline = remove_password_if_present(cmdline)

log.debug("Cmd(%s)'s unused stdout: %s", cmdline, stdout)
_logger.debug("Cmd(%s)'s unused stdout: %s", cmdline, stdout)

Check failure

Code scanning / CodeQL

Clear-text logging of sensitive information

This expression logs [sensitive data (password)](1) as clear text. This expression logs [sensitive data (password)](1) as clear text. This expression logs [sensitive data (password)](1) as clear text. This expression logs [sensitive data (password)](1) as clear text.
finalize_process(proc, stderr=stderr)

# Our git command could have a different working dir than our actual
8 changes: 4 additions & 4 deletions git/util.py
Original file line number Diff line number Diff line change
@@ -104,7 +104,7 @@
"HIDE_WINDOWS_KNOWN_ERRORS",
]

log = logging.getLogger(__name__)
_logger = logging.getLogger(__name__)


def _read_win_env_flag(name: str, default: bool) -> bool:
@@ -124,7 +124,7 @@ def _read_win_env_flag(name: str, default: bool) -> bool:
except KeyError:
return default

log.warning(
_logger.warning(
"The %s environment variable is deprecated. Its effect has never been documented and changes without warning.",
name,
)
@@ -135,7 +135,7 @@ def _read_win_env_flag(name: str, default: bool) -> bool:
return False
if adjusted_value in {"1", "true", "yes"}:
return True
log.warning("%s has unrecognized value %r, treating as %r.", name, value, default)
_logger.warning("%s has unrecognized value %r, treating as %r.", name, value, default)
return default


@@ -466,7 +466,7 @@ def is_cygwin_git(git_executable: Union[None, PathLike]) -> bool:
# retcode = process.poll()
is_cygwin = "CYGWIN" in uname_out
except Exception as ex:
log.debug("Failed checking if running in CYGWIN due to: %r", ex)
_logger.debug("Failed checking if running in CYGWIN due to: %r", ex)
_is_cygwin_cache[git_executable] = is_cygwin

return is_cygwin
Loading