def load_config_file(filename, log_printer, silent=False): """ Loads sections from a config file. Prints an appropriate warning if it doesn't exist and returns a section dict containing an empty default section in that case. It assumes that the cli_sections are available. :param filename: The file to load settings from. :param log_printer: The log printer to log the warning/error to (in case). :param silent: Whether or not to warn the user/exit if the file doesn't exist. :raises SystemExit: Exits when the given filename is invalid and is not the default coafile. Only raised when ``silent`` is ``False``. """ filename = os.path.abspath(filename) try: return ConfParser().parse(filename) except FileNotFoundError: if not silent: if os.path.basename(filename) == Constants.default_coafile: log_printer.warn("The default coafile {0!r} was not found. " "You can generate a configuration file with " "your current options by adding the `--save` " "flag.".format(Constants.default_coafile)) else: log_printer.err( "The requested coafile {0!r} does not exist. " "You can generate it with your current " "options by adding the `--save` flag.".format(filename)) sys.exit(2) return {"default": Section("default")}
def load_config_file(filename, log_printer, silent=False): """ Loads sections from a config file. Prints an appropriate warning if it doesn't exist and returns a section dict containing an empty default section in that case. It assumes that the cli_sections are available. :param filename: The file to load settings from. :param log_printer: The log printer to log the warning/error to (in case). :param silent: Whether or not to warn the user/exit if the file doesn't exist. :raises SystemExit: Exits when given filename is invalid and is not the default coafile. Only raised when `silent` is `False`. """ filename = os.path.abspath(filename) try: return ConfParser().parse(filename) except FileNotFoundError: if not silent: if os.path.basename(filename) == Constants.default_coafile: log_printer.warn("The default coafile " + repr(Constants.default_coafile) + " was not " "found. Ignoring it.") else: log_printer.err("The requested coafile " + repr(filename) + " does not exist.") sys.exit(2) return {"default": Section("default")}
def load_config_file(filename, log_printer=None, silent=False): """ Loads sections from a config file. Prints an appropriate warning if it doesn't exist and returns a section dict containing an empty default section in that case. It assumes that the cli_sections are available. :param filename: The file to load settings from. :param log_printer: The log printer to log the warning/error to (in case). :param silent: Whether or not to warn the user/exit if the file doesn't exist. :raises SystemExit: Exits when the given filename is invalid and is not the default coafile. Only raised when ``silent`` is ``False``. """ filename = os.path.abspath(filename) try: return ConfParser().parse(filename) except FileNotFoundError: if not silent: if os.path.basename(filename) == Constants.default_coafile: logging.warning( COAFILE_OUTPUT.substitute(type='Default coafile', file=Constants.default_coafile, found='not found')) else: logging.error( COAFILE_OUTPUT.substitute(type='Requested coafile', file=filename, found='does not exist')) sys.exit(2) return {'default': Section('default')}
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 test_warning_typo(self): logger = logging.getLogger() with self.assertLogs(logger, 'WARNING') as cm: newConf = ConfParser(comment_seperators=('#', )) self.assertEquals( cm.output[0], 'WARNING:root:The setting ' '`comment_seperators` is deprecated. ' 'Please use `comment_separators` ' 'instead.')
def test_remove_empty_iter_elements(self): # Test with empty-elem stripping. uut = ConfParser(remove_empty_iter_elements=True) uut.parse(self.file) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]), ["a", "b", "c"]) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]), ["a", "d"]) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]), []) # Test without stripping. uut = ConfParser(remove_empty_iter_elements=False) uut.parse(self.file) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]), ["a", "b", "c"]) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]), ["a", "", "", "d"]) self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]), ["", "", "", ""])
def test_remove_empty_iter_elements(self): # Test with empty-elem stripping. uut = ConfParser(remove_empty_iter_elements=True) uut.parse(self.file) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']), ['a', 'b', 'c']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']), ['a', 'd']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']), []) # Test without stripping. uut = ConfParser(remove_empty_iter_elements=False) uut.parse(self.file) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']), ['a', 'b', 'c']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']), ['a', '', '', 'd']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']), ['', '', '', ''])
def __init__(self): self.cli_sections = None self.default_section = None self.conf_sections = None self.cli_parser = CliParser() self.conf_parser = ConfParser() self.conf_writer = None self.local_bears = {} self.global_bears = {}
def test_remove_empty_iter_elements(self): # Test with empty-elem stripping. uut = ConfParser(remove_empty_iter_elements=True) isnotdir = mock.Mock(return_value=False) with mock.patch('os.path.isdir', isnotdir): uut.parse(self.file) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']), ['a', 'b', 'c']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']), ['a', 'd']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']), []) # Test without stripping. uut = ConfParser(remove_empty_iter_elements=False) with mock.patch('os.path.isdir', isnotdir): uut.parse(self.file) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']), ['a', 'b', 'c']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']), ['a', '', '', 'd']) self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']), ['', '', '', ''])
def setUp(self): self.tempdir = tempfile.gettempdir() self.file = os.path.join(self.tempdir, '.coafile') self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t') with open(self.file, 'w') as file: file.write(self.example_file) self.uut = ConfParser() try: os.remove(self.nonexistentfile) except FileNotFoundError: pass self.sections = self.uut.parse(self.file)
def test_run(self): defaults = ConfParser().parse( os.path.abspath( os.path.join(StringConstants.coalib_root, "default_coafile"))) uut = SectionManager() # We need to use a bad filename or this will parse the .coafile we use for coala conf_sections = uut.run( arg_list=['-S', "test=5", "-c", "some_bad_filename"])[0] self.assertEqual(str(conf_sections["default"]), "Default {config : some_bad_filename, test : 5}") self.assertEqual(str(conf_sections["default"].defaults), str(defaults["default"]))
def load(cls, language: str, docstyle: str, coalang_dir=None): """ Loads a ``DocstyleDefinition`` from the coala docstyle definition files. This function considers all settings inside the according coalang-files as markers. :param language: The case insensitive programming language of the documentation comment as a string. :param docstyle: The case insensitive documentation style/tool used to document code, e.g. ``"default"`` or ``"doxygen"``. :param coalang_dir: Path to directory with coalang docstyle definition files. This replaces the default path if given. :raises FileNotFoundError: Raised when the given docstyle was not found. :raises KeyError: Raised when the given language is not defined for given docstyle. :return: The ``DocstyleDefinition`` for given language and docstyle. """ docstyle = docstyle.lower() language_config_parser = ConfParser(remove_empty_iter_elements=False) coalang_file = os.path.join(coalang_dir or os.path.dirname(__file__), docstyle + ".coalang") try: docstyle_settings = language_config_parser.parse(coalang_file) except FileNotFoundError: raise FileNotFoundError("Docstyle definition " + repr(docstyle) + " not found.") language = language.lower() try: docstyle_settings = docstyle_settings[language] except KeyError: raise KeyError( "Language {!r} is not defined for docstyle {!r}.".format( language, docstyle)) marker_sets = (tuple(value) for key, value in filter( lambda kv: not kv[0].startswith("comment"), docstyle_settings.contents.items())) return cls(language, docstyle, marker_sets)
def __init__(self): self.cli_sections = None self.default_sections = None self.user_sections = None self.coafile_sections = None self.sections = None self.cli_parser = CliParser() self.conf_parser = ConfParser() self.conf_writer = None self.local_bears = {} self.global_bears = {} self.targets = []
def setUp(self): self.tempdir = tempfile.gettempdir() self.file = os.path.join(self.tempdir, ".coafile") self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t") with open(self.file, "w") as filehandler: filehandler.write(self.example_file) self.uut = ConfParser() if sys.version_info < (3, 3): err = OSError else: err = FileNotFoundError try: os.remove(self.nonexistentfile) except err: pass
def get_available_definitions(): """ Returns a sequence of pairs with ``(docstyle, language)`` which are available when using ``load()``. :return: A sequence of pairs with ``(docstyle, language)``. """ language_config_parser = ConfParser(remove_empty_iter_elements=False) pattern = os.path.join(os.path.dirname(__file__), '*.coalang') for coalang_file in iglob(pattern): docstyle = os.path.splitext(os.path.basename(coalang_file))[0] # Ignore files that are not lowercase, as coalang files have to be. if docstyle.lower() == docstyle: for language in language_config_parser.parse(coalang_file): yield docstyle, language.lower()
def __init__(self, language: str, coalang_dir=None): """ Creates a new LanguageDefinition object from file. A Language Definition holds constants which may help parsing the language. If you want to write a bear you'll probably want to use those definitions to keep your bear independent of the semantics of each language. You can easily get your language definition by just creating it with the name of the language desired: >>> list(LanguageDefinition("cpp")['extensions']) ['.c', '.cpp', '.h', '.hpp'] For some languages aliases exist, the name is case insensitive: >>> list(LanguageDefinition("C++")['extensions']) ['.c', '.cpp', '.h', '.hpp'] If no language exists, you will get a ``FileNotFoundError``: >>> LanguageDefinition("BULLSHIT!") # +ELLIPSIS Traceback (most recent call last): ... FileNotFoundError: ... :param language: The actual language (e.g. C++). :param coalang_dir: Path to directory with coalang language definition files. This replaces the default path if given. :raises FileNotFoundError: Raised when no definition is available for the given language. """ SectionCreatable.__init__(self) self.language = language.lower() if self.language in LANGUAGE_DICT: self.language = LANGUAGE_DICT[self.language] coalang_file = os.path.join( coalang_dir or Constants.language_definitions, self.language + ".coalang") self.lang_dict = ConfParser().parse(coalang_file)["default"]
def setUp(self): self.tempdir = tempfile.gettempdir() self.file = os.path.join(self.tempdir, '.coafile') self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t') with open(self.file, 'w') as file: file.write(self.example_file) self.uut = ConfParser() try: os.remove(self.nonexistentfile) except FileNotFoundError: pass logger = logging.getLogger() isnotdir = mock.Mock(return_value=False) with self.assertLogs(logger, 'WARNING') as self.cm: with mock.patch('os.path.isdir', isnotdir): self.sections = self.uut.parse(self.file)
def __init__(self, language: str): """ Creates a new LanguageDefinition object from file. A Language Definition holds constants which may help parsing the language. If you want to write a bear you'll probably want to use those definitions to keep your bear independent of the semantics of each language. :param language: The actual language (e.g. C++). :raises FileNotFoundError: Raised when no definition is available for the given family. :raises KeyError: Raised when no definition is available for the given language. """ SectionCreatable.__init__(self) self.language = language.lower() filename = os.path.join(Constants.language_definitions, language.lower() + ".coalang") self.lang_dict = ConfParser().parse(filename)["default"]
def __init__(self, language: str, coalang_dir=None): """ Creates a new LanguageDefinition object from file. A Language Definition holds constants which may help parsing the language. If you want to write a bear you'll probably want to use those definitions to keep your bear independent of the semantics of each language. :param language: The actual language (e.g. C++). :param coalang_dir: Path to directory with coalang language definition files. This replaces the default path if given. :raises FileNotFoundError: Raised when no definition is available for the given language. """ SectionCreatable.__init__(self) self.language = language.lower() coalang_file = os.path.join( coalang_dir or Constants.language_definitions, self.language + ".coalang") self.lang_dict = ConfParser().parse(coalang_file)["default"]
def load(cls, language: str, docstyle: str, coalang_dir=None): """ Loads a ``DocstyleDefinition`` from the coala docstyle definition files. This function considers all settings inside the according coalang-files as markers, except ``param_start``, ``param_end`` and ``return_sep`` which are considered as special metadata markers. .. note:: When placing new coala docstyle definition files, these must consist of only lowercase letters and end with ``.coalang``! :param language: The case insensitive programming language of the documentation comment as a string. :param docstyle: The case insensitive documentation style/tool used to document code, e.g. ``"default"`` or ``"doxygen"``. :param coalang_dir: Path to directory with coalang docstyle definition files. This replaces the default path if given. :raises FileNotFoundError: Raised when the given docstyle was not found. :raises KeyError: Raised when the given language is not defined for given docstyle. :return: The ``DocstyleDefinition`` for given language and docstyle. """ docstyle = docstyle.lower() language_config_parser = ConfParser(remove_empty_iter_elements=False) coalang_file = os.path.join(coalang_dir or os.path.dirname(__file__), docstyle + '.coalang') try: docstyle_settings = language_config_parser.parse(coalang_file) except FileNotFoundError: raise FileNotFoundError('Docstyle definition ' + repr(docstyle) + ' not found.') language = language.lower() try: docstyle_settings = docstyle_settings[language] except KeyError: raise KeyError( 'Language {!r} is not defined for docstyle {!r}.'.format( language, docstyle)) metadata_settings = ('param_start', 'param_end', 'exception_start', 'exception_end', 'return_sep') metadata = cls.Metadata(*(str(docstyle_settings.get(req_setting, '')) for req_setting in metadata_settings)) marker_sets = ( tuple(value) for key, value in docstyle_settings.contents.items() if key not in metadata_settings and not key.startswith('comment')) return cls(language, docstyle, marker_sets, metadata)