コード例 #1
0
ファイル: commit.py プロジェクト: modlin/commitizen
    def __call__(self):
        if git.is_staging_clean():
            out.write("No files added to staging!")
            raise SystemExit(NOTHING_TO_COMMIT)

        retry: bool = self.arguments.get("retry")

        if retry:
            m = self.read_backup_message()
        else:
            m = self.prompt_commit_questions()

        out.info(f"\n{m}\n")
        c = git.commit(m)

        if c.err:
            out.error(c.err)

            # Create commit backup
            with open(self.temp_file, "w") as f:
                f.write(m)

            raise SystemExit(COMMIT_ERROR)

        if "nothing added" in c.out or "no changes added to commit" in c.out:
            out.error(c.out)
        elif c.err:
            out.error(c.err)
        else:
            with contextlib.suppress(FileNotFoundError):
                os.remove(self.temp_file)
            out.write(c.out)
            out.success("Commit successful!")
コード例 #2
0
    def __call__(self):
        values_to_add = {}

        # No config for commitizen exist
        if not self.config.path:
            config_path = self._ask_config_path()

            if "toml" in config_path:
                self.config = TomlConfig(data="", path=config_path)
            else:
                self.config = IniConfig(data="", path=config_path)

            self.config.init_empty_config_content()

            values_to_add["name"] = self._ask_name()
            tag = self._ask_tag()
            values_to_add["version"] = Version(tag).public
            values_to_add["tag_format"] = self._ask_tag_format(tag)
            self._update_config_file(values_to_add)
            out.write(
                "You can bump the version and create cangelog running:\n")
            out.info("cz bump --changelog")
            out.success("The configuration are all set.")
        else:
            # TODO: handle the case that config file exist but no value
            out.line(f"Config file {self.config.path} already exists")
コード例 #3
0
    def __call__(self):
        values_to_add = {}

        # No config for commitizen exist
        if not self.config.path:
            config_path = self._ask_config_path()
            if "toml" in config_path:
                self.config = TomlConfig(data="", path=config_path)
            elif "json" in config_path:
                self.config = JsonConfig(data="{}", path=config_path)
            elif "yaml" in config_path:
                self.config = YAMLConfig(data="", path=config_path)

            self.config.init_empty_config_content()

            values_to_add["name"] = self._ask_name()
            tag = self._ask_tag()
            values_to_add["version"] = Version(tag).public
            values_to_add["tag_format"] = self._ask_tag_format(tag)
            self._update_config_file(values_to_add)

            if questionary.confirm(
                    "Do you want to install pre-commit hook?").ask():
                self._install_pre_commit_hook()

            out.write(
                "You can bump the version and create changelog running:\n")
            out.info("cz bump --changelog")
            out.success("The configuration are all set.")
        else:
            out.line(f"Config file {self.config.path} already exists")
コード例 #4
0
    def _update_config_file(self, values):
        if not values:
            out.write("The configuration were all set. Nothing to add.")
            raise SystemExit()

        for key, value in values.items():
            self.config.set_key(key, value)
コード例 #5
0
ファイル: changelog.py プロジェクト: kudlatyamroth/commitizen
    def __call__(self):
        commit_parser = self.cz.commit_parser
        changelog_pattern = self.cz.changelog_pattern
        start_rev = self.start_rev
        unreleased_version = self.unreleased_version
        changelog_meta: Dict = {}

        if not changelog_pattern or not commit_parser:
            out.error(
                f"'{self.config.settings['name']}' rule does not support changelog"
            )
            raise SystemExit(NO_PATTERN_MAP)

        tags = git.get_tags()
        if not tags:
            tags = []

        if self.incremental:
            changelog_meta = changelog.get_metadata(self.file_name)
            latest_version = changelog_meta.get("latest_version")
            if latest_version:
                start_rev = self._find_incremental_rev(latest_version, tags)

        commits = git.get_commits(start=start_rev, args="--author-date-order")
        if not commits:
            out.error("No commits found")
            raise SystemExit(NO_COMMITS_FOUND)

        tree = changelog.generate_tree_from_commits(commits, tags,
                                                    commit_parser,
                                                    changelog_pattern,
                                                    unreleased_version)
        changelog_out = changelog.render_changelog(tree)

        if self.dry_run:
            out.write(changelog_out)
            raise SystemExit(0)

        lines = []
        if self.incremental and os.path.isfile(self.file_name):
            with open(self.file_name, "r") as changelog_file:
                lines = changelog_file.readlines()

        with open(self.file_name, "w") as changelog_file:
            if self.incremental:
                new_lines = changelog.incremental_build(
                    changelog_out, lines, changelog_meta)
                changelog_file.writelines(new_lines)
            else:
                changelog_file.write(changelog_out)
