Skip to content

Commit

Permalink
Reland "Replace code quality checks for left over print debug stateme…
Browse files Browse the repository at this point in the history
…nt with semgrep rules"

This reverts commit 23ed539.

Change-Id: Ieaccf48871c176d1f98ae0b2abcc36058bb923b7
  • Loading branch information
LarsMichelsen committed Nov 23, 2024
1 parent 8028618 commit ca14690
Show file tree
Hide file tree
Showing 24 changed files with 95 additions and 187 deletions.
4 changes: 2 additions & 2 deletions cmk/active_checks/check_cmk_inv.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ def main(
completed_process = subprocess.run(cmd, capture_output=True, encoding="utf8", check=False)

if completed_process.stderr:
print(completed_process.stderr, file=sys.stderr)
sys.stderr.write(completed_process.stderr + "\n")

if completed_process.stdout:
print(completed_process.stdout)
sys.stdout.write(completed_process.stdout + "\n")

return completed_process.returncode
7 changes: 3 additions & 4 deletions cmk/base/automations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,10 @@ def execute(self, cmd: str, args: list[str]) -> AutomationExitCode:
profiling.output_profile()

with suppress(IOError):
print(
result.serialize(cmk_version.Version.from_str(cmk_version.__version__)),
flush=True,
file=sys.stdout,
sys.stdout.write(
result.serialize(cmk_version.Version.from_str(cmk_version.__version__)) + "\n"
)
sys.stdout.flush()

return AutomationExitCode.SUCCESS

Expand Down
3 changes: 2 additions & 1 deletion cmk/base/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ def activation_lock(mode: Literal["abort", "wait"] | None) -> Iterator[None]:

def print_(txt: str) -> None:
with suppress(IOError):
print(txt, end="", flush=True, file=sys.stdout)
sys.stdout.write(txt)
sys.stdout.flush()


def do_core_action(
Expand Down
6 changes: 2 additions & 4 deletions cmk/base/core_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,12 +278,10 @@ def do_create_config(
and available for starting the monitoring.
"""
with suppress(IOError):
print(
sys.stdout.write(
"Generating configuration for core (type %s)...\n" % core.name(),
end="",
flush=True,
file=sys.stdout,
)
sys.stdout.flush()

try:
with tracer.start_as_current_span(
Expand Down
6 changes: 4 additions & 2 deletions cmk/base/core_nagios/_create_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,17 @@ def _precompile_hostchecks(
precompile_mode: PrecompileMode,
) -> None:
with suppress(IOError):
print("Precompiling host checks...", end="", flush=True, file=sys.stdout)
sys.stdout.write("Precompiling host checks...")
sys.stdout.flush()
precompile_hostchecks(
config_path,
self._config_cache,
plugins,
precompile_mode=precompile_mode,
)
with suppress(IOError):
print(tty.ok + "\n", end="", flush=True, file=sys.stdout)
sys.stdout.write(tty.ok + "\n")
sys.stdout.flush()


# .--Create config-------------------------------------------------------.
Expand Down
3 changes: 2 additions & 1 deletion cmk/base/core_nagios/_host_check_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ def main() -> int:
)
except KeyboardInterrupt:
with suppress(IOError):
print("<Interrupted>\n", end="", flush=True, file=sys.stderr)
sys.stderr.write("<Interrupted>\n")
sys.stderr.flush()
return 1
except Exception as e:
import traceback
Expand Down
3 changes: 2 additions & 1 deletion cmk/base/dump_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ def _agent_description(cds: ComputedDataSources) -> str:

def print_(txt: str) -> None:
with suppress(IOError):
print(txt, end="", flush=True, file=sys.stdout)
sys.stdout.write(txt)
sys.stdout.flush()


def dump_host(
Expand Down
6 changes: 4 additions & 2 deletions cmk/base/nagios_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

def print_(txt: str) -> None:
with suppress(IOError):
print(txt, end="", flush=True, file=sys.stdout)
sys.stdout.write(txt)
sys.stdout.flush()


def do_check_nagiosconfig() -> bool:
Expand All @@ -37,5 +38,6 @@ def do_check_nagiosconfig() -> bool:

print_("ERROR:\n")
with suppress(IOError):
print(completed_process.stdout, end="", flush=True, file=sys.stderr)
sys.stderr.write(completed_process.stdout)
sys.stdout.flush()
return False
3 changes: 2 additions & 1 deletion cmk/base/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -1816,7 +1816,8 @@ def plugin_log(s: str) -> None:
output_lines.append(output)
if _log_to_stdout:
with suppress(IOError):
print(line, end="", flush=True, file=sys.stdout)
sys.stdout.write(line)
sys.stdout.flush()
except MKTimeout:
plugin_log(
"Notification plug-in did not finish within %d seconds. Terminating."
Expand Down
3 changes: 2 additions & 1 deletion cmk/base/parent_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ def scan_parents_of(
def dot(color: str, dot: str = "o") -> None:
if not silent:
with suppress(IOError):
print(tty.bold + color + dot + tty.normal, end="", flush=True, file=sys.stdout)
sys.stdout.write(tty.bold + color + dot + tty.normal)
sys.stdout.flush()

# Now all run and we begin to read the answers. For each host
# we add a triple to gateways: the gateway, a scan state and a diagnostic output
Expand Down
8 changes: 2 additions & 6 deletions cmk/base/profiling.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,5 @@ def output_profile() -> None:

show_profile.chmod(0o755)
with suppress(IOError):
print(
f"Profile '{_profile_path}' written. Please run {show_profile}.\n",
end="",
flush=True,
file=sys.stderr,
)
sys.stderr.write(f"Profile '{_profile_path}' written. Please run {show_profile}.\n")
sys.stderr.flush()
4 changes: 2 additions & 2 deletions cmk/cmkpasswd.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def _run_cmkpasswd(
if dst_file is not None:
Htpasswd(dst_file).save(user_id, pw_hash)
else:
print(Htpasswd.serialize_entries([(user_id, pw_hash)]))
sys.stdout.write(Htpasswd.serialize_entries([(user_id, pw_hash)]) + "\n")


def main(args: Sequence[str]) -> int:
Expand All @@ -123,7 +123,7 @@ def main(args: Sequence[str]) -> int:
InvalidPasswordError,
InvalidUsernameError,
) as e:
print("cmk-passwd:", e, file=sys.stderr)
sys.stderr.write(f"cmk-passwd: {e}\n")
return 1

return 0
2 changes: 1 addition & 1 deletion omd/packages/omd/omdlib/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def _run_dialog(args: list[str]) -> DialogResult:
# dialog returns 1 on the nolabel answer. But a return code of 1 is
# used for errors. So we need to check the output.
if completed_process.returncode != 0 and completed_process.stderr != "":
print(completed_process.stderr, file=sys.stderr)
sys.stderr.write(completed_process.stderr + "\n")
return completed_process.returncode == 0, completed_process.stderr


Expand Down
8 changes: 4 additions & 4 deletions packages/cmk-frontend-vue/scripts/test_license_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def check(suffix: str, path: Path) -> bool:


def main() -> int:
print("Checking license headers...")
sys.stdout.write("Checking license headers...\n")
problems = []
for root, _dirs, files in Path(".").walk():
if root.parts and root.parts[0] in ROOT_FOLDERS_IGNORED:
Expand All @@ -149,10 +149,10 @@ def main() -> int:
problems.append(path)

if problems:
print("Please check the license header for the following files:")
print("\n".join(str(p) for p in problems))
sys.stdout.write("Please check the license header for the following files:\n")
sys.stdout.write("\n".join(str(p) for p in problems) + "\n")
return 1
print("Done!")
sys.stdout.write("Done!\n")
return 0


Expand Down
9 changes: 5 additions & 4 deletions packages/cmk-frontend/scripts/test_scss_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# conditions defined in the file COPYING, which is part of this source code package.

import re
import sys
import traceback
from collections.abc import Callable, Iterable
from pathlib import Path
Expand Down Expand Up @@ -96,14 +97,14 @@ def test_hex_color_codes() -> None:


def test(function: Callable) -> None:
print(function.__name__)
sys.stdout.write(function.__name__ + "\n")
try:
function()
except Exception:
print(indent(traceback.format_exc().rstrip("\n"), " "))
print(" FAIL")
sys.stdout.write(indent(traceback.format_exc().rstrip("\n"), " ") + "\n")
sys.stdout.write(" FAIL\n")
else:
print(" OK")
sys.stdout.write(" OK\n")


if __name__ == "__main__":
Expand Down
12 changes: 6 additions & 6 deletions packages/cmk-livestatus-client/example_multisite.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@

c = livestatus.MultiSiteConnection(sites) # type: ignore[arg-type]
c.set_prepend_site(True)
print(c.query("GET hosts\nColumns: name state\n"))
sys.stdout.write("%s\n" % c.query("GET hosts\nColumns: name state\n"))
c.set_prepend_site(False)
print(c.query("GET hosts\nColumns: name state\n"))
sys.stdout.write("%s\n" % c.query("GET hosts\nColumns: name state\n"))

# Beware: When doing stats, you need to aggregate yourself:
print(sum(c.query_column("GET hosts\nStats: state >= 0\n")))
sys.stdout.write("%d\n" % sum(c.query_column("GET hosts\nStats: state >= 0\n")))

# Detect errors:
sites = {
Expand All @@ -70,7 +70,7 @@

c = livestatus.MultiSiteConnection(sites) # type: ignore[arg-type]
for name, state in c.query("GET hosts\nColumns: name state\n"):
print("%-15s: %d" % (name, state))
print("Dead sites:")
sys.stdout.write("%-15s: %d\n" % (name, state))
sys.stdout.write("Dead sites:\n")
for sitename, info in c.dead_sites().items():
print("{}: {}".format(sitename, info["exception"]))
sys.stdout.write("{}: {}\n".format(sitename, info["exception"]))
20 changes: 11 additions & 9 deletions packages/cmk-livestatus-client/example_singlesite.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,22 @@

try:
# Make a single connection for each query
print("\nPerformance:")
sys.stdout.write("\nPerformance:\n")
for key, value in (
livestatus.SingleSiteConnection(socket_path).query_row_assoc("GET status").items()
):
print("%-30s: %s" % (key, value))
print("\nHosts:")
sys.stdout.write("%-30s: %s\n" % (key, value))
sys.stdout.write("\nHosts:\n")
hosts = livestatus.SingleSiteConnection(socket_path).query_table(
"GET hosts\nColumns: name alias address"
)
for name, alias, address in hosts:
print("%-16s %-16s %s" % (name, address, alias))
sys.stdout.write("%-16s %-16s %s\n" % (name, address, alias))

# Do several queries in one connection
conn = livestatus.SingleSiteConnection(socket_path)
num_up = conn.query_value("GET hosts\nStats: hard_state = 0")
print("\nHosts up: %d" % num_up)
sys.stdout.write("\nHosts up: %d\n" % num_up)

stats = conn.query_row(
"GET services\n"
Expand All @@ -44,12 +44,14 @@
"Stats: state = 2\n"
"Stats: state = 3\n"
)
print("Service stats: %d/%d/%d/%d" % tuple(stats))
sys.stdout.write("Service stats: %d/%d/%d/%d\n" % tuple(stats))

print("List of commands: %s" % ", ".join(conn.query_column("GET commands\nColumns: name")))
sys.stdout.write(
"List of commands: %s\n" % ", ".join(conn.query_column("GET commands\nColumns: name"))
)

print("Query error:")
sys.stdout.write("Query error:\n")
conn.query_value("GET hosts\nColumns: hirni")

except Exception as e: # livestatus.MKLivestatusException, e:
print("Livestatus error: %s" % str(e))
sys.stdout.write("Livestatus error: %s\n" % str(e))
14 changes: 6 additions & 8 deletions packages/cmk-werks/cmk/werks/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -871,14 +871,12 @@ def edit_werk(werk_path: Path, custom_files: list[str] | None = None, commit: bo
cmk_werks_load_werk(file_content=werk.path.read_text(), file_name=werk.path.name)
break
except Exception: # pylint: disable=broad-exception-caught
print(initial_werk_text)
print()
print(traceback.format_exc())
print()
print(
sys.stdout.write(initial_werk_text + "\n\n")
sys.stdout.write(traceback.format_exc() + "\n\n")
sys.stdout.write(
"Could not load the werk, see exception above.\n"
"You may copy the initial werk text above the exception to fix your werk.\n"
"Will reopen the editor, after you acknowledged with enter"
"Will reopen the editor, after you acknowledged with enter\n"
)
input()

Expand Down Expand Up @@ -1071,7 +1069,7 @@ def meta_data() -> Iterator[str]:
yield f"<dt>{item}<dt><dd>{getattr(werk, item)}</dd>"

definition_list = "\n".join(meta_data())
print(
sys.stdout.write(
f'<!DOCTYPE html><html lang="en" style="font-family:sans-serif;">'
"<head>"
f"<title>Preview of werk {args.id}</title>"
Expand All @@ -1081,7 +1079,7 @@ def meta_data() -> Iterator[str]:
f'<div style="background-color:#fff; padding: 10px;">{werk.description}</div>'
f"<dl>{definition_list}</dl>"
"</body>"
"</html>"
"</html>\n"
)


Expand Down
3 changes: 2 additions & 1 deletion packages/cmk-werks/cmk/werks/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import logging
import re
import sys
from collections import defaultdict
from collections.abc import Iterable, Mapping
from pathlib import Path
Expand Down Expand Up @@ -158,4 +159,4 @@ def main(config: Config, repo_path: Path, branches: Mapping[str, str]) -> None:
**werk_dict, # type: ignore[arg-type]
).model_dump(by_alias=True, mode="json")

print(json.dumps(all_werks_by_id))
sys.stdout.write(json.dumps(all_werks_by_id) + "\n")
3 changes: 2 additions & 1 deletion packages/cmk-werks/cmk/werks/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import argparse
import os
import re
import sys
from pathlib import Path

from . import load_werk
Expand Down Expand Up @@ -49,7 +50,7 @@ def main(
except Exception as e:
raise RuntimeError(f"Error while loading werk {werk_path}\n\n{werk_content}") from e

print(f"Successfully validated {len(werks_to_check)} werks")
sys.stdout.write(f"Successfully validated {len(werks_to_check)} werks\n")


def parse_args() -> argparse.Namespace:
Expand Down
31 changes: 0 additions & 31 deletions tests/code_quality/file_content/test_find_debug_code_web.py

This file was deleted.

Loading

0 comments on commit ca14690

Please sign in to comment.