1# -*- coding: UTF-8 -*-
2"""
3Basic support to use a --dry-run mode w/ invoke tasks.
4
5.. code-block::
6
7    from ._dry_run import DryRunContext
8
9    @task
10    def destroy_something(ctx, path, dry_run=False):
11        if dry_run:
12            ctx = DryRunContext(ctx)
13
14        # -- DRY-RUN MODE: Only echos commands.
15        ctx.run("rm -rf {}".format(path))
16"""
17
18from __future__ import print_function
19
20class DryRunContext(object):
21    PREFIX = "DRY-RUN: "
22    SCHEMA = "{prefix}{command}"
23    SCHEMA_WITH_KWARGS = "{prefix}{command} (with kwargs={kwargs})"
24
25    def __init__(self, ctx=None, prefix=None, schema=None):
26        if prefix is None:
27            prefix = self.PREFIX
28        if schema is None:
29            schema = self.SCHEMA
30
31        self.ctx = ctx
32        self.prefix = prefix
33        self.schema = schema
34
35    def run(self, command, **kwargs):
36        message = self.schema.format(command=command,
37                                     prefix=self.prefix,
38                                     kwargs=kwargs)
39        print(message)
40
41
42    def sudo(self, command, **kwargs):
43        command2 = "sudo %s" % command
44        self.run(command2, **kwargs)
45