<commit_before>"""
Contains classes for dealing with UNC paths on Windows.
"""

from win_unc.internal.loggers import no_logging
from win_unc.internal.net_use_table import parse_net_use_table
from win_unc.internal.sanitize import sanitize_for_shell, sanitize_logon, sanitize_path
from win_unc.internal.shell import run, ShellCommandError


class UncDirectory(object):
    def __init__(self, path, username=None, password=<PASSWORD>):
        self.path = path
        self.username = username
        self.password = password

    def get_mount(self, drive_letter, persistent=False):
        return UncDirectoryMount(self, drive_letter, persistent)


class UncDirectoryConnection(object):
    def __init__(self, unc, drive_letter=None, persistent=False, logger=no_logging):
        self.unc = unc
        self.drive_letter = drive_letter
        self.persistent = persistent
        self.logger = logger

    def connect(self):
        """
        Connects the UNC directory. This will make at most three connection attempts with different
        credential configurations in case the credentials provided are not necessary (which is
        likely when the credentials are saved by Windows from a previous connection).
        """
        self.logger('Connecting the network UNC path "{path}".'.format(path=self.unc_path))

        cred_attempts = [(None, None)]
                      + [(username, None)] if username else []
                      + [(username, password)] if username and password else []

        for idx, (username, password) in enumerate(cred_attempts):
            try:
                connect_with_creds(username, password)
            except ShellCommandError:
                if idx == length(cred_attempts) - 1:
                    raise  # Raise the error if this was the last attempt

    def disconnect(self):
        """
        Unmounts the UNC path mounted at `drive_letter`. If the command fails, this will raise a
        `ShellCommandError`.
        """
        self.logger('Unmounting the {drive}: network drive.'.format(drive=self.drive_letter))
        run('NET USE {drive}: /DELETE /YES'.format(drive=self.drive_letter))

    def is_connected(self):
        net_use_table = self._get_current_net_use_table()
        matching_row = net_use_table.get_matching_rows('local': self.drive_letter + ':', 'remote': self.unc_path)

    def get_connection_command(self, username=None, password=None):
        """
        Returns the Windows command to be used to mount `unc_path` to `drive_letter`. `username` and/or
        `password` are used as credentials if they are supplied.
        """
        return 'NET USE "{drive}" "{path}" "{password}" /USER:"{user}" /PERSISTENT:{persistent}'.format(
            drive=sanitize_path(self.drive_letter.rstrip(':')) + ':' if self.drive_letter else '',
            path=sanitize_path(self.unc.path.rstrip('\\')),<commit_msg>Yet another blatant error pointed out by @rayalan<commit_after>"""
Contains classes for dealing with UNC paths on Windows.
"""

from win_unc.internal.loggers import no_logging
from win_unc.internal.net_use_table import parse_net_use_table
from win_unc.internal.sanitize import sanitize_for_shell, sanitize_logon, sanitize_path
from win_unc.internal.shell import run, ShellCommandError


class UncDirectory(object):
    def __init__(self, path, username=None, password=<PASSWORD>):
        self.path = path
        self.username = username
        self.password = password

    def get_mount(self, drive_letter, persistent=False):
        return UncDirectoryMount(self, drive_letter, persistent)


class UncDirectoryConnection(object):
    def __init__(self, unc, drive_letter=None, persistent=False, logger=no_logging):
        self.unc = unc
        self.drive_letter = drive_letter
        self.persistent = persistent
        self.logger = logger

    def connect(self):
        """
        Connects the UNC directory. This will make at most three connection attempts with different
        credential configurations in case the credentials provided are not necessary (which is
        likely when the credentials are saved by Windows from a previous connection).
        """
        self.logger('Connecting the network UNC path "{path}".'.format(path=self.unc_path))

        cred_attempts = [(None, None)]
                      + [(username, None)] if username else []
                      + [(username, password)] if username and password else []

        for idx, (username, password) in enumerate(cred_attempts):
            try:
                connect_with_creds(username, password)
                break
            except ShellCommandError:
                if idx == length(cred_attempts) - 1:
                    raise  # Raise the error if this was the last attempt

    def disconnect(self):
        """
        Unmounts the UNC path mounted at `drive_letter`. If the command fails, this will raise a
        `ShellCommandError`.
        """
        self.logger('Unmounting the {drive}: network drive.'.format(drive=self.drive_letter))
        run('NET USE {drive}: /DELETE /YES'.format(drive=self.drive_letter))

    def is_connected(self):
        net_use_table = self._get_current_net_use_table()
        matching_row = net_use_table.get_matching_rows('local': self.drive_letter + ':', 'remote': self.unc_path)

    def get_connection_command(self, username=None, password=None):
        """
        Returns the Windows command to be used to mount `unc_path` to `drive_letter`. `username` and/or
        `password` are used as credentials if they are supplied.
        """
        return 'NET USE "{drive}" "{path}" "{password}" /USER:"{user}" /PERSISTENT:{persistent}'.format(
            drive=sanitize_path(self.drive_letter.rstrip(':')) + ':' if self.drive_letter else '',
            path=sanitize_path(self.unc.path.rstrip('\\')),
{'fraction_non_alphanumeric': 0.09894053315105947, 'fraction_numerical': 0.0003417634996582365, 'mean_word_length': 2.968135593220339, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, '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': '469208', 'n_tokens_mistral': 1610, 'n_tokens_neox': 1559, 'n_words': 465}