|
| 1 | +# Copyright (c) 2025 - 2025, Oracle and/or its affiliates. All rights reserved. |
| 2 | +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/. |
| 3 | + |
| 4 | +"""This script compares 2 Reproducible Central Buildspec files.""" |
| 5 | + |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from collections.abc import Callable |
| 10 | + |
| 11 | +CompareFn = Callable[[object, object], bool] |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | +logger.setLevel(logging.DEBUG) |
| 15 | +logging.basicConfig(format="[%(filename)s:%(lineno)s %(tag)s] %(message)s") |
| 16 | + |
| 17 | + |
| 18 | +def log_with_tag(tag: str) -> Callable[[str], None]: |
| 19 | + """Generate a log function that prints the name of the file and a tag at the beginning of each line.""" |
| 20 | + |
| 21 | + def log_fn(msg: str) -> None: |
| 22 | + logger.info(msg, extra={"tag": tag}) |
| 23 | + |
| 24 | + return log_fn |
| 25 | + |
| 26 | + |
| 27 | +log_info = log_with_tag("INFO") |
| 28 | +log_err = log_with_tag("ERROR") |
| 29 | +log_failed = log_with_tag("FAILED") |
| 30 | +log_passed = log_with_tag("PASSED") |
| 31 | + |
| 32 | + |
| 33 | +def log_diff_str(name: str, result: str, expected: str) -> None: |
| 34 | + """Pretty-print the diff of two Python strings.""" |
| 35 | + output = [ |
| 36 | + f"'{name}'", |
| 37 | + *("---- Result ---", f"{result}"), |
| 38 | + *("---- Expected ---", f"{expected}"), |
| 39 | + "-----------------", |
| 40 | + ] |
| 41 | + log_info("\n".join(output)) |
| 42 | + |
| 43 | + |
| 44 | +def skip_compare(_result: object, _expected: object) -> bool: |
| 45 | + """Return ``True`` always. |
| 46 | +
|
| 47 | + This compare function is used when we want to skip comparing a field. |
| 48 | + """ |
| 49 | + return True |
| 50 | + |
| 51 | + |
| 52 | +def compare_rc_build_spec( |
| 53 | + result: dict[str, str], |
| 54 | + expected: dict[str, str], |
| 55 | + compare_fn_map: dict[str, CompareFn], |
| 56 | +) -> bool: |
| 57 | + """Compare two dictionaries obatained from 2 Reproducible Central build spec. |
| 58 | +
|
| 59 | + Parameters |
| 60 | + ---------- |
| 61 | + result : dict[str, str] |
| 62 | + The result object. |
| 63 | + expected : dict[str, str] |
| 64 | + The expected object. |
| 65 | + compare_fn_map : str |
| 66 | + A map from field name to corresponding compare function. |
| 67 | +
|
| 68 | + Returns |
| 69 | + ------- |
| 70 | + bool |
| 71 | + ``True`` if the comparison is successful, ``False`` otherwise. |
| 72 | + """ |
| 73 | + result_keys_only = result.keys() - expected.keys() |
| 74 | + expected_keys_only = expected.keys() - result.keys() |
| 75 | + |
| 76 | + equal = True |
| 77 | + |
| 78 | + if len(result_keys_only) > 0: |
| 79 | + log_err(f"Result has the following extraneous fields: {result_keys_only}") |
| 80 | + equal = False |
| 81 | + |
| 82 | + if len(expected_keys_only) > 0: |
| 83 | + log_err(f"Result does not contain these expected fields: {expected_keys_only}") |
| 84 | + equal = False |
| 85 | + |
| 86 | + common_keys = set(result.keys()).intersection(set(expected.keys())) |
| 87 | + |
| 88 | + for key in common_keys: |
| 89 | + if key in compare_fn_map: |
| 90 | + equal &= compare_fn_map[key](result, expected) |
| 91 | + continue |
| 92 | + |
| 93 | + if result[key] != expected[key]: |
| 94 | + log_err(f"Mismatch found in '{key}'") |
| 95 | + log_diff_str(key, result[key], expected[key]) |
| 96 | + equal = False |
| 97 | + |
| 98 | + return equal |
| 99 | + |
| 100 | + |
| 101 | +def extract_data_from_build_spec(build_spec_path: str) -> dict[str, str] | None: |
| 102 | + """Extract data from build spec.""" |
| 103 | + original_build_spec_content = None |
| 104 | + try: |
| 105 | + with open(build_spec_path, encoding="utf-8") as build_spec_file: |
| 106 | + original_build_spec_content = build_spec_file.read() |
| 107 | + except OSError as error: |
| 108 | + log_err(f"Failed to read the Reproducible Central Buildspec file at {build_spec_path}. Error {error}.") |
| 109 | + return None |
| 110 | + |
| 111 | + build_spec_values: dict[str, str] = {} |
| 112 | + |
| 113 | + # A Reproducible Central buildspec is a valid bash script. |
| 114 | + # We use the following assumption to parse all key value mapping in a Reproducible Central buildspec. |
| 115 | + # 1. Each variable-value mapping has the form of |
| 116 | + # <variable>=<value> |
| 117 | + # For example ``tool=mvn`` |
| 118 | + # 2. If the first letter of a line is "#" we treat that line as a comment and ignore |
| 119 | + # it. |
| 120 | + for line in original_build_spec_content.splitlines(): |
| 121 | + if not line or line.startswith("#"): |
| 122 | + continue |
| 123 | + |
| 124 | + variable, _, value = line.partition("=") |
| 125 | + # We allow defining a variable multiple times, where subsequent definition |
| 126 | + # override the previous one. |
| 127 | + build_spec_values[variable] = value |
| 128 | + |
| 129 | + return build_spec_values |
| 130 | + |
| 131 | + |
| 132 | +def main() -> int: |
| 133 | + """Compare a Reproducible Central Buildspec file with an expected output.""" |
| 134 | + result_path = sys.argv[1] |
| 135 | + expect_path = sys.argv[2] |
| 136 | + |
| 137 | + result_build_spec = extract_data_from_build_spec(result_path) |
| 138 | + expect_build_spec = extract_data_from_build_spec(expect_path) |
| 139 | + |
| 140 | + if not expect_build_spec: |
| 141 | + log_err(f"Failed to extract bash variables from expected Buildspec at {expect_path}.") |
| 142 | + return os.EX_USAGE |
| 143 | + |
| 144 | + if not result_build_spec: |
| 145 | + log_err(f"Failed to extract bash variables from result Buildspec at {result_build_spec}.") |
| 146 | + return os.EX_USAGE |
| 147 | + |
| 148 | + equal = compare_rc_build_spec( |
| 149 | + result=result_build_spec, |
| 150 | + expected=expect_build_spec, |
| 151 | + compare_fn_map={ |
| 152 | + "buildinfo": skip_compare, |
| 153 | + }, |
| 154 | + ) |
| 155 | + |
| 156 | + if not equal: |
| 157 | + log_failed("The result RC Buildspec does not match the RC Buildspec.") |
| 158 | + return os.EX_DATAERR |
| 159 | + |
| 160 | + log_passed("The result RC Buildspec matches the RC Buildspec.") |
| 161 | + return os.EX_OK |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + raise SystemExit(main()) |
0 commit comments