コード例 #6
0
ファイル: init.py プロジェクト: zombig/commitizen
    def _install_pre_commit_hook(self):
        pre_commit_config_filename = ".pre-commit-config.yaml"
        cz_hook_config = {
            "repo": "https://github.com/commitizen-tools/commitizen",
            "rev": f"v{__version__}",
            "hooks": [{
                "id": "commitizen",
                "stages": ["commit-msg"]
            }],
        }

        config_data = {}
        if not os.path.isfile(pre_commit_config_filename):
            # .pre-commit-config does not exist
            config_data["repos"] = [cz_hook_config]
        else:
            # breakpoint()
            with open(pre_commit_config_filename) as config_file:
                yaml_data = yaml.safe_load(config_file)
                if yaml_data:
                    config_data = yaml_data

            if "repos" in config_data:
                for pre_commit_hook in config_data["repos"]:
                    if "commitizen" in pre_commit_hook["repo"]:
                        out.write("commitizen already in pre-commit config")
                        break
                else:
                    config_data["repos"].append(cz_hook_config)
            else:
                # .pre-commit-config exists but there's no "repos" key
                config_data["repos"] = [cz_hook_config]

        with open(pre_commit_config_filename, "w") as config_file:
            yaml.safe_dump(config_data, stream=config_file)

        c = cmd.run("pre-commit install --hook-type commit-msg")
        if c.return_code == 127:
            out.error(
                "pre-commit is not installed in current environement.\n"
                "Run 'pre-commit install --hook-type commit-msg' again after it's installed"
            )
        elif c.return_code != 0:
            out.error(c.err)
        else:
            out.write(
                "commitizen pre-commit hook is now installed in your '.git'\n")
コード例 #7
0
ファイル: commit.py プロジェクト: saygox/commitizen
    def __call__(self):
        dry_run: bool = self.arguments.get("dry_run")

        if git.is_staging_clean() and not dry_run:
            raise NothingToCommitError("No files added to staging!")

        retry: bool = self.arguments.get("retry")

        if retry:
            m = self.read_backup_message()
        else:
            m = self.prompt_commit_questions()

        out.info(f"\n{m}\n")

        if dry_run:
            raise DryRunExit()

        signoff: bool = self.arguments.get("signoff")

        if signoff:
            c = git.commit(m, "-s")
        else:
            c = git.commit(m)

        if c.return_code != 0:
            out.error(c.err)

            # Create commit backup
            with open(self.temp_file, "w") as f:
                f.write(m)

            raise CommitError()

        if "nothing added" in c.out or "no changes added to commit" in c.out:
            out.error(c.out)
        else:
            with contextlib.suppress(FileNotFoundError):
                os.remove(self.temp_file)
            out.write(c.err)
            out.write(c.out)
            out.success("Commit successful!")
コード例 #8
0
ファイル: commit.py プロジェクト: esciara/commitizen
    def __call__(self):
        cz = self.cz
        questions = cz.questions()
        answers = questionary.prompt(questions)
        if not answers:
            raise SystemExit(NO_ANSWERS)
        m = cz.message(answers)
        out.info(f"\n{m}\n")
        c = git.commit(m)

        if c.err:
            out.error(c.err)
            raise SystemExit(COMMIT_ERROR)

        if "nothing added" in c.out or "no changes added to commit" in c.out:
            out.error(c.out)
        elif c.err:
            out.error(c.err)
        else:
            out.write(c.out)
            out.success("Commit successful!")
