Ejemplo n.º 1
0
def ensure_group():
    """Create Perforce group git-fusion-group if not already exists."""
    users = []
    # Keep the order of the users in the same order that P4 insists on
    # (if the order doesn't match then the group is updated repeatedly).
    users.append(p4gf_const.P4GF_REVIEWS__ALL_GF)
    users.append(p4gf_const.P4GF_REVIEWS__NON_GF)
    users.append(p4gf_util.gf_reviews_user_name())
    users.append(p4gf_const.P4GF_USER)
    args = [p4, NTR("group")]
    spec = {'Timeout': NTR('unlimited'), 'Users': users}
    kwargs = {'spec_id': p4gf_const.P4GF_GROUP, 'values': spec}
    if not p4gf_util.ensure_spec(*args, **kwargs):
        # We change the list of users in the group from time to time,
        # so ensure the membership is up to date.
        users = p4gf_util.first_dict(p4.run('group', '-o', p4gf_const.P4GF_GROUP))['Users']
        # Add the gf_reviews_user_name if not already in the group.
        # This avoids removing already existing reviews users from multiple GF instances.
        if not p4gf_util.gf_reviews_user_name() in users:
            users.append(p4gf_util.gf_reviews_user_name())
            spec = {'Timeout': NTR('unlimited'), 'Users': users}
            kwargs = {'spec_id': p4gf_const.P4GF_GROUP, 'values': spec}
            if p4gf_util.ensure_spec_values(*args, **kwargs):
                Verbosity.report(Verbosity.INFO
                                , _("Group '{}' updated.").format(p4gf_const.P4GF_GROUP))
            else:
                Verbosity.report(Verbosity.INFO, _("Group '{}' already up to date.")
                                 .format(p4gf_const.P4GF_GROUP))
        else:
            Verbosity.report(Verbosity.INFO, _("Group '{}' already up to date.")
                             .format(p4gf_const.P4GF_GROUP))
        return False
    else:
        Verbosity.report(Verbosity.INFO, _("Group '{}' created.").format(p4gf_const.P4GF_GROUP))
    return True
Ejemplo n.º 2
0
def set_passwd_and_login(created, user, passwd=None):
    """If creating the user, conditionally prompt for and set the passwd."""
    global P4_PASSWD, PROMPT_FOR_PASSWD
    if created:
        if PROMPT_FOR_PASSWD:
            prompt_msg = _("Set one password for Perforce users 'git-fusion-user'"
                           "\nand 'git-fusion-reviews-*'.")
            # When creating additional Git Fusion instance only the new reviews will be created.
            # Catch this case and avoid a misleading prompt.
            if user == p4gf_util.gf_reviews_user_name():
                prompt_msg = _("Enter a new password for Perforce user '{user}'.").format(
                    user=user)
            try:
                P4_PASSWD = get_passwd(prompt_msg)
            except KeyboardInterrupt:
                Verbosity.report(
                    Verbosity.INFO,
                    _("\n Stopping. Passwords not set."))
                sys.exit(1)
            # If we prompted, do so once and use for all the service users,
            # even if the user enters no password at all.
            PROMPT_FOR_PASSWD = False
            if not P4_PASSWD:
                Verbosity.report(
                    Verbosity.INFO,
                    _("Empty password. Not setting passwords."))

        # passwd may be suppressed with --nopasswd option, which also suppresses the prompt.
        # We always set the passwd for unknown_git - from random passwd=xxx parameter
        # The global P4_PASSWd for the GF users may not be set (--nopasswd)
        if P4_PASSWD or passwd:
            if passwd:
                set_passwd(user, passwd)
            else:
                set_passwd(user, P4_PASSWD)
            Verbosity.report(
                Verbosity.INFO, _("Password set for Perforce user '{user}'.")
                .format(user=user))
            r = p4.run_login(user)
            msg = re.sub(user, "'" + user + "'", r[0])
            Verbosity.report(Verbosity.INFO, msg)
    else:
        if user in (p4gf_const.P4GF_USER, p4gf_const.P4GF_REVIEWS__NON_GF,
                    p4gf_const.P4GF_REVIEWS__ALL_GF, p4gf_util.gf_reviews_user_name()):
            if p4_has_login(user) == LOGIN_NEEDS_TICKET:
                r = p4.run_login(user)
                msg = re.sub(user, "'" + user + "'", r[0])
                Verbosity.report(Verbosity.INFO, msg)
