Ejemplo n.º 1
0
 def delete_row(self, button, listboxrow):
     del self.sections_dict[self.section_stack_map[listboxrow].get_name()]
     self.section_stack_map[listboxrow].destroy()
     del self.section_stack_map[listboxrow]
     listboxrow.destroy()
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 2
0
 def delete_row(self, button, listboxrow):
     del self.sections_dict[self.section_stack_map[listboxrow].get_name()]
     self.section_stack_map[listboxrow].destroy()
     del self.section_stack_map[listboxrow]
     listboxrow.destroy()
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 3
0
class ConfWriterTest(unittest.TestCase):
    example_file = ("to be ignored \n"
                    "    save=true\n"
                    "    a_default, another = val \n"
                    "    TEST = tobeignored  # thats a comment \n"
                    "    test = push \n"
                    "    t = \n"
                    "    [Section] \n"
                    "    [MakeFiles] \n"
                    "     j  , ANother = a \n"
                    "                   multiline \n"
                    "                   value \n"
                    "    ; just a omment \n"
                    "    ; just a omment \n"
                    "    key\\ space = value space\n"
                    "    key\\=equal = value=equal\n"
                    "    key\\\\backslash = value\\\\backslash\n"
                    "    key\\,comma = value,comma\n"
                    "    key\\#hash = value\\#hash\n"
                    "    key\\.dot = value.dot\n")

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), "ConfParserTestFile")
        with open(self.file, "w", encoding='utf-8') as file:
            file.write(self.example_file)

        self.conf_parser = ConfParser()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            "ConfWriterTestFile")
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = [
            "[Default]\n", "save = true\n", "a_default, another = val\n",
            "# thats a comment\n", "test = push\n", "t = \n", "[Section]\n",
            "[MakeFiles]\n", "j, ANother = a\n", "multiline\n", "value\n",
            "; just a omment\n", "; just a omment\n",
            "key\\ space = value space\n", "key\\=equal = value=equal\n",
            "key\\\\backslash = value\\\\backslash\n",
            "key\\,comma = value,comma\n", "key\\#hash = value\\#hash\n",
            "key\\.dot = value.dot\n"
        ]
        self.uut.write_sections(self.conf_parser.parse(self.file))
        self.uut.close()

        with open(self.write_file_name, "r") as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)
Ejemplo n.º 4
0
 def update_section_name(self, widget, arg, old_name, section_view):
     section_view.set_name(widget.get_name())
     self.sections_dict[old_name].name = widget.get_name()
     self.sections_dict = update_ordered_dict_key(self.sections_dict,
                                                  old_name,
                                                  widget.get_name())
     widget.connect("edited", self.update_section_name, widget.get_name())
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 5
0
 def update_section_name(self, widget, arg, old_name, section_view):
     section_view.set_name(widget.get_name())
     self.sections_dict[old_name].name = widget.get_name()
     self.sections_dict = update_ordered_dict_key(self.sections_dict,
                                                  old_name,
                                                  widget.get_name())
     widget.connect("edited", self.update_section_name, widget.get_name())
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 6
0
 def on_key_changed(self, widget, arg, sensitive_button, value_entry):
     setting = Setting(widget.get_name(), value_entry.get_text())
     self.sections_dict[self.get_name()].append(setting)
     self.add_setting()
     sensitive_button.set_sensitive(True)
     sensitive_button.set_name(setting.key)
     widget.connect("edited", self.update_key, setting, sensitive_button)
     value_entry.connect("focus-out-event", self.update_value, setting)
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 7
0
 def on_key_changed(self, widget, arg, sensitive_button, value_entry):
     setting = Setting(widget.get_name(), value_entry.get_text())
     self.sections_dict[self.get_name()].append(setting)
     self.add_setting()
     sensitive_button.set_sensitive(True)
     sensitive_button.set_name(setting.key)
     widget.connect("edited", self.update_key, setting, sensitive_button)
     value_entry.connect("focus-out-event", self.update_value, setting)
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 8
0
class ConfWriterTest(unittest.TestCase):
    example_file = ("to be ignored \n"
                    "    save=true\n"
                    "    a_default, another = val \n"
                    "    TEST = tobeignored  # thats a comment \n"
                    "    test = push \n"
                    "    t = \n"
                    "    [MakeFiles] \n"
                    "     j  , ANother = a \n"
                    "                   multiline \n"
                    "                   value \n"
                    "    ; just a omment \n"
                    "    ; just a omment \n")

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), "ConfParserTestFile")
        with open(self.file, "w", encoding='utf-8') as filehandler:
            filehandler.write(self.example_file)

        self.conf_parser = ConfParser()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            "ConfWriterTestFile")
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = ["[Default]\n",
                       "save = true\n",
                       "a_default, another = val\n",
                       "# thats a comment\n",
                       "test = push\n",
                       "t = \n",
                       "\n",
                       "[MakeFiles]\n",
                       "j, ANother = a\n",
                       "multiline\n",
                       "value\n",
                       "; just a omment\n",
                       "; just a omment\n"]
        self.uut.write_sections(self.conf_parser.parse(self.file))
        self.uut.close()

        with open(self.write_file_name, "r") as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)
