Source code for suricata_check.utils._path

 1import logging
 2import os
 3
 4import click
 5
 6_logger = logging.getLogger(__name__)
 7
 8
[docs] 9def find_rules_file(root: str) -> str: 10 """Find the Suricata rules file in the given directory. 11 12 Returns an absolute path to the rules file. 13 """ 14 if not os.path.exists(root): 15 msg = f"Error: {root} does not exist." 16 _logger.critical(msg) 17 raise click.BadParameter(f"Error: {msg}") 18 19 is_root_dir = os.path.isdir(root) 20 if not root.endswith(".rules") and not is_root_dir: 21 msg = f"Error: {root} is not a rules file or directory." 22 _logger.critical(msg) 23 raise click.BadParameter(f"Error: {msg}") 24 25 if not is_root_dir: 26 rules_file = root 27 else: 28 full_path = os.path.abspath(root) 29 _logger.info("Searching for Suricata rules file in %s", full_path) 30 31 rules_files: list[str] = [] 32 for path, _, files in os.walk(full_path): 33 for file in files: 34 if file.endswith(".rules"): 35 rules_files.append(os.path.join(path, file)) 36 37 if len(rules_files) == 0: 38 msg = f"No Suricata rules file found in {full_path}" 39 _logger.critical(msg) 40 raise click.BadParameter(f"Error: {msg}") 41 if len(rules_files) > 1: 42 msg = f"Multiple Suricata rules files found in {full_path}\n" + "\n".join( 43 rules_files, 44 ) 45 _logger.critical(msg) 46 raise click.BadParameter(f"Error: {msg}") 47 48 rules_file = rules_files[0] 49 50 _logger.debug("Found Suricata rules file: %s", rules_file) 51 52 return rules_file