11#!/usr/bin/env python
22import json
3+ import shutil
4+ import stat
35from pathlib import Path
6+ from typing import Any
7+ from typing import Callable
8+
9+
10+ REMOVE_PATHS : list [str ] = [
11+ "{% if cookiecutter.platform_provider != github %}.github{% endif %}" ,
12+ "{% if cookiecutter.platform_provider != gitlab %}.gitlab-ci.yml{% endif %}" ,
13+ "{% if cookiecutter.platform_provider != bitbucket %}.bitbucket-pipelines.yml{% endif %}" ,
14+ ]
15+
16+
17+ def post_gen_project () -> None :
18+ """Run post-generation tasks."""
19+ reindent_cookiecutter_json ()
20+ remove_undesired_files ()
421
522
623def reindent_cookiecutter_json ():
@@ -20,5 +37,30 @@ def reindent_cookiecutter_json():
2037 io .write ("\n " )
2138
2239
40+ def remove_undesired_files () -> None :
41+ """Removes any files that are not desired in the generated project based on the cookiecutter.json.
42+
43+ This is done to avoid issues that tend to arise when the name of the template file contains a conditional.
44+ """
45+ for path in REMOVE_PATHS :
46+ if path == "" :
47+ continue
48+
49+ path : Path = Path .cwd () / path
50+ if path .is_dir ():
51+ shutil .rmtree (path , onerror = remove_readonly )
52+ else :
53+ path .unlink ()
54+
55+
56+ def remove_readonly (func : Callable [[str ], Any ], path : str , _ : Any ) -> None :
57+ """Clears the readonly bit and attempts to call the provided function.
58+
59+ This is passed to shutil.rmtree as the onerror kwarg.
60+ """
61+ Path (path ).chmod (stat .S_IWRITE )
62+ func (path )
63+
64+
2365if __name__ == "__main__" :
2466 reindent_cookiecutter_json ()
0 commit comments