From ee79940717e354d26954fc4401dc5b0c38980509 Mon Sep 17 00:00:00 2001
From: Hasan <hasan.aleeyev@gmail.com>
Date: Tue, 13 Feb 2024 19:34:11 +0400
Subject: [PATCH] feat: handle error when log file is empty (#4859)

Fixes GH-4686
---
 cloudinit/analyze/show.py            |  4 ++++
 tests/unittests/analyze/test_show.py | 24 ++++++++++++++++++++++++
 2 files changed, 28 insertions(+)
 create mode 100644 tests/unittests/analyze/test_show.py

diff --git a/cloudinit/analyze/show.py b/cloudinit/analyze/show.py
index 8d5866e..7938252 100644
--- a/cloudinit/analyze/show.py
+++ b/cloudinit/analyze/show.py
@@ -7,6 +7,7 @@
 import datetime
 import json
 import os
+import sys
 import time
 
 from cloudinit import subp, util
@@ -370,6 +371,9 @@ def load_events_infile(infile):
     :return: json version of logfile, raw file
     """
     data = infile.read()
+    if not data.strip():
+        sys.stderr.write("Empty file %s\n" % infile.name)
+        sys.exit(1)
     try:
         return json.loads(data), data
     except ValueError:
diff --git a/tests/unittests/analyze/test_show.py b/tests/unittests/analyze/test_show.py
new file mode 100644
index 0000000..0984e90
--- /dev/null
+++ b/tests/unittests/analyze/test_show.py
@@ -0,0 +1,24 @@
+from collections import namedtuple
+
+import pytest
+
+from cloudinit.analyze import analyze_show
+
+
+@pytest.fixture
+def mock_io(tmp_path):
+    """Mock args for configure_io function"""
+    infile = tmp_path / "infile"
+    outfile = tmp_path / "outfile"
+    return namedtuple("MockIO", ["infile", "outfile"])(infile, outfile)
+
+
+class TestAnalyzeShow:
+    """Test analyze_show (and/or helpers) in cloudinit/analyze/__init__.py"""
+
+    def test_empty_logfile(self, mock_io, capsys):
+        """Test analyze_show with an empty logfile"""
+        mock_io.infile.write_text("")
+        with pytest.raises(SystemExit):
+            analyze_show("dontcare", mock_io)
+        assert capsys.readouterr().err == f"Empty file {mock_io.infile}\n"
-- 
2.27.0