Ejemplo n.º 9
0
class SettingsTest(unittest.TestCase):

    def setUp(self):
        self.project_dir = os.getcwd()
        self.printer = ConsolePrinter()
        self.coafile = os.path.join(tempfile.gettempdir(), '.coafile')
        self.writer = ConfWriter(self.coafile)
        self.arg_parser = _get_arg_parser()
        self.old_argv = deepcopy(sys.argv)
        del sys.argv[1:]

    def tearDown(self):
        self.writer.close()
        os.remove(self.coafile)
        sys.argv = self.old_argv

    def test_write_info(self):
        result_date = date.today().strftime("%d %b %Y")
        result_comment = ('# Generated by coala-quickstart on '
                          '{date}.\n'.format(date=result_date))
        write_info(self.writer)
        self.writer.close()

        with open(self.coafile, 'r') as f:
            line = f.readline()

        self.assertEqual(result_comment, line)

    def test_allow_complete_section_mode(self):
        project_dir = "/repo"
        project_files = ['/repo/hello.html']
        ignore_globs = []

        used_languages = list(get_used_languages(project_files))
        relevant_bears = filter_relevant_bears(
            used_languages, self.printer, self.arg_parser, {})

        res = generate_settings(
            project_dir, project_files, ignore_globs, relevant_bears, {}, True)

        bears_list = res["all.HTML"]["bears"].value.replace(" ", "").split(",")

        files_list = res["all.HTML"]["files"].value.replace(" ", "").split(",")

        self.assertEqual(
            ['HTMLLintBear', 'coalaBear', 'BootLintBear',
             'LicenseCheckBear', 'SpaceConsistencyBear', 'KeywordBear',
             'LineLengthBear', 'DuplicateFileBear'].sort(),
            bears_list.sort())

        self.assertEqual(['**.html'], files_list)
Ejemplo n.º 10
0
 def create_section_view(self, widget=None, arg=None, row_obejct=None):
     section_view = SectionView(self.sections_dict, self.src)
     section_view.set_visible(True)
     section_view.set_name(widget.get_name())
     self.sections.add_named(section_view, widget.get_name())
     self.sections.set_visible_child_name(widget.get_name())
     if arg is not None:
         widget.connect("edited", self.update_section_name,
                        widget.get_name(), section_view)
         self.sections_dict[widget.get_name()] = Section(widget.get_name())
         section_view.add_setting()
         conf_writer = ConfWriter(self.src + '/.coafile')
         conf_writer.write_sections(self.sections_dict)
         conf_writer.close()
     self.section_stack_map[row_obejct] = section_view
Ejemplo n.º 11
0
 def create_section_view(self, widget=None, arg=None, row_obejct=None):
     section_view = SectionView(self.sections_dict, self.src)
     section_view.set_visible(True)
     section_view.set_name(widget.get_name())
     self.sections.add_named(section_view, widget.get_name())
     self.sections.set_visible_child_name(widget.get_name())
     if arg is not None:
         widget.connect("edited",
                        self.update_section_name,
                        widget.get_name(),
                        section_view)
         self.sections_dict[widget.get_name()] = Section(widget.get_name())
         section_view.add_setting()
         conf_writer = ConfWriter(self.src+'/.coafile')
         conf_writer.write_sections(self.sections_dict)
         conf_writer.close()
     self.section_stack_map[row_obejct] = section_view
