<commit_before># Write interface
import shutil
from string import Template
import toolutils


class InterfacesWriter:
    ''' Short lived class to write interfaces file '''

    # Define templetes for blocks used in /etc/network/interfaces.
    _auto = Template('auto $name\n')
    _hotplug = Template('allow-hotplug $name\n')
    _iface = Template('iface $name $addrFam $source\n')
    _cmd = Template('\t$varient $value\n')

    _addressFields = ['address', 'network', 'netmask', 'broadcast', 'gateway', 'dns-nameservers']
    _prepFields = ['pre-up', 'up', 'down', 'post-down']
    _bridgeFields = ['ports', 'fd', 'hello', 'maxage', 'stp']
    _plugins = ["hostapd"]

    def __init__(self, adapters, interfaces_path, backup_path=None):
        ''' if backup_path is None => no backup '''
        self._adapters = adapters
        self._interfaces_path = interfaces_path
        self._backup_path = backup_path

    @property
    def adapters(self):
        return self._adapters

    @adapters.setter
    def adapters(self, value):
        self._adapters = value

    def write_interfaces(self):
        # Back up the old interfaces file.
        self._backup_interfaces()

        try:
            # Prepare to write the new interfaces file.
            with toolutils.atomic_write(self._interfaces_path) as interfaces:
                # Loop through the provided networkAdaprers and write the new file.
                for adapter in self._adapters:
                    # Get dict of details about the adapter.
                    self._write_adapter(interfaces, adapter)
            self._check_interfaces(self._interfaces_path)
        except Exception as ex:
            # Any error, let's roll back
            self._restore_interfaces()
            raise


    def _check_interfaces(self, interfaces_path):
        """Uses ifup to check interfaces file. If it is not in the default place,
        each interface must be checked one by one.
            Args:
                interfaces_path (string) : the path to interfaces file

            Raises:
                ValueError : if invalid network interfaces
        """
        if interfaces_path == "/etc/network/interfaces":
            ret, output = toolutils.safe_subprocess(["ifup", "-a", "--no-act"])
        else:
            for adapter in self._adapters:
                ret, output = toolutils.safe_subprocess([
                    "ifup", "--no-act",
                    "interfaces={}".format(interfaces_path),
                    adapter.attributes["name"]
                ])
                if not ret:
                    break
        if not ret:
            raise ValueError("Invalid network interfaces file written to disk, restoring to previous one : {}".format(output))

    def _write_adapter(self, interfaces, adapter):
        try:
            adapter.validateAll()
        except ValueError as e:
            print(e.message)
            raise

        ifAttributes = adapter.export()

        self._write_auto(interfaces, adapter, ifAttributes)
        self._write_hotplug(interfaces, adapter, ifAttributes)
        self._write_addrFam(interfaces, adapter, ifAttributes)
        self._write_addressing(interfaces, adapter, ifAttributes)
        self._write_bridge(interfaces, adapter, ifAttributes)
        self._write_plugins(interfaces, adapter, ifAttributes)
        self._write_callbacks(interfaces, adapter, ifAttributes)<commit_msg>Print repr of e instead of message<commit_after># Write interface
import shutil
from string import Template
import toolutils


class InterfacesWriter:
    ''' Short lived class to write interfaces file '''

    # Define templetes for blocks used in /etc/network/interfaces.
    _auto = Template('auto $name\n')
    _hotplug = Template('allow-hotplug $name\n')
    _iface = Template('iface $name $addrFam $source\n')
    _cmd = Template('\t$varient $value\n')

    _addressFields = ['address', 'network', 'netmask', 'broadcast', 'gateway', 'dns-nameservers']
    _prepFields = ['pre-up', 'up', 'down', 'post-down']
    _bridgeFields = ['ports', 'fd', 'hello', 'maxage', 'stp']
    _plugins = ["hostapd"]

    def __init__(self, adapters, interfaces_path, backup_path=None):
        ''' if backup_path is None => no backup '''
        self._adapters = adapters
        self._interfaces_path = interfaces_path
        self._backup_path = backup_path

    @property
    def adapters(self):
        return self._adapters

    @adapters.setter
    def adapters(self, value):
        self._adapters = value

    def write_interfaces(self):
        # Back up the old interfaces file.
        self._backup_interfaces()

        try:
            # Prepare to write the new interfaces file.
            with toolutils.atomic_write(self._interfaces_path) as interfaces:
                # Loop through the provided networkAdaprers and write the new file.
                for adapter in self._adapters:
                    # Get dict of details about the adapter.
                    self._write_adapter(interfaces, adapter)
            self._check_interfaces(self._interfaces_path)
        except Exception as ex:
            # Any error, let's roll back
            self._restore_interfaces()
            raise


    def _check_interfaces(self, interfaces_path):
        """Uses ifup to check interfaces file. If it is not in the default place,
        each interface must be checked one by one.
            Args:
                interfaces_path (string) : the path to interfaces file

            Raises:
                ValueError : if invalid network interfaces
        """
        if interfaces_path == "/etc/network/interfaces":
            ret, output = toolutils.safe_subprocess(["ifup", "-a", "--no-act"])
        else:
            for adapter in self._adapters:
                ret, output = toolutils.safe_subprocess([
                    "ifup", "--no-act",
                    "interfaces={}".format(interfaces_path),
                    adapter.attributes["name"]
                ])
                if not ret:
                    break
        if not ret:
            raise ValueError("Invalid network interfaces file written to disk, restoring to previous one : {}".format(output))

    def _write_adapter(self, interfaces, adapter):
        try:
            adapter.validateAll()
        except ValueError as e:
            print(repr(e))
            raise

        ifAttributes = adapter.export()

        self._write_auto(interfaces, adapter, ifAttributes)
        self._write_hotplug(interfaces, adapter, ifAttributes)
        self._write_addrFam(interfaces, adapter, ifAttributes)
        self._write_addressing(interfaces, adapter, ifAttributes)
        self._write_bridge(interfaces, adapter, ifAttributes)
        self._write_plugins(interfaces, adapter, ifAttributes)
        self._write_callbacks(interfaces, adapter, ifAttributes)
{'fraction_non_alphanumeric': 0.09419129422041055, 'fraction_numerical': 0.0, 'mean_word_length': 2.28080229226361, 'pattern_counts': {'":': 2, '<': 3, '<?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': '5427550', 'n_tokens_mistral': 1885, 'n_tokens_neox': 1778, 'n_words': 523}