File: example_project.py

package info (click to toggle)
python-semantic-release 10.5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,980 kB
  • sloc: python: 43,374; sh: 695; makefile: 158
file content (832 lines) | stat: -rw-r--r-- 25,105 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
from __future__ import annotations

import os
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING, Generator, cast
from unittest import mock

import pytest
import tomlkit

# NOTE: use backport with newer API
from importlib.resources import files

import semantic_release
from semantic_release.cli.config import (
    GlobalCommandLineOptions,
    RawConfig,
    RuntimeContext,
)
from semantic_release.cli.util import load_raw_config_file
from semantic_release.commit_parser import (
    ConventionalCommitParser,
    EmojiCommitParser,
    ScipyCommitParser,
)
from semantic_release.commit_parser.conventional.parser_monorepo import (
    ConventionalCommitMonorepoParser,
)
from semantic_release.hvcs import Bitbucket, Gitea, Github, Gitlab

import tests.conftest
import tests.const
import tests.util
from tests.const import (
    EXAMPLE_CHANGELOG_MD_CONTENT,
    EXAMPLE_CHANGELOG_RST_CONTENT,
    EXAMPLE_PROJECT_NAME,
    EXAMPLE_PROJECT_VERSION,
    EXAMPLE_PYPROJECT_TOML_CONTENT,
    EXAMPLE_RELEASE_NOTES_TEMPLATE,
    EXAMPLE_SETUP_CFG_CONTENT,
    EXAMPLE_SETUP_PY_CONTENT,
)
from tests.util import copy_dir_tree, temporary_working_directory

if TYPE_CHECKING:
    from typing import Any, Protocol, Sequence

    from tomlkit.container import Container as TOMLContainer

    from semantic_release.commit_parser import CommitParser
    from semantic_release.commit_parser._base import ParserOptions
    from semantic_release.commit_parser.token import ParseResult
    from semantic_release.hvcs import HvcsBase
    from semantic_release.version.version import Version

    from tests.conftest import (
        BuildRepoOrCopyCacheFn,
        GetMd5ForSetOfFilesFn,
    )
    from tests.fixtures.git_repo import RepoActions

    ExProjectDir = Path

    class GetWheelFileFn(Protocol):
        def __call__(self, version_str: str, pkg_name: str = ...) -> Path: ...

    class SetFlagFn(Protocol):
        def __call__(self, flag: bool, toml_file: Path | str = ...) -> None: ...

    class UpdatePyprojectTomlFn(Protocol):
        def __call__(
            self, setting: str, value: Any, toml_file: Path | str = ...
        ) -> None: ...

    class UseCustomParserFn(Protocol):
        def __call__(
            self, module_import_str: str, toml_file: Path | str = ...
        ) -> None: ...

    class UseHvcsFn(Protocol):
        def __call__(
            self, domain: str | None = None, toml_file: Path | str = ...
        ) -> type[HvcsBase]: ...

    class UseParserFn(Protocol):
        def __call__(
            self, toml_file: Path | str = ..., monorepo: bool = ...
        ) -> type[CommitParser[ParseResult, ParserOptions]]: ...

    class UseReleaseNotesTemplateFn(Protocol):
        def __call__(self, toml_file: Path | str = ...) -> None: ...

    class UpdateVersionPyFileFn(Protocol):
        def __call__(
            self, version: Version | str, version_file: Path | str = ...
        ) -> None: ...

    class GetHvcsFn(Protocol):
        def __call__(
            self,
            hvcs_client_name: str,
            origin_url: str = ...,
            hvcs_domain: str | None = None,
        ) -> Github | Gitlab | Gitea | Bitbucket: ...

    class ReadConfigFileFn(Protocol):
        """Read the raw config file from `config_path`."""

        def __call__(self, file: Path | str = ...) -> RawConfig: ...

    class LoadRuntimeContextFn(Protocol):
        """Load the runtime context from the config file."""

        def __call__(
            self, cli_opts: GlobalCommandLineOptions | None = None
        ) -> RuntimeContext: ...

    class GetParserFromConfigFileFn(Protocol):
        """Get the commit parser from the config file."""

        def __call__(
            self, file: Path | str = ...
        ) -> CommitParser[ParseResult, ParserOptions]: ...

    class GetExpectedVersionPyFileContentFn(Protocol):
        def __call__(self, version: Version | str) -> str: ...