コード例 #9
0
ファイル: init.py プロジェクト: AlexandrDragunkin/commitizen
    def __call__(self):
        values_to_add = {}

        # No config file exist
        if not self.config.path:
            config_path = self._ask_config_path()

            if "toml" in config_path:
                self.config = TomlConfig(data="", path=config_path)
            else:
                self.config = IniConfig(data="", path=config_path)

            self.config.init_empty_config_file()

            values_to_add["name"] = self._ask_name()
            tag = self._ask_tag()
            values_to_add["version"] = Version(tag).public
            values_to_add["tag_format"] = self._ask_tag_format(tag)
            self._update_config_file(values_to_add)
            out.write("The configuration are all set.")
        else:
            # TODO: handle the case that config file exist but no value
            out.line(f"Config file {self.config.path} already exists")
コード例 #10
0
 def __call__(self):
     if self.parameter.get("project"):
         version = self.config.settings["version"]
         if version:
             out.write(f"{version}")
         else:
             out.error(f"No project information in this project.")
     elif self.parameter.get("verbose"):
         out.write(f"Installed Commitizen Version: {__version__}")
         version = self.config.settings["version"]
         if version:
             out.write(f"Project Version: {version}")
         else:
             out.error(f"No project information in this project.")
     else:
         # if no argument is given, show installed commitizen version
         out.write(f"{__version__}")
コード例 #11
0
    def __call__(self):
        commit_parser = self.cz.commit_parser
        changelog_pattern = self.cz.changelog_pattern
        start_rev = self.start_rev
        unreleased_version = self.unreleased_version
        changelog_meta: Dict = {}
        change_type_map: Optional[Dict] = self.change_type_map
        changelog_message_builder_hook: Optional[
            Callable
        ] = self.cz.changelog_message_builder_hook

        if not changelog_pattern or not commit_parser:
            raise NoPatternMapError(
                f"'{self.config.settings['name']}' rule does not support changelog"
            )

        if self.incremental and self.rev_range:
            raise NotAllowed("--incremental cannot be combined with a rev_range")

        tags = git.get_tags()
        if not tags:
            tags = []

        end_rev = ""

        if self.incremental:
            changelog_meta = changelog.get_metadata(self.file_name)
            latest_version = changelog_meta.get("latest_version")
            if latest_version:
                start_rev = self._find_incremental_rev(latest_version, tags)

        if self.rev_range and self.tag_format:
            start_rev, end_rev = changelog.get_oldest_and_newest_rev(
                tags,
                version=self.rev_range,
                tag_format=self.tag_format,
            )

        commits = git.get_commits(
            start=start_rev, end=end_rev, args="--author-date-order"
        )
        if not commits:
            raise NoCommitsFoundError("No commits found")

        tree = changelog.generate_tree_from_commits(
            commits,
            tags,
            commit_parser,
            changelog_pattern,
            unreleased_version,
            change_type_map=change_type_map,
            changelog_message_builder_hook=changelog_message_builder_hook,
        )
        if self.change_type_order:
            tree = changelog.order_changelog_tree(tree, self.change_type_order)
        changelog_out = changelog.render_changelog(tree)
        changelog_out = changelog_out.lstrip("\n")

        if self.dry_run:
            out.write(changelog_out)
            raise DryRunExit()

        lines = []
        if self.incremental and os.path.isfile(self.file_name):
            with open(self.file_name, "r") as changelog_file:
                lines = changelog_file.readlines()

        self.write_changelog(changelog_out, lines, changelog_meta)
