Skip to content

main.py

Main functions and classes, used to generate or update projects.

Worker

Copier process state manager.

This class represents the state of a copier work, and contains methods to actually produce the desired work.

To use it properly, use it as a context manager and fill all dataclass fields.

Then, execute one of its main methods, which are prefixed with run_:

Example
with Worker(
    src_path="https://github.com/copier-org/autopretty.git", "output"
) as worker:
    worker.run_copy()

Attributes:

Name Type Description
src_path Optional[str]

String that can be resolved to a template path, be it local or remote.

See copier.vcs.get_repo.

If it is None, then it means that you are updating a project, and the original src_path will be obtained from the answers file.

dst_path Path

Destination path where to render the subproject.

answers_file Optional[RelativePath]

Indicates the path for the answers file.

The path must be relative to dst_path.

If it is None, the default value will be obtained from copier.template.Template.answers_relpath.

vcs_ref OptStr

Specify the VCS tag/commit to use in the template.

data AnyByStrDict

Answers to the questionary defined in the template.

exclude StrSeq

User-chosen additional file exclusion patterns.

use_prereleases bool

Consider prereleases when detecting the latest one?

See use_prereleases.

Useless if specifying a vcs_ref.

skip_if_exists StrSeq

User-chosen additional file skip patterns.

cleanup_on_error bool

Delete dst_path if there's an error?

See cleanup_on_error.

defaults bool

When True, use default answers to questions, which might be null if not specified.

See defaults.

user_defaults AnyByStrDict

Specify user defaults that may override a template's defaults during question prompts.

overwrite bool

When True, Overwrite files that already exist, without asking.

See overwrite.

pretend bool

When True, produce no real rendering.

See pretend.

quiet bool

When True, disable all output.

See quiet.

conflict Literal['inline', 'rej']

One of "inline" (default), "rej".

context_lines PositiveInt

Lines of context to consider when solving conflicts in updates.

With more lines, context resolution is more accurate, but it will also produce more conflicts if your subproject has evolved.

With less lines, context resolution is less accurate, but it will respect better the evolution of your subproject.

unsafe bool

When True, allow usage of unsafe templates.

See unsafe

