def find_and_write_commits(): if git.has_changes(): print("You have modified files!\n\n") print("Only run this script on a pristine tree.") sys.exit(1) for change_file in git.list_text_files(): if len(change_file) == 0: continue try: abspath = os.path.abspath(change_file) editorconfig = get_properties(abspath) generate_changes(editorconfig, abspath, change_file) except EditorConfigError: print("Error occurred while getting EditorConfig properties") # Generate the commits: changes_sorted = Change.sort_by_date(changes_by_commit) changes_by_commit.clear() # save memory for commit, gitinfo, change in changes_sorted: for change_file in change.files(): line_numbers = change.line_numbers_for_file(change_file) editorconfig = get_properties(change_file) old_contents, new_contents = replace_editorconfig( editorconfig, change_file, line_numbers) with open(change_file, 'wb') as f: try: f.write(new_contents) except IOError as e: print("Error writing " + change_file) raise e gitinfo.impersonate_and_write_commit(change.files())
def config(self): try: self._config = get_properties(self.view) except EditorConfigError: print('Error occurred while getting EditorConfig properties') return self._config
def process_one_file(file_path, c_or_f): """ Format one file with a file path file_path """ import os import shutil import editorconfig path = os.path.abspath(file_path) _, ext = os.path.splitext(path) # check the corresponding language ext = ext[1:] if ext not in extension_language_map: return 2 lang = extension_language_map[ext] lang_info = get_language_info(lang, c_or_f) # get editorconfig properties ec_properties = editorconfig.get_properties(path) succeed = -1 for b in lang_info['beautifier']: b_info = get_beautifier_info(lang, b) if shutil.which(b_info['executable']) == None: # The executable does not exist continue # If the spawning succeeds, then we are finished; otherwise, let's try the next beautifier if b_info['func_handling'](b_info['executable'], path, path + global_options['output_suffix'], ec_properties, c_or_f) == 0: succeed = 0 break if succeed != 0: raise EditorConfigCfError('Failed to check/format "' + path + '"')
def get_properties_from_filename(self, filename): """Retrieve dict of EditorConfig properties for the given filename""" try: return get_properties(filename) except EditorConfigError: logging.error("Error reading EditorConfig file", exc_info=True) return {}
def set_file_editorconfig_opts(filename, js_options): from editorconfig import get_properties, EditorConfigError try: _ecoptions = get_properties(os.path.abspath(filename)) if _ecoptions.get("indent_style") == "tab": js_options.indent_with_tabs = True elif _ecoptions.get("indent_style") == "space": js_options.indent_with_tabs = False if _ecoptions.get("indent_size"): js_options.indent_size = int(_ecoptions["indent_size"]) if _ecoptions.get("max_line_length"): if _ecoptions.get("max_line_length") == "off": js_options.wrap_line_length = 0 else: js_options.wrap_line_length = int(_ecoptions["max_line_length"]) if _ecoptions.get("insert_final_newline") == 'true': js_options.end_with_newline = True elif _ecoptions.get("insert_final_newline") == 'false': js_options.end_with_newline = False if _ecoptions.get("end_of_line"): if _ecoptions["end_of_line"] == "cr": js_options.eol = '\r' elif _ecoptions["end_of_line"] == "lf": js_options.eol = '\n' elif _ecoptions["end_of_line"] == "crlf": js_options.eol = '\r\n' except EditorConfigError as ex: # do not error on bad editor config print("Error loading EditorConfig. Ignoring.", file=sys.stderr)
def parse_config(self, doc): location = doc.get_location() if location is not None and location.query_exists(): try: return editorconfig.get_properties(location.get_path()) except editorconfig.EditorConfigError: pass
def dump_manifest(contents: t.Dict, manifest_path: t.Union[Path, str]): """Writes back 'contents' to 'manifest_path'. For YAML, we make a best-effort attempt to preserve formatting; for JSON, we use the canonical 4-space indentation, but add a trailing newline if originally present.""" manifest_path = Path(manifest_path) assert manifest_path.is_absolute() conf = editorconfig.get_properties(manifest_path) # Determine indentation preference indent: t.Union[str, int] if conf.get("indent_style") == "space": indent = int(conf.get("indent_size", 4)) elif conf.get("indent_style") == "tab": indent = "\t" else: indent = 4 # Determine trailing newline preference newline: t.Optional[bool] if "insert_final_newline" in conf: newline = {"true": True, "false": False}.get(conf["insert_final_newline"]) else: with manifest_path.open("r") as fp: newline = _check_newline(fp) with manifest_path.open("w", encoding="utf-8") as fp: if manifest_path.suffix in (".yaml", ".yml"): _yaml.dump(contents, fp) else: json.dump(obj=contents, fp=fp, indent=indent) if newline: fp.write("\n")
def get_editor_config(file_path): """ Returns editorConfig profile for the file at given path Keyword arguments: file_path -- /path/to/file """ return exec_fn(lambda: get_properties(file_path))
def on_load(self, view): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print 'Error occurred while getting EditorConfig properties' else: if config: self.apply_config(view, config)
def save(self, file): if not self.savable and not file: return False if not file: file = self.file if not file: return False self.file = file self.project = Project.getProjectOf(self.file) self.savable = True try: self.props = editorconfig.get_properties(self.file) except editorconfig.EditorConfigError: self.props = {} self.modificationTime = time.time() return True
def init(self, view, pre_save): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print('Error occurred while getting EditorConfig properties') else: if config: if pre_save: self.apply_charset(view, config) else: self.apply_config(view, config)
def open(self, file=None, reloading=False): if reloading and not self.reloadable and not file: return False if file: self.file = file if not self.file: return False self.project = Project.getProjectOf(self.file) self.reloadable = True try: self.props = editorconfig.get_properties(self.file) except editorconfig.EditorConfigError: self.props = {} try: self.modificationTime = os.stat(self.file).st_mtime except (FileNotFoundError, OSError): self.modificationTime = -1 return True
def ec_UseConfigFiles(): ec_data['filename'] = vim.eval("expand('%:p')") ec_data['conf_file'] = ".editorconfig" try: ec_data['options'] = editorconfig.get_properties(ec_data['filename']) except editorconfig_except.EditorConfigError as e: if int(vim.eval('g:EditorConfig_verbose')) != 0: print(str(e), file=sys.stderr) vim.command('let l:ret = 1') return for key, value in ec_data['options'].items(): vim.command("let l:config['" + key.replace("'", "''") + "'] = " + "'" + value.replace("'", "''") + "'")
def on_load(self, view): try: config = get_properties(view.file_name()) except EditorConfigError: print 'Error occurred while getting EditorConfig properties' else: if config: settings = view.settings() # EOL view.set_line_endings(LINE_ENDINGS[config['end_of_line']]) # Indent type settings.set('translate_tabs_to_spaces', config['indent_style'] == 'space') # Indent size settings.set('tab_size', int(config['indent_size'])) else: print 'There seems to be an error with your .editorconfig file'
def ec_UseConfigFiles(): ec_data['filename'] = vim.eval("expand('%:p')") ec_data['conf_file'] = ".editorconfig" try: ec_data['options'] = editorconfig.get_properties( ec_data['filename']) except editorconfig_except.EditorConfigError as e: if int(vim.eval('g:EditorConfig_verbose')) != 0: print(str(e), file=sys.stderr) vim.command('let l:ret = 1') return for key, value in ec_data['options'].items(): vim.command("let l:config['" + key.replace("'", "''") + "'] = " + "'" + value.replace("'", "''") + "'")
def get_properties(self, filename, interpret=True): try: options = get_properties(filename) except exceptions.ParsingError: log.warning("Error parsing an .editorconfig file") return "" except exceptions.PathError: log.error("Invalid filename specified") return "" except exceptions.EditorConfigError: log.error("An unknown EditorConfig error occurred") return "" if interpret: items = {} for key, value in options.iteritems(): if value.isdigit(): value = int(value) elif value == "true" or value == "false": value = value == "true" if key == "indent_style": items["useTabs"] = value == "tab" elif key == "indent_size": if value != "tab": items["indentWidth"] = value elif key == "tab_width": items["tabWidth"] = value elif key == "end_of_line": items["endOfLine"] = value.upper() elif key == "charset": items["encodingDefault"] = value elif key == "trim_trailing_whitespace": items["cleanLineEnds"] = value elif key == "insert_final_newline": items["ensureFinalEOL"] = value elif key == "max_line_length": # not exactly the same, we're just setting the guide line items["editAutoWrapColumn"] = value else: items[key] = value else: items = options.items() return json.dumps(items)
def init(self, view, event): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print('Error occurred while getting EditorConfig properties') else: if config: if event == 'activated' or event == 'load': debug('File Path \n%s' % unexpanduser(path)) debug('Applied Settings \n%s' % pprint.pformat(config)) if event == 'pre_save': self.apply_pre_save(view, config) else: self.apply_config(view, config)
def init(self, view, event): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print('Error occurred while getting EditorConfig properties') else: if config: if event == 'activated': debug('File Path \n%s' % unexpanduser(path)) debug('Applied Settings \n%s' % pprint.pformat(config)) if event == 'pre_save': self.apply_pre_save(view, config) else: self.apply_config(view, config)
def editorconfig( config: c2cciutils.configuration.ChecksEditorconfigConfig, full_config: c2cciutils.configuration.Configuration, args: Namespace, ) -> bool: """ Check the editorconfig configuration. config is like: properties: <file_pattern>: {} # dictionary of properties to check Arguments: config: The check section config full_config: All the CI config args: The parsed command arguments """ del full_config, args success = True for pattern, wanted_properties in config.get("properties", {}).items(): try: for filename in subprocess.check_output(["git", "ls-files", pattern]).decode().split("\n"): if os.path.isfile(filename): properties = get_properties(os.path.abspath(filename)) for key, value in wanted_properties.items(): if value is not None and (key not in properties or properties[key] != value): c2cciutils.error( "editorconfig", f"For pattern: {pattern} the property '{key}' is " f"'{properties.get(key, '')}' but should be '{value}'.", ".editorconfig", ) success = False break except EditorConfigError: c2cciutils.error( "editorconfig", "Error occurred while getting EditorConfig properties", ".editorconfig", ) return False return success
def get_indentation_from_editorconfig(self) -> Indentation: """ @brief Guess the indentation from the .editorconfig file. @param self The object @return Indentation namedtuple """ indentation = INDENTATION_UNKNOWN._asdict() file_path = self.view.file_name() # is a new buffer so no file path if not file_path: return INDENTATION_UNKNOWN try: options = editorconfig.get_properties(file_path) except editorconfig.EditorConfigError: return INDENTATION_UNKNOWN indent_style = options.get("indent_style") indent_size = options.get("indent_size") # sanitize indent_style if indent_style != "space" and indent_style != "tab": indent_style = INDENTATION_UNKNOWN.type # sanitize indent_size try: indent_size = int(indent_size) except (TypeError, ValueError): indent_size = INDENTATION_UNKNOWN.size if indent_style == "space" or indent_style == "tab": indentation["type"] = indent_style indentation["size"] = indent_size return Indentation(**indentation) return INDENTATION_UNKNOWN
def init(self, view, event): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print('Error occurred while getting EditorConfig properties') else: if config: if event == 'activated': print('\nEditorConfig') path = unexpanduser(path) print(path) pprint.pprint(config) print('') if event == 'pre_save': self.apply_pre_save(view, config) else: self.apply_config(view, config)
def main(): invalid_files = args.not_flags.not_files.all if any(f for f in args.flags.all if f not in FLAGS): usage() sys.exit(1) if args.contains(('-h', '--help')): usage() sys.exit() if invalid_files: print "Invalid files found" # TODO sys.exit(1) fix = args.contains(('-f', '--fix')) for filename in args.files: checker = EditorConfigChecker(fix=fix) try: props = get_properties(abspath(filename)) except EditorConfigError, e: print e continue else: for error in checker.check(filename, props): print "%s: %s" % (filename, error)
def main(): args = arguments.Args() invalid_files = args.not_flags.not_files.all if any(f for f in args.flags.all if f not in FLAGS): usage() sys.exit(1) if args.contains(('-h', '--help')): usage() sys.exit() if invalid_files: print("Invalid files found") # TODO sys.exit(1) fix = args.contains(('-f', '--fix')) for filename in args.files: checker = EditorConfigChecker(fix=fix) try: props = get_properties(abspath(filename)) except EditorConfigError as e: print(e) continue else: for error in checker.check(filename, props): print("%s: %s" % (filename, error))
def iter_rc_file(path_to_edit: Optional[pl.Path], paths_rc_base: List[pl.Path]) -> Iterator[str]: config_ec = {} if path_to_edit: config_ec = ec.get_properties(path_to_edit.expanduser().resolve()) yield from iter_rc_file_from_config(paths_rc_base, config_ec)
def assertFileErrors(self, filename, expected_errors): full_filename = get_filename(filename) props = get_properties(full_filename) checker = EditorConfigChecker() errors = checker.check(full_filename, props) self.assertEquals((filename, errors), (filename, expected_errors))
return contents, newcontents modified_files = run(['git', 'ls-files', '-m']) if modified_files[0] != '' or len(modified_files) > 1: print( "You have modified files!\n\nOnly run this script on a pristine tree.") print(modified_files) sys.exit(1) files = run(['git', 'ls-files']) for changefile in files: if changefile == "": continue try: abspath = os.path.abspath(changefile) options = get_properties(abspath) generate_changes(options, abspath, changefile) except EditorConfigError: print("Error occurred while getting EditorConfig properties") # Generate the commits: for commit, change in changes_by_commit.items(): # get info for the commit: gitinfo = extract_git_info(commit) for changefile in change.files(): line_numbers = change.line_numbers_for_file(changefile) options = get_properties(changefile) contents, newcontents = run_editorconfig_changes( options, changefile, line_numbers) with open(changefile, 'w') as f: f.write(newcontents)
def assertFileErrors(self, filename, expected_errors): full_filename = get_filename(filename) props = get_properties(full_filename) checker = EditorConfigChecker() errors = checker.check(full_filename, props) self.assertEquals((filename, set(errors)), (filename, set(expected_errors)))