def generate_file(self, p: Path):
try:
template = Template(p.read_text())
text = template.render(**self.ctx)
except TemplateError as e:
raise TemplateError('error in {}'.format(p)) from e
text = text.strip('\n\t ')
new_path = self.project_root / p.relative_to(self.template_dir)
if len(text) < 3:
# empty files don't get created, in case a few characters get left behind
logger.debug('not creating "%s", as it would be empty', new_path)
return
logger.debug('creating "%s"', new_path)
if p.name == 'requirements.txt':
packages = {p.strip() for p in text.split('\n') if p.strip() and p.strip() != '#'}
text = '\n'.join(sorted(packages))
else:
# helpful when debugging: print(text.replace(' ', '·').replace('\n', '?\n'))
if p.suffix == '.py':
text = SortImports(file_contents=text).output
regexes = FILES_REGEXES.get(p.suffix, [])
for regex, repl in regexes:
text = regex.sub(repl, text)
# re-add a trailing newline accounting for newlines added by PY_REGEXES
text = re.sub('\n*$', '\n', text)
new_path.parent.mkdir(parents=True, exist_ok=True)
new_path.write_text(text)
self.files_created += 1
评论列表
文章目录