<commit_before>import contextlib
import getpass
import logging
import os

logger = logging.getLogger(__name__)


@contextlib.contextmanager
def dropped_privileges(passwd, group):
    """
    Context manager for temporarily switching real and effective UID and real
    and effective GID.
    """
    logger.debug("Dropping privileges temporary to user %s and group %s",
                 passwd.pw_name, group.gr_name)
    # To handle multiple users with the same UID correctly, we obtain the
    # current user name with getpass
    saved_user = getpass.getuser()
    saved_uid = os.geteuid()
    saved_gid = os.getegid()
    os.setresgid(group.gr_gid, group.gr_gid, saved_gid)
    os.initgroups(passwd.pw_name, group.gr_gid)
    os.setresuid(passwd.pw_uid, passwd.pw_uid, saved_uid)
    yield
    os.seteuid(saved_uid)
    os.setreuid(saved_uid, saved_uid)
    os.setregid(saved_gid, saved_gid)
    os.initgroups(saved_user, saved_gid)
    logger.debug("Restoring previous privileges as user %s", saved_user)<commit_msg>Restore privileges if exception occurs<commit_after>import contextlib
import getpass
import logging
import os

logger = logging.getLogger(__name__)


@contextlib.contextmanager
def dropped_privileges(passwd, group):
    """
    Context manager for temporarily switching real and effective UID and real
    and effective GID.
    """
    logger.debug("Dropping privileges temporary to user %s and group %s",
                 passwd.pw_name, group.gr_name)
    # To handle multiple users with the same UID correctly, we obtain the
    # current user name with getpass
    saved_user = getpass.getuser()
    saved_uid = os.geteuid()
    saved_gid = os.getegid()
    os.setresgid(group.gr_gid, group.gr_gid, saved_gid)
    os.initgroups(passwd.pw_name, group.gr_gid)
    os.setresuid(passwd.pw_uid, passwd.pw_uid, saved_uid)
    try:
        yield
    finally:
        os.seteuid(saved_uid)
        os.setreuid(saved_uid, saved_uid)
        os.setregid(saved_gid, saved_gid)
        os.initgroups(saved_user, saved_gid)
        logger.debug("Restoring previous privileges as user %s", saved_user)
{'fraction_non_alphanumeric': 0.08424041646947468, 'fraction_numerical': 0.0, 'mean_word_length': 3.585683297180043, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4799067', 'n_tokens_mistral': 695, 'n_tokens_neox': 669, 'n_words': 175}