Source code in copier/main.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
@dataclass(config=ConfigDict(extra="forbid"))
class Worker:
    """Copier process state manager.

    This class represents the state of a copier work, and contains methods to
    actually produce the desired work.

    To use it properly, use it as a context manager and fill all dataclass fields.

    Then, execute one of its main methods, which are prefixed with `run_`:

    -   [run_copy][copier.main.Worker.run_copy] to copy a subproject.
    -   [run_recopy][copier.main.Worker.run_recopy] to recopy a subproject.
    -   [run_update][copier.main.Worker.run_update] to update a subproject.

    Example:
        ```python
        with Worker(
            src_path="https://github.com/copier-org/autopretty.git", "output"
        ) as worker:
            worker.run_copy()
        ```

    Attributes:
        src_path:
            String that can be resolved to a template path, be it local or remote.

            See [copier.vcs.get_repo][].

            If it is `None`, then it means that you are
            [updating a project][updating-a-project], and the original
            `src_path` will be obtained from
            [the answers file][the-copier-answersyml-file].

        dst_path:
            Destination path where to render the subproject.

        answers_file:
            Indicates the path for [the answers file][the-copier-answersyml-file].

            The path must be relative to `dst_path`.

            If it is `None`, the default value will be obtained from
            [copier.template.Template.answers_relpath][].

        vcs_ref:
            Specify the VCS tag/commit to use in the template.

        data:
            Answers to the questionary defined in the template.

        exclude:
            User-chosen additional [file exclusion patterns][exclude].

        use_prereleases:
            Consider prereleases when detecting the *latest* one?

            See [use_prereleases][].

            Useless if specifying a [vcs_ref][].

        skip_if_exists:
            User-chosen additional [file skip patterns][skip_if_exists].

        cleanup_on_error:
            Delete `dst_path` if there's an error?

            See [cleanup_on_error][].

        defaults:
            When `True`, use default answers to questions, which might be null if not specified.

            See [defaults][].

        user_defaults:
            Specify user defaults that may override a template's defaults during question prompts.

        overwrite:
            When `True`, Overwrite files that already exist, without asking.

            See [overwrite][].

        pretend:
            When `True`, produce no real rendering.

            See [pretend][].

        quiet:
            When `True`, disable all output.

            See [quiet][].

        conflict:
            One of "inline" (default), "rej".

        context_lines:
            Lines of context to consider when solving conflicts in updates.

            With more lines, context resolution is more accurate, but it will
            also produce more conflicts if your subproject has evolved.

            With less lines, context resolution is less accurate, but it will
            respect better the evolution of your subproject.

        unsafe:
            When `True`, allow usage of unsafe templates.

            See [unsafe][]
    """

    src_path: Optional[str] = None
    dst_path: Path = Path(".")
    answers_file: Optional[RelativePath] = None
    vcs_ref: OptStr = None
    data: AnyByStrDict = field(default_factory=dict)
    exclude: StrSeq = ()
    use_prereleases: bool = False
    skip_if_exists: StrSeq = ()
    cleanup_on_error: bool = True
    defaults: bool = False
    user_defaults: AnyByStrDict = field(default_factory=dict)
    overwrite: bool = False
    pretend: bool = False
    quiet: bool = False
    conflict: Literal["inline", "rej"] = "inline"
    context_lines: PositiveInt = 3
    unsafe: bool = False
    skip_answered: bool = False

    answers: AnswersMap = field(default_factory=AnswersMap, init=False)
    _cleanup_hooks: List[Callable] = field(default_factory=list, init=False)

    def __enter__(self):
        """Allow using worker as a context manager."""
        return self

    def __exit__(self, type, value, traceback):
        """Clean up garbage files after worker usage ends."""
        if value is not None:
            # exception was raised from code inside context manager:
            # try to clean up, ignoring any exception, then re-raise
            with suppress(Exception):
                self._cleanup()
            raise value
        # otherwise clean up and let any exception bubble up
        self._cleanup()

    def _cleanup(self):
        """Execute all stored cleanup methods."""
        for method in self._cleanup_hooks:
            method()

    def _check_unsafe(self, mode: Literal["copy", "update"]) -> None:
        """Check whether a template uses unsafe features."""
        if self.unsafe:
            return
        features: Set[str] = set()
        if self.template.jinja_extensions:
            features.add("jinja_extensions")
        if self.template.tasks:
            features.add("tasks")
        if mode == "update" and self.subproject.template:
            if self.subproject.template.jinja_extensions:
                features.add("jinja_extensions")
            if self.subproject.template.tasks:
                features.add("tasks")
            for stage in get_args(Literal["before", "after"]):
                if self.template.migration_tasks(stage, self.subproject.template):
                    features.add("migrations")
                    break
        if features:
            raise UnsafeTemplateError(sorted(features))

    def _print_message(self, message: str) -> None:
        if message and not self.quiet:
            print(self._render_string(message), file=sys.stderr)

    def _answers_to_remember(self) -> Mapping:
        """Get only answers that will be remembered in the copier answers file."""
        # All internal values must appear first
        answers: AnyByStrDict = {}
        commit = self.template.commit
        src = self.template.url
        for key, value in (("_commit", commit), ("_src_path", src)):
            if value is not None:
                answers[key] = value
        # Other data goes next
        answers.update(
            (str(k), v)
            for (k, v) in self.answers.combined.items()
            if not k.startswith("_")
            and k not in self.answers.hidden
            and k not in self.template.secret_questions
            and k in self.template.questions_data
            and isinstance(k, JSONSerializable)
            and isinstance(v, JSONSerializable)
        )
        return answers

    def _execute_tasks(self, tasks: Sequence[Task]) -> None:
        """Run the given tasks.

        Arguments:
            tasks: The list of tasks to run.
        """
        for i, task in enumerate(tasks):
            task_cmd = task.cmd
            if isinstance(task_cmd, str):
                task_cmd = self._render_string(task_cmd)
                use_shell = True
            else:
                task_cmd = [self._render_string(str(part)) for part in task_cmd]
                use_shell = False
            if not self.quiet:
                print(
                    colors.info
                    | f" > Running task {i + 1} of {len(tasks)}: {task_cmd}",
                    file=sys.stderr,
                )
            if self.pretend:
                continue
            with local.cwd(self.subproject.local_abspath), local.env(**task.extra_env):
                subprocess.run(task_cmd, shell=use_shell, check=True, env=local.env)

    def _render_context(self) -> Mapping:
        """Produce render context for Jinja."""
        # Backwards compatibility
        # FIXME Remove it?
        conf = asdict(self)
        conf.pop("_cleanup_hooks")
        conf.update(
            {
                "answers_file": self.answers_relpath,
                "src_path": self.template.local_abspath,
                "vcs_ref_hash": self.template.commit_hash,
                "sep": os.sep,
                "os": OS,
            }
        )

        return dict(
            DEFAULT_DATA,
            **self.answers.combined,
            _copier_answers=self._answers_to_remember(),
            _copier_conf=conf,
            _folder_name=self.subproject.local_abspath.name,
            _copier_python=sys.executable,
        )

    def _path_matcher(self, patterns: Iterable[str]) -> Callable[[Path], bool]:
        """Produce a function that matches against specified patterns."""
        # TODO Is normalization really needed?
        normalized_patterns = (normalize("NFD", pattern) for pattern in patterns)
        spec = PathSpec.from_lines("gitwildmatch", normalized_patterns)
        return spec.match_file

    def _solve_render_conflict(self, dst_relpath: Path):
        """Properly solve render conflicts.

        It can ask the user if running in interactive mode.
        """
        assert not dst_relpath.is_absolute()
        printf(
            "conflict",
            dst_relpath,
            style=Style.DANGER,
            quiet=self.quiet,
            file_=sys.stderr,
        )
        if self.match_skip(dst_relpath):
            printf(
                "skip",
                dst_relpath,
                style=Style.OK,
                quiet=self.quiet,
                file_=sys.stderr,
            )
            return False
        if self.overwrite or dst_relpath == self.answers_relpath:
            printf(
                "overwrite",
                dst_relpath,
                style=Style.WARNING,
                quiet=self.quiet,
                file_=sys.stderr,
            )
            return True
        return bool(ask(f" Overwrite {dst_relpath}?", default=True))

    def _render_allowed(
        self,
        dst_relpath: Path,
        is_dir: bool = False,
        is_symlink: bool = False,
        expected_contents: Union[bytes, Path] = b"",
    ) -> bool:
        """Determine if a file or directory can be rendered.

        Args:
            dst_relpath:
                Relative path to destination.
            is_dir:
                Indicate if the path must be treated as a directory or not.
            is_symlink:
                Indicate if the path must be treated as a symlink or not.
            expected_contents:
                Used to compare existing file contents with them. Allows to know if
                rendering is needed.
        """
        assert not dst_relpath.is_absolute()
        assert not expected_contents or not is_dir, "Dirs cannot have expected content"
        dst_abspath = Path(self.subproject.local_abspath, dst_relpath)
        if dst_relpath != Path(".") and self.match_exclude(dst_relpath):
            return False
        try:
            previous_content: Union[bytes, Path]
            if is_symlink:
                previous_content = readlink(dst_abspath)
            else:
                previous_content = dst_abspath.read_bytes()
        except FileNotFoundError:
            printf(
                "create",
                dst_relpath,
                style=Style.OK,
                quiet=self.quiet,
                file_=sys.stderr,
            )
            return True
        except PermissionError as error:
            # HACK https://bugs.python.org/issue43095
            if not (error.errno == 13 and platform.system() == "Windows"):
                raise
        except IsADirectoryError:
            assert is_dir
        if is_dir or previous_content == expected_contents:
            printf(
                "identical",
                dst_relpath,
                style=Style.IGNORE,
                quiet=self.quiet,
                file_=sys.stderr,
            )
            return True
        return self._solve_render_conflict(dst_relpath)

    def _ask(self) -> None:
        """Ask the questions of the questionary and record their answers."""
        result = AnswersMap(
            user_defaults=self.user_defaults,
            init=self.data,
            last=self.subproject.last_answers,
            metadata=self.template.metadata,
        )

        for var_name, details in self.template.questions_data.items():
            question = Question(
                answers=result,
                jinja_env=self.jinja_env,
                var_name=var_name,
                **details,
            )
            if self.skip_answered and var_name in result.last:
                # Skip a question when the user already answered it.
                continue
            # Skip a question when the skip condition is met.
            if not question.get_when():
                # Omit its answer from the answers file.
                result.hide(var_name)
                # Skip immediately to the next question when it has no default
                # value.
                if question.default is MISSING:
                    continue
            if var_name in result.init:
                # Try to parse the answer value.
                answer = question.parse_answer(result.init[var_name])
                # Try to validate the answer value if the question has a
                # validator.
                question.validate_answer(answer)
                # At this point, the answer value is valid. Do not ask the
                # question again, but set answer as the user's answer instead.
                result.user[var_name] = answer
                continue

            # Display TUI and ask user interactively only without --defaults
            try:
                if self.defaults:
                    new_answer = question.get_default()
                    if new_answer is MISSING:
                        raise ValueError(f'Question "{var_name}" is required')
                else:
                    new_answer = unsafe_prompt(
                        [question.get_questionary_structure()],
                        answers={question.var_name: question.get_default()},
                    )[question.var_name]
            except KeyboardInterrupt as err:
                raise CopierAnswersInterrupt(result, question, self.template) from err
            result.user[var_name] = new_answer

        self.answers = result

    @cached_property
    def answers_relpath(self) -> Path:
        """Obtain the proper relative path for the answers file.

        It comes from:

        1. User choice.
        2. Template default.
        3. Copier default.
        """
        path = self.answers_file or self.template.answers_relpath
        template = self.jinja_env.from_string(str(path))
        return Path(template.render(**self.answers.combined))

    @cached_property
    def all_exclusions(self) -> StrSeq:
        """Combine default, template and user-chosen exclusions."""
        return self.template.exclude + tuple(self.exclude)

    @cached_property
    def jinja_env(self) -> SandboxedEnvironment:
        """Return a pre-configured Jinja environment.

        Respects template settings.
        """
        paths = [str(self.template.local_abspath)]
        loader = FileSystemLoader(paths)
        default_extensions = [
            "jinja2_ansible_filters.AnsibleCoreFiltersExtension",
        ]
        extensions = default_extensions + list(self.template.jinja_extensions)
        # We want to minimize the risk of hidden malware in the templates
        # so we use the SandboxedEnvironment instead of the regular one.
        # Of course we still have the post-copy tasks to worry about, but at least
        # they are more visible to the final user.
        try:
            env = SandboxedEnvironment(
                loader=loader, extensions=extensions, **self.template.envops
            )
        except ModuleNotFoundError as error:
            raise ExtensionNotFoundError(
                f"Copier could not load some Jinja extensions:\n{error}\n"
                "Make sure to install these extensions alongside Copier itself.\n"
                "See the docs at https://copier.readthedocs.io/en/latest/configuring/#jinja_extensions"
            )
        # patch the `to_json` filter to support Pydantic dataclasses
        env.filters["to_json"] = partial(
            env.filters["to_json"], default=to_jsonable_python
        )

        # Add a global function to join filesystem paths.
        separators = {
            "posix": "/",
            "windows": "\\",
            "native": os.path.sep,
        }

        def _pathjoin(
            *path: str, mode: Literal["posix", "windows", "native"] = "posix"
        ) -> str:
            return separators[mode].join(path)

        env.globals["pathjoin"] = _pathjoin
        return env

    @cached_property
    def match_exclude(self) -> Callable[[Path], bool]:
        """Get a callable to match paths against all exclusions."""
        return self._path_matcher(self.all_exclusions)

    @cached_property
    def match_skip(self) -> Callable[[Path], bool]:
        """Get a callable to match paths against all skip-if-exists patterns."""
        return self._path_matcher(
            map(
                self._render_string,
                tuple(chain(self.skip_if_exists, self.template.skip_if_exists)),
            )
        )

    def _render_file(self, src_abspath: Path) -> None:
        """Render one file.

        Args:
            src_abspath:
                The absolute path to the file that will be rendered.
        """
        # TODO Get from main.render_file()
        assert src_abspath.is_absolute()
        src_relpath = src_abspath.relative_to(self.template.local_abspath).as_posix()
        src_renderpath = src_abspath.relative_to(self.template_copy_root)
        dst_relpath = self._render_path(src_renderpath)
        if dst_relpath is None:
            return
        if src_abspath.name.endswith(self.template.templates_suffix):
            try:
                tpl = self.jinja_env.get_template(src_relpath)
            except UnicodeDecodeError:
                if self.template.templates_suffix:
                    # suffix is not empty, re-raise
                    raise
                # suffix is empty, fallback to copy
                new_content = src_abspath.read_bytes()
            else:
                new_content = tpl.render(**self._render_context()).encode()
        else:
            new_content = src_abspath.read_bytes()
        dst_abspath = Path(self.subproject.local_abspath, dst_relpath)
        src_mode = src_abspath.stat().st_mode
        if not self._render_allowed(dst_relpath, expected_contents=new_content):
            return
        if not self.pretend:
            dst_abspath.parent.mkdir(parents=True, exist_ok=True)
            dst_abspath.write_bytes(new_content)
            dst_abspath.chmod(src_mode)

    def _render_symlink(self, src_abspath: Path) -> None:
        """Render one symlink.

        Args:
            src_abspath:
                Symlink to be rendered. It must be an absolute path within
                the template.
        """
        assert src_abspath.is_absolute()
        src_relpath = src_abspath.relative_to(self.template_copy_root)
        dst_relpath = self._render_path(src_relpath)
        if dst_relpath is None:
            return
        dst_abspath = Path(self.subproject.local_abspath, dst_relpath)

        src_target = readlink(src_abspath)
        if src_abspath.name.endswith(self.template.templates_suffix):
            dst_target = Path(self._render_string(str(src_target)))
        else:
            dst_target = src_target

        if not self._render_allowed(
            dst_relpath,
            expected_contents=dst_target,
            is_symlink=True,
        ):
            return

        if not self.pretend:
            # symlink_to doesn't overwrite existing files, so delete it first
            if dst_abspath.is_symlink() or dst_abspath.exists():
                dst_abspath.unlink()
            dst_abspath.symlink_to(dst_target)
            if sys.platform == "darwin":
                # Only macOS supports permissions on symlinks.
                # Other platforms just copy the permission of the target
                src_mode = src_abspath.lstat().st_mode
                dst_abspath.lchmod(src_mode)

    def _render_folder(self, src_abspath: Path) -> None:
        """Recursively render a folder.

        Args:
            src_path:
                Folder to be rendered. It must be an absolute path within
                the template.
        """
        assert src_abspath.is_absolute()
        src_relpath = src_abspath.relative_to(self.template_copy_root)
        dst_relpath = self._render_path(src_relpath)
        if dst_relpath is None:
            return
        if not self._render_allowed(dst_relpath, is_dir=True):
            return
        dst_abspath = Path(self.subproject.local_abspath, dst_relpath)
        if not self.pretend:
            dst_abspath.mkdir(parents=True, exist_ok=True)
        for file in src_abspath.iterdir():
            if file.is_symlink() and self.template.preserve_symlinks:
                self._render_symlink(file)
            elif file.is_dir():
                self._render_folder(file)
            else:
                self._render_file(file)

    def _render_path(self, relpath: Path) -> Optional[Path]:
        """Render one relative path.

        Args:
            relpath:
                The relative path to be rendered. Obviously, it can be templated.
        """
        is_template = relpath.name.endswith(self.template.templates_suffix)
        templated_sibling = (
            self.template.local_abspath / f"{relpath}{self.template.templates_suffix}"
        )
        # With an empty suffix, the templated sibling always exists.
        if templated_sibling.exists() and self.template.templates_suffix:
            return None
        if self.template.templates_suffix and is_template:
            relpath = relpath.with_suffix("")
        rendered_parts = []
        for part in relpath.parts:
            # Skip folder if any part is rendered as an empty string
            part = self._render_string(part)
            if not part:
                return None
            # {{ _copier_conf.answers_file }} becomes the full path; in that case,
            # restore part to be just the end leaf
            if str(self.answers_relpath) == part:
                part = Path(part).name
            rendered_parts.append(part)
        result = Path(*rendered_parts)
        if not is_template:
            templated_sibling = (
                self.template.local_abspath
                / f"{result}{self.template.templates_suffix}"
            )
            if templated_sibling.exists():
                return None
        return result

    def _render_string(self, string: str) -> str:
        """Render one templated string.

        Args:
            string:
                The template source string.
        """
        tpl = self.jinja_env.from_string(string)
        return tpl.render(**self._render_context())

    @cached_property
    def subproject(self) -> Subproject:
        """Get related subproject."""
        result = Subproject(
            local_abspath=self.dst_path.absolute(),
            answers_relpath=self.answers_file or Path(".copier-answers.yml"),
        )
        self._cleanup_hooks.append(result._cleanup)
        return result

    @cached_property
    def template(self) -> Template:
        """Get related template."""
        url = self.src_path
        if not url:
            if self.subproject.template is None:
                raise TypeError("Template not found")
            url = str(self.subproject.template.url)
        result = Template(
            url=url, ref=self.vcs_ref, use_prereleases=self.use_prereleases
        )
        self._cleanup_hooks.append(result._cleanup)
        return result

    @cached_property
    def template_copy_root(self) -> Path:
        """Absolute path from where to start copying.

        It points to the cloned template local abspath + the rendered subdir, if any.
        """
        subdir = self._render_string(self.template.subdirectory) or ""
        return self.template.local_abspath / subdir

    # Main operations
    def run_copy(self) -> None:
        """Generate a subproject from zero, ignoring what was in the folder.

        If `dst_path` was missing, it will be
        created. Otherwise, `src_path` be rendered
        directly into it, without worrying about evolving what was there
        already.

        See [generating a project][generating-a-project].
        """
        self._check_unsafe("copy")
        self._print_message(self.template.message_before_copy)
        self._ask()
        was_existing = self.subproject.local_abspath.exists()
        src_abspath = self.template_copy_root
        try:
            if not self.quiet:
                # TODO Unify printing tools
                print(
                    f"\nCopying from template version {self.template.version}",
                    file=sys.stderr,
                )
            self._render_folder(src_abspath)
            if not self.quiet:
                # TODO Unify printing tools
                print("")  # padding space
            self._execute_tasks(self.template.tasks)
        except Exception:
            if not was_existing and self.cleanup_on_error:
                rmtree(self.subproject.local_abspath)
            raise
        self._print_message(self.template.message_after_copy)
        if not self.quiet:
            # TODO Unify printing tools
            print("")  # padding space

    def run_recopy(self) -> None:
        """Update a subproject, keeping answers but discarding evolution."""
        if self.subproject.template is None:
            raise UserMessageError(
                "Cannot recopy because cannot obtain old template references "
                f"from `{self.subproject.answers_relpath}`."
            )
        with replace(self, src_path=self.subproject.template.url) as new_worker:
            return new_worker.run_copy()

    def run_update(self) -> None:
        """Update a subproject that was already generated.

        See [updating a project][updating-a-project].
        """
        self._check_unsafe("update")
        # Check all you need is there
        if self.subproject.vcs != "git":
            raise UserMessageError(
                "Updating is only supported in git-tracked subprojects."
            )
        if self.subproject.is_dirty():
            raise UserMessageError(
                "Destination repository is dirty; cannot continue. "
                "Please commit or stash your local changes and retry."
            )
        if self.subproject.template is None or self.subproject.template.ref is None:
            raise UserMessageError(
                "Cannot update because cannot obtain old template references "
                f"from `{self.subproject.answers_relpath}`."
            )
        if self.template.commit is None:
            raise UserMessageError(
                "Updating is only supported in git-tracked templates."
            )
        if not self.subproject.template.version:
            raise UserMessageError(
                "Cannot update: version from last update not detected."
            )
        if not self.template.version:
            raise UserMessageError("Cannot update: version from template not detected.")
        if self.subproject.template.version > self.template.version:
            raise UserMessageError(
                f"You are downgrading from {self.subproject.template.version} to {self.template.version}. "
                "Downgrades are not supported."
            )
        if not self.overwrite:
            # Only git-tracked subprojects can be updated, so the user can
            # review the diff before committing; so we can safely avoid
            # asking for confirmation
            raise UserMessageError("Enable overwrite to update a subproject.")
        self._print_message(self.template.message_before_update)
        if not self.quiet:
            # TODO Unify printing tools
            print(
                f"Updating to template version {self.template.version}", file=sys.stderr
            )
        self._apply_update()
        self._print_message(self.template.message_after_update)

    def _apply_update(self):
        git = get_git()
        subproject_top = Path(
            git(
                "-C",
                self.subproject.local_abspath,
                "rev-parse",
                "--show-toplevel",
            ).strip()
        )
        subproject_subdir = self.subproject.local_abspath.relative_to(subproject_top)

        with TemporaryDirectory(
            prefix=f"{__name__}.old_copy."
        ) as old_copy, TemporaryDirectory(prefix=f"{__name__}.new_copy.") as new_copy:
            # Copy old template into a temporary destination
            with replace(
                self,
                dst_path=old_copy / subproject_subdir,
                data=self.subproject.last_answers,
                defaults=True,
                quiet=True,
                src_path=self.subproject.template.url,
                vcs_ref=self.subproject.template.commit,
            ) as old_worker:
                old_worker.run_copy()
            # Extract diff between temporary destination and real destination
            with local.cwd(old_copy):
                self._git_initialize_repo()
                git("remote", "add", "real_dst", "file://" + str(subproject_top))
                git("fetch", "--depth=1", "real_dst", "HEAD")
                diff_cmd = git[
                    "diff-tree", f"--unified={self.context_lines}", "HEAD...FETCH_HEAD"
                ]
                try:
                    diff = diff_cmd("--inter-hunk-context=-1")
                except ProcessExecutionError:
                    print(
                        colors.warn
                        | "Make sure Git >= 2.24 is installed to improve updates.",
                        file=sys.stderr,
                    )
                    diff = diff_cmd("--inter-hunk-context=0")
            # Run pre-migration tasks
            self._execute_tasks(
                self.template.migration_tasks("before", self.subproject.template)
            )
            # Clear last answers cache to load possible answers migration, if skip_answered flag is not set
            if self.skip_answered is False:
                self.answers = AnswersMap()
                with suppress(AttributeError):
                    del self.subproject.last_answers
            # Do a normal update in final destination
            with replace(
                self,
                # Files can change due to the historical diff, and those
                # changes are not detected in this process, so it's better to
                # say nothing than lie.
                # TODO
                quiet=True,
            ) as current_worker:
                current_worker.run_copy()
                self.answers = current_worker.answers
            # Render with the same answers in an empty dir to avoid pollution
            with replace(
                self,
                dst_path=new_copy / subproject_subdir,
                data=self.answers.combined,
                defaults=True,
                quiet=True,
                src_path=self.subproject.template.url,
            ) as new_worker:
                new_worker.run_copy()
            compared = dircmp(old_copy, new_copy)
            # Try to apply cached diff into final destination
            with local.cwd(subproject_top):
                apply_cmd = git["apply", "--reject", "--exclude", self.answers_relpath]
                for skip_pattern in chain(
                    self.skip_if_exists, self.template.skip_if_exists
                ):
                    apply_cmd = apply_cmd["--exclude", skip_pattern]
                (apply_cmd << diff)(retcode=None)
                if self.conflict == "inline":
                    status = git("status", "--porcelain").strip().splitlines()
                    for line in status:
                        # Find merge rejections
                        if not (line.startswith("?? ") and line.endswith(".rej")):
                            continue
                        # FIXME Test with a file named '`â ñ"', see it fail, fix it
                        fname = line[3:-4]
                        # Undo possible non-rejected chunks
                        git("checkout", "--", fname)
                        # 3-way-merge the file directly
                        git(
                            "merge-file",
                            "-L",
                            "before updating",
                            "-L",
                            "last update",
                            "-L",
                            "after updating",
                            fname,
                            Path(old_copy) / fname,
                            Path(new_copy) / fname,
                            retcode=None,
                        )
                        # Remove rejection witness
                        Path(f"{fname}.rej").unlink()
            # Trigger recursive removal of deleted files in last template version
            _remove_old_files(subproject_top, compared)

        # Run post-migration tasks
        self._execute_tasks(
            self.template.migration_tasks("after", self.subproject.template)
        )

    def _git_initialize_repo(self):
        """Initialize a git repository in the current directory."""
        git = get_git()
        git("init", retcode=None)
        git("add", ".")
        git("config", "user.name", "Copier")
        git("config", "user.email", "copier@copier")
        # 1st commit could fail if any pre-commit hook reformats code
        # 2nd commit uses --no-verify to disable pre-commit-like checks
        git(
            "commit",
            "--allow-empty",
            "-am",
            "dumb commit 1",
            "--no-gpg-sign",
            retcode=None,
        )
        git(
            "commit",
            "--allow-empty",
            "-am",
            "dumb commit 2",
            "--no-gpg-sign",
            "--no-verify",
        )
        git("config", "--unset", "user.name")
        git("config", "--unset", "user.email")

