Debian Codegraph @

tests/commands/test_changelog_command.py

raw
1 from __future__ import annotations
2
3 import itertools
4 from pathlib import Path
5 from textwrap import dedent
6 from typing import TYPE_CHECKING
7
8 import pytest
9 from jinja2 import FileSystemLoader
10
11 from commitizen import git
12 from commitizen.commands.changelog import Changelog
13 from commitizen.cz.conventional_commits import ConventionalCommitsCz
14 from commitizen.exceptions import (
15 DryRunExit,
16 InvalidCommandArgumentError,
17 NoCommitsFoundError,
18 NoRevisionError,
19 NotAGitProjectError,
20 NotAllowed,
21 )
22
23 if TYPE_CHECKING:
24 from pytest_mock import MockFixture
25 from pytest_regressions.file_regression import FileRegressionFixture
26
27 from commitizen.changelog_formats import ChangelogFormat
28 from commitizen.config.base_config import BaseConfig
29 from commitizen.config.json_config import JsonConfig
30 from commitizen.cz.base import BaseCommitizen
31 from tests.utils import UtilFixture
32
33
34 @pytest.fixture
35 def changelog_jinja_file(tmp_commitizen_project: Path) -> Path:
36 return tmp_commitizen_project / "changelog.jinja"
37
38
39 @pytest.fixture
40 def changelog_tpl(
41 tmp_commitizen_project: Path, any_changelog_format: ChangelogFormat
42 ) -> Path:
43 return tmp_commitizen_project / any_changelog_format.template
44
45
46 @pytest.fixture
47 def changelog_file(
48 tmp_commitizen_project: Path, any_changelog_format: ChangelogFormat
49 ) -> Path:
50 return tmp_commitizen_project / any_changelog_format.default_changelog_file
51
52
53 @pytest.mark.usefixtures("tmp_commitizen_project")
54 def test_changelog_from_version_zero_point_two(
55 capsys: pytest.CaptureFixture,
56 file_regression: FileRegressionFixture,
57 util: UtilFixture,
58 ):
59 util.create_file_and_commit("feat: new file")
60 util.create_file_and_commit("refactor: not in changelog")
61
62 # create tag
63 util.run_cli("bump", "--yes")
64 capsys.readouterr()
65
66 util.create_file_and_commit("feat: after 0.2.0")
67 util.create_file_and_commit("feat: after 0.2")
68
69 with pytest.raises(DryRunExit):
70 util.run_cli("changelog", "--dry-run", "--start-rev", "0.2.0")
71
72 out, _ = capsys.readouterr()
73 file_regression.check(out, extension=".md")
74
75
76 @pytest.mark.usefixtures("tmp_commitizen_project")
77 def test_changelog_with_different_cz(
78 capsys: pytest.CaptureFixture,
79 file_regression: FileRegressionFixture,
80 util: UtilFixture,
81 ):
82 util.create_file_and_commit("JRA-34 #comment corrected indent issue")
83 util.create_file_and_commit("JRA-35 #time 1w 2d 4h 30m Total work logged")
84
85 with pytest.raises(DryRunExit):
86 util.run_cli("-n", "cz_jira", "changelog", "--dry-run")
87 out, _ = capsys.readouterr()
88 file_regression.check(out, extension=".md")
89
90
91 @pytest.mark.usefixtures("tmp_commitizen_project")
92 def test_changelog_filters_commits_before_generating_tree(
93 capsys: pytest.CaptureFixture,
94 util: UtilFixture,
95 mocker: MockFixture,
96 ):
97 """Changelog generation excludes commits rejected by the rule hook."""
98
99 def filter_app_a_commits(
100 self: ConventionalCommitsCz, commits: list[git.GitCommit]
101 ) -> list[git.GitCommit]:
102 """Keep commits whose full message declares AppA."""
103 return [
104 commit
105 for commit in commits
106 if "'AppA'" in commit.message.partition("Applications:")[2]
107 ]
108
109 mocker.patch.object(
110 ConventionalCommitsCz,
111 "filter_commits_before_changelog",
112 filter_app_a_commits,
113 )
114 util.create_file_and_commit(
115 "feat: add AppB feature\n\nApplications: ['AppB']",
116 filename="app-b",
117 )
118 util.create_file_and_commit(
119 "fix: correct shared behavior\n\nApplications: ['AppA', 'AppB']",
120 filename="app-a",
121 )
122
123 with pytest.raises(DryRunExit):
124 util.run_cli("changelog", "--dry-run")
125
126 out, _ = capsys.readouterr()
127 assert "correct shared behavior" in out
128 assert "add AppB feature" not in out
129
130
131 @pytest.mark.usefixtures("tmp_commitizen_project")
132 def test_changelog_from_start(
133 changelog_format: ChangelogFormat,
134 file_regression: FileRegressionFixture,
135 util: UtilFixture,
136 ):
137 util.create_file_and_commit("feat: new file")
138 util.create_file_and_commit("refactor: is in changelog")
139 util.create_file_and_commit("Merge into master")
140 changelog_file = f"CHANGELOG.{changelog_format.extension}"
141 template = f"CHANGELOG.{changelog_format.extension}.j2"
142
143 util.run_cli("changelog", "--file-name", changelog_file, "--template", template)
144
145 out = Path(changelog_file).read_text(encoding="utf-8")
146 file_regression.check(out, extension=changelog_format.ext)
147
148
149 @pytest.mark.usefixtures("tmp_commitizen_project")
150 @pytest.mark.freeze_time("2022-08-14")
151 def test_changelog_replacing_unreleased_using_incremental(
152 changelog_format: ChangelogFormat,
153 file_regression: FileRegressionFixture,
154 util: UtilFixture,
155 ):
156 util.create_file_and_commit("feat: add new output")
157 util.create_file_and_commit("fix: output glitch")
158 util.create_file_and_commit("Merge into master")
159 changelog_file = f"CHANGELOG.{changelog_format.extension}"
160 template = f"CHANGELOG.{changelog_format.extension}.j2"
161
162 util.run_cli("changelog", "--file-name", changelog_file, "--template", template)
163
164 util.run_cli("bump", "--yes", "--file-name", changelog_file, "--template", template)
165
166 util.create_file_and_commit("fix: mama gotta work")
167 util.create_file_and_commit("feat: add more stuff")
168 util.create_file_and_commit("Merge into master")
169
170 util.run_cli(
171 "changelog",
172 "--incremental",
173 "--file-name",
174 changelog_file,
175 "--template",
176 template,
177 )
178
179 out = Path(changelog_file).read_text(encoding="utf-8")
180
181 file_regression.check(out, extension=changelog_format.ext)
182
183
184 @pytest.mark.usefixtures("tmp_commitizen_project")
185 @pytest.mark.freeze_time("2022-08-14")
186 def test_changelog_is_persisted_using_incremental(
187 changelog_path: Path,
188 file_regression: FileRegressionFixture,
189 util: UtilFixture,
190 ):
191 util.create_file_and_commit("feat: add new output")
192 util.create_file_and_commit("fix: output glitch")
193 util.create_file_and_commit("Merge into master")
194
195 util.run_cli("bump", "--yes")
196
197 util.run_cli("changelog")
198
199 with changelog_path.open("a", encoding="utf-8") as f:
200 f.write("\nnote: this should be persisted using increment\n")
201
202 util.create_file_and_commit("fix: mama gotta work")
203 util.create_file_and_commit("feat: add more stuff")
204 util.create_file_and_commit("Merge into master")
205
206 util.run_cli("changelog", "--incremental")
207
208 out = changelog_path.read_text(encoding="utf-8")
209
210 file_regression.check(out, extension=".md")
211
212
213 @pytest.mark.usefixtures("tmp_commitizen_project")
214 def test_changelog_incremental_angular_sample(
215 changelog_path: Path,
216 file_regression: FileRegressionFixture,
217 util: UtilFixture,
218 ):
219 with changelog_path.open("w", encoding="utf-8") as f:
220 f.write(
221 "# [10.0.0-rc.3](https://github.com/angular/angular/compare/10.0.0-rc.2...10.0.0-rc.3) (2020-04-22)\n"
222 "\n"
223 "### Bug Fixes"
224 "\n"
225 "* **common:** format day-periods that cross midnight ([#36611](https://github.com/angular/angular/issues/36611)) ([c6e5fc4](https://github.com/angular/angular/commit/c6e5fc4)), closes [#36566](https://github.com/angular/angular/issues/36566)\n"
226 )
227 util.create_file_and_commit("irrelevant commit")
228 util.create_tag("10.0.0-rc.3")
229
230 util.create_file_and_commit("feat: add new output")
231 util.create_file_and_commit("fix: output glitch")
232 util.create_file_and_commit("fix: mama gotta work")
233 util.create_file_and_commit("feat: add more stuff")
234 util.create_file_and_commit("Merge into master")
235
236 util.run_cli("changelog", "--incremental")
237
238 out = changelog_path.read_text(encoding="utf-8")
239
240 file_regression.check(out, extension=".md")
241
242
243 KEEP_A_CHANGELOG = """# Changelog
244 All notable changes to this project will be documented in this file.
245
246 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
247 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
248
249 ## [Unreleased]
250
251 ## [1.0.0] - 2017-06-20
252 ### Added
253 - New visual identity by [@tylerfortune8](https://github.com/tylerfortune8).
254 - Version navigation.
255
256 ### Changed
257 - Start using "changelog" over "change log" since it's the common usage.
258
259 ### Removed
260 - Section about "changelog" vs "CHANGELOG".
261
262 ## [0.3.0] - 2015-12-03
263 ### Added
264 - RU translation from [@aishek](https://github.com/aishek).
265 """
266
267
268 @pytest.mark.usefixtures("tmp_commitizen_project")
269 def test_changelog_incremental_keep_a_changelog_sample(
270 changelog_path: Path,
271 file_regression: FileRegressionFixture,
272 util: UtilFixture,
273 ):
274 with changelog_path.open("w", encoding="utf-8") as f:
275 f.write(KEEP_A_CHANGELOG)
276 util.create_file_and_commit("irrelevant commit")
277 util.create_tag("1.0.0")
278
279 util.create_file_and_commit("feat: add new output")
280 util.create_file_and_commit("fix: output glitch")
281 util.create_file_and_commit("fix: mama gotta work")
282 util.create_file_and_commit("feat: add more stuff")
283 util.create_file_and_commit("Merge into master")
284
285 util.run_cli("changelog", "--incremental")
286
287 out = changelog_path.read_text(encoding="utf-8")
288
289 file_regression.check(out, extension=".md")
290
291
292 @pytest.mark.usefixtures("tmp_commitizen_project")
293 @pytest.mark.parametrize("dry_run", [True, False])
294 def test_changelog_hook(
295 mocker: MockFixture, config: BaseConfig, dry_run: bool, util: UtilFixture
296 ):
297 changelog_hook_mock = mocker.Mock()
298 changelog_hook_mock.return_value = "cool changelog hook"
299
300 util.create_file_and_commit("feat: new file")
301 util.create_file_and_commit("refactor: is in changelog")
302 util.create_file_and_commit("Merge into master")
303
304 config.settings["change_type_order"] = ["Refactor", "Feat"] # type: ignore[typeddict-unknown-key]
305 changelog = Changelog(
306 config, {"unreleased_version": None, "incremental": True, "dry_run": dry_run}
307 )
308 mocker.patch.object(changelog.cz, "changelog_hook", changelog_hook_mock)
309 if dry_run:
310 with pytest.raises(DryRunExit):
311 changelog()
312 else:
313 changelog()
314
315 full_changelog = (
316 "## Unreleased\n\n### Refactor\n\n- is in changelog\n\n### Feat\n\n- new file\n"
317 )
318 partial_changelog = full_changelog
319 if dry_run:
320 partial_changelog = ""
321
322 changelog_hook_mock.assert_called_with(full_changelog, partial_changelog)
323
324
325 @pytest.mark.usefixtures("tmp_commitizen_project")
326 def test_changelog_hook_customize(
327 mocker: MockFixture, config_customize: JsonConfig, util: UtilFixture
328 ):
329 changelog_hook_mock = mocker.Mock()
330 changelog_hook_mock.return_value = "cool changelog hook"
331
332 util.create_file_and_commit("feat: new file")
333 util.create_file_and_commit("refactor: is in changelog")
334 util.create_file_and_commit("Merge into master")
335
336 changelog = Changelog(
337 config_customize,
338 {"unreleased_version": None, "incremental": True, "dry_run": False},
339 )
340 mocker.patch.object(changelog.cz, "changelog_hook", changelog_hook_mock)
341 changelog()
342 full_changelog = (
343 "## Unreleased\n\n### Refactor\n\n- is in changelog\n\n### Feat\n\n- new file\n"
344 )
345
346 changelog_hook_mock.assert_called_with(full_changelog, full_changelog)
347
348
349 @pytest.mark.usefixtures("tmp_commitizen_project")
350 def test_changelog_release_hook(
351 mocker: MockFixture, config: BaseConfig, util: UtilFixture
352 ):
353 def changelog_release_hook(release: dict, tag: git.GitTag) -> dict:
354 return release
355
356 for i in range(3):
357 util.create_file_and_commit("feat: new file")
358 util.create_file_and_commit("refactor: is in changelog")
359 util.create_file_and_commit("Merge into master")
360 util.create_tag(f"0.{i + 1}.0")
361
362 # changelog = Changelog(config, {})
363 changelog = Changelog(
364 config, {"unreleased_version": None, "incremental": True, "dry_run": False}
365 )
366 mocker.patch.object(changelog.cz, "changelog_release_hook", changelog_release_hook)
367 spy = mocker.spy(changelog.cz, "changelog_release_hook")
368 changelog()
369
370 assert spy.call_count == 3
371
372
373 @pytest.mark.usefixtures("tmp_commitizen_project")
374 def test_changelog_with_non_linear_merges_commit_order(
375 mocker: MockFixture, config_customize: JsonConfig, util: UtilFixture
376 ):
377 """Test that commits merged non-linearly are correctly ordered in the changelog
378
379 A typical scenario is having two branches from main like so:
380 * feat: I will be merged first - (2023-03-01 11:35:51 +0100) | (branchB)
381 | * feat: I will be merged second - (2023-03-01 11:35:22 +0100) | (branchA)
382 |/
383 * feat: initial commit - (2023-03-01 11:34:54 +0100) | (HEAD -> main)
384
385 And merging them, for example in the reverse order they were created on would give the following:
386 * Merge branch 'branchA' - (2023-03-01 11:42:59 +0100) | (HEAD -> main)
387 |\
388 | * feat: I will be merged second - (2023-03-01 11:35:22 +0100) | (branchA)
389 * | feat: I will be merged first - (2023-03-01 11:35:51 +0100) | (branchB)
390 |/
391 * feat: initial commit - (2023-03-01 11:34:54 +0100) |
392
393 In this case we want the changelog to reflect the topological order of commits,
394 i.e. the order in which they were merged into the main branch
395
396 So the above example should result in the following:
397 ## Unreleased
398
399 ### Feat
400 - I will be merged second
401 - I will be merged first
402 - initial commit
403 """
404 changelog_hook_mock = mocker.Mock()
405 changelog_hook_mock.return_value = "cool changelog hook"
406
407 util.create_file_and_commit("feat: initial commit")
408
409 main_branch = util.get_current_branch()
410
411 util.create_branch("branchA")
412 util.create_branch("branchB")
413
414 util.switch_branch("branchA")
415 util.create_file_and_commit("feat: I will be merged second")
416
417 util.switch_branch("branchB")
418 util.create_file_and_commit("feat: I will be merged first")
419
420 # Note we merge branches opposite order than author_date
421 util.switch_branch(main_branch)
422 util.merge_branch("branchB")
423 util.merge_branch("branchA")
424
425 changelog = Changelog(
426 config_customize,
427 {"unreleased_version": None, "incremental": True, "dry_run": False},
428 )
429 mocker.patch.object(changelog.cz, "changelog_hook", changelog_hook_mock)
430 changelog()
431 full_changelog = "\
432 ## Unreleased\n\n\
433 \
434 ### Feat\n\n\
435 - I will be merged second\n\
436 - I will be merged first\n\
437 - initial commit\n"
438
439 changelog_hook_mock.assert_called_with(full_changelog, full_changelog)
440
441
442 @pytest.mark.usefixtures("tmp_commitizen_project")
443 def test_changelog_multiple_incremental_do_not_add_new_lines(
444 changelog_path: Path,
445 file_regression: FileRegressionFixture,
446 util: UtilFixture,
447 ):
448 """Test for bug https://github.com/commitizen-tools/commitizen/issues/192"""
449 for commit_message in [
450 "feat: add new output",
451 "fix: output glitch",
452 "fix: no more explosions",
453 "feat: add more stuff",
454 ]:
455 util.create_file_and_commit(commit_message)
456 util.run_cli("changelog", "--incremental")
457
458 out = changelog_path.read_text(encoding="utf-8")
459
460 file_regression.check(out, extension=".md")
461
462
463 @pytest.mark.usefixtures("tmp_commitizen_project")
464 def test_changelog_incremental_newline_separates_new_content_from_old(
465 changelog_path: Path,
466 util: UtilFixture,
467 file_regression: FileRegressionFixture,
468 ):
469 """Test for https://github.com/commitizen-tools/commitizen/issues/509"""
470 with changelog_path.open("w", encoding="utf-8") as f:
471 f.write("Pre-existing content that should be kept\n")
472
473 util.create_file_and_commit("feat: add more cat videos")
474 util.run_cli("changelog", "--incremental")
475 out = changelog_path.read_text(encoding="utf-8")
476
477 file_regression.check(out, extension=".md")
478
479
480 def test_changelog_without_revision(tmp_commitizen_project, util: UtilFixture):
481 (tmp_commitizen_project / "CHANGELOG.md").write_text(
482 """
483 # Unreleased
484
485 ## v1.0.0
486 """
487 )
488
489 # No revision
490 with pytest.raises(NoRevisionError):
491 util.run_cli("changelog", "--incremental")
492
493 util.create_file_and_commit("feat: new file")
494 util.create_tag("2.0.0")
495
496 # With different tag name and changelog content
497 with pytest.raises(NoRevisionError):
498 util.run_cli("changelog", "--incremental")
499
500
501 @pytest.mark.usefixtures("tmp_commitizen_project")
502 def test_changelog_incremental_with_revision(util: UtilFixture):
503 """combining incremental with a revision doesn't make sense"""
504 with pytest.raises(NotAllowed):
505 util.run_cli("changelog", "--incremental", "0.2.0")
506
507
508 @pytest.mark.usefixtures("chdir")
509 def test_changelog_in_non_git_project(util: UtilFixture):
510 with pytest.raises(NotAGitProjectError):
511 util.run_cli("changelog", "--incremental")
512
513
514 @pytest.mark.parametrize(
515 "commit_message",
516 [
517 "feat(users): email pattern corrected\n\n"
518 "BREAKING CHANGE: migrate by renaming user to users\n\n"
519 "footer content",
520 "feat(users): email pattern corrected\n\n"
521 "body content\n\n"
522 "BREAKING CHANGE: migrate by renaming user to users",
523 ],
524 )
525 @pytest.mark.usefixtures("tmp_commitizen_project")
526 def test_breaking_change_content_v1_beta(
527 capsys: pytest.CaptureFixture,
528 file_regression: FileRegressionFixture,
529 util: UtilFixture,
530 commit_message: str,
531 ):
532 util.create_file_and_commit(commit_message)
533 with pytest.raises(DryRunExit):
534 util.run_cli("changelog", "--dry-run")
535 out, _ = capsys.readouterr()
536 file_regression.check(out, extension=".md")
537
538
539 @pytest.mark.usefixtures("tmp_commitizen_project")
540 def test_breaking_change_content_v1_multiline(
541 capsys: pytest.CaptureFixture,
542 file_regression: FileRegressionFixture,
543 util: UtilFixture,
544 ):
545 commit_message = (
546 "feat(users): email pattern corrected\n\n"
547 "body content\n\n"
548 "BREAKING CHANGE: migrate by renaming user to users.\n"
549 "and then connect the thingy with the other thingy\n\n"
550 "footer content"
551 )
552 util.create_file_and_commit(commit_message)
553 with pytest.raises(DryRunExit):
554 util.run_cli("changelog", "--dry-run")
555 out, _ = capsys.readouterr()
556 file_regression.check(out, extension=".md")
557
558
559 @pytest.mark.usefixtures("tmp_commitizen_project")
560 def test_breaking_change_content_v1_with_exclamation_mark(
561 capsys: pytest.CaptureFixture,
562 file_regression: FileRegressionFixture,
563 util: UtilFixture,
564 ):
565 commit_message = "chore!: drop support for py36"
566 util.create_file_and_commit(commit_message)
567 with pytest.raises(DryRunExit):
568 util.run_cli("changelog", "--dry-run")
569 out, _ = capsys.readouterr()
570
571 file_regression.check(out, extension=".md")
572
573
574 @pytest.mark.usefixtures("tmp_commitizen_project")
575 def test_breaking_change_content_v1_with_exclamation_mark_feat(
576 capsys: pytest.CaptureFixture,
577 file_regression: FileRegressionFixture,
578 util: UtilFixture,
579 ):
580 commit_message = "feat(pipeline)!: some text with breaking change"
581 util.create_file_and_commit(commit_message)
582 with pytest.raises(DryRunExit):
583 util.run_cli("changelog", "--dry-run")
584 out, _ = capsys.readouterr()
585
586 file_regression.check(out, extension=".md")
587
588
589 @pytest.mark.usefixtures("tmp_commitizen_project")
590 def test_changelog_config_flag_increment(
591 changelog_path: Path,
592 config_path: Path,
593 file_regression: FileRegressionFixture,
594 util: UtilFixture,
595 ):
596 with config_path.open("a", encoding="utf-8") as f:
597 f.write("changelog_incremental = true\n")
598 with changelog_path.open("a", encoding="utf-8") as f:
599 f.write("\nnote: this should be persisted using increment\n")
600
601 util.create_file_and_commit("feat: add new output")
602
603 util.run_cli("changelog")
604
605 out = changelog_path.read_text(encoding="utf-8")
606
607 assert "this should be persisted using increment" in out
608 file_regression.check(out, extension=".md")
609
610
611 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
612 @pytest.mark.usefixtures("tmp_commitizen_project")
613 @pytest.mark.freeze_time("2025-12-29")
614 def test_changelog_config_flag_merge_prerelease(
615 changelog_path: Path,
616 config_path: Path,
617 file_regression: FileRegressionFixture,
618 test_input: str,
619 util: UtilFixture,
620 ):
621 with config_path.open("a") as f:
622 f.write("changelog_merge_prerelease = true\n")
623
624 util.create_file_and_commit("irrelevant commit")
625 util.create_tag("1.0.0")
626
627 util.create_file_and_commit("feat: add new output")
628 util.create_file_and_commit("fix: output glitch")
629
630 util.run_cli("bump", "--prerelease", test_input, "--yes")
631
632 util.create_file_and_commit("fix: mama gotta work")
633 util.create_file_and_commit("feat: add more stuff")
634 util.create_file_and_commit("Merge into master")
635
636 util.run_cli("changelog")
637
638 out = changelog_path.read_text()
639
640 file_regression.check(out, extension=".md")
641
642
643 @pytest.mark.usefixtures("tmp_commitizen_project")
644 def test_changelog_config_start_rev_option(
645 capsys: pytest.CaptureFixture,
646 config_path: Path,
647 file_regression: FileRegressionFixture,
648 util: UtilFixture,
649 ):
650 # create commit and tag
651 util.create_file_and_commit("feat: new file")
652 util.run_cli("bump", "--yes")
653 capsys.readouterr()
654
655 util.create_file_and_commit("feat: after 0.2.0")
656 util.create_file_and_commit("feat: after 0.2")
657
658 with config_path.open("a", encoding="utf-8") as f:
659 f.write('changelog_start_rev = "0.2.0"\n')
660
661 with pytest.raises(DryRunExit):
662 util.run_cli("changelog", "--dry-run")
663
664 out, _ = capsys.readouterr()
665 file_regression.check(out, extension=".md")
666
667
668 @pytest.mark.usefixtures("tmp_commitizen_project")
669 def test_changelog_incremental_keep_a_changelog_sample_with_annotated_tag(
670 changelog_path: Path,
671 file_regression: FileRegressionFixture,
672 util: UtilFixture,
673 ):
674 """Fix #378"""
675 with changelog_path.open("w", encoding="utf-8") as f:
676 f.write(KEEP_A_CHANGELOG)
677 util.create_file_and_commit("irrelevant commit")
678 util.create_tag("1.0.0", annotated=True)
679
680 util.create_file_and_commit("feat: add new output")
681 util.create_file_and_commit("fix: output glitch")
682 util.create_file_and_commit("fix: mama gotta work")
683 util.create_file_and_commit("feat: add more stuff")
684 util.create_file_and_commit("Merge into master")
685
686 util.run_cli("changelog", "--incremental")
687
688 out = changelog_path.read_text(encoding="utf-8")
689
690 file_regression.check(out, extension=".md")
691
692
693 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
694 @pytest.mark.usefixtures("tmp_commitizen_project")
695 @pytest.mark.freeze_time("2021-06-11")
696 def test_changelog_incremental_with_release_candidate_version(
697 changelog_path: Path,
698 file_regression: FileRegressionFixture,
699 test_input: str,
700 util: UtilFixture,
701 ):
702 """Fix #357"""
703 with changelog_path.open("w", encoding="utf-8") as f:
704 f.write(KEEP_A_CHANGELOG)
705 util.create_file_and_commit("irrelevant commit")
706 util.create_tag("1.0.0", annotated=True)
707
708 util.create_file_and_commit("feat: add new output")
709 util.create_file_and_commit("fix: output glitch")
710
711 util.run_cli("bump", "--changelog", "--prerelease", test_input, "--yes")
712
713 util.create_file_and_commit("fix: mama gotta work")
714 util.create_file_and_commit("feat: add more stuff")
715 util.create_file_and_commit("Merge into master")
716
717 util.run_cli("changelog", "--incremental")
718
719 out = changelog_path.read_text(encoding="utf-8")
720
721 file_regression.check(out, extension=".md")
722
723
724 @pytest.mark.parametrize(
725 ("from_pre", "to_pre"), itertools.product(["alpha", "beta", "rc"], repeat=2)
726 )
727 @pytest.mark.usefixtures("tmp_commitizen_project")
728 @pytest.mark.freeze_time("2021-06-11")
729 def test_changelog_incremental_with_prerelease_version_to_prerelease_version(
730 changelog_path: Path,
731 file_regression: FileRegressionFixture,
732 from_pre: str,
733 to_pre: str,
734 util: UtilFixture,
735 ):
736 with changelog_path.open("w") as f:
737 f.write(KEEP_A_CHANGELOG)
738 util.create_file_and_commit("irrelevant commit")
739 util.create_tag("1.0.0", annotated=True)
740
741 util.create_file_and_commit("feat: add new output")
742 util.create_file_and_commit("fix: output glitch")
743
744 util.run_cli("bump", "--changelog", "--prerelease", from_pre, "--yes")
745
746 util.run_cli("bump", "--changelog", "--prerelease", to_pre, "--yes")
747
748 out = changelog_path.read_text()
749
750 file_regression.check(out, extension=".md")
751
752
753 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
754 @pytest.mark.usefixtures("tmp_commitizen_project")
755 @pytest.mark.freeze_time("2025-12-29")
756 def test_changelog_release_candidate_version_with_merge_prerelease(
757 changelog_path: Path,
758 file_regression: FileRegressionFixture,
759 test_input: str,
760 util: UtilFixture,
761 ):
762 """Fix #357"""
763 with changelog_path.open("w") as f:
764 f.write(KEEP_A_CHANGELOG)
765 util.create_file_and_commit("irrelevant commit")
766 util.create_tag("1.0.0")
767
768 util.create_file_and_commit("feat: add new output")
769 util.create_file_and_commit("fix: output glitch")
770
771 util.run_cli("bump", "--prerelease", test_input, "--yes")
772
773 util.create_file_and_commit("fix: mama gotta work")
774 util.create_file_and_commit("feat: add more stuff")
775 util.create_file_and_commit("Merge into master")
776
777 util.run_cli("changelog", "--merge-prerelease")
778
779 out = changelog_path.read_text()
780
781 file_regression.check(out, extension=".md")
782
783
784 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
785 @pytest.mark.usefixtures("tmp_commitizen_project")
786 @pytest.mark.freeze_time("2023-04-16")
787 def test_changelog_incremental_with_merge_prerelease(
788 changelog_path: Path,
789 file_regression: FileRegressionFixture,
790 test_input: str,
791 util: UtilFixture,
792 ):
793 """Fix #357"""
794 with changelog_path.open("w") as f:
795 f.write(KEEP_A_CHANGELOG)
796 util.create_file_and_commit("irrelevant commit")
797 util.create_tag("1.0.0")
798
799 util.create_file_and_commit("feat: add new output")
800
801 util.run_cli("bump", "--prerelease", test_input, "--yes", "--changelog")
802
803 util.create_file_and_commit("fix: output glitch")
804
805 util.run_cli("bump", "--prerelease", test_input, "--yes")
806
807 util.create_file_and_commit("fix: mama gotta work")
808 util.create_file_and_commit("feat: add more stuff")
809 util.create_file_and_commit("Merge into master")
810
811 util.run_cli("changelog", "--merge-prerelease", "--incremental")
812
813 out = changelog_path.read_text()
814
815 file_regression.check(out, extension=".md")
816
817
818 @pytest.mark.usefixtures("tmp_commitizen_project")
819 def test_changelog_with_filename_as_empty_string(config_path: Path, util: UtilFixture):
820 with config_path.open("a", encoding="utf-8") as f:
821 f.write("changelog_file = true\n")
822
823 util.create_file_and_commit("feat: add new output")
824
825 with pytest.raises(NotAllowed):
826 util.run_cli("changelog")
827
828
829 @pytest.mark.usefixtures("tmp_commitizen_project")
830 @pytest.mark.freeze_time("2022-02-13")
831 def test_changelog_from_rev_first_version_from_arg(
832 config_path: Path,
833 changelog_path: Path,
834 file_regression: FileRegressionFixture,
835 util: UtilFixture,
836 ):
837 with config_path.open("a", encoding="utf-8") as f:
838 f.write('tag_format = "$version"\n')
839
840 # create commit and tag
841 util.create_file_and_commit("feat: new file")
842 util.run_cli("bump", "--yes")
843
844 util.create_file_and_commit("feat: after 0.2.0")
845 util.create_file_and_commit("feat: another feature")
846
847 util.run_cli("bump", "--yes")
848
849 util.run_cli("changelog", "0.2.0")
850 out = changelog_path.read_text(encoding="utf-8")
851
852 file_regression.check(out, extension=".md")
853
854
855 @pytest.mark.usefixtures("tmp_commitizen_project")
856 @pytest.mark.freeze_time("2022-02-13")
857 def test_changelog_from_rev_latest_version_from_arg(
858 config_path: Path,
859 changelog_path: Path,
860 file_regression: FileRegressionFixture,
861 util: UtilFixture,
862 ):
863 with config_path.open("a", encoding="utf-8") as f:
864 f.write('tag_format = "$version"\n')
865
866 # create commit and tag
867 util.create_file_and_commit("feat: new file")
868 util.run_cli("bump", "--yes")
869
870 util.create_file_and_commit("feat: after 0.2.0")
871 util.create_file_and_commit("feat: another feature")
872
873 util.run_cli("bump", "--yes")
874
875 util.run_cli("changelog", "0.3.0")
876
877 out = changelog_path.read_text()
878
879 file_regression.check(out, extension=".md")
880
881
882 @pytest.mark.usefixtures("tmp_commitizen_project")
883 @pytest.mark.parametrize(
884 ("rev_range", "tag"),
885 [
886 pytest.param("0.8.0", "0.2.0", id="single-not-found"),
887 pytest.param("0.1.0..0.3.0", "0.3.0", id="lower-bound-not-found"),
888 pytest.param("0.1.0..0.3.0", "0.1.0", id="upper-bound-not-found"),
889 pytest.param("0.3.0..0.4.0", "0.2.0", id="none-found"),
890 ],
891 )
892 def test_changelog_from_rev_range_not_found(
893 config_path: Path, rev_range: str, tag: str, util: UtilFixture
894 ):
895 """Provides an invalid revision ID to changelog command"""
896 with config_path.open("a", encoding="utf-8") as f:
897 f.write('tag_format = "$version"\n')
898
899 # create commit and tag
900 util.create_file_and_commit("feat: new file")
901 util.create_tag(tag)
902 util.create_file_and_commit("feat: new file")
903 util.create_tag("1.0.0")
904
905 with pytest.raises(NoCommitsFoundError, match="Could not find a valid revision"):
906 util.run_cli("changelog", rev_range) # it shouldn't exist
907
908
909 @pytest.mark.usefixtures("tmp_commitizen_project")
910 def test_changelog_multiple_matching_tags(
911 config_path: Path, changelog_path: Path, util: UtilFixture
912 ):
913 with config_path.open("a", encoding="utf-8") as f:
914 f.write('tag_format = "new-$version"\nlegacy_tag_formats = ["legacy-$version"]')
915
916 util.create_file_and_commit("feat: new file")
917 util.create_tag("legacy-1.0.0")
918 util.create_file_and_commit("feat: new file")
919 util.create_tag("legacy-2.0.0")
920 util.create_tag("new-2.0.0")
921
922 with pytest.warns() as warnings:
923 util.run_cli("changelog", "1.0.0..2.0.0") # it shouldn't exist
924
925 assert len(warnings) == 1
926 warning = warnings[0]
927 assert "Multiple tags found for version 2.0.0" in str(warning.message)
928
929 out = changelog_path.read_text()
930
931 # Ensure only one tag is rendered
932 assert out.count("2.0.0") == 1
933
934
935 @pytest.mark.usefixtures("tmp_commitizen_project")
936 def test_changelog_from_rev_range_default_tag_format(
937 changelog_path: Path, util: UtilFixture
938 ):
939 """Checks that rev_range is calculated with the default (None) tag format"""
940 # create commit and tag
941 util.create_file_and_commit("feat: new file")
942 util.run_cli("bump", "--yes")
943
944 util.create_file_and_commit("feat: after 0.2.0")
945 util.create_file_and_commit("feat: another feature")
946
947 util.run_cli("bump", "--yes")
948
949 util.run_cli("changelog", "0.3.0")
950
951 out = changelog_path.read_text()
952
953 assert "new file" not in out
954
955
956 @pytest.mark.usefixtures("tmp_commitizen_project")
957 @pytest.mark.freeze_time("2022-02-13")
958 def test_changelog_from_rev_version_range_including_first_tag(
959 config_path: Path,
960 changelog_path: Path,
961 file_regression: FileRegressionFixture,
962 util: UtilFixture,
963 ):
964 with config_path.open("a", encoding="utf-8") as f:
965 f.write('tag_format = "$version"\n')
966
967 # create commit and tag
968 util.create_file_and_commit("feat: new file")
969 util.run_cli("bump", "--yes")
970
971 util.create_file_and_commit("feat: after 0.2.0")
972 util.create_file_and_commit("feat: another feature")
973
974 util.run_cli("bump", "--yes")
975
976 util.run_cli("changelog", "0.2.0..0.3.0")
977 out = changelog_path.read_text(encoding="utf-8")
978
979 file_regression.check(out, extension=".md")
980
981
982 @pytest.mark.usefixtures("tmp_commitizen_project")
983 @pytest.mark.freeze_time("2022-02-13")
984 def test_changelog_from_rev_version_range_from_arg(
985 config_path: Path,
986 changelog_path: Path,
987 file_regression: FileRegressionFixture,
988 util: UtilFixture,
989 ):
990 with config_path.open("a", encoding="utf-8") as f:
991 f.write('tag_format = "$version"\n')
992
993 # create commit and tag
994 util.create_file_and_commit("feat: new file")
995 util.run_cli("bump", "--yes")
996 util.create_file_and_commit("feat: after 0.2.0")
997 util.create_file_and_commit("feat: another feature")
998
999 util.run_cli("bump", "--yes")
1000
1001 util.create_file_and_commit("feat: getting ready for this")
1002
1003 util.run_cli("bump", "--yes")
1004
1005 util.run_cli("changelog", "0.3.0..0.4.0")
1006 out = changelog_path.read_text()
1007
1008 file_regression.check(out, extension=".md")
1009
1010
1011 @pytest.mark.usefixtures("tmp_commitizen_project")
1012 @pytest.mark.freeze_time("2022-02-13")
1013 def test_changelog_from_rev_version_range_with_legacy_tags(
1014 config_path: Path,
1015 changelog_path: Path,
1016 file_regression: FileRegressionFixture,
1017 util: UtilFixture,
1018 ):
1019 Path(config_path).write_text(
1020 "\n".join(
1021 [
1022 "[tool.commitizen]",
1023 'version_provider = "scm"',
1024 'tag_format = "v$version"',
1025 "legacy_tag_formats = [",
1026 ' "legacy-${version}",',
1027 ' "old-${version}",',
1028 "]",
1029 ]
1030 ),
1031 )
1032
1033 util.create_file_and_commit("feat: new file")
1034 util.create_tag("old-0.2.0")
1035 util.create_file_and_commit("feat: new file")
1036 util.create_tag("legacy-0.3.0")
1037 util.create_file_and_commit("feat: new file")
1038 util.create_tag("legacy-0.4.0")
1039
1040 util.run_cli("changelog", "0.2.0..0.4.0")
1041 file_regression.check(Path(changelog_path).read_text(), extension=".md")
1042
1043
1044 @pytest.mark.usefixtures("tmp_commitizen_project")
1045 @pytest.mark.freeze_time("2022-02-13")
1046 def test_changelog_from_rev_version_with_big_range_from_arg(
1047 config_path, changelog_path, file_regression, util: UtilFixture
1048 ):
1049 with config_path.open("a", encoding="utf-8") as f:
1050 f.write('tag_format = "$version"\n')
1051
1052 # create commit and tag
1053 util.create_file_and_commit("feat: new file")
1054
1055 util.run_cli("bump", "--yes")
1056
1057 util.create_file_and_commit("feat: after 0.2.0")
1058 util.create_file_and_commit("feat: another feature")
1059
1060 util.run_cli("bump", "--yes") # 0.3.0
1061 util.create_file_and_commit("feat: getting ready for this")
1062
1063 util.run_cli("bump", "--yes") # 0.4.0
1064 util.create_file_and_commit("fix: small error")
1065
1066 util.run_cli("bump", "--yes") # 0.4.1
1067 util.create_file_and_commit("feat: new shinny feature")
1068
1069 util.run_cli("bump", "--yes") # 0.5.0
1070 util.create_file_and_commit("feat: amazing different shinny feature")
1071
1072 util.run_cli("bump", "--yes") # 0.6.0
1073
1074 util.run_cli("changelog", "0.3.0..0.5.0")
1075 out = changelog_path.read_text()
1076
1077 file_regression.check(out, extension=".md")
1078
1079
1080 @pytest.mark.usefixtures("tmp_commitizen_project")
1081 @pytest.mark.freeze_time("2022-02-13")
1082 def test_changelog_from_rev_latest_version_dry_run(
1083 capsys: pytest.CaptureFixture,
1084 config_path: Path,
1085 file_regression: FileRegressionFixture,
1086 util: UtilFixture,
1087 ):
1088 with config_path.open("a") as f:
1089 f.write('tag_format = "$version"\n')
1090
1091 # create commit and tag
1092 util.create_file_and_commit("feat: new file")
1093 util.run_cli("bump", "--yes")
1094
1095 util.create_file_and_commit("feat: after 0.2.0")
1096 util.create_file_and_commit("feat: another feature")
1097
1098 util.run_cli("bump", "--yes")
1099 capsys.readouterr()
1100
1101 with pytest.raises(DryRunExit):
1102 util.run_cli("changelog", "0.3.0", "--dry-run")
1103
1104 out, _ = capsys.readouterr()
1105
1106 file_regression.check(out, extension=".md")
1107
1108
1109 @pytest.mark.usefixtures("tmp_commitizen_project")
1110 def test_invalid_subject_is_skipped(
1111 capsys: pytest.CaptureFixture,
1112 file_regression: FileRegressionFixture,
1113 util: UtilFixture,
1114 ):
1115 """Fix #510"""
1116 non_conformant_commit_title = (
1117 "Merge pull request #487 from manang/master\n\n"
1118 "feat: skip merge messages that start with Pull request\n"
1119 )
1120 util.create_file_and_commit(non_conformant_commit_title)
1121 util.create_file_and_commit("feat: a new world")
1122 with pytest.raises(DryRunExit):
1123 util.run_cli("changelog", "--dry-run")
1124 out, _ = capsys.readouterr()
1125
1126 file_regression.check(out, extension=".md")
1127
1128
1129 @pytest.mark.usefixtures("tmp_commitizen_project")
1130 @pytest.mark.freeze_time("2022-02-13")
1131 def test_changelog_with_customized_change_type_order(
1132 config_path: Path,
1133 changelog_path: Path,
1134 file_regression: FileRegressionFixture,
1135 util: UtilFixture,
1136 ):
1137 with config_path.open("a") as f:
1138 f.write('tag_format = "$version"\n')
1139 f.write(
1140 'change_type_order = ["BREAKING CHANGE", "Perf", "Fix", "Feat", "Refactor"]\n'
1141 )
1142
1143 # create commit and tag
1144 util.create_file_and_commit("feat: new file")
1145 util.run_cli("bump", "--yes")
1146 util.create_file_and_commit("feat: after 0.2.0")
1147 util.create_file_and_commit("feat: another feature")
1148 util.create_file_and_commit("fix: fix bug")
1149
1150 util.run_cli("bump", "--yes")
1151
1152 util.create_file_and_commit("feat: getting ready for this")
1153 util.create_file_and_commit("perf: perf improvement")
1154
1155 util.run_cli("bump", "--yes")
1156
1157 util.run_cli("changelog", "0.3.0..0.4.0")
1158 out = changelog_path.read_text()
1159
1160 file_regression.check(out, extension=".md")
1161
1162
1163 @pytest.mark.usefixtures("tmp_commitizen_project")
1164 def test_empty_commit_list(mocker: MockFixture, util: UtilFixture):
1165 util.create_file_and_commit("feat: a new world")
1166
1167 # test changelog properly handles when no commits are found for the revision
1168 mocker.patch("commitizen.git.get_commits", return_value=[])
1169 with pytest.raises(NoCommitsFoundError):
1170 util.run_cli("changelog")
1171
1172
1173 @pytest.mark.usefixtures("tmp_commitizen_project")
1174 @pytest.mark.freeze_time("2022-02-13")
1175 def test_changelog_prerelease_rev_with_use_scheme_semver(
1176 capsys: pytest.CaptureFixture,
1177 config_path: Path,
1178 file_regression: FileRegressionFixture,
1179 util: UtilFixture,
1180 ):
1181 with config_path.open("a") as f:
1182 f.write('tag_format = "$version"\nversion_scheme = "semver"')
1183
1184 # create commit and tag
1185 util.create_file_and_commit("feat: new file")
1186 util.run_cli("bump", "--yes")
1187
1188 util.create_file_and_commit("feat: after 0.2.0")
1189 util.create_file_and_commit("feat: another feature")
1190
1191 util.run_cli("bump", "--yes", "--prerelease", "alpha")
1192 capsys.readouterr()
1193
1194 assert git.tag_exist("0.3.0-a0")
1195
1196 with pytest.raises(DryRunExit):
1197 util.run_cli("changelog", "0.3.0-a0", "--dry-run")
1198
1199 out, _ = capsys.readouterr()
1200 file_regression.check(out, extension=".md")
1201
1202 util.run_cli("bump", "--yes", "--prerelease", "alpha")
1203 capsys.readouterr()
1204
1205 assert git.tag_exist("0.3.0-a1")
1206
1207 with pytest.raises(DryRunExit):
1208 util.run_cli("changelog", "0.3.0-a1", "--dry-run")
1209
1210 out, _ = capsys.readouterr()
1211 file_regression.check(out, extension=".second-prerelease.md")
1212
1213
1214 @pytest.mark.usefixtures("tmp_commitizen_project")
1215 def test_changelog_uses_version_tags_for_header(
1216 mocker: MockFixture, config: BaseConfig, util: UtilFixture
1217 ):
1218 """Tests that changelog headers always use version tags even if there are non-version tags
1219
1220 This tests a scenario fixed in this commit:
1221 The first header was using a non-version tag and outputting "## 0-not-a-version" instead of "## 1.0.0
1222 """
1223 util.create_file_and_commit("feat: commit in 1.0.0")
1224 util.create_tag("0-not-a-version")
1225 util.create_tag("1.0.0")
1226 util.create_tag("also-not-a-version")
1227
1228 write_patch = mocker.patch("commitizen.commands.changelog.out.write")
1229
1230 changelog = Changelog(
1231 config, {"dry_run": True, "incremental": True, "unreleased_version": None}
1232 )
1233
1234 with pytest.raises(DryRunExit):
1235 changelog()
1236
1237 changelog_output = write_patch.call_args[0][0]
1238
1239 assert changelog_output.startswith("## 1.0.0")
1240 assert "0-no-a-version" not in changelog_output
1241 assert "also-not-a-version" not in changelog_output
1242
1243
1244 @pytest.mark.usefixtures("tmp_commitizen_project")
1245 @pytest.mark.freeze_time("2022-02-13")
1246 def test_changelog_from_current_version_tag_with_nonversion_tag(
1247 mocker: MockFixture, config: BaseConfig, util: UtilFixture
1248 ):
1249 """Tests that changelog generation for a single version works even if
1250 there is a non-version tag in the list of tags
1251
1252 This tests a scenario which is fixed in this commit:
1253 You have a commit in between two versions (1.0.0..2.0.0) which is tagged with a non-version tag (not-a-version).
1254 In this case commitizen should disregard the non-version tag when determining the rev-range & generating the changelog.
1255 """
1256 util.create_file_and_commit("feat: initial commit")
1257 util.create_tag("1.0.0")
1258
1259 util.create_file_and_commit("feat: commit 1")
1260 util.create_tag("1-not-a-version")
1261
1262 util.create_file_and_commit("feat: commit 2")
1263
1264 util.create_file_and_commit("bump: version 1.0.0 → 2.0.0")
1265 util.create_tag("2.0.0")
1266
1267 write_patch = mocker.patch("commitizen.commands.changelog.out.write")
1268
1269 with pytest.raises(DryRunExit):
1270 Changelog(
1271 config,
1272 {
1273 "dry_run": True,
1274 "incremental": False,
1275 "unreleased_version": None,
1276 "rev_range": "2.0.0",
1277 },
1278 )()
1279
1280 write_patch.assert_called_with(
1281 "\
1282 ## 2.0.0 (2022-02-13)\n\n\
1283 ### Feat\n\n\
1284 - commit 2\n\
1285 - commit 1\n"
1286 )
1287
1288
1289 @pytest.mark.parametrize(
1290 ("arg", "cfg", "expected"),
1291 [
1292 pytest.param("", "", "default", id="default"),
1293 pytest.param("", "changelog.cfg", "from config", id="from-config"),
1294 pytest.param(
1295 "--template=changelog.cmd", "changelog.cfg", "from cmd", id="from-command"
1296 ),
1297 ],
1298 )
1299 def test_changelog_template_option_precedence(
1300 tmp_commitizen_project: Path,
1301 arg: str,
1302 cfg: str,
1303 expected: str,
1304 util: UtilFixture,
1305 changelog_file: Path,
1306 changelog_tpl: Path,
1307 ):
1308 project_root = tmp_commitizen_project
1309 cfg_template = project_root / "changelog.cfg"
1310 cmd_template = project_root / "changelog.cmd"
1311
1312 cfg_template.write_text("from config")
1313 cmd_template.write_text("from cmd")
1314 changelog_tpl.write_text("default")
1315
1316 util.create_file_and_commit("feat: new file")
1317
1318 if cfg:
1319 pyproject = project_root / "pyproject.toml"
1320 pyproject.write_text(
1321 dedent(
1322 f"""\
1323 [tool.commitizen]
1324 version = "0.1.0"
1325 template = "{cfg}"
1326 """
1327 )
1328 )
1329
1330 testargs = ["changelog"]
1331 if arg:
1332 testargs.append(arg)
1333 util.run_cli(*testargs)
1334
1335 assert changelog_file.read_text() == expected
1336
1337
1338 def test_changelog_template_extras_precedence(
1339 changelog_tpl: Path,
1340 mock_plugin: BaseCommitizen,
1341 pyproject: Path,
1342 changelog_file: Path,
1343 util: UtilFixture,
1344 ):
1345 changelog_tpl.write_text("{{first}} - {{second}} - {{third}}")
1346
1347 mock_plugin.template_extras = dict(
1348 first="from-plugin", second="from-plugin", third="from-plugin"
1349 )
1350
1351 pyproject.write_text(
1352 dedent(
1353 """\
1354 [tool.commitizen]
1355 version = "0.1.0"
1356 [tool.commitizen.extras]
1357 first = "from-config"
1358 second = "from-config"
1359 """
1360 )
1361 )
1362
1363 util.create_file_and_commit("feat: new file")
1364 util.run_cli("changelog", "--extra", "first=from-command")
1365
1366 assert changelog_file.read_text() == "from-command - from-config - from-plugin"
1367
1368
1369 @pytest.mark.usefixtures("tmp_commitizen_project")
1370 @pytest.mark.freeze_time("2021-06-11")
1371 def test_changelog_only_tag_matching_tag_format_included_prefix(
1372 changelog_path: Path,
1373 config_path: Path,
1374 util: UtilFixture,
1375 ):
1376 with config_path.open("a", encoding="utf-8") as f:
1377 f.write('\ntag_format = "custom${version}"\n')
1378 util.create_file_and_commit("feat: new file")
1379 util.create_tag("v0.2.0")
1380 util.create_file_and_commit("feat: another new file")
1381 util.create_tag("0.2.0")
1382 util.create_tag("random0.2.0")
1383 util.run_cli("bump", "--changelog", "--yes")
1384 util.create_file_and_commit("feat: another new file")
1385 util.run_cli("bump", "--changelog", "--yes")
1386 out = changelog_path.read_text()
1387 assert out.startswith("## custom0.3.0 (2021-06-11)")
1388 assert "## v0.2.0 (2021-06-11)" not in out
1389 assert "## 0.2.0 (2021-06-11)" not in out
1390
1391
1392 @pytest.mark.usefixtures("tmp_commitizen_project")
1393 def test_changelog_only_tag_matching_tag_format_included_prefix_sep(
1394 changelog_path: Path,
1395 config_path: Path,
1396 util: UtilFixture,
1397 ):
1398 with config_path.open("a", encoding="utf-8") as f:
1399 f.write('\ntag_format = "custom-${version}"\n')
1400 util.create_file_and_commit("feat: new file")
1401 util.create_tag("v0.2.0")
1402 util.create_file_and_commit("feat: another new file")
1403 util.create_tag("0.2.0")
1404 util.create_tag("random0.2.0")
1405 util.run_cli("bump", "--changelog", "--yes")
1406 util.create_file_and_commit("feat: new version another new file")
1407 util.create_file_and_commit("feat: new version some new file")
1408 util.run_cli("bump", "--changelog")
1409 out = changelog_path.read_text()
1410 assert out.startswith("## custom-0.3.0")
1411 assert "## v0.2.0" not in out
1412 assert "## 0.2.0" not in out
1413
1414
1415 @pytest.mark.usefixtures("tmp_commitizen_project")
1416 @pytest.mark.freeze_time("2021-06-11")
1417 def test_changelog_only_tag_matching_tag_format_included_suffix(
1418 changelog_path: Path,
1419 config_path: Path,
1420 util: UtilFixture,
1421 ):
1422 with config_path.open("a", encoding="utf-8") as f:
1423 f.write('\ntag_format = "${version}custom"\n')
1424 util.create_file_and_commit("feat: new file")
1425 util.create_tag("v0.2.0")
1426 util.create_file_and_commit("feat: another new file")
1427 util.create_tag("0.2.0")
1428 util.create_tag("random0.2.0")
1429 # bump to 0.2.0custom
1430 util.run_cli("bump", "--changelog", "--yes")
1431
1432 util.create_file_and_commit("feat: another new file")
1433 # bump to 0.3.0custom
1434 util.run_cli("bump", "--changelog", "--yes")
1435 out = changelog_path.read_text()
1436 assert out.startswith("## 0.3.0custom (2021-06-11)")
1437 assert "## v0.2.0 (2021-06-11)" not in out
1438 assert "## 0.2.0 (2021-06-11)" not in out
1439
1440
1441 @pytest.mark.usefixtures("tmp_commitizen_project")
1442 @pytest.mark.freeze_time("2021-06-11")
1443 def test_changelog_only_tag_matching_tag_format_included_suffix_sep(
1444 changelog_path: Path,
1445 config_path: Path,
1446 util: UtilFixture,
1447 ):
1448 with config_path.open("a", encoding="utf-8") as f:
1449 f.write('\ntag_format = "${version}-custom"\n')
1450 util.create_file_and_commit("feat: new file")
1451 util.create_tag("v0.2.0")
1452 util.create_file_and_commit("feat: another new file")
1453 util.create_tag("0.2.0")
1454 util.create_tag("random0.2.0")
1455 util.run_cli("bump", "--changelog", "--yes")
1456 util.create_file_and_commit("feat: another new file")
1457 util.run_cli("bump", "--changelog", "--yes")
1458 out = changelog_path.read_text()
1459 assert out.startswith("## 0.3.0-custom (2021-06-11)")
1460 assert "## v0.2.0 (2021-06-11)" not in out
1461 assert "## 0.2.0 (2021-06-11)" not in out
1462
1463
1464 @pytest.mark.usefixtures("tmp_commitizen_project")
1465 def test_changelog_legacy_tags(
1466 changelog_path: Path,
1467 config_path: Path,
1468 util: UtilFixture,
1469 ):
1470 with config_path.open("a", encoding="utf-8") as f:
1471 f.writelines(
1472 [
1473 'tag_format = "v${version}"\n',
1474 "legacy_tag_formats = [\n",
1475 ' "older-${version}",\n',
1476 ' "oldest-${version}",\n',
1477 "]\n",
1478 ]
1479 )
1480 util.create_file_and_commit("feat: new file")
1481 util.create_tag("oldest-0.1.0")
1482 util.create_file_and_commit("feat: new file")
1483 util.create_tag("older-0.2.0")
1484 util.create_file_and_commit("feat: another new file")
1485 util.create_tag("v0.3.0")
1486 util.create_file_and_commit("feat: another new file")
1487 util.create_tag("not-0.3.1")
1488 util.run_cli("bump", "--changelog", "--yes")
1489 out = changelog_path.read_text()
1490 assert "## v0.3.0" in out
1491 assert "## older-0.2.0" in out
1492 assert "## oldest-0.1.0" in out
1493 assert "## v0.3.0" in out
1494 assert "## not-0.3.1" not in out
1495
1496
1497 @pytest.mark.usefixtures("tmp_commitizen_project")
1498 @pytest.mark.freeze_time("2024-11-18")
1499 def test_changelog_incremental_change_tag_format(
1500 changelog_path: Path,
1501 config_path: Path,
1502 file_regression: FileRegressionFixture,
1503 util: UtilFixture,
1504 ):
1505 util.freezer.move_to("2024-11-18")
1506 config = Path(config_path)
1507 base_config = config.read_text()
1508 config.write_text(
1509 "\n".join(
1510 (
1511 base_config,
1512 'tag_format = "older-${version}"',
1513 )
1514 )
1515 )
1516 util.create_file_and_commit("feat: new file")
1517 util.create_tag("older-0.1.0")
1518 util.create_file_and_commit("feat: new file")
1519 util.create_tag("older-0.2.0")
1520 util.run_cli("changelog")
1521
1522 config.write_text(
1523 "\n".join(
1524 (
1525 base_config,
1526 'tag_format = "v${version}"',
1527 'legacy_tag_formats = ["older-${version}"]',
1528 )
1529 )
1530 )
1531 util.create_file_and_commit("feat: another new file")
1532 util.create_tag("v0.3.0")
1533 util.run_cli("changelog", "--incremental")
1534 out = changelog_path.read_text()
1535 assert "## v0.3.0" in out
1536 assert "## older-0.2.0" in out
1537 assert "## older-0.1.0" in out
1538 file_regression.check(out, extension=".md")
1539
1540
1541 @pytest.mark.usefixtures("tmp_commitizen_project")
1542 def test_changelog_ignored_tags(
1543 changelog_path: Path,
1544 config_path: Path,
1545 capsys: pytest.CaptureFixture,
1546 util: UtilFixture,
1547 ):
1548 with config_path.open("a", encoding="utf-8") as f:
1549 f.writelines(
1550 [
1551 'tag_format = "v${version}"\n',
1552 "ignored_tag_formats = [\n",
1553 ' "ignored",\n',
1554 ' "ignore-${version}",\n',
1555 "]\n",
1556 ]
1557 )
1558 util.create_file_and_commit("feat: new file")
1559 util.create_tag("ignore-0.1.0")
1560 util.create_file_and_commit("feat: new file")
1561 util.create_tag("ignored")
1562 util.create_file_and_commit("feat: another new file")
1563 util.create_tag("v0.3.0")
1564 util.create_file_and_commit("feat: another new file")
1565 util.create_tag("not-ignored")
1566 util.run_cli("bump", "--changelog", "--yes")
1567 out = changelog_path.read_text()
1568 assert "## ignore-0.1.0" not in out
1569 assert "## ignored" not in out
1570 assert "## not-ignored" not in out
1571 assert "## v0.3.0" in out
1572
1573 _, err = capsys.readouterr()
1574 assert "Invalid version tag: 'ignore-0.1.0'" not in err
1575 assert "Invalid version tag: 'ignored'" not in err
1576 assert "Invalid version tag: 'not-ignored'" in err
1577 assert "Invalid version tag: 'v0.3.0'" not in err
1578
1579
1580 def test_changelog_template_extra_quotes(
1581 changelog_tpl: Path,
1582 changelog_file: Path,
1583 util: UtilFixture,
1584 ):
1585 changelog_tpl.write_text("{{first}} - {{second}} - {{third}}")
1586 util.create_file_and_commit("feat: new file")
1587 util.run_cli(
1588 "changelog",
1589 "-e",
1590 "first=no-quote",
1591 "-e",
1592 "second='single quotes'",
1593 "-e",
1594 'third="double quotes"',
1595 )
1596
1597 assert changelog_file.read_text() == "no-quote - single quotes - double quotes"
1598
1599
1600 @pytest.mark.parametrize(
1601 ("extra", "expected"),
1602 [
1603 pytest.param("key=value=", "value=", id="2-equals"),
1604 pytest.param("key==value", "=value", id="2-consecutive-equals"),
1605 pytest.param("key==value==", "=value==", id="multiple-equals"),
1606 ],
1607 )
1608 def test_changelog_template_extra_weird_but_valid(
1609 changelog_tpl: Path,
1610 changelog_file: Path,
1611 extra: str,
1612 expected: str,
1613 util: UtilFixture,
1614 ):
1615 changelog_tpl.write_text("{{key}}")
1616 util.create_file_and_commit("feat: new file")
1617 util.run_cli("changelog", "-e", extra)
1618
1619 assert changelog_file.read_text() == expected
1620
1621
1622 @pytest.mark.parametrize("extra", ["no-equal", "", "=no-key"])
1623 def test_changelog_template_extra_bad_format(
1624 changelog_tpl: Path,
1625 extra: str,
1626 util: UtilFixture,
1627 ):
1628 changelog_tpl.write_text("")
1629 util.create_file_and_commit("feat: new file")
1630 with pytest.raises(InvalidCommandArgumentError):
1631 util.run_cli("changelog", "-e", extra)
1632
1633
1634 def test_export_changelog_template_from_default(
1635 any_changelog_format: ChangelogFormat,
1636 util: UtilFixture,
1637 changelog_jinja_file: Path,
1638 repo_root: Path,
1639 ):
1640 src = repo_root / "commitizen" / "templates" / any_changelog_format.template
1641
1642 util.run_cli("changelog", "--export-template", str(changelog_jinja_file))
1643
1644 assert changelog_jinja_file.exists()
1645 assert changelog_jinja_file.read_text() == src.read_text()
1646
1647
1648 def test_export_changelog_template_from_plugin(
1649 changelog_jinja_file: Path,
1650 mock_plugin: BaseCommitizen,
1651 changelog_format: ChangelogFormat,
1652 tmp_path: Path,
1653 util: UtilFixture,
1654 ):
1655 src = tmp_path / changelog_format.template
1656 tpl = "I am a custom template"
1657 src.write_text(tpl)
1658 mock_plugin.template_loader = FileSystemLoader(tmp_path)
1659
1660 util.run_cli("changelog", "--export-template", str(changelog_jinja_file))
1661
1662 assert changelog_jinja_file.exists()
1663 assert changelog_jinja_file.read_text() == tpl
1664
1665
1666 def test_export_changelog_template_fails_when_template_has_no_filename(
1667 mocker: MockFixture,
1668 changelog_jinja_file: Path,
1669 util: UtilFixture,
1670 ):
1671 # Mock a template object with no filename
1672 class FakeTemplate:
1673 filename = None
1674
1675 # Patch get_changelog_template to return a template without a filename
1676 mocker.patch(
1677 "commitizen.changelog.get_changelog_template", return_value=FakeTemplate()
1678 )
1679
1680 with pytest.raises(NotAllowed) as exc_info:
1681 util.run_cli("changelog", "--export-template", str(changelog_jinja_file))
1682
1683 assert not changelog_jinja_file.exists()
1684 assert "Template filename is not set" in str(exc_info.value)
1685
1686
1687 def test_changelog_template_incremental_variable(
1688 tmp_commitizen_project: Path,
1689 any_changelog_format: ChangelogFormat,
1690 util: UtilFixture,
1691 file_regression: FileRegressionFixture,
1692 ):
1693 """
1694 Test that the changelog template is not rendered when the incremental flag is not set.
1695 Reference: https://github.com/commitizen-tools/commitizen/discussions/1620
1696 """
1697 project_root = tmp_commitizen_project
1698 changelog_tpl = project_root / any_changelog_format.template
1699 changelog_tpl.write_text(
1700 dedent("""
1701 {% if not incremental %}
1702 # CHANGELOG
1703 {% endif %}
1704
1705 {% for entry in tree %}
1706
1707 ## {{ entry.version }}{% if entry.date %} ({{ entry.date }}){% endif %}
1708
1709 {% for change_key, changes in entry.changes.items() %}
1710
1711 {% if change_key %}
1712 ### {{ change_key }}
1713 {% endif %}
1714
1715 {% for change in changes %}
1716 {% if change.scope %}
1717 - **{{ change.scope }}**: {{ change.message }}
1718 {% elif change.message %}
1719 - {{ change.message }}
1720 {% endif %}
1721 {% endfor %}
1722 {% endfor %}
1723 {% endfor %}
1724 """)
1725 )
1726 target = "CHANGELOG.md"
1727
1728 util.create_file_and_commit("feat(foo): new file")
1729 util.run_cli("changelog", "--file-name", target)
1730 out = Path(target).read_text(encoding="utf-8")
1731 file_regression.check(out, extension=".md")
1732
1733 util.create_file_and_commit("refactor(bar): another new file")
1734 util.run_cli("changelog", "--file-name", target, "--incremental")
1735 out = Path(target).read_text(encoding="utf-8")
1736 file_regression.check(out, extension=".incremental.md")