Source code for runway.cfngin.hooks.staticsite.utils
"""Utility functions for website build/upload."""from__future__importannotationsimporthashlibimportloggingimportosfrompathlibimportPathfromtypingimportTYPE_CHECKING,castimportigittigittfrom....utilsimportFileHash,change_dirifTYPE_CHECKING:fromcollections.abcimportIterablefrom_typeshedimportStrPathLOGGER=logging.getLogger(__name__)
[docs]defcalculate_hash_of_files(files:Iterable[StrPath],root:Path)->str:"""Return a hash of all of the given files at the given root. Args: files: file names to include in the hash calculation, relative to ``root``. root: base directory to analyze files in. Returns: A hash of the hashes of the given files. """file_hash=FileHash(hashlib.md5())# noqa: S324file_hash.add_files(sorted(str(f)forfinfiles),relative_to=root)returnfile_hash.hexdigest
[docs]defget_hash_of_files(root_path:Path,directories:list[dict[str,list[str]|str|None]]|None=None,)->str:"""Generate md5 hash of files. Args: root_path: Base directory where all paths will be relative to. This should already be resolve to an absolute path. directories: List of mappings that describe the paths to hash and files to exclude. """directories=directoriesor[{"path":"./"}]files_to_hash:list[StrPath]=[]foriindirectories:gitignore=get_ignorer(root_path/cast("str",i["path"]),cast("list[str] | None",i.get("exclusions")),)withchange_dir(root_path):forroot,dirs,filesinos.walk(cast("str",i["path"]),topdown=True):sub_root=Path(root).resolve()ifroot!="./"andgitignore.match(sub_root):dirs[:]=[]files[:]=[]else:forfilenameinfiles:filepath=sub_root/filenameifnotgitignore.match(filepath):files_to_hash.append(filepath)returncalculate_hash_of_files(files_to_hash,root_path)
[docs]defget_ignorer(path:Path,additional_exclusions:list[str]|None=None)->igittigitt.IgnoreParser:"""Create gitignore filter from directory ``.gitignore`` file. Args: path: Top-level directory that the gitignore filter will be created for. This directory and it's subdirectories will be searched for ``.gitignore`` files to use. additional_exclusions: Additional gitignore patterns to add. """additional_exclusions=additional_exclusionsor[]gitignore=igittigitt.IgnoreParser()gitignore.parse_rule_files(path)forruleinadditional_exclusions:gitignore.add_rule(rule,path)returngitignore