all_exclusions: StrSeq cached property

Combine default, template and user-chosen exclusions.

answers_relpath: Path cached property

Obtain the proper relative path for the answers file.

It comes from:

  1. User choice.
  2. Template default.
  3. Copier default.

jinja_env: SandboxedEnvironment cached property

Return a pre-configured Jinja environment.

Respects template settings.

match_exclude: Callable[[Path], bool] cached property

Get a callable to match paths against all exclusions.

match_skip: Callable[[Path], bool] cached property

Get a callable to match paths against all skip-if-exists patterns.

subproject: Subproject cached property

Get related subproject.

template: Template cached property

Get related template.

template_copy_root: Path cached property

Absolute path from where to start copying.

It points to the cloned template local abspath + the rendered subdir, if any.

__enter__()

Allow using worker as a context manager.

Source code in copier/main.py
194
195
196
def __enter__(self):
    """Allow using worker as a context manager."""
    return self

__exit__(type, value, traceback)

Clean up garbage files after worker usage ends.

Source code in copier/main.py
198
199
200
201
202
203
204
205
206
207
def __exit__(self, type, value, traceback):
    """Clean up garbage files after worker usage ends."""
    if value is not None:
        # exception was raised from code inside context manager:
        # try to clean up, ignoring any exception, then re-raise
        with suppress(Exception):
            self._cleanup()
        raise value
    # otherwise clean up and let any exception bubble up
    self._cleanup()