Ejemplo n.º 3
0
    def connect(self):
        '''
        Connect the p4 and p4gf connections.

        Note: p4gf_reviews and p4gf_reviews_non_gf are not connected!

        If this is the first time connecting, complete context initialization.
        '''

        # if previously connected, just reconnect
        if self.p4:
            if not self.p4.connected():
                p4_connect(self.p4)
            if not self.p4gf.connected():
                p4_connect(self.p4gf)
            return

        # create connections and use them to complete initialization of context
        self.p4                  = self.__make_p4( client=self.config.p4client )
        self.p4gf                = self.__make_p4( client=self.config.p4client_gf )
        self.p4gf_reviews        = self.__make_p4( user    = p4gf_util.gf_reviews_user_name()
                                                 , connect = False )
        self.p4gf_reviews_non_gf = self.__make_p4( user    = p4gf_const.P4GF_REVIEWS__NON_GF
                                                 , connect = False )
        self._client_pool        = ClientPool(self)
        self.__wrangle_charset()
        self.get_timezone_serverversion()
        self.__set_branch_creation()
        self.__set_merge_commits()
        self.__set_submodules()
        self.__set_change_owner()
        self.__set_up_paths()
Ejemplo n.º 4
0
def set_user_passwd_if_created(created, user):
    '''If creating the user, conditionally prompt for and set the passwd.'''
    global P4_PASSWD, PROMPT_FOR_PASSWD
    if created:
        if PROMPT_FOR_PASSWD:
            prompt_msg = _("Set one password for Perforce users 'git-fusion-user'"
                           "\nand 'git-fusion-reviews-*'.")
            # When creating additional Git Fusion instance only the new reviews will be created.
            # Catch this case and avoid a misleading prompt.
            if user == p4gf_util.gf_reviews_user_name():
                prompt_msg = _("Enter a new password for Perforce user '{0}'.").format(user)
            try:
                P4_PASSWD = get_passwd(prompt_msg)
            except KeyboardInterrupt:
                Verbosity.report(Verbosity.INFO,
                    _("\n Stopping. Passwords not set."))
                sys.exit(1)
            # If we prompted, do so once and use for all the service users,
            # even if the user enters no password at all.
            PROMPT_FOR_PASSWD = False
            if not P4_PASSWD:
                Verbosity.report(Verbosity.INFO,
                    _("Empty password. Not setting passwords."))

        # passwd may be suppressed with --nopasswd option, which also suppresses the prompt.
        if P4_PASSWD:
            set_passwd(user, P4_PASSWD)
            Verbosity.report(Verbosity.INFO,
                    _("Password set for Perforce user '{}'.").format(user))
Ejemplo n.º 5
0
    def connect(self):
        '''
        Connect the p4 and p4gf connections.

        Note: p4gf_reviews and p4gf_reviews_non_gf are not connected!

        If this is the first time connecting, complete context initialization.
        '''

        # if previously connected, just reconnect
        if self.p4:
            if not self.p4.connected():
                p4_connect(self.p4)
            if not self.p4gf.connected():
                p4_connect(self.p4gf)
            return

        # create connections and use them to complete initialization of context
        self.p4 = self.__make_p4(client=self.config.p4client)
        self.p4gf = self.__make_p4(client=self.config.p4client_gf)
        self.p4gf_reviews = self.__make_p4(
            user=p4gf_util.gf_reviews_user_name(), connect=False)
        self.p4gf_reviews_non_gf = self.__make_p4(
            user=p4gf_const.P4GF_REVIEWS__NON_GF, connect=False)
        self._client_pool = ClientPool(self)
        self.__wrangle_charset()
        self.get_timezone_serverversion()
        self.__set_branch_creation()
        self.__set_merge_commits()
        self.__set_submodules()
        self.__set_change_owner()
        self.__set_up_paths()