@pytest.fixture(scope="session")
def deps_files_4_example_project() -> list[Path]:
    return [
        # This file
        Path(__file__).absolute(),
        # because of imports
        Path(tests.const.__file__).absolute(),
        Path(tests.util.__file__).absolute(),
        # because of the fixtures
        Path(tests.conftest.__file__).absolute(),
    ]


@pytest.fixture(scope="session")
def build_spec_hash_4_example_project(
    get_md5_for_set_of_files: GetMd5ForSetOfFilesFn,
    deps_files_4_example_project: list[Path],
) -> str:
    # Generates a hash of the build spec to set when to invalidate the cache
    return get_md5_for_set_of_files(deps_files_4_example_project)


@pytest.fixture(scope="session")
def cached_example_project(
    build_repo_or_copy_cache: BuildRepoOrCopyCacheFn,
    version_py_file: Path,
    pyproject_toml_file: Path,
    setup_cfg_file: Path,
    setup_py_file: Path,
    changelog_md_file: Path,
    changelog_rst_file: Path,
    build_spec_hash_4_example_project: str,
    update_version_py_file: UpdateVersionPyFileFn,
) -> Path:
    """
    Initializes the example project. DO NOT USE DIRECTLY

    Use the `init_example_project` fixture instead.
    """

    def _build_project(cached_project_path: Path) -> Sequence[RepoActions]:
        # purposefully a relative path
        example_dir = version_py_file.parent
        gitignore_contents = dedent(
            f"""
            *.pyc
            /src/**/{version_py_file.name}
            """
        ).lstrip()
        init_py_contents = dedent(
            '''
            """
            An example package with a very informative docstring
            """
            from ._version import __version__


            def hello_world() -> None:
                print("Hello World")
            '''
        ).lstrip()

        with temporary_working_directory(cached_project_path):
            update_version_py_file(EXAMPLE_PROJECT_VERSION)

        file_2_contents: list[tuple[str | Path, str]] = [
            (example_dir / "__init__.py", init_py_contents),
            (".gitignore", gitignore_contents),
            (pyproject_toml_file, EXAMPLE_PYPROJECT_TOML_CONTENT),
            (setup_cfg_file, EXAMPLE_SETUP_CFG_CONTENT),
            (setup_py_file, EXAMPLE_SETUP_PY_CONTENT),
            (changelog_md_file, EXAMPLE_CHANGELOG_MD_CONTENT),
            (changelog_rst_file, EXAMPLE_CHANGELOG_RST_CONTENT),
        ]

        for file, contents in file_2_contents:
            abs_filepath = cached_project_path.joinpath(file).resolve()
            # make sure the parent directory exists
            abs_filepath.parent.mkdir(parents=True, exist_ok=True)
            # write file contents
            abs_filepath.write_text(contents)

        # This is a special build, we don't expose the Repo Actions to the caller
        return []

    # End of _build_project()

    return build_repo_or_copy_cache(
        repo_name=f"project_{EXAMPLE_PROJECT_NAME}",
        build_spec_hash=build_spec_hash_4_example_project,
        build_repo_func=_build_project,
    )


@pytest.fixture
def init_example_project(
    example_project_dir: ExProjectDir,
    cached_example_project: Path,
    change_to_ex_proj_dir: None,
) -> None:
    """This fixture initializes the example project in the current test's project directory."""
    if not cached_example_project.exists():
        raise RuntimeError(
            f"Unable to find cached project files for {EXAMPLE_PROJECT_NAME}"
        )

    # Copy the cached project files into the current test's project directory
    copy_dir_tree(cached_example_project, example_project_dir)


@pytest.fixture
def example_project_with_release_notes_template(
    init_example_project: None,
    use_release_notes_template: UseReleaseNotesTemplateFn,
) -> None:
    use_release_notes_template()


@pytest.fixture(scope="session")
def version_py_file() -> Path:
    return Path("src", EXAMPLE_PROJECT_NAME, "_version.py")


@pytest.fixture(scope="session")
def pyproject_toml_file() -> Path:
    return Path("pyproject.toml")


