Skip to content

cli.py

Command line entrypoint. This module declares the Copier CLI applications.

Basically, there are 3 different commands you can run:

  • copier, the main app, which includes shortcuts for the copy and update subapps.
  • copier copy, used to bootstrap a new project from a template.
  • copier update to update a preexisting project to a newer version of its template.

Below are the docs of each one of those.

CLI help generated from copier --help-all:

copier 0.0.0

Create a new project from a template.

Docs in https://copier.readthedocs.io/

WARNING! Use only trusted project templates, as they might execute code with the
same level of access as your user.


Usage:
copier [MAIN_SWITCHES] [copy] [SUB_SWITCHES] template_src destination_path
copier [MAIN_SWITCHES] [update] [SUB_SWITCHES] [destination_path]

Meta-switches:
    -h, --help                      Prints this help message and quits
    --help-all                      Prints help messages of all sub-commands and
                                    quits
    -v, --version                   Prints the program's version and quits

Switches:
    -a, --answers-file VALUE:str    Update using this path (relative to
                                    `destination_path`) to find the answers file
    -b, --subdirectory VALUE:str    Subdirectory to use when generating the
                                    project. If you do not specify it, the root
                                    of the template is used.
    -d, --data VARIABLE=VALUE:str   Make VARIABLE available as VALUE when
                                    rendering the template; may be given
                                    multiple times
    -f, --force                     Overwrite files that already exist, without
                                    asking
    -g, --prereleases               Use prereleases to compare template VCS
                                    tags.
    -n, --pretend                   Run but do not make any changes
    -p, --extra-paths VALUE:str     Additional directories to find parent
                                    templates in; may be given multiple times
    -q, --quiet                     Suppress status output
    -r, --vcs-ref VALUE:str         Git reference to checkout in `template_src`.
                                    If you do not specify it, it will try to
                                    checkout the latest git tag, as sorted using
                                    the PEP 440 algorithm. If you want to
                                    checkout always the latest version, use
                                    `--vcs-ref=HEAD`.
    -s, --skip                      Skip files that already exist, without
                                    asking
    -x, --exclude VALUE:str         A name or shell-style pattern matching files
                                    or folders that must not be copied; may be
                                    given multiple times

Sub-commands:
    copy                            Copy form a template source to a
                                    destination.; see 'copier copy --help' for
                                    more info
    update                          Update a copy from its original template;
                                    see 'copier update --help' for more info

copier copy 0.0.0

Copy form a template source to a destination.

Usage:
    copier copy [SWITCHES] args...

Hidden-switches:
    -h, --help         Prints this help message and quits
    --help-all         Prints help messages of all sub-commands and quits
    -v, --version      Prints the program's version and quits


copier update 0.0.0

Update a copy from its original template

The copy must have a valid answers file which contains info from the last Copier
execution, including the source template (it must be a key called `_src_path`).

If that file contains also `_commit` and `destination_path` is a git repository,
this command will do its best to respect the diff that you have generated since
the last `copier` execution. To disable that, use `--no-diff`.

Usage:
    copier update [SWITCHES] args...

Hidden-switches:
    -h, --help         Prints this help message and quits
    --help-all         Prints help messages of all sub-commands and quits
    -v, --version      Prints the program's version and quits

Switches:
    -D, --no-diff      Disable smart diff detection.

CopierApp

The Copier CLI application.

Attributes:

Name Type Description
answers_file SwitchAttr

Set answers_file option.

extra_paths SwitchAttr

Set extra_paths option.

exclude SwitchAttr

Set exclude option.

vcs_ref SwitchAttr

Set vcs_ref option.

subdirectory SwitchAttr

Set subdirectory option.

pretend Flag

Set pretend option.

force Flag

Set force option.

skip Flag

Set skip_if_exists option.

prereleases Flag

Set use_prereleases option.

quiet Flag

Set quiet option.

data_switch(self, values)

Update data with provided values.

Parameters:

Name Type Description Default
values List[str]

The list of values to apply. Each value in the list is of the following form: NAME=VALUE.