Ejemplo n.º 6
0
def set_user_passwd_if_created(created, user):
    '''If creating the user, conditionally prompt for and set the passwd.'''
    global P4_PASSWD, PROMPT_FOR_PASSWD
    if created:
        if PROMPT_FOR_PASSWD:
            prompt_msg = _(
                "Set one password for Perforce users 'git-fusion-user'"
                "\nand 'git-fusion-reviews-*'.")
            # When creating additional Git Fusion instance only the new reviews will be created.
            # Catch this case and avoid a misleading prompt.
            if user == p4gf_util.gf_reviews_user_name():
                prompt_msg = _("Enter a new password for Perforce user '{0}'."
                               ).format(user)
            try:
                P4_PASSWD = get_passwd(prompt_msg)
            except KeyboardInterrupt:
                Verbosity.report(Verbosity.INFO,
                                 _("\n Stopping. Passwords not set."))
                sys.exit(1)
            # If we prompted, do so once and use for all the service users,
            # even if the user enters no password at all.
            PROMPT_FOR_PASSWD = False
            if not P4_PASSWD:
                Verbosity.report(Verbosity.INFO,
                                 _("Empty password. Not setting passwords."))

        # passwd may be suppressed with --nopasswd option, which also suppresses the prompt.
        if P4_PASSWD:
            set_passwd(user, P4_PASSWD)
            Verbosity.report(
                Verbosity.INFO,
                _("Password set for Perforce user '{}'.").format(user))
Ejemplo n.º 7
0
def ensure_group():
    """Create Perforce group git-fusion-group if not already exists."""
    users = []
    # Keep the order of the users in the same order that P4 insists on
    # (if the order doesn't match then the group is updated repeatedly).
    users.append(p4gf_const.P4GF_REVIEWS__ALL_GF)
    users.append(p4gf_const.P4GF_REVIEWS__NON_GF)
    users.append(p4gf_util.gf_reviews_user_name())
    users.append(p4gf_const.P4GF_USER)
    args = [p4, NTR("group")]
    spec = {'Timeout': NTR('unlimited'), 'Users': users}
    kwargs = {'spec_id': p4gf_const.P4GF_GROUP, 'values': spec}
    if not p4gf_util.ensure_spec(*args, **kwargs):
        # We change the list of users in the group from time to time,
        # so ensure the membership is up to date.
        users = p4gf_util.first_dict(
            p4.run('group', '-o', p4gf_const.P4GF_GROUP))['Users']
        # Add the gf_reviews_user_name if not already in the group.
        # This avoids removing already existing reviews users from multiple GF instances.
        if not p4gf_util.gf_reviews_user_name() in users:
            users.append(p4gf_util.gf_reviews_user_name())
            spec = {'Timeout': NTR('unlimited'), 'Users': users}
            kwargs = {'spec_id': p4gf_const.P4GF_GROUP, 'values': spec}
            if p4gf_util.ensure_spec_values(*args, **kwargs):
                Verbosity.report(
                    Verbosity.INFO,
                    _("Group '{}' updated.").format(p4gf_const.P4GF_GROUP))
            else:
                Verbosity.report(
                    Verbosity.INFO,
                    _("Group '{}' already up to date.").format(
                        p4gf_const.P4GF_GROUP))
        else:
            Verbosity.report(
                Verbosity.INFO,
                _("Group '{}' already up to date.").format(
                    p4gf_const.P4GF_GROUP))
        return False
    else:
        Verbosity.report(
            Verbosity.INFO,
            _("Group '{}' created.").format(p4gf_const.P4GF_GROUP))
    return True
Ejemplo n.º 8
0
def ensure_users():
    """Create Perforce user git-fusion-user, and reviews users if not already extant."""
    default_auth_method = get_auth_method()
    has_auth_check, has_service_check = has_auth_check_trigger()
    set_perforce_auth_method = default_auth_method and default_auth_method != 'perforce'

    # These ensure_user-* methods always set AuthMethod to 'perforce'
    created = p4gf_p4spec.ensure_user_gf(p4, set_perforce_auth_method)
    log_user_info(created, has_auth_check, p4gf_const.P4GF_USER, default_auth_method)
    if not has_auth_check:
        set_passwd_and_login(created, p4gf_const.P4GF_USER)

    created = p4gf_p4spec.ensure_user_reviews(p4, set_perforce_auth_method)
    log_user_info(created, has_service_check, p4gf_util.gf_reviews_user_name(), default_auth_method)
    if not has_service_check:
        set_passwd_and_login(created, p4gf_util.gf_reviews_user_name())

    created = p4gf_p4spec.ensure_user_reviews_non_gf(p4, set_perforce_auth_method)
    log_user_info(created, has_service_check, p4gf_const.P4GF_REVIEWS__NON_GF, default_auth_method)
    if not has_service_check:
        set_passwd_and_login(created, p4gf_const.P4GF_REVIEWS__NON_GF)

    created = p4gf_p4spec.ensure_user_reviews_all_gf(p4, set_perforce_auth_method)
    log_user_info(created, has_service_check, p4gf_const.P4GF_REVIEWS__ALL_GF, default_auth_method)
    if not has_service_check:
        set_passwd_and_login(created, p4gf_const.P4GF_REVIEWS__ALL_GF)

    if CREATE_UNKNOWN_GIT:
        created = p4gf_p4spec.ensure_unknown_git(p4, set_perforce_auth_method)
        log_user_info(created, has_auth_check, p4gf_const.P4GF_UNKNOWN_USER, default_auth_method)
        if not has_auth_check:
            passwd = str(uuid.uuid4().hex).upper()[-10:] + '$#z'
            set_passwd_and_login(created, p4gf_const.P4GF_UNKNOWN_USER, passwd=passwd)

    # Report whether 'unknown_git' exists.
    e = p4gf_util.service_user_exists(p4, p4gf_const.P4GF_UNKNOWN_USER)
    _exists = ( _("Git Fusion user '{user}' does not exist.")
              , _("Git Fusion user '{user}' exists."))
    Verbosity.report(Verbosity.INFO, _exists[e].format(user=p4gf_const.P4GF_UNKNOWN_USER))