コード例 #12
0
ファイル: bump.py プロジェクト: multimac/commitizen
    def __call__(self):  # noqa: C901
        """Steps executed to bump."""
        try:
            current_version_instance: Version = Version(self.bump_settings["version"])
        except TypeError:
            out.error(
                "[NO_VERSION_SPECIFIED]\n"
                "Check if current version is specified in config file, like:\n"
                "version = 0.4.3\n"
            )
            raise SystemExit(NO_VERSION_SPECIFIED)

        # Initialize values from sources (conf)
        current_version: str = self.config.settings["version"]

        tag_format: str = self.bump_settings["tag_format"]
        bump_commit_message: str = self.bump_settings["bump_message"]
        version_files: List[str] = self.bump_settings["version_files"]

        dry_run: bool = self.arguments["dry_run"]
        is_yes: bool = self.arguments["yes"]
        increment: Optional[str] = self.arguments["increment"]
        prerelease: str = self.arguments["prerelease"]
        is_files_only: Optional[bool] = self.arguments["files_only"]

        current_tag_version: str = bump.create_tag(
            current_version, tag_format=tag_format
        )

        is_initial = self.is_initial_tag(current_tag_version, is_yes)
        if is_initial:
            commits = git.get_commits()
        else:
            commits = git.get_commits(current_tag_version)

        # No commits, there is no need to create an empty tag.
        # Unless we previously had a prerelease.
        if not commits and not current_version_instance.is_prerelease:
            out.error("[NO_COMMITS_FOUND]\n" "No new commits found.")
            raise SystemExit(NO_COMMITS_FOUND)

        if increment is None:
            increment = self.find_increment(commits)

        # Increment is removed when current and next version
        # are expected to be prereleases.
        if prerelease and current_version_instance.is_prerelease:
            increment = None

        new_version = bump.generate_version(
            current_version, increment, prerelease=prerelease
        )
        new_tag_version = bump.create_tag(new_version, tag_format=tag_format)
        message = bump.create_commit_message(
            current_version, new_version, bump_commit_message
        )

        # Report found information
        out.write(
            f"message\n"
            f"tag to create: {new_tag_version}\n"
            f"increment detected: {increment}\n"
        )

        # Do not perform operations over files or git.
        if dry_run:
            raise SystemExit()

        bump.update_version_in_files(
            current_version,
            new_version.public,
            version_files,
            check_consistency=self.check_consistency,
        )
        if is_files_only:
            raise SystemExit()

        if self.changelog:
            changelog = Changelog(
                self.config,
                {
                    "unreleased_version": new_tag_version,
                    "incremental": True,
                    "dry_run": dry_run,
                },
            )
            changelog()

        self.config.set_key("version", new_version.public)
        c = git.commit(message, args=self._get_commit_args())
        if c.err:
            out.error('git.commit error: "{}"'.format(c.err.strip()))
            raise SystemExit(COMMIT_FAILED)
        c = git.tag(new_tag_version)
        if c.err:
            out.error(c.err)
            raise SystemExit(TAG_FAILED)
        out.success("Done!")
コード例 #13
0
    def __call__(self):
        commit_parser = self.cz.commit_parser
        changelog_pattern = self.cz.changelog_pattern
        start_rev = self.start_rev
        unreleased_version = self.unreleased_version
        changelog_meta: Dict = {}
        change_type_map: Optional[Dict] = self.change_type_map
        changelog_message_builder_hook: Optional[
            Callable] = self.cz.changelog_message_builder_hook
        changelog_hook: Optional[Callable] = self.cz.changelog_hook

        if not changelog_pattern or not commit_parser:
            out.error(
                f"'{self.config.settings['name']}' rule does not support changelog"
            )
            raise SystemExit(NO_PATTERN_MAP)

        tags = git.get_tags()
        if not tags:
            tags = []

        if self.incremental:
            changelog_meta = changelog.get_metadata(self.file_name)
            latest_version = changelog_meta.get("latest_version")
            if latest_version:
                start_rev = self._find_incremental_rev(latest_version, tags)

        commits = git.get_commits(start=start_rev, args="--author-date-order")
        if not commits:
            out.error("No commits found")
            raise SystemExit(NO_COMMITS_FOUND)

        tree = changelog.generate_tree_from_commits(
            commits,
            tags,
            commit_parser,
            changelog_pattern,
            unreleased_version,
            change_type_map=change_type_map,
            changelog_message_builder_hook=changelog_message_builder_hook,
        )
        changelog_out = changelog.render_changelog(tree)
        changelog_out = changelog_out.lstrip("\n")

        if self.dry_run:
            out.write(changelog_out)
            raise SystemExit(0)

        lines = []
        if self.incremental and os.path.isfile(self.file_name):
            with open(self.file_name, "r") as changelog_file:
                lines = changelog_file.readlines()

        with open(self.file_name, "w") as changelog_file:
            partial_changelog: Optional[str] = None
            if self.incremental:
                new_lines = changelog.incremental_build(
                    changelog_out, lines, changelog_meta)
                changelog_out = "".join(new_lines)
                partial_changelog = changelog_out

            if changelog_hook:
                changelog_out = changelog_hook(changelog_out,
                                               partial_changelog)
            changelog_file.write(changelog_out)