run_copy()

Generate a subproject from zero, ignoring what was in the folder.

If dst_path was missing, it will be created. Otherwise, src_path be rendered directly into it, without worrying about evolving what was there already.

See generating a project.

Source code in copier/main.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
def run_copy(self) -> None:
    """Generate a subproject from zero, ignoring what was in the folder.

    If `dst_path` was missing, it will be
    created. Otherwise, `src_path` be rendered
    directly into it, without worrying about evolving what was there
    already.

    See [generating a project][generating-a-project].
    """
    self._check_unsafe("copy")
    self._print_message(self.template.message_before_copy)
    self._ask()
    was_existing = self.subproject.local_abspath.exists()
    src_abspath = self.template_copy_root
    try:
        if not self.quiet:
            # TODO Unify printing tools
            print(
                f"\nCopying from template version {self.template.version}",
                file=sys.stderr,
            )
        self._render_folder(src_abspath)
        if not self.quiet:
            # TODO Unify printing tools
            print("")  # padding space
        self._execute_tasks(self.template.tasks)
    except Exception:
        if not was_existing and self.cleanup_on_error:
            rmtree(self.subproject.local_abspath)
        raise
    self._print_message(self.template.message_after_copy)
    if not self.quiet:
        # TODO Unify printing tools
        print("")  # padding space