Ejemplo n.º 9
0
def _ensure_specs_created(p4):
    """Ensure that various specs have been created by p4gf_super_init."""
    spec_list = [
        ['user', p4gf_const.P4GF_USER],
        ['user', p4gf_util.gf_reviews_user_name()],
        ['user', p4gf_const.P4GF_REVIEWS__NON_GF],
        ['group', p4gf_const.P4GF_GROUP],
        ['depot', p4gf_const.P4GF_DEPOT]
    ]
    for spec_type, spec_id in spec_list:
        if not p4gf_p4spec.spec_exists(p4, spec_type, spec_id):
            raise RuntimeError(_("error: {spec_type} '{spec_id}' does not exist."
                                 " Please contact your administrator.")
                               .format(spec_type=spec_type, spec_id=spec_id))
Ejemplo n.º 10
0
def ensure_users():
    """Create Perforce user git-fusion-user, and reviews users if not already extant."""
    created = p4gf_util.ensure_user_gf(p4)
    log_info(created, p4gf_const.P4GF_USER)
    set_user_passwd_if_created(created, p4gf_const.P4GF_USER)

    created = p4gf_util.ensure_user_reviews(p4)
    log_info(created, p4gf_util.gf_reviews_user_name())
    set_user_passwd_if_created(created, p4gf_util.gf_reviews_user_name())

    created = p4gf_util.ensure_user_reviews_non_gf(p4)
    log_info(created, p4gf_const.P4GF_REVIEWS__NON_GF)
    set_user_passwd_if_created(created, p4gf_const.P4GF_REVIEWS__NON_GF)

    created = p4gf_util.ensure_user_reviews_all_gf(p4)
    log_info(created, p4gf_const.P4GF_REVIEWS__ALL_GF)
    set_user_passwd_if_created(created, p4gf_const.P4GF_REVIEWS__ALL_GF)

    # Report whether 'unknown_git' exists. Do not create.
    e = p4gf_util.service_user_exists(p4, p4gf_const.P4GF_UNKNOWN_USER)
    _exists = ( _("Git Fusion user '{0}' does not exist.")
              , _("Git Fusion user '{0}' exists."))
    Verbosity.report(Verbosity.INFO, _exists[e].format(p4gf_const.P4GF_UNKNOWN_USER))
Ejemplo n.º 11
0
def ensure_users():
    """Create Perforce user git-fusion-user, and reviews users if not already extant."""
    created = p4gf_util.ensure_user_gf(p4)
    log_info(created, p4gf_const.P4GF_USER)
    set_user_passwd_if_created(created, p4gf_const.P4GF_USER)

    created = p4gf_util.ensure_user_reviews(p4)
    log_info(created, p4gf_util.gf_reviews_user_name())
    set_user_passwd_if_created(created, p4gf_util.gf_reviews_user_name())

    created = p4gf_util.ensure_user_reviews_non_gf(p4)
    log_info(created, p4gf_const.P4GF_REVIEWS__NON_GF)
    set_user_passwd_if_created(created, p4gf_const.P4GF_REVIEWS__NON_GF)

    created = p4gf_util.ensure_user_reviews_all_gf(p4)
    log_info(created, p4gf_const.P4GF_REVIEWS__ALL_GF)
    set_user_passwd_if_created(created, p4gf_const.P4GF_REVIEWS__ALL_GF)

    # Report whether 'unknown_git' exists. Do not create.
    e = p4gf_util.service_user_exists(p4, p4gf_const.P4GF_UNKNOWN_USER)
    _exists = (_("Git Fusion user '{0}' does not exist."),
               _("Git Fusion user '{0}' exists."))
    Verbosity.report(Verbosity.INFO,
                     _exists[e].format(p4gf_const.P4GF_UNKNOWN_USER))
