def render_file(self, target, template, context=None, *, executable=False, override=False, force_python=False): with self.file(target, executable=executable, override=override) as f: content = format_file_content(self.render(template, context)) if force_python or target.endswith('.py'): content, modified = yapf_api.FormatCode(content, filename=target) f.write(content) self._log_file(target, override, content)
def _write_file(self, path: pathlib.Path) -> None: if self.YAPF: code = yapf_api.FormatCode('\n'.join(self._output_buffer), style_config='pep8')[0] else: code = '\n'.join(self._output_buffer) with path.open('w') as handle: handle.write(code)
def render_file_inline(self, target, template_string, context=None, override=False, force_python=False): with self.file(target, override=override) as f: content = format_file_content(Template(template_string).render(**(context or {}))) if force_python or target.endswith('.py'): content, modified = yapf_api.FormatCode( content, filename=target, style_config=settings.YAPF_STYLE_CONFIG ) f.write(content) self._log_file(target, override, content)
def yapify(self, virgin, path): try: fmt_code, _ = yapf_api.FormatCode(virgin, filename=path, style_config='google', verify=False) return fmt_code, None except Exception as e: return virgin, e
def cleansource(source: str) -> str: """ Auto-format w/ yapf and clean a Python function 's source code. Do away with whitespace, empty lines and comments. (docstrings + single-line) """ # Format code with yapf source, _ = yapf_api.FormatCode(source) # Remove # comments source = re.sub(r'\s*#.*\n', '\n', source) # Remove triple quotes comments source = re.sub(r'\n\s*"""(.|\n|(\n\r))*?"""', '\n', source) source = re.sub(r"\n\s*'''(.|\n|(\n\r))*?'''", '\n', source) # Remove trailing whitespace source = re.sub(r'\s+$', '\n', source) # Remove empty lines source = re.sub(r'\n\s*\n', '\n', source) return source
raise EnvironmentError('must set CPPTRAJHOME') with open(cpptrajhome + '/src/Command.cpp') as fh: lines = fh.readlines() cpptraj_actlist = [line.split()[1] for line in lines if line.startswith('#include "Action_')] cpptraj_actlist = sorted([word.replace('"Action_', '').replace('.h"', '').lower() for word in cpptraj_actlist]) cpptraj_analist = [line.split()[1] for line in lines if line.startswith('#include "Analysis_')] cpptraj_analist = sorted([word.replace('"Analysis_', '').replace('.h"', '').lower() for word in cpptraj_analist]) excluded_command_from_pmap = [ 'hbond' ] code = """ # this file was auto-generated by scripts/find_action_and_ANALYSIS_COMMANDS.py" # require: yapf ACTION_COMMANDS = {cpptraj_actlist} ANALYSIS_COMMANDS = {cpptraj_analist} PMAP_EXCLUDED_COMMANDS = {excluded_command_from_pmap} """.format(cpptraj_actlist=cpptraj_actlist, cpptraj_analist=cpptraj_analist, excluded_command_from_pmap=excluded_command_from_pmap) print(yapf_api.FormatCode(code)[0])