run_recopy()

Update a subproject, keeping answers but discarding evolution.

Source code in copier/main.py
761
762
763
764
765
766
767
768
769
def run_recopy(self) -> None:
    """Update a subproject, keeping answers but discarding evolution."""
    if self.subproject.template is None:
        raise UserMessageError(
            "Cannot recopy because cannot obtain old template references "
            f"from `{self.subproject.answers_relpath}`."
        )
    with replace(self, src_path=self.subproject.template.url) as new_worker:
        return new_worker.run_copy()

run_update()

Update a subproject that was already generated.

See updating a project.

Source code in copier/main.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def run_update(self) -> None:
    """Update a subproject that was already generated.

    See [updating a project][updating-a-project].
    """
    self._check_unsafe("update")
    # Check all you need is there
    if self.subproject.vcs != "git":
        raise UserMessageError(
            "Updating is only supported in git-tracked subprojects."
        )
    if self.subproject.is_dirty():
        raise UserMessageError(
            "Destination repository is dirty; cannot continue. "
            "Please commit or stash your local changes and retry."
        )
    if self.subproject.template is None or self.subproject.template.ref is None:
        raise UserMessageError(
            "Cannot update because cannot obtain old template references "
            f"from `{self.subproject.answers_relpath}`."
        )
    if self.template.commit is None:
        raise UserMessageError(
            "Updating is only supported in git-tracked templates."
        )
    if not self.subproject.template.version:
        raise UserMessageError(
            "Cannot update: version from last update not detected."
        )
    if not self.template.version:
        raise UserMessageError("Cannot update: version from template not detected.")
    if self.subproject.template.version > self.template.version:
        raise UserMessageError(
            f"You are downgrading from {self.subproject.template.version} to {self.template.version}. "
            "Downgrades are not supported."
        )
    if not self.overwrite:
        # Only git-tracked subprojects can be updated, so the user can
        # review the diff before committing; so we can safely avoid
        # asking for confirmation
        raise UserMessageError("Enable overwrite to update a subproject.")
    self._print_message(self.template.message_before_update)
    if not self.quiet:
        # TODO Unify printing tools
        print(
            f"Updating to template version {self.template.version}", file=sys.stderr
        )
    self._apply_update()
    self._print_message(self.template.message_after_update)