Ejemplo n.º 12
0
def is_locked_by_review(p4, clientmap, check_for_self=False):
    """Check whether any other GF/submit users have my views under Review"""
    gf_user = p4gf_util.gf_reviews_user_name()
    repo_views = remove_exclusionary_maps(clientmap.lhs())
    cmd = [NTR('reviews')] + [p4gf_util.dequote(l) for l in repo_views]
    reviewers = p4gf_util.p4run_logged(p4, cmd)
    for user in reviewers:
        _user = user['user']
        if _user.startswith(p4gf_const.P4GF_REVIEWS_GF):
            if _user == p4gf_const.P4GF_REVIEWS__ALL_GF:
                continue        # skip the union Reviews - used only by trigger
            if check_for_self:
                if _user == gf_user:
                    return True, gf_user
            if _user != gf_user:    # always check if another user has this view locked
                return True, _user
    return False, None
Ejemplo n.º 13
0
def ensure_user_reviews(p4, auth_method=None):
    """Create user git-fusion-reviews it not already exists.

    Requires that connection p4 has super permissions.

    Return True if created, False if already exists.
    """
    user = p4gf_util.gf_reviews_user_name()
    if auth_method:
        spec = {
            'FullName': _('Git Fusion Reviews'),
            'AuthMethod': 'perforce',
            'Type': 'service'
        }
    else:
        spec = {
            'FullName': _('Git Fusion Reviews'),
            'Type': 'service'
        }
    return ensure_spec(p4, NTR('user'), spec_id=user, args='-f', values=spec)
Ejemplo n.º 14
0
def lock_update_repo_reviews(ctx, repo, clientmap, action=None):
    """Lock on this gf-instance counter lock then add the repo views to the
    service user account. Use 'p4 reviews' to check whether views are locked.
    Cleanup reviews on rejection.
    """
    p4 = ctx.p4gf
    user = p4gf_util.gf_reviews_user_name()
    if not p4gf_util.service_user_exists(p4, user):
        raise RuntimeError(_("Git Fusion: GF instance reviews user '{}' does not exist")
                           .format(user))
    LOG.debug3("user:{} repo:{} action:{}".format(user, repo, action))
    if p4gf_version.p4d_version(p4) <  P4D_VERSION_NO_NON_GF_CLEANUP:
        with p4gf_create_p4.Connector(ctx.p4gf_reviews_non_gf) as p4_reviews_non_gf:
            cleanup_non_gf_reviews(p4, p4_reviews_non_gf)

    with p4gf_create_p4.Connector(ctx.p4gf_reviews) as p4_reviews:
        with p4gf_lock.user_spec_lock(p4, user):
            intersects = update_repo_reviews(p4_reviews, user, clientmap, action=action)

        # When action == ADD, before updating reviews
        # update_repo_reviews checks for a conflict with self - this p4_reviews user
        # this check handles the case of overlapping views pushed to the same GF server
        # if it detects a conflict it returns INTERSECT and does not update the user reviews
        if intersects == INTERSECT:
            msg = p4gf_const.P4GF_LOCKED_BY_MSG.format(user=user)
            LOG.error(msg)
            LOG.error("clientmap: {}".format(clientmap))
            raise LockConflict(msg)

        if action == ADD:
            # Here we check if another P4GF_REVIEWS_GF service user already has locked the view
            # After we have released the lock
            is_locked, by_user = is_locked_by_review(p4, clientmap)
            if is_locked:
                # get the lock again for cleanup and remove the views we just added
                with p4gf_lock.user_spec_lock(p4, user):
                    update_repo_reviews(p4_reviews, user, clientmap, action=REMOVE)
                msg = p4gf_const.P4GF_LOCKED_BY_MSG.format(user=by_user)
                LOG.error(msg)
                LOG.error("clientmap: {}".format(clientmap))
                raise LockConflict(msg)
