|
| 1 | +# ---------------------------------------------------------------------- |
| 2 | +# | |
| 3 | +# | Copyright (c) 2024 Scientific Software Engineering Center at Georgia Tech |
| 4 | +# | Distributed under the MIT License. |
| 5 | +# | |
| 6 | +# ---------------------------------------------------------------------- |
| 7 | +import hashlib |
| 8 | +import itertools |
| 9 | +import os |
| 10 | +import sys |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +from rich import print # pylint: disable=redefined-builtin |
| 14 | +from rich.panel import Panel |
| 15 | +import yaml |
| 16 | + |
| 17 | +from dbrownell_Common import PathEx |
| 18 | +from PythonProjectBootstrapper import __version__ |
| 19 | + |
| 20 | +# The following imports are used in cookiecutter hooks. Import them here to |
| 21 | +# ensure that they are frozen when creating binaries, |
| 22 | +import shutil # pylint: disable=unused-import, wrong-import-order |
| 23 | +import textwrap # pylint: disable=unused-import, wrong-import-order |
| 24 | + |
| 25 | + |
| 26 | +# ---------------------------------------------------------------------- |
| 27 | +def GenerateFileHash(filepath: Path, hash_fn="sha256") -> str: |
| 28 | + PathEx.EnsureFile(filepath) |
| 29 | + |
| 30 | + hasher = hashlib.new(hash_fn) |
| 31 | + with open(filepath, "rb") as file: |
| 32 | + while True: |
| 33 | + chunk = file.read(8192) |
| 34 | + if not chunk: |
| 35 | + break |
| 36 | + |
| 37 | + hasher.update(chunk) |
| 38 | + |
| 39 | + hash_value = hasher.hexdigest() |
| 40 | + return hash_value |
| 41 | + |
| 42 | + |
| 43 | +# ---------------------------------------------------------------------- |
| 44 | +def CreateManifest(generated_dir: Path) -> dict[str, str]: |
| 45 | + manifest_dict: dict[str, str] = {} |
| 46 | + |
| 47 | + for root, _, files in os.walk(generated_dir): |
| 48 | + root_path = Path(root) |
| 49 | + |
| 50 | + for file in files: |
| 51 | + full_path = root_path / Path(file) |
| 52 | + rel_path = PathEx.CreateRelativePath(generated_dir, full_path) |
| 53 | + manifest_dict[rel_path.as_posix()] = GenerateFileHash(filepath=full_path) |
| 54 | + |
| 55 | + return manifest_dict |
| 56 | + |
| 57 | + |
| 58 | +# ---------------------------------------------------------------------- |
| 59 | +def ConditionallyRemoveUnchangedTemplateFiles( |
| 60 | + new_manifest_dict: dict[str, str], |
| 61 | + existing_manifest_dict: dict[str, str], |
| 62 | + output_dir: Path, |
| 63 | +) -> None: |
| 64 | + # Removes any template files no longer being generated as long as the file was never modified by the user |
| 65 | + |
| 66 | + # files no longer in template |
| 67 | + removed_template_files: set[str] = set(existing_manifest_dict.keys()) - set( |
| 68 | + new_manifest_dict.keys() |
| 69 | + ) |
| 70 | + |
| 71 | + PathEx.EnsureDir(output_dir) |
| 72 | + |
| 73 | + # remove files no longer in template if they are unchanged |
| 74 | + for removed_file_rel_path in removed_template_files: |
| 75 | + removed_full_path = output_dir / removed_file_rel_path |
| 76 | + |
| 77 | + if removed_full_path.is_file(): |
| 78 | + current_hash = GenerateFileHash(filepath=removed_full_path) |
| 79 | + original_hash = existing_manifest_dict[removed_file_rel_path] |
| 80 | + |
| 81 | + if current_hash == original_hash: |
| 82 | + removed_full_path.unlink() |
| 83 | + |
| 84 | + |
| 85 | +# ---------------------------------------------------------------------- |
| 86 | +def CopyToOutputDir( |
| 87 | + src_dir: Path, |
| 88 | + dest_dir: Path, |
| 89 | +) -> None: |
| 90 | + # Copies all generated files into the output directory and handles the creation/updating of the manifest file |
| 91 | + |
| 92 | + PathEx.EnsureDir(src_dir) |
| 93 | + PathEx.EnsureDir(dest_dir) |
| 94 | + |
| 95 | + # existing_manifest will be populated/updated as necessary and saved |
| 96 | + generated_manifest: dict[str, str] = CreateManifest(src_dir) |
| 97 | + existing_manifest: dict[str, str] = {} |
| 98 | + |
| 99 | + potential_manifest: Path = dest_dir / ".manifest.yml" |
| 100 | + |
| 101 | + # if this is not our first time generating, remove unwanted template files |
| 102 | + if potential_manifest.is_file(): |
| 103 | + with open(potential_manifest, "r") as existing_manifest_file: |
| 104 | + existing_manifest = yaml.load(existing_manifest_file, Loader=yaml.Loader) |
| 105 | + |
| 106 | + ConditionallyRemoveUnchangedTemplateFiles( |
| 107 | + new_manifest_dict=generated_manifest, |
| 108 | + existing_manifest_dict=existing_manifest, |
| 109 | + output_dir=dest_dir, |
| 110 | + ) |
| 111 | + |
| 112 | + merged_manifest = dict(existing_manifest) |
| 113 | + merged_manifest.update(generated_manifest) |
| 114 | + |
| 115 | + # Ask user if they would like to overwrite their changes if any conflicts detected |
| 116 | + for rel_filepath, generated_hash in generated_manifest.items(): |
| 117 | + output_dir_filepath: Path = dest_dir / rel_filepath |
| 118 | + |
| 119 | + if output_dir_filepath.is_file(): |
| 120 | + current_file_hash: str = GenerateFileHash(filepath=output_dir_filepath) |
| 121 | + |
| 122 | + # Changes detected in file and file modified by xser (changes do not stem only from changes in the contents of the template file) |
| 123 | + |
| 124 | + if rel_filepath in existing_manifest.keys() and current_file_hash not in ( |
| 125 | + generated_hash, |
| 126 | + existing_manifest[rel_filepath], |
| 127 | + ): |
| 128 | + while True: |
| 129 | + sys.stdout.write( |
| 130 | + f"\nWould you like to overwrite your changes in {str(output_dir_filepath)}? [yes/no]: " |
| 131 | + ) |
| 132 | + overwrite = input().strip().lower() |
| 133 | + |
| 134 | + if overwrite in ["yes", "y"]: |
| 135 | + break |
| 136 | + |
| 137 | + # Here, we are copying the file from the output directory to the temporary directory in the case that the user answers "no" |
| 138 | + # to whether or not they would like to overwrite their changes. This implementation builds the final directory in the temporary directory then copies everything over. |
| 139 | + # This makes it much easier to copy over generated files since we do not need to case on whether we are copying over a directory or a file (for example if we generated an empty directory) |
| 140 | + |
| 141 | + if overwrite in ["no", "n"]: |
| 142 | + merged_manifest[rel_filepath] = existing_manifest[rel_filepath] |
| 143 | + shutil.copy2(output_dir_filepath, src_dir / rel_filepath) |
| 144 | + break |
| 145 | + else: |
| 146 | + merged_manifest[rel_filepath] = generated_hash |
| 147 | + |
| 148 | + # create and save manifest |
| 149 | + with open(potential_manifest, "w") as manifest_file: |
| 150 | + yaml.dump(merged_manifest, manifest_file) |
| 151 | + |
| 152 | + # copy temporary directory to final output directory and remove temporary directory |
| 153 | + shutil.copytree( |
| 154 | + src_dir, |
| 155 | + dest_dir, |
| 156 | + dirs_exist_ok=True, |
| 157 | + ignore_dangling_symlinks=True, |
| 158 | + copy_function=shutil.copy, |
| 159 | + ) |
| 160 | + shutil.rmtree(src_dir) |
| 161 | + |
| 162 | + |
| 163 | +# ---------------------------------------------------------------------- |
| 164 | +def DisplayPrompt(output_dir: Path) -> None: |
| 165 | + PathEx.EnsureDir(output_dir) |
| 166 | + |
| 167 | + prompt_text_path = PathEx.EnsureFile(output_dir / "prompt_text.yml") |
| 168 | + |
| 169 | + with open(prompt_text_path, "r") as prompt_file: |
| 170 | + _prompts = yaml.load(prompt_file, Loader=yaml.Loader) |
| 171 | + |
| 172 | + prompt_text_path.unlink() |
| 173 | + |
| 174 | + # Display prompts |
| 175 | + border_colors = itertools.cycle( |
| 176 | + ["yellow", "blue", "magenta", "cyan", "green"], |
| 177 | + ) |
| 178 | + |
| 179 | + sys.stdout.write("\n\n") |
| 180 | + |
| 181 | + for prompt_index, ((_, title), prompt) in enumerate(sorted(_prompts.items())): |
| 182 | + print( |
| 183 | + Panel( |
| 184 | + prompt.rstrip(), |
| 185 | + border_style=next(border_colors), |
| 186 | + padding=1, |
| 187 | + title=f"[{prompt_index + 1}/{len(_prompts)}] {title}", |
| 188 | + title_align="left", |
| 189 | + ), |
| 190 | + ) |
| 191 | + |
| 192 | + sys.stdout.write("\nPress <enter> to continue") |
| 193 | + input() |
| 194 | + sys.stdout.write("\n\n") |
| 195 | + |
| 196 | + # Final prompt |
| 197 | + sys.stdout.write( |
| 198 | + textwrap.dedent( |
| 199 | + """\ |
| 200 | + The project has now been bootstrapped! |
| 201 | +
|
| 202 | + To begin development, run these commands: |
| 203 | +
|
| 204 | + 1. cd "{output_dir}" |
| 205 | + 2. Bootstrap{ext} |
| 206 | + 3. {source}{prefix}Activate{ext} |
| 207 | + 4. python Build.py pytest |
| 208 | +
|
| 209 | +
|
| 210 | + """, |
| 211 | + ).format( |
| 212 | + output_dir=output_dir, |
| 213 | + ext=".cmd" if os.name == "nt" else ".sh", |
| 214 | + source="source " if os.name != "nt" else "", |
| 215 | + prefix="./" if os.name != "nt" else "", |
| 216 | + ), |
| 217 | + ) |
0 commit comments