1. import os
  2. import sys
  3. import argparse
  4. def flush_and_validate(filepath, expected_lines=None):
  5. """
  6. Flushes the output of a file and performs basic sanity checks.
  7. Args:
  8. filepath (str): The path to the file.
  9. expected_lines (list, optional): A list of expected lines. Defaults to None.
  10. Returns:
  11. bool: True if the flush was successful and the file contents are valid, False otherwise.
  12. """
  13. try:
  14. with open(filepath, 'r') as f:
  15. content = f.read() # Read the file content
  16. except FileNotFoundError:
  17. print(f"Error: File not found at {filepath}", file=sys.stderr)
  18. return False
  19. # Flush the output (simulated by writing to a temporary file)
  20. temp_filepath = f"{filepath}.tmp"
  21. with open(temp_filepath, 'w') as temp_f:
  22. temp_f.write(content)
  23. os.replace(temp_filepath, filepath) # Replace original with temp file
  24. if expected_lines:
  25. lines = content.splitlines()
  26. if lines != expected_lines:
  27. print("Error: File content does not match expected lines.", file=sys.stderr)
  28. print(f"Expected: {expected_lines}", file=sys.stderr)
  29. print(f"Actual: {lines}", file=sys.stderr)
  30. return False
  31. else:
  32. print("File flushed successfully and content appears valid.", file=sys.stderr)
  33. return True
  34. if __name__ == '__main__':
  35. parser = argparse.ArgumentParser(description="Flush and validate file contents.")
  36. parser.add_argument("filepath", help="Path to the file.")
  37. parser.add_argument("--expected", nargs='+', help="Expected lines (optional).")
  38. args = parser.parse_args()
  39. if flush_and_validate(args.filepath, args.expected):
  40. sys.exit(0) # Success
  41. else:
  42. sys.exit(1) # Failure

Add your comment