import os
import sys
import argparse
def flush_and_validate(filepath, expected_lines=None):
"""
Flushes the output of a file and performs basic sanity checks.
Args:
filepath (str): The path to the file.
expected_lines (list, optional): A list of expected lines. Defaults to None.
Returns:
bool: True if the flush was successful and the file contents are valid, False otherwise.
"""
try:
with open(filepath, 'r') as f:
content = f.read() # Read the file content
except FileNotFoundError:
print(f"Error: File not found at {filepath}", file=sys.stderr)
return False
# Flush the output (simulated by writing to a temporary file)
temp_filepath = f"{filepath}.tmp"
with open(temp_filepath, 'w') as temp_f:
temp_f.write(content)
os.replace(temp_filepath, filepath) # Replace original with temp file
if expected_lines:
lines = content.splitlines()
if lines != expected_lines:
print("Error: File content does not match expected lines.", file=sys.stderr)
print(f"Expected: {expected_lines}", file=sys.stderr)
print(f"Actual: {lines}", file=sys.stderr)
return False
else:
print("File flushed successfully and content appears valid.", file=sys.stderr)
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Flush and validate file contents.")
parser.add_argument("filepath", help="Path to the file.")
parser.add_argument("--expected", nargs='+', help="Expected lines (optional).")
args = parser.parse_args()
if flush_and_validate(args.filepath, args.expected):
sys.exit(0) # Success
else:
sys.exit(1) # Failure
Add your comment