Esempio n. 1
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.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!")
Esempio n. 2
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!")
 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!")