run_copy(src_path, dst_path='.', data=None, **kwargs)

Copy a template to a destination, from zero.

This is a shortcut for run_copy.

See Worker fields to understand this function's args.

Source code in copier/main.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
def run_copy(
    src_path: str,
    dst_path: StrOrPath = ".",
    data: Optional[AnyByStrDict] = None,
    **kwargs,
) -> Worker:
    """Copy a template to a destination, from zero.

    This is a shortcut for [run_copy][copier.main.Worker.run_copy].

    See [Worker][copier.main.Worker] fields to understand this function's args.
    """
    if data is not None:
        kwargs["data"] = data
    with Worker(src_path=src_path, dst_path=Path(dst_path), **kwargs) as worker:
        worker.run_copy()
    return worker

run_recopy(dst_path='.', data=None, **kwargs)

Update a subproject from its template, discarding subproject evolution.

This is a shortcut for run_recopy.

See Worker fields to understand this function's args.

Source code in copier/main.py
985
986
987
988
989
990
991
992
993
994
995
996
997
998
def run_recopy(
    dst_path: StrOrPath = ".", data: Optional[AnyByStrDict] = None, **kwargs
) -> Worker:
    """Update a subproject from its template, discarding subproject evolution.

    This is a shortcut for [run_recopy][copier.main.Worker.run_recopy].

    See [Worker][copier.main.Worker] fields to understand this function's args.
    """
    if data is not None:
        kwargs["data"] = data
    with Worker(dst_path=Path(dst_path), **kwargs) as worker:
        worker.run_recopy()
    return worker

run_update(dst_path='.', data=None, **kwargs)

Update a subproject, from its template.

This is a shortcut for run_update.

See Worker fields to understand this function's args.

Source code in copier/main.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def run_update(
    dst_path: StrOrPath = ".",
    data: Optional[AnyByStrDict] = None,
    **kwargs,
) -> Worker:
    """Update a subproject, from its template.

    This is a shortcut for [run_update][copier.main.Worker.run_update].

    See [Worker][copier.main.Worker] fields to understand this function's args.
    """
    if data is not None:
        kwargs["data"] = data
    with Worker(dst_path=Path(dst_path), **kwargs) as worker:
        worker.run_update()
    return worker