Ejemplo n.º 12
0
def save_sections(sections):
    """
    Saves the given sections if they are to be saved.

    :param sections: A section dict.
    """
    default_section = sections["default"]
    try:
        if bool(default_section.get("save", "false")):
            conf_writer = ConfWriter(str(default_section.get("config", ".coafile")))
        else:
            return
    except ValueError:
        conf_writer = ConfWriter(str(default_section.get("save", ".coafile")))

    conf_writer.write_sections(sections)
    conf_writer.close()
Ejemplo n.º 13
0
def save_sections(sections):
    """
    Saves the given sections if they are to be saved.

    :param sections: A section dict.
    """
    default_section = sections["default"]
    try:
        if bool(default_section.get("save", "false")):
            conf_writer = ConfWriter(
                str(default_section.get("config", Constants.default_coafile)))
        else:
            return
    except ValueError:
        conf_writer = ConfWriter(str(default_section.get("save", ".coafile")))

    conf_writer.write_sections(sections)
    conf_writer.close()
Ejemplo n.º 14
0
def save_sections(sections):
    """
    Saves the given sections if they are to be saved.

    :param sections: A section dict.
    """
    default_section = sections['cli']
    try:
        if bool(default_section.get('save', 'false')):
            conf_writer = ConfWriter(
                str(default_section.get('config', Constants.local_coafile)))
        else:
            return
    except ValueError:
        conf_writer = ConfWriter(str(default_section.get('save', '.coafile')))

    conf_writer.write_sections(sections)
    conf_writer.close()
Ejemplo n.º 15
0
def save_sections(sections):
    """
    Saves the given sections if they are to be saved.

    :param sections: A section dict.
    """
    default_section = sections['default']
    try:
        if bool(default_section.get('save', 'false')):
            conf_writer = ConfWriter(
                str(default_section.get('config', Constants.default_coafile)))
        else:
            return
    except ValueError:
        conf_writer = ConfWriter(str(default_section.get('save', '.coafile')))

    conf_writer.write_sections(sections)
    conf_writer.close()
Ejemplo n.º 16
0
class SettingsTest(unittest.TestCase):
    def setUp(self):
        self.coafile = os.path.join(tempfile.gettempdir(), '.coafile')
        self.writer = ConfWriter(self.coafile)

    def tearDown(self):
        self.writer.close()
        os.remove(self.coafile)

    def test_write_info(self):
        result_date = date.today().strftime("%d %b %Y")
        result_comment = ('# Generated by coala-quickstart on '
                          '{date}.\n'.format(date=result_date))
        write_info(self.writer)
        self.writer.close()

        with open(self.coafile, 'r') as f:
            line = f.readline()

        self.assertEqual(result_comment, line)
Ejemplo n.º 17
0
def write_coafile(printer, project_dir, settings):
    """
    Writes the coafile to disk.

    :param printer:
        A ``ConsolePrinter`` object used for console interactions.
    :param project_dir:
        Full path of the user's project directory.
    :param settings:
        A dict with section name as key and a ``Section`` object as value.
    """
    coafile = os.path.join(project_dir, ".coafile")
    if os.path.isfile(coafile):
        printer.print("'" + coafile + "' already exists.\nThe settings will be"
                      " written to '" + coafile + ".new'",
                      color="yellow")
        coafile = coafile + ".new"

    writer = ConfWriter(coafile)
    writer.write_sections(settings)
    writer.close()

    printer.print("'" + coafile + "' successfully generated.", color="green")