コード例 #14
0
    def __call__(self):  # noqa: C901
        """Steps executed to bump."""
        try:
            current_version_instance: Version = Version(self.bump_settings["version"])
        except TypeError:
            raise NoVersionSpecifiedError()

        # Initialize values from sources (conf)
        current_version: str = self.config.settings["version"]

        tag_format: str = self.bump_settings["tag_format"]
        bump_commit_message: str = self.bump_settings["bump_message"]
        version_files: List[str] = self.bump_settings["version_files"]

        dry_run: bool = self.arguments["dry_run"]
        is_yes: bool = self.arguments["yes"]
        increment: Optional[str] = self.arguments["increment"]
        prerelease: str = self.arguments["prerelease"]
        is_files_only: Optional[bool] = self.arguments["files_only"]
        is_local_version: Optional[bool] = self.arguments["local_version"]

        current_tag_version: str = bump.create_tag(
            current_version, tag_format=tag_format
        )

        is_initial = self.is_initial_tag(current_tag_version, is_yes)
        if is_initial:
            commits = git.get_commits()
        else:
            commits = git.get_commits(current_tag_version)

        # No commits, there is no need to create an empty tag.
        # Unless we previously had a prerelease.
        if not commits and not current_version_instance.is_prerelease:
            raise NoCommitsFoundError("[NO_COMMITS_FOUND]\n" "No new commits found.")

        if increment is None:
            increment = self.find_increment(commits)

        # Increment is removed when current and next version
        # are expected to be prereleases.
        if prerelease and current_version_instance.is_prerelease:
            increment = None

        new_version = bump.generate_version(
            current_version,
            increment,
            prerelease=prerelease,
            is_local_version=is_local_version,
        )
        new_tag_version = bump.create_tag(new_version, tag_format=tag_format)
        message = bump.create_commit_message(
            current_version, new_version, bump_commit_message
        )

        # Report found information
        out.write(
            f"{message}\n"
            f"tag to create: {new_tag_version}\n"
            f"increment detected: {increment}\n"
        )

        if increment is None and new_tag_version == current_tag_version:
            raise NoneIncrementExit()

        # Do not perform operations over files or git.
        if dry_run:
            raise DryRunExit()

        bump.update_version_in_files(
            current_version,
            str(new_version),
            version_files,
            check_consistency=self.check_consistency,
        )

        if self.changelog:
            changelog_cmd = Changelog(
                self.config,
                {
                    "unreleased_version": new_tag_version,
                    "incremental": True,
                    "dry_run": dry_run,
                },
            )
            changelog_cmd()
            c = cmd.run(f"git add {changelog_cmd.file_name}")

        self.config.set_key("version", str(new_version))

        if is_files_only:
            raise ExpectedExit()

        c = git.commit(message, args=self._get_commit_args())
        if c.return_code != 0:
            raise BumpCommitFailedError(f'git.commit error: "{c.err.strip()}"')
        c = git.tag(new_tag_version)
        if c.return_code != 0:
            raise BumpTagFailedError(c.err)
        out.success("Done!")
