Exemple #1
0
    def apply_admin_change(change: Change[Admin],
                           org: Organization) -> Change[Admin]:
        if change.action not in [ChangeActions.ADD, ChangeActions.REMOVE]:
            print_warning("Unsupported change action for org admins: %s" %
                          change.action)
            return change.skipped()

        from ghconf.github import gh
        if change.action == ChangeActions.ADD and change.after is not None:
            try:
                user = gh.get_user(change.after.username)
                org.add_to_members(user, role="admin")
            except GithubException as e:
                print_debug("Unable to add admin user %s: %s" %
                            (change.after.username, str(e)))
                return change.failure()
        elif change.action == ChangeActions.REMOVE and change.before is not None:
            try:
                user = gh.get_user(change.before.username)
                org.remove_from_members(user)
            except GithubException as e:
                print_debug("Unable to remove admin user %s: %s" %
                            (change.before.username, str(e)))
                return change.failure()
        return change.success()
Exemple #2
0
 def _protect_branch_with_approvals(
         org: Organization, repo: Repository,
         branches: Dict[str, Branch]) -> List[Change[str]]:
     if branch_name in branches:
         return _protect_branch(branches[branch_name], count)
     else:
         print_warning(
             "Requested to protect branch %s on repo %s, but the branch does not exist."
             % (highlight(branch_name), highlight(repo.name)))
         return []
Exemple #3
0
 def _force_branch_stale_review_dismissal(
         org: Organization, repo: Repository,
         branches: Dict[str, Branch]) -> List[Change[str]]:
     if branch_name in branches:
         return _set_dismiss_stale_approvals(branches[branch_name])
     else:
         print_warning(
             "Requested to dismiss stale reviews on branch %s on repo %s, but the branch does not exist."
             % (highlight(branch_name), highlight(repo.name)))
         return []
Exemple #4
0
    def apply_attr_change(change: Change[str], org: Organization, team: Team,
                          attr: str) -> Change[str]:
        if change.action not in [ChangeActions.REPLACE]:
            print_warning("Unsupported change action for team attributes: %s" %
                          change.action)
            return change.skipped()

        ghteam = org.get_team(team.id)  # type: GithubTeam

        if getattr(ghteam, attr) == change.before:
            print_info(
                "Setting {attr} from {before} to {after} on team {id}".format(
                    attr=attr,
                    before=change.before,
                    after=change.after,
                    id=team.id))
            ghteam.edit(team.name, **{attr: change.after})
            return change.success()

        return change
Exemple #5
0
    def apply_subteam_change(change: Change[Team], org: Organization,
                             parent: Team) -> Change[Team]:
        if change.action not in [ChangeActions.ADD, ChangeActions.REMOVE]:
            print_warning("Unsupported change action for subteams: %s" %
                          change.action)
            return change.skipped()

        if change.action == ChangeActions.ADD and change.after is not None:
            child = org.get_team(change.after.id)  # type: GithubTeam
            child.edit(child.name, parent_team_id=parent.id)
            if child.parent.id == parent.id:
                return change.success()
            else:
                return change.failure()
        elif change.action == ChangeActions.REMOVE and change.before is not None:
            child = org.get_team(change.before.id)
            if child.delete():
                return change.success()
            else:
                return change.failure()
        return change.success()
Exemple #6
0
def assemble_repolist(args: Namespace, org: Organization) -> List[Repository]:
    repolist = []
    if not args.skip_repo_changes:
        print_info("Assembling repository list...")
        if args.repos:
            for reponame in args.repos:
                try:
                    r = org.get_repo(reponame)
                    repolist.append(r)
                except GithubException:
                    raise utils.ErrorMessage(
                        "Repository %s not found. At least with this API key."
                        % utils.highlight(reponame))

        if args.reporegexes:
            for reporegex in args.reporegexes:
                try:
                    regex = re.compile(reporegex)
                except error as e:
                    raise utils.ErrorMessage(
                        "Not a valid regular expression %s (%s)" %
                        (utils.highlight(reporegex), str(e)))
                for repo in org.get_repos():
                    if regex.match(repo.name):
                        repolist.append(repo)

        if not args.repos and not args.reporegexes:
            print_info(
                "No repository regex or name specified, run against %s repos" %
                utils.highlight("all"))
            repolist = list(org.get_repos())
        elif not repolist:
            if args.skip_org_changes:
                print_warning(
                    "No repos matched and skipping org changes. Nothing to do."
                )
            else:
                print_warning("No repos matched!")
    return repolist