Ejemplo n.º 18
0
 def update_key(self, widget, arg, setting, delete_button):
     setting.key = widget.get_name()
     delete_button.set_name(widget.get_name())
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 19
0
class SettingsTest(unittest.TestCase):

    def path_leaf(self, path):
        """
        :return: The file name from the given path.
        """
        head, tail = os.path.split(path)
        return tail or os.path.basename(head)

    def setUp(self):
        self.project_dir = os.getcwd()
        self.printer = ConsolePrinter()
        self.coafile = os.path.join(tempfile.gettempdir(), '.coafile')
        self.writer = ConfWriter(self.coafile)
        self.arg_parser = _get_arg_parser()
        self.old_argv = deepcopy(sys.argv)
        del sys.argv[1:]

    def tearDown(self):
        self.writer.close()
        os.remove(self.coafile)
        sys.argv = self.old_argv

    def test_write_info(self):
        result_date = date.today().strftime("%d %b %Y")
        result_comment = ('# Generated by coala-quickstart on '
                          '{date}.\n'.format(date=result_date))
        write_info(self.writer)
        self.writer.close()

        with open(self.coafile, 'r') as f:
            line = f.readline()

        self.assertEqual(result_comment, line)

    def test_allow_complete_section_mode_with_ignore_globs(self):
        project_dir = "/repo"
        project_files = ['/repo/hello.html']
        ignore_globs = ["/repo/style.css"]
        used_languages = list(get_used_languages(project_files))
        relevant_bears = filter_relevant_bears(
            used_languages, self.printer, self.arg_parser, {})

        res = generate_settings(
            project_dir, project_files, ignore_globs, relevant_bears, {}, True)

        bears_list = res["all.HTML"]["bears"].value.replace(" ", "").split(",")

        files_list = res["all.HTML"]["files"].value.replace(" ", "").split(",")

        self.assertEqual(
            ['HTMLLintBear', 'coalaBear', 'BootLintBear',
             'LicenseCheckBear', 'SpaceConsistencyBear', 'KeywordBear',
             'LineLengthBear', 'DuplicateFileBear'].sort(),
            bears_list.sort())

        ignore_file = str(os.path.normpath(self.path_leaf(
            str(res["all"]["ignore"]))))
        self.assertEqual(['**.html'], files_list)
        self.assertEqual('style.css', ignore_file)

    def test_allow_complete_section_mode(self):
        project_dir = "/repo"
        project_files = ['/repo/hello.html']
        ignore_globs = []

        used_languages = list(get_used_languages(project_files))
        relevant_bears = filter_relevant_bears(
            used_languages, self.printer, self.arg_parser, {})

        res = generate_settings(
            project_dir, project_files, ignore_globs, relevant_bears, {}, True)

        bears_list = res["all.HTML"]["bears"].value.replace(" ", "").split(",")

        files_list = res["all.HTML"]["files"].value.replace(" ", "").split(",")

        self.assertEqual(
            ['HTMLLintBear', 'coalaBear', 'BootLintBear',
             'LicenseCheckBear', 'SpaceConsistencyBear', 'KeywordBear',
             'LineLengthBear', 'DuplicateFileBear'].sort(),
            bears_list.sort())

        self.assertEqual(['**.html'], files_list)
Ejemplo n.º 20
0
def generate_green_mode_sections(data,
                                 project_dir,
                                 project_files,
                                 ignore_globs,
                                 printer=None,
                                 suffix=''):
    """
    Generates the section objects for the green_mode.
    :param data:
        This is the data structure generated from the method
        generate_data_struct_for_sections().
    :param project_dir:
        The path of the project directory.
    :param project_files:
        List of paths to only the files inside the project directory.
    :param ignore_globs:
        The globs of files to ignore.
    :param printer:
        The ConsolePrinter object.
    :param suffix:
        A suffix that can be added to the `.coafile.green`.
    """
    all_sections = {
        'all': [],
    }
    lang_files = split_by_language(project_files)
    extset = get_extensions(project_files)
    ignored_files = generate_ignore_field(project_dir, lang_files.keys(),
                                          extset, ignore_globs)
    if ignored_files:
        section_all = Section('all')
        section_all['ignore'] = ignored_files
        all_sections['all'].append(section_all)

    for bear in data:
        num = 0
        bear_sections = []
        for setting_combs in data[bear]:
            if not setting_combs:
                continue
            for dict_ in setting_combs:
                num = num + 1
                section = Section('all.' + bear.__name__ + str(num), None)
                for key_ in dict_:
                    if key_ == 'filename':
                        file_list_sec = dict_[key_]
                        file_list_sec, ignore_list = aggregate_files(
                            file_list_sec, project_dir)
                        dict_[key_] = file_list_sec
                        section['ignore'] = ', '.join(
                            escape(x, '\\') for x in ignore_list)
                        section['files'] = ', '.join(
                            escape(x, '\\') for x in dict_[key_])
                    else:
                        section[key_] = str(dict_[key_])
                    section['bears'] = bear.__name__
                bear_sections.append(section)
        # Remove sections for the same bear who have common files i.e. more
        # than one setting was found to be green.
        file_list = []
        new_bear_sections = []
        for index, section in enumerate(bear_sections):
            if not section.contents['files'] in file_list:
                file_list.append(section.contents['files'])
                new_bear_sections.append(section)
        all_sections[bear.__name__] = new_bear_sections

    coafile = os.path.join(project_dir, '.coafile.green' + suffix)
    writer = ConfWriter(coafile)
    write_sections(writer, all_sections)
    writer.close()
    printer.print("'" + coafile + "' successfully generated.", color='green')
