import os import time import helper timestamp_file_name = "last-compile.txt" # Check whether we are forced to recompile the entire project. # This is the case if: # (a) the project was not compiled yet or # (b) meta.yml was changed since the last compile or # (c) the layouts have been changed since the last compile # The current time is saved to the cache folder for later use. def is_recompile_obligatory(root, lang): if not os.path.isdir(os.path.join(root, ".onpoint", lang)): # case (a) __init_cache_directory(root, lang) print("First compile, no caches available.") save_compile_timestamp(root, lang) return True if file_touched_since_last_compile(root, lang, "meta.yml"): # case (b) print("meta.yml changed since the last compilation, forced to recompile.") return True for file in os.listdir(os.path.join(root, 'layouts')): if os.path.isfile(os.path.join(root, 'layouts', file)): layout_path = os.path.join('layouts', file) if file_touched_since_last_compile(root, lang, layout_path): # case (c) print("Templates changed since the last compilation, forced to recompile.") return True return False # Check if some file was touched since the last compile. def file_touched_since_last_compile(root, lang, file): file_path = os.path.join(root, file) modification_time = helper.get_modification_time(file_path) compilation_time = __get_last_compile_time(root, lang) return modification_time > compilation_time # Check whether a cached version of this file exists. def not_cached_before(root, lang, file): file_path = os.path.join(root, '.onpoint', lang, file + '.cache') return not os.path.exists(file_path) # Restore the cached chapter. def get_cached_chapter(root, lang, chapter): chapter_path = os.path.join(root, '.onpoint', lang, chapter + '.cache') return open(chapter_path, 'r', encoding='utf8').read() # Store a cached version of a chapter. def store_cached_chapter(root, lang, chapter, content): chapter_path = os.path.join(root, '.onpoint', lang, chapter + '.cache') chapter_file = open(chapter_path, 'w', encoding='utf-8') chapter_file.write(content) chapter_file.close() # Initialize the cache directory '.onpoint' in the project's root folder. # It will contain a file storing the last compile time and a directory # for each language. The latter will have cached versions of each chapter. def __init_cache_directory(root, lang): cache_dir = os.path.join(root, '.onpoint', lang) os.makedirs(cache_dir) # Save the current time to the timestamp file. def save_compile_timestamp(root, lang, file_name=timestamp_file_name): timestamp_file_path = os.path.join(root, '.onpoint', lang, file_name) timestamp_file = open(timestamp_file_path, 'w', encoding='utf-8') timestamp_file.write(str(int(time.time()))) timestamp_file.close() # Retrieve the compile timestamp. def __get_last_compile_time(root, lang): timestamp_file_path = os.path.join(root, '.onpoint', lang, timestamp_file_name) with open(timestamp_file_path, encoding='utf8') as f: return int(f.readline())