Exemple #7
0
 def __init__(self) -> None:
     super().__init__()
     print()
     print_warning("*" * 78)
     print_warning("{:^78}".format("Use ghconf.test.apply or ghconf.test.revert instead!"))
     print_warning("*" * 78)
     print()
     raise ErrorMessage("")
Exemple #8
0
    def apply_team_change(change: Change[Team],
                          org: Organization) -> Change[Team]:
        if change.action not in [ChangeActions.ADD, ChangeActions.REMOVE]:
            print_warning("Unsupported change action for teams: %s" %
                          change.action)
            return change.skipped()

        if change.action == ChangeActions.ADD and change.after is not None:
            to_create = change.after  # type: Team
            if not isinstance(to_create, Team):
                raise ErrorMessage("Create action without team to create")

            created = org.create_team(to_create.name,
                                      permission=to_create.default_permission,
                                      privacy=to_create.privacy)
            created.edit(created.name, description=to_create.description)
            to_create.id = created.id
            return change.success()
        elif change.action == ChangeActions.REMOVE and change.before is not None:
            try:
                print_debug("Retrieving team id %s for deletion" %
                            highlight(str(change.before.id)))
                to_delete = org.get_team(change.before.id)  # type: GithubTeam
            except GithubException:
                # if the team is already gone... ok
                return change.success()

            try:
                print_debug("Deleting team id %s" %
                            highlight(str(change.before.id)))
                to_delete.delete()
            except GithubException as e:
                print_error("Can't delete team id %s: %s" %
                            (highlight(str(change.before.id)), str(e)))
                return change.failure()
            change.before.id = None
        return change.success()
Exemple #9
0
def assemble_changedict(args: Namespace,
                        org: Organization) -> Dict[str, ChangeSet]:
    changedict = {}
    if args.skip_org_changes:
        print_warning("Skipping org changes (as per --no-org-changes)")
    else:
        pbar = None
        if utils.enable_progressbar:
            pbar = progressbar(len(modules))
        for modulename, moduledef in modules.items(
        ):  # type: str, GHConfModuleDef
            if utils.enable_progressbar and pbar:
                pbar.update()
            try:
                print_info("Building org changeset for %s" % modulename)
                cslist = moduledef.build_organization_changesets(org)
                for cs in cslist:
                    changedict.update(cs.todict())
            except NotImplementedError:
                print_debug(
                    "%s does not support creating an organization changeset. It might not modify the "
                    "org at all or it might just not report it." %
                    utils.highlight(modulename))
        if pbar:
            pbar.close()

    capcache = {}  # type: Dict[str, bool]
    repolist = assemble_repolist(args, org)

    pbar = None
    repocount = len(repolist)
    repofmt = "{{ix:>{len}}}/{count} Processing repo {{repo}}".format(
        len=len(str(repocount)), count=str(repocount))
    if utils.enable_progressbar:
        pbar = progressbar(repocount)
    for ix, repo in enumerate(repolist):
        if utils.enable_progressbar:
            pbar.update()

        if utils.enable_verbose_output:
            print_info(repofmt.format(ix=ix, repo=repo.full_name))

        branches = list(repo.get_branches())
        for modulename, moduledef in modules.items():
            if not capcache.get(modulename, True):
                print_debug(
                    "Capability cache for module %s indicates no support for repos"
                    % modulename)
                continue

            try:
                print_debug("Building repo changeset for %s => %s" %
                            (modulename, repo.name))
                cslist = moduledef.build_repository_changesets(
                    org, repo, branches)
                for cs in cslist:
                    changedict.update(cs.todict())
            except NotImplementedError:
                print_debug(
                    "%s does not support creating a repo changeset for repo %s. It might just not "
                    "make any modifications at all or it might not report them."
                    %
                    (utils.highlight(modulename), utils.highlight(repo.name)))
                capcache[modulename] = False
                continue

    pbar.close()
    return changedict