Ejemplo n.º 21
0
 def update_value(self, widget, arg, setting):
     setting.value = widget.get_text()
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 22
0
class ConfWriterTest(unittest.TestCase):
    example_file = ('to be ignored \n'
                    '    save=true\n'
                    '    a_default, another = val \n'
                    '    TEST = tobeignored  # thats a comment \n'
                    '    test = push \n'
                    '    t = \n'
                    '    [Section] \n'
                    '    [MakeFiles] \n'
                    '     j  , ANother = a \n'
                    '                   multiline \n'
                    '                   value \n'
                    '    ; just a omment \n'
                    '    ; just a omment \n'
                    '    key\\ space = value space\n'
                    '    key\\=equal = value=equal\n'
                    '    key\\\\backslash = value\\\\backslash\n'
                    '    key\\,comma = value,comma\n'
                    '    key\\#hash = value\\#hash\n'
                    '    key\\.dot = value.dot\n'
                    '    a_default = val, val2\n')

    append_example_file = ('[defaults]\n'
                           'a = 4\n'
                           'b = 4,5,6\n'
                           'c = 4,5\n'
                           'd = 4\n'
                           '[defaults.new]\n'
                           'a = 4,5,6,7\n'
                           'b = 4,5,6,7\n'
                           'c = 4,5,6,7\n'
                           'd = 4,5,6,7\n')

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), 'ConfParserTestFile')
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.example_file)

        self.log_printer = LogPrinter()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            'ConfWriterTestFile')
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = ['[Section]\n',
                       '[MakeFiles]\n',
                       'j, ANother = a\n',
                       'multiline\n',
                       'value\n',
                       '; just a omment\n',
                       '; just a omment\n',
                       'key\\ space = value space\n',
                       'key\\=equal = value=equal\n',
                       'key\\\\backslash = value\\\\backslash\n',
                       'key\\,comma = value,comma\n',
                       'key\\#hash = value\\#hash\n',
                       'key\\.dot = value.dot\n',
                       'a_default += val2\n',
                       '[cli]\n',
                       'save = true\n',
                       'a_default, another = val\n',
                       '# thats a comment\n',
                       'test = push\n',
                       't = \n']
        sections = load_configuration(['-c', escape(self.file, '\\')],
                                      self.log_printer)[0]
        del sections['cli'].contents['config']
        self.uut.write_sections(sections)
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)

    def test_append(self):
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.append_example_file)

        result_file = ['[defaults]\n',
                       'a = 4\n',
                       'b = 4,5,6\n',
                       'c = 4,5\n',
                       'd = 4\n',
                       '[defaults.new]\n',
                       'b += 7\n',
                       'c += 6, 7\n',
                       'a, d += 5, 6, 7\n',
                       '[cli]\n']

        sections = load_configuration(['-c', escape(self.file, '\\')],
                                      self.log_printer)[0]
        del sections['cli'].contents['config']
        self.uut.write_sections(sections)
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)

    def test_write_with_dir(self):
        self.uut_dir = ConfWriter(tempfile.gettempdir())
        self.uut_dir.write_sections({'name': Section('name')})
        self.uut_dir.close()

        with open(os.path.join(tempfile.gettempdir(), '.coafile'), 'r') as f:
            lines = f.readlines()

        self.assertEqual(['[name]\n'], lines)
        os.remove(os.path.join(tempfile.gettempdir(), '.coafile'))
