Skip to content
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

[DRAFT] Make ChecksumMismatch prettier, CLI and __str__ #27

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
33 changes: 30 additions & 3 deletions src/ansible_sign/checksum/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,33 @@ class NoDifferException(Exception):


class ChecksumMismatch(Exception):
pass
def __init__(self, msg, differences={}):
super().__init__(msg)
self.msg = msg
self.differences = differences

def __str__(self):
"""
This *must* be something human-readable, it is currently used in the AWX
action plugin on project sync when validation fails.
"""
out = self.msg
extra_info = ""
if "changes" in self.differences and self.differences["changes"]:
extra_info += f"Files changed: {', '.join(self.differences['changes'])}"

if "added" in self.differences and self.differences["added"]:
sep = "; " if extra_info else ""
extra_info += f"{sep}Files added: {', '.join(self.differences['added'])}"

if "removed" in self.differences and self.differences["removed"]:
sep = "; " if extra_info else ""
extra_info += f"{sep}Files removed: {', '.join(self.differences['removed'])}"

if extra_info:
return f"{out}. {extra_info}"

return out


class ChecksumFile:
Expand Down Expand Up @@ -166,14 +192,15 @@ def verify(self, parsed_manifest_dct, diff=True):
# If there are any differences in existing paths, fail the check...
differences = self.diff(parsed_manifest_dct.keys())
if differences["added"] or differences["removed"]:
raise ChecksumMismatch(differences)
raise ChecksumMismatch("Files were added or removed", differences)

recalculated = self.calculate_checksums_from_root(verifying=True)
mismatches = set()
for parsed_path, parsed_checksum in parsed_manifest_dct.items():
if recalculated[parsed_path] != parsed_checksum:
mismatches.add(parsed_path)
if mismatches:
raise ChecksumMismatch(f"Checksum mismatch: {', '.join(mismatches)}")
differences = {"changes": list(mismatches)}
raise ChecksumMismatch("Checksum mismatch", differences)

return True
29 changes: 28 additions & 1 deletion src/ansible_sign/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ def parse_args(self, args):
dest="gnupg_home",
default=None,
)
cmd_gpg_verify.add_argument(
"--no-truncate",
help="Disable truncation of file listings when enumerating file differences",
required=False,
dest="no_truncate",
default=False,
action="store_true",
)
cmd_gpg_verify.add_argument(
"project_root",
help="The directory containing the files being validated and verified",
Expand Down Expand Up @@ -227,7 +235,26 @@ def validate_checksum(self):
checksum.verify(manifest, diff=True)
except ChecksumMismatch as e:
self._error("Checksum validation failed.")
self._error(str(e))
if e.differences:
differences = (
("added", "added"),
("removed", "removed"),
("changes", "changed"),
)
for key, verb in differences:
if key in e.differences and e.differences[key]:
self._note(f"Files {verb}:")
num_changes = len(e.differences[key])
if self.args.no_truncate:
truncate_at = num_changes
truncated = False
else:
truncate_at = 6
truncated = num_changes > truncate_at
for path in e.differences[key][0:(truncate_at)]:
self._note(f" - {path}")
if truncated:
self._note(f" [{num_changes - truncate_at} lines omitted, use --no-truncate to see all...]")
return 2
except FileNotFoundError as e:
if os.path.islink(e.filename):
Expand Down
10 changes: 5 additions & 5 deletions tests/test_checksum.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,27 +116,27 @@ def test_parse_manifest_empty():
[
(
"files-added",
"{'added': ['hello2', 'hello3'], 'removed': []}",
"Files were added or removed. Files added: hello2, hello3",
),
(
"files-added-removed",
"{'added': ['hello2', 'hello3'], 'removed': ['hello1']}",
"Files were added or removed. Files added: hello2, hello3; Files removed: hello1",
),
(
"files-removed",
"{'added': [], 'removed': ['hello1']}",
"Files were added or removed. Files removed: hello1",
),
(
"files-changed",
"Checksum mismatch: hello1",
"Checksum mismatch. Files changed: hello1",
),
(
"success",
True,
),
],
)
def test_directory_diff(
def test_directory_diff_human_readable_exc(
fixture,
diff_output,
):
Expand Down