コード例 #15
0
 def __call__(
     self,
     current_version,
     version_filepaths=[],
     increment=None,
     prerelease=None,
     dry_run=False,
     autoconfirm_initial_tag=True,
     tag_format=None,
     bump_commit_message=None,
     check_consistency=True,
     update_files_only=False,
     no_verify=False,
 ):
     """
     :param str current_version: Semantic version e.g. '0.1.0'
     """
     # THE FOLLOWING CODE DOESN'T HAVE SIDE EFFECTS TO FILESYS OR GIT:
     current_version_instance = Version(current_version)
     current_tag_version = bump.create_tag(current_version,
                                           tag_format=tag_format)
     #
     is_initial = self.is_initial_tag(current_tag_version,
                                      autoconfirm_initial_tag)
     if is_initial:
         commits = git.get_commits()
     else:
         commits = git.get_commits(current_tag_version)
     #
     if not commits and not current_version_instance.is_prerelease:
         raise NoCommitsFoundError("[NO_COMMITS_FOUND]\n"
                                   "No new commits found.")
     #
     if increment is None:
         increment = self.find_increment(commits)
     #
     if prerelease is not None and current_version_instance.is_prerelease:
         increment = None
     #
     new_version = bump.generate_version(current_version,
                                         increment,
                                         prerelease=prerelease)
     new_tag_version = bump.create_tag(new_version, tag_format=tag_format)
     message = bump.create_commit_message(current_version, new_version,
                                          bump_commit_message)
     # Report found information
     out.write(f"{message}\n"
               f"tag to create: {new_tag_version}\n"
               f"increment detected: {increment}\n")
     #
     if increment is None and new_tag_version == current_tag_version:
         raise NoneIncrementExit()
     #
     if dry_run:
         raise DryRunExit()
     # SIDE EFFECTS TO FILESYSTEM: UPDATE TAG IN VERSION_FILEPATHS
     bump.update_version_in_files(
         current_version,
         new_version.public,
         version_filepaths,
         check_consistency=check_consistency,
     )
     if update_files_only:
         out.write("[update_files_only=True]: Done updating files " +
                   f"{version_filepaths}. ")
         raise ExpectedExit()
     # SIDE EFFECTS TO GIT: TAG AND COMMIT
     try:
         commit_args = "-a"
         if no_verify:
             commit_args += " --no-verify"
         c = git.commit(message, args=commit_args)
         if c.return_code != 0:
             raise BumpCommitFailedError(
                 f'git.commit error: "{c.err.strip()}"')
     except Exception as e:
         # If commit went bad (e.g. due to pre-commit errors), roll
         # back the version updates in filesystem to prevent future
         # "inconsistency errors". Swapping seems to do the trick.
         bump.update_version_in_files(
             new_version.public,  # swapped!
             current_version,  # swapped!
             version_filepaths,
             check_consistency=check_consistency,
         )
         out.write(
             f"\n[ERROR] Resetting version files to {current_version}")
         raise e
     # same as git.tag
     tag_msg = ""  # if changelog_path is None else f" -F {changelog_path}"
     c = cmd.run(f"git tag {new_tag_version}" + tag_msg)
     if c.return_code != 0:
         raise BumpTagFailedError(c.err)
     out.success("Done!")