Ejemplo n.º 23
0
 def update_key(self, widget, arg, setting, delete_button):
     setting.key = widget.get_name()
     delete_button.set_name(widget.get_name())
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 24
0
 def delete_setting(self, button, setting_row):
     self.sections_dict[self.get_name()].delete_setting(button.get_name())
     setting_row.destroy()
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 25
0
 def delete_setting(self, button, setting_row):
     self.sections_dict[self.get_name()].delete_setting(button.get_name())
     setting_row.destroy()
     conf_writer = ConfWriter(self.src+'/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 26
0
class ConfWriterTest(unittest.TestCase):
    example_file = ('to be ignored \n'
                    '    save=true\n'
                    '    a_default, another = val \n'
                    '    TEST = tobeignored  # thats a comment \n'
                    '    test = push \n'
                    '    t = \n'
                    '    [Section] \n'
                    '    [MakeFiles] \n'
                    '     j  , ANother = a \n'
                    '                   multiline \n'
                    '                   value \n'
                    '    ; just a omment \n'
                    '    ; just a omment \n'
                    '    key\\ space = value space\n'
                    '    key\\=equal = value=equal\n'
                    '    key\\\\backslash = value\\\\backslash\n'
                    '    key\\,comma = value,comma\n'
                    '    key\\#hash = value\\#hash\n'
                    '    key\\.dot = value.dot\n')

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), 'ConfParserTestFile')
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.example_file)

        self.conf_parser = ConfParser()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            'ConfWriterTestFile')
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = ['[Default]\n',
                       'save = true\n',
                       'a_default, another = val\n',
                       '# thats a comment\n',
                       'test = push\n',
                       't = \n',
                       '[Section]\n',
                       '[MakeFiles]\n',
                       'j, ANother = a\n',
                       'multiline\n',
                       'value\n',
                       '; just a omment\n',
                       '; just a omment\n',
                       'key\\ space = value space\n',
                       'key\\=equal = value=equal\n',
                       'key\\\\backslash = value\\\\backslash\n',
                       'key\\,comma = value,comma\n',
                       'key\\#hash = value\\#hash\n',
                       'key\\.dot = value.dot\n']
        self.uut.write_sections(self.conf_parser.parse(self.file))
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)
Ejemplo n.º 27
0
def generate_green_mode_sections(data, project_dir, project_files,
                                 ignore_globs, printer=None, suffix=''):
    """
    Generates the section objects for the green_mode.
    :param data:
        This is the data structure generated from the method
        generate_data_struct_for_sections().
    :param project_dir:
        The path of the project directory.
    :param project_files:
        List of paths to only the files inside the project directory.
    :param ignore_globs:
        The globs of files to ignore.
    :param printer:
        The ConsolePrinter object.
    :param suffix:
        A suffix that can be added to the `.coafile.green`.
    """
    all_sections = {'all': [], }
    lang_files = split_by_language(project_files)
    extset = get_extensions(project_files)
    ignored_files = generate_ignore_field(project_dir, lang_files.keys(),
                                          extset, ignore_globs)
    if ignored_files:
        section_all = Section('all')
        section_all['ignore'] = ignored_files
        all_sections['all'].append(section_all)

    for bear in data:
        num = 0
        bear_sections = []
        for setting_combs in data[bear]:
            if not setting_combs:
                continue
            for dict_ in setting_combs:
                num = num + 1
                section = Section('all.' + bear.__name__ + str(num), None)
                for key_ in dict_:
                    if key_ == 'filename':
                        file_list_sec = dict_[key_]
                        file_list_sec, ignore_list = aggregate_files(
                            file_list_sec, project_dir)
                        dict_[key_] = file_list_sec
                        section['ignore'] = ', '.join(
                            escape(x, '\\') for x in ignore_list)
                        section['files'] = ', '.join(
                            escape(x, '\\') for x in dict_[key_])
                    else:
                        section[key_] = str(dict_[key_])
                    section['bears'] = bear.__name__
                bear_sections.append(section)
        # Remove sections for the same bear who have common files i.e. more
        # than one setting was found to be green.
        file_list = []
        new_bear_sections = []
        for index, section in enumerate(bear_sections):
            if not section.contents['files'] in file_list:
                file_list.append(section.contents['files'])
                new_bear_sections.append(section)
        all_sections[bear.__name__] = new_bear_sections

    coafile = os.path.join(project_dir, '.coafile.green' + suffix)
    writer = ConfWriter(coafile)
    write_sections(writer, all_sections)
    writer.close()
    printer.print("'" + coafile + "' successfully generated.", color='green')