Ejemplo n.º 15
0
def set_passwd(user, passwd):
    """Set the P4 passwd for user. Assumes super user priviledge."""
    with p4.at_exception_level(p4.RAISE_NONE):
        p4.input = passwd
        r = p4.run_passwd(user)
        Verbosity.report(Verbosity.DEBUG, NTR('p4 passwd\n{}').format(r))
    if p4.errors:
        Verbosity.report(
            Verbosity.ERROR, _("Unable to run 'p4 passwd -P xxx {user}'.").format(user=user))
        for e in p4.errors:
            Verbosity.report(Verbosity.ERROR, e)
        Verbosity.report(
            Verbosity.ERROR,
            _("You must set passwords for Git Fusion users and re-run configure-git-fusion.sh"))
        Verbosity.report(
            Verbosity.ERROR,
            _("Git Fusion users are: {gf_user}  {reviews_user}  {non_gf}  {all_gf}")
            .format(gf_user=p4gf_const.P4GF_USER,
                    reviews_user=p4gf_util.gf_reviews_user_name(),
                    non_gf=p4gf_const.P4GF_REVIEWS__NON_GF,
                    all_gf=p4gf_const.P4GF_REVIEWS__ALL_GF))
        sys.exit(2)
Ejemplo n.º 16
0
def _global_init(p4):
    """Check that p4gf_super_init has been run and created the following
    * user git-fusion-user
    * depot //P4GF_DEPOT
    * group git-fusion-pull
    * group git-fusion-push
    * protects entries
    """

    #
    # The global initialization process below must be idempotent in the sense
    # that it is safe to perform more than once. As such, there are checks to
    # determine if work is needed or not, and if that work results in an
    # error, log and carry on with the rest of the steps, with the assumption
    # that a previous attempt had failed in the middle (or possibly that
    # another instance of Git Fusion has started at nearly the same time as
    # this one).
    #

    p4gf_util.has_server_id_or_exit()

    spec_list = {
        'user1':  p4gf_const.P4GF_USER,
        'user2':  p4gf_util.gf_reviews_user_name(),
        'user3':  p4gf_const.P4GF_REVIEWS__NON_GF,
        'group':  p4gf_const.P4GF_GROUP,
        'depot':  p4gf_const.P4GF_DEPOT
    }
    for spec_type, spec_id in spec_list.items():
        spec_type = re.sub(NTR(r'\d$'), '', spec_type)
        if not p4gf_util.spec_exists(p4, spec_type, spec_id):
        # pylint:disable=C0301
            raise RuntimeError(_("error: {spec_type} '{spec_id}' does not exist."
                                 " Please contact your administrator.")
                               .format(spec_type=spec_type, spec_id=spec_id))
        # pylint:enable=C0301

    for group in [p4gf_group.PERM_PULL, p4gf_group.PERM_PUSH]:
        c = p4gf_group.create_global_perm(p4, group)
        if c:
            _info(_("Global permission group '{}' created.").format(group))
        else:
            _info(_("Global permission group '{}' already exists.").format(group))

    c = p4gf_group.create_default_perm(p4)
    if c:
        _info(_("Default permission counter '{}' set to '{}'.")
              .format( p4gf_const.P4GF_COUNTER_PERMISSION_GROUP_DEFAULT
                     , p4gf_group.DEFAULT_PERM ))
    else:
        _info(_("Default permission counter '{}' already exists.")
              .format(p4gf_const.P4GF_COUNTER_PERMISSION_GROUP_DEFAULT))

    # Require that single git-fusion-user have admin privileges
    # over the //P4GF_DEPOT/ depot
    is_protects_empty = False
    try:
        p4.run('protects', '-u', p4gf_const.P4GF_USER, '-m',
               '//{depot}/...'.format(depot=p4gf_const.P4GF_DEPOT))
    except P4.P4Exception:
        # Why MsgDm_ReferClient here? Because p4d 11.1 returns
        # "must refer to client" instead of
        # "Protections table is empty" when given a depot path to
        # 'p4 protects -m -u'. Surprise!
        if p4gf_p4msg.find_all_msgid(p4, [ p4gf_p4msgid.MsgDm_ProtectsEmpty
                                         , p4gf_p4msgid.MsgDm_ReferClient  ]):
            is_protects_empty = True
        # All other errors are fatal, propagated.

    if is_protects_empty:
        # - order the lines in increasing permission
        # - end with at least one user (even a not-yet-created user) with super
        #     write user * * //...
        #     admin user git-fusion-user * //...
        #     super user super * //...
        p4gf_util.set_spec(p4, 'protect', values={
            'Protections': ["super user * * //...",
                            "super user {user} * //...".format(user=p4gf_const.P4GF_USER),
                            "admin user {user} * //{depot}/..."
                            .format(user=p4gf_const.P4GF_USER, depot=p4gf_const.P4GF_DEPOT)]})
        _info(_('Protects table set.'))