@pytest.fixture(scope="session")
def setup_cfg_file() -> Path:
    return Path("setup.cfg")


@pytest.fixture(scope="session")
def setup_py_file() -> Path:
    return Path("setup.py")


@pytest.fixture(scope="session")
def dist_dir() -> Path:
    return Path("dist")


@pytest.fixture(scope="session")
def changelog_md_file() -> Path:
    return Path("CHANGELOG.md")


@pytest.fixture(scope="session")
def changelog_rst_file() -> Path:
    return Path("CHANGELOG.rst")


@pytest.fixture(scope="session")
def changelog_template_dir() -> Path:
    return Path("templates")


@pytest.fixture(scope="session")
def default_md_changelog_insertion_flag() -> str:
    return "<!-- version list -->"


@pytest.fixture(scope="session")
def default_rst_changelog_insertion_flag() -> str:
    return f"..{os.linesep}    version list"


@pytest.fixture(scope="session")
def default_changelog_md_template() -> Path:
    """Retrieve the semantic-release default changelog template file"""
    return Path(
        str(
            files(semantic_release.__name__).joinpath(
                Path("data", "templates", "conventional", "md", "CHANGELOG.md.j2")
            )
        )
    ).resolve()


@pytest.fixture(scope="session")
def default_changelog_rst_template() -> Path:
    """Retrieve the semantic-release default changelog template file"""
    return Path(
        str(
            files(semantic_release.__name__).joinpath(
                Path("data", "templates", "conventional", "rst", "CHANGELOG.rst.j2")
            )
        )
    ).resolve()


@pytest.fixture(scope="session")
def get_wheel_file(dist_dir: Path) -> GetWheelFileFn:
    def _get_wheel_file(
        version_str: str,
        pkg_name: str = EXAMPLE_PROJECT_NAME,
    ) -> Path:
        return dist_dir.joinpath(
            f"{pkg_name.replace('-', '_')}-{version_str}-py3-none-any.whl"
        )

    return _get_wheel_file


@pytest.fixture(scope="session")
def read_config_file(pyproject_toml_file: Path) -> ReadConfigFileFn:
    def _read_config_file(file: Path | str = pyproject_toml_file) -> RawConfig:
        config_text = load_raw_config_file(file)
        return RawConfig.model_validate(config_text)

    return _read_config_file


@pytest.fixture(scope="session")
def load_runtime_context(
    read_config_file: ReadConfigFileFn,
    pyproject_toml_file: Path,
) -> LoadRuntimeContextFn:
    def _load_runtime_context(
        cli_opts: GlobalCommandLineOptions | None = None,
    ) -> RuntimeContext:
        opts = cli_opts or GlobalCommandLineOptions(
            config_file=str(pyproject_toml_file),
        )
        raw_config = read_config_file(opts.config_file)
        return RuntimeContext.from_raw_config(raw_config, opts)

    return _load_runtime_context


@pytest.fixture(scope="session")
def get_parser_from_config_file(
    pyproject_toml_file: Path,
    load_runtime_context: LoadRuntimeContextFn,
) -> GetParserFromConfigFileFn:
    def _get_parser_from_config(
        file: Path | str = pyproject_toml_file,
    ) -> CommitParser[ParseResult, ParserOptions]:
        return load_runtime_context(
            cli_opts=GlobalCommandLineOptions(config_file=str(Path(file)))
        ).commit_parser

    return _get_parser_from_config


@pytest.fixture
def example_project_dir(tmp_path: Path) -> ExProjectDir:
    return tmp_path.resolve()


@pytest.fixture
def change_to_ex_proj_dir(
    example_project_dir: ExProjectDir,
) -> Generator[None, None, None]:
    cwd = os.getcwd()
    tgt_dir = str(example_project_dir.resolve())
    if cwd == tgt_dir:
        return

    os.chdir(tgt_dir)
    try:
        yield
    finally:
        os.chdir(cwd)


