check_npk.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. import yaml
  5. import argparse
  6. def find_files(directory, file_name):
  7. """
  8. Recursively search the specified directory and its subdirectories for files with the given name.
  9. :param directory: The path to the directory to search in.
  10. :param file_name: The name of the file to find.
  11. :return: A list of paths to all found files.
  12. """
  13. found_files = []
  14. for root, dirs, files in os.walk(directory):
  15. if file_name in files:
  16. found_files.append(os.path.join(root, file_name))
  17. return found_files
  18. def validate_yaml(file_path):
  19. """
  20. Validate a YAML file to check if it is a valid YAML document.
  21. :param file_path: The path to the YAML file.
  22. :return: A tuple containing a boolean (True if the file is valid, False otherwise) and an error message (if the file is invalid).
  23. """
  24. try:
  25. with open(file_path, 'r') as file:
  26. yaml.safe_load(file)
  27. return True, None
  28. except yaml.YAMLError as exc:
  29. return False, exc
  30. def main():
  31. parser = argparse.ArgumentParser(description="Validate npk.yml files.")
  32. parser.add_argument("-d", "--directory", required=True, help="The directory to search for npk.yml files.")
  33. args = parser.parse_args()
  34. # Check if the directory exists
  35. if not os.path.isdir(args.directory):
  36. print("The directory {} does not exist!".format(args.directory))
  37. sys.exit(1)
  38. yaml_files = find_files(args.directory, "npk.yml")
  39. failed_files = []
  40. for file_path in yaml_files:
  41. is_valid, error = validate_yaml(file_path)
  42. if not is_valid:
  43. print("- {}: FAIL".format(file_path))
  44. failed_files.append((file_path, error))
  45. else:
  46. print("- {}: PASS".format(file_path))
  47. if failed_files:
  48. print("\nFailed npk.yml files with reasons:")
  49. for file_path, error in failed_files:
  50. print("- {}: {}".format(file_path, error))
  51. # Exit with a non-zero status code if there were failures
  52. sys.exit(1)
  53. # Exit with a zero status code if all files are valid
  54. sys.exit(0)
  55. if __name__ == "__main__":
  56. main()