Esempio n. 1
0
def get_non_contributor_stale_branch_names(repo: Repository) -> List[str]:  # noqa: E999
    """Return the list of branches that do not have the prefix of "contrib/" without open pull requests
    and that have not been updated for 2 months (stale). Protected branches are excluded from consideration.

    Args:
        repo (Repository): The repository whose branches will be searched and listed

    Returns:
        (List[str]): List of branch names that are stale and don't have the "contrib/" prefix
    """
    # set now with GMT timezone
    now = datetime.now(timezone.min)
    branch_names = []
    all_branches = repo.get_branches()
    print(f'{all_branches.totalCount=}')
    for branch in all_branches:
        # Make sure the branch is not prefixed with contrib
        if not branch.name.startswith('contrib/'):
            if branch.protected:
                print(f"Skipping branch {branch.name} because it is a protected branch")
                continue
            # Make sure HEAD commit is stale
            if (last_modified := branch.commit.commit.last_modified) and (
                    last_commit_datetime := parse(last_modified)):
                elapsed_days = (now - last_commit_datetime).days
                # print(f'{elapsed_days=}')
                if elapsed_days >= 60:
                    associated_open_prs = branch.commit.get_pulls()
                    associated_open_prs = [pr for pr in associated_open_prs if pr.state == 'open']
                    if len(associated_open_prs) < 1:
                        branch_names.append(branch.name)
Esempio n. 2
0
    def set(repo: Repository.Repository, config):
        print(" Processing branch protection settings...")

        if 'branch-protection' not in config and 'branch-protection-overrides' not in config:
            print(" Nothing to do.")
            return

        should_protect_default_branch = config.get('protect-default-branch')

        for branch in repo.get_branches():
            if not (branch.protected or
                    (should_protect_default_branch
                     and repo.default_branch == branch.name)):
                continue

            rules = BranchProtectionHook.rules_for(branch.name, config)

            newsettings = {}
            if 'dissmiss-stale-reviews' in rules:
                newsettings['dismiss_stale_reviews'] = bool(
                    rules['dissmiss-stale-reviews'])
            if 'required-review-count' in rules:
                newsettings['required_approving_review_count'] = int(
                    rules['required-review-count'])

            if not RepoSetter.has_changes(newsettings,
                                          branch.get_protection()):
                print(
                    f" Branch protection settings for {branch.name} unchanged."
                )
                continue

            print(" Applying branch protection settings...")
            branch.edit_protection(**newsettings)
def get_stale_branch_names_with_contrib(
        repo: Repository) -> List[str]:  # noqa: E999
    """Return the list of branches that have the prefix of "contrib/" without open pull requests
    and that have not been updated for 2 months (stale)

    Args:
        repo (Repository): The repository whose branches will be searched and listed

    Returns:
        (List[str]): List of branch names that are stale and have the "contrib/" prefix
    """
    # set now with GMT timezone
    now = datetime.now(timezone.min)
    organization = 'demisto'
    branch_names = []
    for branch in repo.get_branches():
        # Make sure the branch is contrib
        if branch.name.startswith('contrib/'):
            prs_with_branch_as_base = repo.get_pulls(state='OPEN',
                                                     base=branch.name)
            prs_with_branch_as_head = repo.get_pulls(
                state='OPEN', head=f'{organization}:{branch.name})')

            # Make sure there are no open prs pointing to/from the branch
            if prs_with_branch_as_base.totalCount < 1 and prs_with_branch_as_head.totalCount < 1:
                # Make sure HEAD commit is stale
                if (last_modified := branch.commit.commit.last_modified) and (
                        last_commit_datetime := parse(last_modified)):
                    elapsed_days = (now - last_commit_datetime).days
                    if elapsed_days >= 60:
                        branch_names.append(branch.name)
                else:
                    print(f"Couldn't load HEAD for {branch.name}")
Esempio n. 4
0
 def check_if_branch_exists(repository: Repository, branch_name) -> bool:
     """
     Check if branch with given name exists in the forked repository.
     :param repository: Forked repository.
     :param branch_name: Name of the branch.
     :return: True if branch already exists in the repository, False otherwise.
     """
     return branch_name in [
         branch.name for branch in list(repository.get_branches())
     ]
Esempio n. 5
0
def _get_default_branch_index(repo: Repository) -> int:
    branch_name = repo.default_branch
    branches = repo.get_branches()

    branch_i = 0

    for i, b in enumerate(branches):
        if b.name == branch_name:
            branch_i = i
            break

    return branch_i
Esempio n. 6
0
def __get_sha_for_tag(repository: Repository, tag: str) -> str:
    """
    Gets necessary SHA value from selected repository's branch.
    """
    branches = repository.get_branches()
    matched_branches = [match for match in branches if match.name == tag]
    if matched_branches:
        return matched_branches[0].commit.sha

    tags = repository.get_tags()
    matched_tags = [match for match in tags if match.name == tag]
    if not matched_tags:
        raise ValueError("No Tag or Branch exists with that name")
    return matched_tags[0].commit.sha
Esempio n. 7
0
def get_branch_names_with_contrib(repo: Repository) -> List[str]:  # noqa: E999
    '''Return the list of branches that have the prefix of "contrib/" and that are base branches of open PRs

    Args:
        repo (Repository): The repository whose branches will be searched and listed

    Returns:
        (List[str]): List of branch names that have the "contrib/" prefix and are base branches of open PRs
    '''
    branch_names = []
    for branch in repo.get_branches():
        if branch.name.startswith('contrib/'):
            prs_with_branch_as_base = repo.get_pulls(state='OPEN',
                                                     base=branch.name)
            if prs_with_branch_as_base.totalCount >= 1:
                branch_names.append(branch.name)
    return branch_names
Esempio n. 8
0
 def from_repo(cls, repo: Repository) -> 'ConanRepo':
     return cls.from_branches(repo.get_branches(), repo.default_branch)