@pytest.fixture
def use_release_notes_template(
    example_project_template_dir: Path,
    changelog_template_dir: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_file: Path,
) -> UseReleaseNotesTemplateFn:
    def _use_release_notes_template(
        toml_file: Path | str = pyproject_toml_file,
    ) -> None:
        update_pyproject_toml(
            "tool.semantic_release.changelog.template_dir",
            str(changelog_template_dir),
            toml_file=toml_file,
        )
        example_project_template_dir.mkdir(parents=True, exist_ok=True)
        release_notes_j2 = example_project_template_dir / ".release_notes.md.j2"
        release_notes_j2.write_text(EXAMPLE_RELEASE_NOTES_TEMPLATE)

    return _use_release_notes_template


@pytest.fixture
def example_pyproject_toml(
    example_project_dir: ExProjectDir,
    pyproject_toml_file: Path,
) -> Path:
    return example_project_dir / pyproject_toml_file


@pytest.fixture
def example_setup_cfg(
    example_project_dir: ExProjectDir,
    setup_cfg_file: Path,
) -> Path:
    return example_project_dir / setup_cfg_file


@pytest.fixture
def example_setup_py(
    example_project_dir: ExProjectDir,
    setup_py_file: Path,
) -> Path:
    return example_project_dir / setup_py_file


@pytest.fixture
def example_dist_dir(
    example_project_dir: ExProjectDir,
    dist_dir: Path,
) -> Path:
    return example_project_dir / dist_dir


@pytest.fixture
def example_project_wheel_file(
    example_dist_dir: Path,
    get_wheel_file: GetWheelFileFn,
) -> Path:
    return example_dist_dir / get_wheel_file(EXAMPLE_PROJECT_VERSION)


# Note this is just the path and the content may change
@pytest.fixture
def example_changelog_md(
    example_project_dir: ExProjectDir,
    changelog_md_file: Path,
) -> Path:
    return example_project_dir / changelog_md_file


# Note this is just the path and the content may change
@pytest.fixture
def example_changelog_rst(
    example_project_dir: ExProjectDir,
    changelog_rst_file: Path,
) -> Path:
    return example_project_dir / changelog_rst_file


@pytest.fixture
def example_project_template_dir(
    example_project_dir: ExProjectDir,
    changelog_template_dir: Path,
) -> Path:
    return example_project_dir / changelog_template_dir


@pytest.fixture(scope="session")
def get_expected_version_py_file_content() -> GetExpectedVersionPyFileContentFn:
    def _get_expected_version_py_file_content(version: Version | str) -> str:
        return dedent(
            f"""\
            __version__ = "{version}"
            """
        )

    return _get_expected_version_py_file_content


@pytest.fixture(scope="session")
def update_version_py_file(
    version_py_file: Path,
    get_expected_version_py_file_content: GetExpectedVersionPyFileContentFn,
) -> UpdateVersionPyFileFn:
    """
    Updates the specified file with the expected version string content

    :param version: The version to set in the file
    :type version: Version | str

    :param version_file: The file to update
    :type version_file: Path | str
    """

    def _update_version_py_file(
        version: Version | str, version_file: Path | str = version_py_file
    ) -> None:
        cwd_version_py = Path(version_file).resolve()
        cwd_version_py.parent.mkdir(parents=True, exist_ok=True)
        cwd_version_py.write_text(get_expected_version_py_file_content(version))

    return _update_version_py_file


@pytest.fixture(scope="session")
def update_pyproject_toml(pyproject_toml_file: Path) -> UpdatePyprojectTomlFn:
    """Update the pyproject.toml file with the given content."""

    def _update_pyproject_toml(
        setting: str, value: Any, toml_file: Path | str = pyproject_toml_file
    ) -> None:
        cwd_pyproject_toml = Path(toml_file).resolve()
        with open(cwd_pyproject_toml) as rfd:
            pyproject_toml = tomlkit.load(rfd)

        new_setting = {}
        parts = setting.split(".")
        new_setting_key = parts.pop(-1)
        new_setting[new_setting_key] = value

        pointer: TOMLContainer = pyproject_toml
        for part in parts:
            if (next_pointer := pointer.get(part, None)) is None:
                next_pointer = tomlkit.table()
                pointer.add(part, next_pointer)

            pointer = cast("TOMLContainer", next_pointer)

        if value is None:
            pointer.pop(new_setting_key)
        else:
            pointer.update(new_setting)

        with open(cwd_pyproject_toml, "w") as wfd:
            tomlkit.dump(pyproject_toml, wfd)

    return _update_pyproject_toml


