| 1 |
# -*- coding: UTF-8 -*- |
| 2 |
""" |
| 3 |
Provides cleanup tasks for invoke build scripts (as generic invoke tasklet). |
| 4 |
Simplifies writing common, composable and extendable cleanup tasks. |
| 5 |
|
| 6 |
PYTHON PACKAGE REQUIREMENTS: |
| 7 |
* path.py >= 8.2.1 (as path-object abstraction) |
| 8 |
* pathlib (for ant-like wildcard patterns; since: python > 3.5) |
| 9 |
* pycmd (required-by: clean_python()) |
| 10 |
|
| 11 |
clean task: Add Additional Directories and Files to be removed |
| 12 |
------------------------------------------------------------------------------- |
| 13 |
|
| 14 |
Create an invoke configuration file (YAML of JSON) with the additional |
| 15 |
configuration data: |
| 16 |
|
| 17 |
.. code-block:: yaml |
| 18 |
|
| 19 |
# -- FILE: invoke.yaml |
| 20 |
# USE: clean.directories, clean.files to override current configuration. |
| 21 |
clean: |
| 22 |
extra_directories: |
| 23 |
- **/tmp/ |
| 24 |
extra_files: |
| 25 |
- **/*.log |
| 26 |
- **/*.bak |
| 27 |
|
| 28 |
|
| 29 |
Registration of Cleanup Tasks |
| 30 |
------------------------------ |
| 31 |
|
| 32 |
Other task modules often have an own cleanup task to recover the clean state. |
| 33 |
The :meth:`clean` task, that is provided here, supports the registration |
| 34 |
of additional cleanup tasks. Therefore, when the :meth:`clean` task is executed, |
| 35 |
all registered cleanup tasks will be executed. |
| 36 |
|
| 37 |
EXAMPLE:: |
| 38 |
|
| 39 |
# -- FILE: tasks/docs.py |
| 40 |
from __future__ import absolute_import |
| 41 |
from invoke import task, Collection |
| 42 |
from invoke_tasklet_cleanup import cleanup_tasks, cleanup_dirs |
| 43 |
|
| 44 |
@task |
| 45 |
def clean(ctx, dry_run=False): |
| 46 |
"Cleanup generated documentation artifacts." |
| 47 |
cleanup_dirs(["build/docs"]) |
| 48 |
|
| 49 |
namespace = Collection(clean) |
| 50 |
... |
| 51 |
|
| 52 |
# -- REGISTER CLEANUP TASK: |
| 53 |
cleanup_tasks.add_task(clean, "clean_docs") |
| 54 |
cleanup_tasks.configure(namespace.configuration()) |
| 55 |
""" |
| 56 |
|
| 57 |
# NOT-NEEDED: from invoke.exceptions import Failure |
| 58 |
from __future__ import absolute_import, print_function |
| 59 |
import os.path |
| 60 |
import sys |
| 61 |
import pathlib |
| 62 |
from invoke import task, Collection |
| 63 |
from invoke.executor import Executor |
| 64 |
from path import Path |
| 65 |
|
| 66 |
|
| 67 |
# ----------------------------------------------------------------------------- |
| 68 |
# CLEANUP UTILITIES: |
| 69 |
# ----------------------------------------------------------------------------- |
| 70 |
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False): |
| 71 |
"""Execute several cleanup tasks as part of the cleanup. |
| 72 |
|
| 73 |
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks. |
| 74 |
|
| 75 |
:param ctx: Context object for the tasks. |
| 76 |
:param cleanup_tasks: Collection of cleanup tasks (as Collection). |
| 77 |
:param dry_run: Indicates dry-run mode (bool) |
| 78 |
""" |
| 79 |
# pylint: disable=redefined-outer-name |
| 80 |
executor = Executor(cleanup_tasks, ctx.config) |
| 81 |
for cleanup_task in cleanup_tasks.tasks: |
| 82 |
print("CLEANUP TASK: %s" % cleanup_task) |
| 83 |
executor.execute((cleanup_task, dict(dry_run=dry_run))) |
| 84 |
|
| 85 |
|
| 86 |
def cleanup_dirs(patterns, dry_run=False, workdir="."): |
| 87 |
"""Remove directories (and their contents) recursively. |
| 88 |
Skips removal if directories does not exist. |
| 89 |
|
| 90 |
:param patterns: Directory name patterns, like "**/tmp*" (as list). |
| 91 |
:param dry_run: Dry-run mode indicator (as bool). |
| 92 |
:param workdir: Current work directory (default=".") |
| 93 |
""" |
| 94 |
current_dir = Path(workdir) |
| 95 |
python_basedir = Path(Path(sys.executable).dirname()).joinpath("..").abspath() |
| 96 |
warn2_counter = 0 |
| 97 |
for dir_pattern in patterns: |
| 98 |
for directory in path_glob(dir_pattern, current_dir): |
| 99 |
directory2 = directory.abspath() |
| 100 |
if sys.executable.startswith(directory2): |
| 101 |
# pylint: disable=line-too-long |
| 102 |
print("SKIP-SUICIDE: '%s' contains current python executable" % directory) |
| 103 |
continue |
| 104 |
elif directory2.startswith(python_basedir): |
| 105 |
# -- PROTECT CURRENTLY USED VIRTUAL ENVIRONMENT: |
| 106 |
if warn2_counter <= 4: |
| 107 |
print("SKIP-SUICIDE: '%s'" % directory) |
| 108 |
warn2_counter += 1 |
| 109 |
continue |
| 110 |
|
| 111 |
if dry_run: |
| 112 |
print("RMTREE: %s (dry-run)" % directory) |
| 113 |
else: |
| 114 |
print("RMTREE: %s" % directory) |
| 115 |
directory.rmtree_p() |
| 116 |
|
| 117 |
|
| 118 |
def cleanup_files(patterns, dry_run=False, workdir="."): |
| 119 |
"""Remove files or files selected by file patterns. |
| 120 |
Skips removal if file does not exist. |
| 121 |
|
| 122 |
:param patterns: File patterns, like "**/*.pyc" (as list). |
| 123 |
:param dry_run: Dry-run mode indicator (as bool). |
| 124 |
:param workdir: Current work directory (default=".") |
| 125 |
""" |
| 126 |
current_dir = Path(workdir) |
| 127 |
python_basedir = Path(Path(sys.executable).dirname()).joinpath("..").abspath() |
| 128 |
error_message = None |
| 129 |
error_count = 0 |
| 130 |
for file_pattern in patterns: |
| 131 |
for file_ in path_glob(file_pattern, current_dir): |
| 132 |
if file_.abspath().startswith(python_basedir): |
| 133 |
# -- PROTECT CURRENTLY USED VIRTUAL ENVIRONMENT: |
| 134 |
continue |
| 135 |
|
| 136 |
if dry_run: |
| 137 |
print("REMOVE: %s (dry-run)" % file_) |
| 138 |
else: |
| 139 |
print("REMOVE: %s" % file_) |
| 140 |
try: |
| 141 |
file_.remove_p() |
| 142 |
except os.error as e: |
| 143 |
message = "%s: %s" % (e.__class__.__name__, e) |
| 144 |
print(message + " basedir: "+ python_basedir) |
| 145 |
error_count += 1 |
| 146 |
if not error_message: |
| 147 |
error_message = message |
| 148 |
if False and error_message: |
| 149 |
class CleanupError(RuntimeError): |
| 150 |
pass |
| 151 |
raise CleanupError(error_message) |
| 152 |
|
| 153 |
|
| 154 |
def path_glob(pattern, current_dir=None): |
| 155 |
"""Use pathlib for ant-like patterns, like: "**/*.py" |
| 156 |
|
| 157 |
:param pattern: File/directory pattern to use (as string). |
| 158 |
:param current_dir: Current working directory (as Path, pathlib.Path, str) |
| 159 |
:return Resolved Path (as path.Path). |
| 160 |
""" |
| 161 |
if not current_dir: |
| 162 |
current_dir = pathlib.Path.cwd() |
| 163 |
elif not isinstance(current_dir, pathlib.Path): |
| 164 |
# -- CASE: string, path.Path (string-like) |
| 165 |
current_dir = pathlib.Path(str(current_dir)) |
| 166 |
|
| 167 |
for p in current_dir.glob(pattern): |
| 168 |
yield Path(str(p)) |
| 169 |
|
| 170 |
|
| 171 |
# ----------------------------------------------------------------------------- |
| 172 |
# GENERIC CLEANUP TASKS: |
| 173 |
# ----------------------------------------------------------------------------- |
| 174 |
@task |
| 175 |
def clean(ctx, dry_run=False): |
| 176 |
"""Cleanup temporary dirs/files to regain a clean state.""" |
| 177 |
# -- VARIATION-POINT 1: Allow user to override in configuration-file |
| 178 |
directories = ctx.clean.directories |
| 179 |
files = ctx.clean.files |
| 180 |
|
| 181 |
# -- VARIATION-POINT 2: Allow user to add more files/dirs to be removed. |
| 182 |
extra_directories = ctx.clean.extra_directories or [] |
| 183 |
extra_files = ctx.clean.extra_files or [] |
| 184 |
if extra_directories: |
| 185 |
directories.extend(extra_directories) |
| 186 |
if extra_files: |
| 187 |
files.extend(extra_files) |
| 188 |
|
| 189 |
# -- PERFORM CLEANUP: |
| 190 |
execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=dry_run) |
| 191 |
cleanup_dirs(directories, dry_run=dry_run) |
| 192 |
cleanup_files(files, dry_run=dry_run) |
| 193 |
|
| 194 |
|
| 195 |
@task(name="clean-all", aliases=("distclean",)) |
| 196 |
def clean_all(ctx, dry_run=False): |
| 197 |
"""Clean up everything, even the precious stuff. |
| 198 |
NOTE: clean task is executed first. |
| 199 |
""" |
| 200 |
cleanup_dirs(ctx.clean_all.directories or [], dry_run=dry_run) |
| 201 |
cleanup_dirs(ctx.clean_all.extra_directories or [], dry_run=dry_run) |
| 202 |
cleanup_files(ctx.clean_all.files or [], dry_run=dry_run) |
| 203 |
cleanup_files(ctx.clean_all.extra_files or [], dry_run=dry_run) |
| 204 |
execute_cleanup_tasks(ctx, cleanup_all_tasks, dry_run=dry_run) |
| 205 |
clean(ctx, dry_run=dry_run) |
| 206 |
|
| 207 |
|
| 208 |
@task |
| 209 |
def clean_python(ctx, dry_run=False): |
| 210 |
"""Cleanup python related files/dirs: *.pyc, *.pyo, ...""" |
| 211 |
# MAYBE NOT: "**/__pycache__" |
| 212 |
cleanup_dirs(["build", "dist", "*.egg-info", "**/__pycache__"], |
| 213 |
dry_run=dry_run) |
| 214 |
if not dry_run: |
| 215 |
ctx.run("py.cleanup") |
| 216 |
cleanup_files(["**/*.pyc", "**/*.pyo", "**/*$py.class"], dry_run=dry_run) |
| 217 |
|
| 218 |
|
| 219 |
# ----------------------------------------------------------------------------- |
| 220 |
# TASK CONFIGURATION: |
| 221 |
# ----------------------------------------------------------------------------- |
| 222 |
namespace = Collection(clean, clean_all) |
| 223 |
namespace.configure({ |
| 224 |
"clean": { |
| 225 |
"directories": [], |
| 226 |
"files": [ |
| 227 |
"*.bak", "*.log", "*.tmp", |
| 228 |
"**/.DS_Store", "**/*.~*~", # -- MACOSX |
| 229 |
], |
| 230 |
"extra_directories": [], |
| 231 |
"extra_files": [], |
| 232 |
}, |
| 233 |
"clean_all": { |
| 234 |
"directories": [".venv*", ".tox", "downloads", "tmp"], |
| 235 |
"files": [], |
| 236 |
"extra_directories": [], |
| 237 |
"extra_files": [], |
| 238 |
}, |
| 239 |
}) |
| 240 |
|
| 241 |
# -- EXTENSION-POINT: CLEANUP TASKS (called by: clean, clean_all task) |
| 242 |
# NOTE: Can be used by other tasklets to register cleanup tasks. |
| 243 |
cleanup_tasks = Collection("cleanup_tasks") |
| 244 |
cleanup_all_tasks = Collection("cleanup_all_tasks") |
| 245 |
|
| 246 |
# -- EXTEND NORMAL CLEANUP-TASKS: |
| 247 |
# DISABLED: cleanup_tasks.add_task(clean_python) |
| 248 |
# |
| 249 |
# ----------------------------------------------------------------------------- |
| 250 |
# EXTENSION-POINT: CONFIGURATION HELPERS: Can be used from other task modules |
| 251 |
# ----------------------------------------------------------------------------- |
| 252 |
def config_add_cleanup_dirs(directories): |
| 253 |
# pylint: disable=protected-access |
| 254 |
the_cleanup_directories = namespace._configuration["clean"]["directories"] |
| 255 |
the_cleanup_directories.extend(directories) |
| 256 |
|
| 257 |
def config_add_cleanup_files(files): |
| 258 |
# pylint: disable=protected-access |
| 259 |
the_cleanup_files = namespace._configuration["clean"]["files"] |
| 260 |
the_cleanup_files.extend(files) |