コード例 #16
0
ファイル: bump.py プロジェクト: commitizen-tools/commitizen
    def __call__(self):  # noqa: C901
        """Steps executed to bump."""
        try:
            current_version_instance: Version = Version(
                self.bump_settings["version"])
        except TypeError:
            raise NoVersionSpecifiedError()

        # Initialize values from sources (conf)
        current_version: str = self.config.settings["version"]

        tag_format: str = self.bump_settings["tag_format"]
        bump_commit_message: str = self.bump_settings["bump_message"]
        version_files: List[str] = self.bump_settings["version_files"]

        dry_run: bool = self.arguments["dry_run"]
        is_yes: bool = self.arguments["yes"]
        increment: Optional[str] = self.arguments["increment"]
        prerelease: str = self.arguments["prerelease"]
        is_files_only: Optional[bool] = self.arguments["files_only"]
        is_local_version: Optional[bool] = self.arguments["local_version"]

        current_tag_version: str = bump.normalize_tag(current_version,
                                                      tag_format=tag_format)

        is_initial = self.is_initial_tag(current_tag_version, is_yes)
        if is_initial:
            commits = git.get_commits()
        else:
            commits = git.get_commits(current_tag_version)

        # If user specified changelog_to_stdout, they probably want the
        # changelog to be generated as well, this is the most intuitive solution
        if not self.changelog and self.changelog_to_stdout:
            self.changelog = True

        # No commits, there is no need to create an empty tag.
        # Unless we previously had a prerelease.
        if not commits and not current_version_instance.is_prerelease:
            raise NoCommitsFoundError("[NO_COMMITS_FOUND]\n"
                                      "No new commits found.")

        if increment is None:
            increment = self.find_increment(commits)

        # It may happen that there are commits, but they are not elegible
        # for an increment, this generates a problem when using prerelease (#281)
        if (prerelease and increment is None
                and not current_version_instance.is_prerelease):
            raise NoCommitsFoundError(
                "[NO_COMMITS_FOUND]\n"
                "No commits found to generate a pre-release.\n"
                "To avoid this error, manually specify the type of increment with `--increment`"
            )

        # Increment is removed when current and next version
        # are expected to be prereleases.
        if prerelease and current_version_instance.is_prerelease:
            increment = None

        new_version = bump.generate_version(
            current_version,
            increment,
            prerelease=prerelease,
            is_local_version=is_local_version,
        )

        new_tag_version = bump.normalize_tag(new_version,
                                             tag_format=tag_format)
        message = bump.create_commit_message(current_version, new_version,
                                             bump_commit_message)

        # Report found information
        information = (f"{message}\n"
                       f"tag to create: {new_tag_version}\n"
                       f"increment detected: {increment}\n")

        if self.changelog_to_stdout:
            # When the changelog goes to stdout, we want to send
            # the bump information to stderr, this way the
            # changelog output can be captured
            out.diagnostic(information)
        else:
            out.write(information)

        if increment is None and new_tag_version == current_tag_version:
            raise NoneIncrementExit(
                "[NO_COMMITS_TO_BUMP]\n"
                "The commits found are not elegible to be bumped")

        # Do not perform operations over files or git.
        if dry_run:
            raise DryRunExit()

        bump.update_version_in_files(
            current_version,
            str(new_version),
            version_files,
            check_consistency=self.check_consistency,
        )

        if self.changelog:
            if self.changelog_to_stdout:
                changelog_cmd = Changelog(
                    self.config,
                    {
                        "unreleased_version": new_tag_version,
                        "incremental": True,
                        "dry_run": True,
                    },
                )
                try:
                    changelog_cmd()
                except DryRunExit:
                    pass
            changelog_cmd = Changelog(
                self.config,
                {
                    "unreleased_version": new_tag_version,
                    "incremental": True,
                    "dry_run": dry_run,
                },
            )
            changelog_cmd()
            c = cmd.run(
                f"git add {changelog_cmd.file_name} {' '.join(version_files)}")

        self.config.set_key("version", str(new_version))

        if is_files_only:
            raise ExpectedExit()

        c = git.commit(message, args=self._get_commit_args())
        if self.retry and c.return_code != 0 and self.changelog:
            # Maybe pre-commit reformatted some files? Retry once
            logger.debug("1st git.commit error: %s", c.err)
            logger.info("1st commit attempt failed; retrying once")
            cmd.run(
                f"git add {changelog_cmd.file_name} {' '.join(version_files)}")
            c = git.commit(message, args=self._get_commit_args())
        if c.return_code != 0:
            raise BumpCommitFailedError(
                f'2nd git.commit error: "{c.err.strip()}"')
        c = git.tag(
            new_tag_version,
            annotated=self.bump_settings.get("annotated_tag", False)
            or bool(self.config.settings.get("annotated_tag", False)),
        )
        if c.return_code != 0:
            raise BumpTagFailedError(c.err)

        # TODO: For v3 output this only as diagnostic and remove this if
        if self.changelog_to_stdout:
            out.diagnostic("Done!")
        else:
            out.success("Done!")
コード例 #17
0
ファイル: version.py プロジェクト: modlin/commitizen
 def __call__(self):
     out.write(__version__)
コード例 #18
0
ファイル: schema.py プロジェクト: zombig/commitizen
 def __call__(self):
     out.write(self.cz.schema())
コード例 #19
0
ファイル: list_cz.py プロジェクト: zombig/commitizen
 def __call__(self):
     out.write("\n".join(registry.keys()))