Ejemplo n.º 17
0
def _global_init(p4):
    """Check that p4gf_super_init has been run and created the following
    * user git-fusion-user
    * depot //P4GF_DEPOT
    * group git-fusion-pull
    * group git-fusion-push
    * protects entries
    """

    #
    # The global initialization process below must be idempotent in the sense
    # that it is safe to perform more than once. As such, there are checks to
    # determine if work is needed or not, and if that work results in an
    # error, log and carry on with the rest of the steps, with the assumption
    # that a previous attempt had failed in the middle (or possibly that
    # another instance of Git Fusion has started at nearly the same time as
    # this one).
    #

    p4gf_util.has_server_id_or_exit()

    spec_list = {
        'user1': p4gf_const.P4GF_USER,
        'user2': p4gf_util.gf_reviews_user_name(),
        'user3': p4gf_const.P4GF_REVIEWS__NON_GF,
        'group': p4gf_const.P4GF_GROUP,
        'depot': p4gf_const.P4GF_DEPOT
    }
    for spec_type, spec_id in spec_list.items():
        spec_type = re.sub(NTR(r'\d$'), '', spec_type)
        if not p4gf_util.spec_exists(p4, spec_type, spec_id):
            # pylint:disable=C0301
            raise RuntimeError(
                _("error: {spec_type} '{spec_id}' does not exist."
                  " Please contact your administrator.").format(
                      spec_type=spec_type, spec_id=spec_id))
        # pylint:enable=C0301

    for group in [p4gf_group.PERM_PULL, p4gf_group.PERM_PUSH]:
        c = p4gf_group.create_global_perm(p4, group)
        if c:
            _info(_("Global permission group '{}' created.").format(group))
        else:
            _info(
                _("Global permission group '{}' already exists.").format(
                    group))

    c = p4gf_group.create_default_perm(p4)
    if c:
        _info(
            _("Default permission counter '{}' set to '{}'.").format(
                p4gf_const.P4GF_COUNTER_PERMISSION_GROUP_DEFAULT,
                p4gf_group.DEFAULT_PERM))
    else:
        _info(
            _("Default permission counter '{}' already exists.").format(
                p4gf_const.P4GF_COUNTER_PERMISSION_GROUP_DEFAULT))

    # Require that single git-fusion-user have admin privileges
    # over the //P4GF_DEPOT/ depot
    is_protects_empty = False
    try:
        p4.run('protects', '-u', p4gf_const.P4GF_USER, '-m',
               '//{depot}/...'.format(depot=p4gf_const.P4GF_DEPOT))
    except P4.P4Exception:
        # Why MsgDm_ReferClient here? Because p4d 11.1 returns
        # "must refer to client" instead of
        # "Protections table is empty" when given a depot path to
        # 'p4 protects -m -u'. Surprise!
        if p4gf_p4msg.find_all_msgid(
                p4,
            [p4gf_p4msgid.MsgDm_ProtectsEmpty, p4gf_p4msgid.MsgDm_ReferClient
             ]):
            is_protects_empty = True
        # All other errors are fatal, propagated.

    if is_protects_empty:
        # - order the lines in increasing permission
        # - end with at least one user (even a not-yet-created user) with super
        #     write user * * //...
        #     admin user git-fusion-user * //...
        #     super user super * //...
        p4gf_util.set_spec(p4,
                           'protect',
                           values={
                               'Protections': [
                                   "super user * * //...",
                                   "super user {user} * //...".format(
                                       user=p4gf_const.P4GF_USER),
                                   "admin user {user} * //{depot}/...".format(
                                       user=p4gf_const.P4GF_USER,
                                       depot=p4gf_const.P4GF_DEPOT)
                               ]
                           })
        _info(_('Protects table set.'))