Ejemplo n.º 28
0
 def update_value(self, widget, arg, setting):
     setting.value = widget.get_text()
     conf_writer = ConfWriter(self.src + '/.coafile')
     conf_writer.write_sections(self.sections_dict)
     conf_writer.close()
Ejemplo n.º 29
0
class ConfWriterTest(unittest.TestCase):
    example_file = ('to be ignored \n'
                    '    save=true\n'
                    '    a_default, another = val \n'
                    '    TEST = tobeignored  # thats a comment \n'
                    '    test = push \n'
                    '    t = \n'
                    '    [Section] \n'
                    '    [MakeFiles] \n'
                    '     j  , ANother = a \n'
                    '                   multiline \n'
                    '                   value \n'
                    '    ; just a omment \n'
                    '    ; just a omment \n'
                    '    key\\ space = value space\n'
                    '    key\\=equal = value=equal\n'
                    '    key\\\\backslash = value\\\\backslash\n'
                    '    key\\,comma = value,comma\n'
                    '    key\\#hash = value\\#hash\n'
                    '    key\\.dot = value.dot\n'
                    '    a_default = val, val2\n')

    append_example_file = ('[defaults]\n'
                           'a = 4\n'
                           'b = 4,5,6\n'
                           'c = 4,5\n'
                           'd = 4\n'
                           '[defaults.new]\n'
                           'a = 4,5,6,7\n'
                           'b = 4,5,6,7\n'
                           'c = 4,5,6,7\n'
                           'd = 4,5,6,7\n')

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), 'ConfParserTestFile')
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.example_file)

        self.log_printer = LogPrinter()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            'ConfWriterTestFile')
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = [
            '[Section]\n', '[MakeFiles]\n', 'j, ANother = a\n', 'multiline\n',
            'value\n', '; just a omment\n', '; just a omment\n',
            'key\\ space = value space\n', 'key\\=equal = value=equal\n',
            'key\\\\backslash = value\\\\backslash\n',
            'key\\,comma = value,comma\n', 'key\\#hash = value\\#hash\n',
            'key\\.dot = value.dot\n', 'a_default += val2\n', '[cli]\n',
            'save = true\n', 'a_default, another = val\n',
            '# thats a comment\n', 'test = push\n', 't = \n'
        ]
        sections = load_configuration(['-c', escape(self.file, '\\')],
                                      self.log_printer)[0]
        del sections['cli'].contents['config']
        self.uut.write_sections(sections)
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)

    def test_append(self):
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.append_example_file)

        result_file = [
            '[defaults]\n', 'a = 4\n', 'b = 4,5,6\n', 'c = 4,5\n', 'd = 4\n',
            '[defaults.new]\n', 'b += 7\n', 'c += 6, 7\n', 'a, d += 5, 6, 7\n',
            '[cli]\n'
        ]

        sections = load_configuration(['-c', escape(self.file, '\\')],
                                      self.log_printer)[0]
        del sections['cli'].contents['config']
        self.uut.write_sections(sections)
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)

    def test_write_with_dir(self):
        self.uut_dir = ConfWriter(tempfile.gettempdir())
        self.uut_dir.write_sections({'name': Section('name')})
        self.uut_dir.close()

        with open(os.path.join(tempfile.gettempdir(), '.coafile'), 'r') as f:
            lines = f.readlines()

        self.assertEqual(['[name]\n'], lines)
        os.remove(os.path.join(tempfile.gettempdir(), '.coafile'))