"""AaC Module for easy file writing."""importsysimportloggingfromosimportpath,makedirsfromaac.context.definitionimportDefinitionfromaac.in_out.constantsimportDEFINITION_SEPARATORfromaac.in_out.pathsimportsanitize_filesystem_path
[docs]defwrite_file(uri:str,content:str,overwrite:bool=False)->None:""" Write string content to a file. Args: uri (str): the file's full uri content (str): contents of the file to write overwrite (bool): True to overwrite an existing file or false to not. """sanitized_uri=sanitize_filesystem_path(uri)does_file_exist=path.exists(sanitized_uri)file_parent_dir=path.dirname(sanitized_uri)ifnotpath.exists(file_parent_dir):makedirs(file_parent_dir,exist_ok=True)ifnotoverwriteanddoes_file_exist:logging.info(f"{sanitized_uri} already exists, skipping write.")returntry:withopen(sanitized_uri,"w")asfile:file.writelines(content)exceptIOErroraserror:logging.error(f"Failed to write file {sanitized_uri} due to error: {error}")
[docs]defwrite_definitions_to_file(definitions:list[Definition],file_uri:str,is_user_editable:bool=True)->None:""" Given a list of definitions, write them to file uri. Updates the source for definitions passed in. Args: definitions (list[Definition]): The definitions to write to file. file_uri (str): The URI of the file to write the definitions to. is_user_editable (bool): True if the AaC file can be edited by users. """defsort_definitions_by_lexeme_line(definition:Definition)->int:line=sys.maxsizeifdefinition.lexemesanddefinition.lexemes[0].source==file_uri:line=definition.lexemes[0].location.linereturnlinedefinitions.sort(key=sort_definitions_by_lexeme_line)file_content=""fordefinitionindefinitions:definition.source.uri=file_uridefinition.source.is_user_editable=is_user_editableyaml_doc_separator=DEFINITION_SEPARATORiffile_contentelse""file_content+=f"{yaml_doc_separator}{definition.to_yaml()}"write_file(file_uri,file_content,True)