def checkout_branch(repo, branch_name, no_pull=False): """Checkout a branch and optionally pull updates. :param repo: Repo object :param branch_name: Name of the branch to checkout :param no_pull: (Default: False) If True, don't pull changes to branch :return: Head object for the checked out branch """ base_head = Head(repo, f'refs/heads/{branch_name}') if repo.active_branch != base_head: print(f'Checking out {branch_name}.') base_head.checkout() if not no_pull and base_head.tracking_branch(): print(f'Pulling updates to {branch_name}...') remote_name = base_head.tracking_branch().remote_name remote = Remote(repo, remote_name) base_commit = base_head.commit for fetch_info in remote.pull(): if fetch_info.ref == base_head.tracking_branch(): if fetch_info.commit != base_commit: print( f'Updated {branch_name} to {fetch_info.commit.hexsha}') else: print(f'{branch_name} already up to date.') print('') return base_head
def _create_commit_and_push(self, context: PublisherContext, repository: git.Repo, target_branch: git.Head) -> None: original_branch = repository.active_branch changes_pushed = False try: target_branch.checkout() logger.info("Active branch after checkout: %s", repository.active_branch) feature_file = self._file_manager.produce_feature_file( context=context) logger.info("Untracked files after feature creation: %s", repository.untracked_files) repository.index.add([feature_file.as_posix()]) logger.info("Untracked files after index update: %s", repository.untracked_files) repository.index.commit( (f"Added feature {context.feature.name} " f"(id {context.feature.id}) " f"by {context.test_run.executed_by}"), skip_hooks=True, ) logger.info("Commit successfully created") if repository.active_branch == original_branch: raise CurrentBranchEqualToDefaultError( f"Current branch could not be equal to default: '{original_branch}'!" ) if repository.active_branch != target_branch: raise CurrentBranchNotEqualToTargetError( f"Current branch should be equal to target: '{target_branch}'!" ) logger.info("Remote origin url: %s", repository.remotes.origin.url) repository.git.push("origin", target_branch, force=True) logger.info("Changes successfully pushed to remote repository") changes_pushed = True except (git.GitCommandError, BaseGitVersionPublisherError): logger.exception("Error while trying to commit feature file!") if original_branch != repository.active_branch: logger.info("Current branch is '%s'", repository.active_branch) original_branch.checkout() logger.info("Branch returned to '%s'", repository.active_branch) if not changes_pushed: raise CommitNotCreatedError("Commit has not been created!")