@pytest.fixture(scope="session")
def pyproject_toml_config_option_parser() -> str:
    return f"tool.{semantic_release.__name__}.commit_parser"


@pytest.fixture(scope="session")
def pyproject_toml_config_option_remote_type() -> str:
    return f"tool.{semantic_release.__name__}.remote.type"


@pytest.fixture(scope="session")
def pyproject_toml_config_option_remote_domain() -> str:
    return f"tool.{semantic_release.__name__}.remote.domain"


@pytest.fixture(scope="session")
def set_major_on_zero(
    pyproject_toml_file: Path, update_pyproject_toml: UpdatePyprojectTomlFn
) -> SetFlagFn:
    """Turn on/off the major_on_zero setting."""

    def _set_major_on_zero(
        flag: bool, toml_file: Path | str = pyproject_toml_file
    ) -> None:
        update_pyproject_toml("tool.semantic_release.major_on_zero", flag, toml_file)

    return _set_major_on_zero


@pytest.fixture(scope="session")
def set_allow_zero_version(
    pyproject_toml_file: Path, update_pyproject_toml: UpdatePyprojectTomlFn
) -> SetFlagFn:
    """Turn on/off the allow_zero_version setting."""

    def _set_allow_zero_version(
        flag: bool, toml_file: Path | str = pyproject_toml_file
    ) -> None:
        update_pyproject_toml(
            "tool.semantic_release.allow_zero_version", flag, toml_file
        )

    return _set_allow_zero_version


@pytest.fixture(scope="session")
def use_conventional_parser(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_parser: str,
) -> UseParserFn:
    """Modify the configuration file to use the Conventional parser."""

    def _use_conventional_parser(
        toml_file: Path | str = pyproject_toml_file, monorepo: bool = False
    ) -> type[CommitParser[ParseResult, ParserOptions]]:
        update_pyproject_toml(
            pyproject_toml_config_option_parser,
            f"conventional{'-monorepo' if monorepo else ''}",
            toml_file=toml_file,
        )
        return cast(
            "type[CommitParser[ParseResult, ParserOptions]]",
            ConventionalCommitMonorepoParser if monorepo else ConventionalCommitParser,
        )

    return _use_conventional_parser


@pytest.fixture(scope="session")
def use_emoji_parser(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_parser: str,
) -> UseParserFn:
    """Modify the configuration file to use the Emoji parser."""

    def _use_emoji_parser(
        toml_file: Path | str = pyproject_toml_file, monorepo: bool = False
    ) -> type[CommitParser[ParseResult, ParserOptions]]:
        if monorepo:
            raise ValueError(
                "The Emoji parser does not support monorepo mode. "
                "Use the conventional parser instead."
            )

        update_pyproject_toml(
            pyproject_toml_config_option_parser, "emoji", toml_file=toml_file
        )
        return cast("type[CommitParser[ParseResult, ParserOptions]]", EmojiCommitParser)

    return _use_emoji_parser


@pytest.fixture(scope="session")
def use_scipy_parser(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_parser: str,
) -> UseParserFn:
    """Modify the configuration file to use the Scipy parser."""

    def _use_scipy_parser(
        toml_file: Path | str = pyproject_toml_file, monorepo: bool = False
    ) -> type[CommitParser[ParseResult, ParserOptions]]:
        if monorepo:
            raise ValueError(
                "The Scipy parser does not support monorepo mode. "
                "Use the conventional parser instead."
            )

        update_pyproject_toml(
            pyproject_toml_config_option_parser, "scipy", toml_file=toml_file
        )
        return cast("type[CommitParser[ParseResult, ParserOptions]]", ScipyCommitParser)

    return _use_scipy_parser


@pytest.fixture(scope="session")
def use_custom_parser(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_parser: str,
) -> UseCustomParserFn:
    """Modify the configuration file to use a user defined string parser."""

    def _use_custom_parser(
        module_import_str: str, toml_file: Path | str = pyproject_toml_file
    ) -> None:
        update_pyproject_toml(
            pyproject_toml_config_option_parser, module_import_str, toml_file=toml_file
        )

    return _use_custom_parser