コード例 #20
0
    def __call__(self):
        """Steps executed to bump."""
        try:
            current_version_instance: Version = Version(self.parameters["version"])
        except TypeError:
            out.error("[NO_VERSION_SPECIFIED]")
            out.error("Check if current version is specified in config file, like:")
            out.error("version = 0.4.3")
            raise SystemExit(NO_VERSION_SPECIFIED)

        # Initialize values from sources (conf)
        current_version: str = self.config["version"]
        tag_format: str = self.parameters["tag_format"]
        bump_commit_message: str = self.parameters["bump_message"]
        current_tag_version: str = bump.create_tag(
            current_version, tag_format=tag_format
        )
        files: list = self.parameters["files"]
        dry_run: bool = self.parameters["dry_run"]

        is_yes: bool = self.arguments["yes"]
        prerelease: str = self.arguments["prerelease"]
        increment: Optional[str] = self.arguments["increment"]

        is_initial = self.is_initial_tag(current_tag_version, is_yes)
        commits = git.get_commits(current_tag_version, from_beginning=is_initial)

        # No commits, there is no need to create an empty tag.
        # Unless we previously had a prerelease.
        if not commits and not current_version_instance.is_prerelease:
            out.error("[NO_COMMITS_FOUND]")
            out.error("No new commits found.")
            raise SystemExit(NO_COMMITS_FOUND)

        if increment is None:
            bump_pattern = self.cz.bump_pattern
            bump_map = self.cz.bump_map
            if not bump_map or not bump_pattern:
                out.error(f"'{self.config['name']}' rule does not support bump")
                raise SystemExit(NO_PATTERN_MAP)
            increment = bump.find_increment(
                commits, regex=bump_pattern, increments_map=bump_map
            )

        # Increment is removed when current and next version
        # are expected to be prereleases.
        if prerelease and current_version_instance.is_prerelease:
            increment = None

        new_version = bump.generate_version(
            current_version, increment, prerelease=prerelease
        )
        new_tag_version = bump.create_tag(new_version, tag_format=tag_format)
        message = bump.create_commit_message(
            current_version, new_version, bump_commit_message
        )

        # Report found information
        out.write(message)
        out.write(f"tag to create: {new_tag_version}")
        out.write(f"increment detected: {increment}")

        # Do not perform operations over files or git.
        if dry_run:
            raise SystemExit()

        config.set_key("version", new_version.public)
        bump.update_version_in_files(current_version, new_version.public, files)
        c = git.commit(message, args="-a")
        if c.err:
            out.error(c.err)
            raise SystemExit(COMMIT_FAILED)
        c = git.tag(new_tag_version)
        if c.err:
            out.error(c.err)
            raise SystemExit(TAG_FAILED)
        out.success("Done!")
コード例 #21
0
 def __call__(self):
     out.write(self.cz.info())
コード例 #22
0
ファイル: example.py プロジェクト: zombig/commitizen
 def __call__(self):
     out.write(self.cz.example())
コード例 #23
0
 def __call__(
     self,
     chlog_path,
     latest_version,
     start_rev=None,
     incremental=False,
     dry_run=False,
     change_type_map=None,
 ):
     """
     :param start_rev: If None, changelog from beginning
     """
     # THE FOLLOWING CODE DOESN'T HAVE SIDE EFFECTS TO FILESYS OR GIT:
     commit_parser = self.cz.commit_parser
     changelog_pattern = self.cz.changelog_pattern
     changelog_meta = {}
     changelog_message_builder_hook = self.cz.changelog_message_builder_hook
     changelog_hook = self.cz.changelog_hook
     if not changelog_pattern or not commit_parser:
         raise NoPatternMapError(
             f"'{self.commiter_name}' rule doesn't support changelog")
     #
     tags = git.get_tags()
     if not tags:
         tags = []
     #
     if incremental:
         changelog_meta = changelog.get_metadata(chlog_path)
         latest_version = changelog_meta.get("latest_version")
         if latest_version:
             start_rev = self._find_incremental_rev(latest_version, tags)
     #
     commits = git.get_commits(start=start_rev, args="--author-date-order")
     if not commits:
         raise NoCommitsFoundError("No commits found")
     #
     tree = changelog.generate_tree_from_commits(
         commits,
         tags,
         commit_parser,
         changelog_pattern,
         latest_version,
         change_type_map=change_type_map,
         changelog_message_builder_hook=changelog_message_builder_hook,
     )
     changelog_out = changelog.render_changelog(tree)
     changelog_out = changelog_out.lstrip("\n")
     #
     if dry_run:
         out.write(changelog_out)
         raise DryRunExit()
     #
     # CHANGES TO FILESYSTEM: WRITE TO CHLOG_PATH (AFTER READING)
     lines = []
     if incremental and os.path.isfile(chlog_path):
         with open(chlog_path, "r") as changelog_file:
             lines = changelog_file.readlines()
     #
     with open(chlog_path, "w") as changelog_file:
         partial_changelog = None
         if incremental:
             new_lines = changelog.incremental_build(
                 changelog_out, lines, changelog_meta)
             changelog_out = "".join(new_lines)
             partial_changelog = changelog_out
         if changelog_hook:
             changelog_out = changelog_hook(changelog_out,
                                            partial_changelog)
         changelog_file.write(changelog_out)
         out.write(f"Wrote changelog to {chlog_path}!\n")