required
Source code in copier/cli.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@cli.switch(
    ["-d", "--data"],
    str,
    "VARIABLE=VALUE",
    list=True,
    help="Make VARIABLE available as VALUE when rendering the template",
)
def data_switch(self, values: List[str]) -> None:
    """Update [data][] with provided values.

    Arguments:
        values: The list of values to apply.
            Each value in the list is of the following form: `NAME=VALUE`.
    """
    self.data.update(value.split("=", 1) for value in values)  # type: ignore

main(self, *args)

Copier CLI app shortcuts.

This method redirects abstract CLI calls (those that don't specify copy or update) to CopierCopySubApp.main or CopierUpdateSubApp.main automatically.

Examples:

  • copier from tocopier copy from to
  • copier fromcopier update from
  • copiercopier update .
Source code in copier/cli.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
@handle_exceptions
def main(self, *args: str) -> int:
    """Copier CLI app shortcuts.

    This method redirects abstract CLI calls
    (those that don't specify `copy` or `update`)
    to [CopierCopySubApp.main][copier.cli.CopierCopySubApp.main]
    or [CopierUpdateSubApp.main][copier.cli.CopierUpdateSubApp.main]
    automatically.

    Examples:
        - `copier from to` → `copier copy from to`
        - `copier from` → `copier update from`
        - `copier` → `copier update .`
    """
    # Redirect to subcommand if supplied
    if args and args[0] in self._subcommands:
        self.nested_command = (
            self._subcommands[args[0]].subapplication,
            ["copier %s" % args[0]] + list(args[1:]),
        )
    # If using 0 or 1 args, you want to update
    elif len(args) in {0, 1}:
        self.nested_command = (
            self._subcommands["update"].subapplication,
            ["copier update"] + list(args),
        )
    # If using 2 args, you want to copy
    elif len(args) == 2:
        self.nested_command = (
            self._subcommands["copy"].subapplication,
            ["copier copy"] + list(args),
        )
    # If using more args, you're wrong
    else:
        self.help()
        raise UserMessageError("Unsupported arguments")
    return 0

CopierCopySubApp

The copier copy subcommand.

Use this subcommand to bootstrap a new subproject from a template.

main(self, template_src, destination_path)

Call copy in copy mode.

Parameters:

Name Type Description Default
template_src str

Indicate where to get the template from.

This can be a git URL or a local path.

required
destination_path str

Where to generate the new subproject. It must not exist or be empty.

required
Source code in copier/cli.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
@handle_exceptions
def main(self, template_src: str, destination_path: str) -> int:
    """Call [`copy`][copier.main.copy] in copy mode.

    Params:
        template_src:
            Indicate where to get the template from.

            This can be a git URL or a local path.

        destination_path:
            Where to generate the new subproject. It must not exist or be empty.
    """
    self.parent._copy(template_src, destination_path)
    return 0

CopierUpdateSubApp

The copier update subcommand.

Use this subcommand to update an existing subrpoject from a template that supports updates.

Attributes:

Name Type Description
only_diff Flag

Set only_diff option.

main(self, destination_path='.')

Call copy in update mode.

Parameters:

Name Type Description Default
destination_path ExistingDirectory

Only the destination path is needed to update, because the src_path comes from the answers file.

The subproject must exist. If not specified, the currently working directory is used.

'.'
Source code in copier/cli.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
@handle_exceptions
def main(self, destination_path: cli.ExistingDirectory = ".") -> int:
    """Call [`copy`][copier.main.copy] in update mode.

    Parameters:
        destination_path:
            Only the destination path is needed to update, because the
            `src_path` comes from [the answers file][the-copier-answersyml-file].

            The subproject must exist. If not specified, the currently
            working directory is used.
    """
    self.parent._copy(
        dst_path=destination_path, only_diff=self.only_diff,
    )
    return 0

handle_exceptions(method)

Handle keyboard interruption while running a method.

Source code in copier/cli.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def handle_exceptions(method):
    """Handle keyboard interruption while running a method."""

    @wraps(method)
    def _wrapper(*args, **kwargs):
        try:
            try:
                return method(*args, **kwargs)
            except KeyboardInterrupt:
                raise UserMessageError("Execution stopped by user")
        except UserMessageError as error:
            print(colors.red | "\n".join(error.args), file=sys.stderr)
            return 1

    return _wrapper