@pytest.fixture(scope="session")
def get_hvcs(example_git_https_url: str) -> GetHvcsFn:
    hvcs_clients: dict[str, type[HvcsBase]] = {
        "github": Github,
        "gitlab": Gitlab,
        "gitea": Gitea,
        "bitbucket": Bitbucket,
    }

    def _get_hvcs(
        hvcs_client_name: str,
        origin_url: str = example_git_https_url,
        hvcs_domain: str | None = None,
    ) -> Github | Gitlab | Gitea | Bitbucket:
        if (hvcs_class := hvcs_clients.get(hvcs_client_name)) is None:
            raise ValueError(f"Unknown HVCS client name: {hvcs_client_name}")

        # Create HVCS Client instance
        with mock.patch.dict(os.environ, {}, clear=True):
            hvcs = hvcs_class(origin_url, hvcs_domain=hvcs_domain)
            assert hvcs.repo_name  # Force the HVCS client to cache the repo name
            assert hvcs.owner  # Force the HVCS client to cache the owner

        return cast("Github | Gitlab | Gitea | Bitbucket", hvcs)

    return _get_hvcs


@pytest.fixture(scope="session")
def use_github_hvcs(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_remote_type: str,
    pyproject_toml_config_option_remote_domain: str,
) -> UseHvcsFn:
    """Modify the configuration file to use GitHub as the HVCS."""

    def _use_github_hvcs(
        domain: str | None = None, toml_file: Path | str = pyproject_toml_file
    ) -> type[HvcsBase]:
        update_pyproject_toml(
            pyproject_toml_config_option_remote_type,
            Github.__name__.lower(),
            toml_file=toml_file,
        )

        if domain is not None:
            update_pyproject_toml(
                pyproject_toml_config_option_remote_domain, domain, toml_file=toml_file
            )

        return Github

    return _use_github_hvcs


@pytest.fixture(scope="session")
def use_gitlab_hvcs(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_remote_type: str,
    pyproject_toml_config_option_remote_domain: str,
) -> UseHvcsFn:
    """Modify the configuration file to use GitLab as the HVCS."""

    def _use_gitlab_hvcs(
        domain: str | None = None, toml_file: Path | str = pyproject_toml_file
    ) -> type[HvcsBase]:
        update_pyproject_toml(
            pyproject_toml_config_option_remote_type,
            Gitlab.__name__.lower(),
            toml_file=toml_file,
        )

        if domain is not None:
            update_pyproject_toml(
                pyproject_toml_config_option_remote_domain, domain, toml_file=toml_file
            )

        return Gitlab

    return _use_gitlab_hvcs


@pytest.fixture(scope="session")
def use_gitea_hvcs(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_remote_type: str,
    pyproject_toml_config_option_remote_domain: str,
) -> UseHvcsFn:
    """Modify the configuration file to use Gitea as the HVCS."""

    def _use_gitea_hvcs(
        domain: str | None = None, toml_file: Path | str = pyproject_toml_file
    ) -> type[HvcsBase]:
        update_pyproject_toml(
            pyproject_toml_config_option_remote_type,
            Gitea.__name__.lower(),
            toml_file=toml_file,
        )

        if domain is not None:
            update_pyproject_toml(
                pyproject_toml_config_option_remote_domain, domain, toml_file=toml_file
            )

        return Gitea

    return _use_gitea_hvcs


@pytest.fixture(scope="session")
def use_bitbucket_hvcs(
    pyproject_toml_file: Path,
    update_pyproject_toml: UpdatePyprojectTomlFn,
    pyproject_toml_config_option_remote_type: str,
    pyproject_toml_config_option_remote_domain: str,
) -> UseHvcsFn:
    """Modify the configuration file to use BitBucket as the HVCS."""

    def _use_bitbucket_hvcs(
        domain: str | None = None, toml_file: Path | str = pyproject_toml_file
    ) -> type[HvcsBase]:
        update_pyproject_toml(
            pyproject_toml_config_option_remote_type,
            Bitbucket.__name__.lower(),
            toml_file=toml_file,
        )

        if domain is not None:
            update_pyproject_toml(
                pyproject_toml_config_option_remote_domain, domain, toml_file=toml_file
            )

        return Bitbucket

    return _use_bitbucket_hvcs