From 3a47d4ef7d251fd4e9dd39018174a6f53b3ce020 Mon Sep 17 00:00:00 2001 From: Anton Shuvalov Date: Sun, 31 Jul 2022 17:36:26 +0700 Subject: [PATCH 1/2] Blackify --- src/builder/builder.py | 42 ++++++++--------- src/cli.py | 14 +++--- src/converters/markdown.py | 14 +++--- src/dataclasses/asset_data.py | 6 +-- src/dataclasses/config_data.py | 22 ++++----- src/dataclasses/content_data.py | 34 +++++++------- src/entities/image.py | 2 +- src/entities/inline_image.py | 4 +- src/entities/markdown_image.py | 4 +- src/entities/obsidian_embed.py | 22 ++++----- src/entities/obsidian_link.py | 24 +++++----- src/entities/parser.py | 13 ++++-- src/entities/reference_image.py | 6 +-- src/lib/http_server.py | 10 ++-- src/obsidian/vault.py | 2 +- src/preprocessors/further_reading.py | 22 ++++----- src/preprocessors/include_header.py | 4 +- src/preprocessors/note_delimeters.py | 6 +-- src/tasks/builder.py | 4 +- src/tasks/preflight_check.py | 2 +- src/tasks/watcher.py | 2 +- src/tree/node.py | 2 +- tests/blog/layout_test.py | 18 +++---- tests/dataclasses/asset_data_test.py | 8 ++-- tests/dataclasses/config_data_test.py | 14 +++--- tests/dataclasses/content_data_test.py | 52 ++++++++++----------- tests/entities/inline_image_test.py | 16 +++---- tests/entities/obsidian_embed_test.py | 20 ++++---- tests/entities/obsidian_link_test.py | 6 +-- tests/entities/parser_test.py | 50 ++++++++++---------- tests/entities/reference_image_test.py | 18 +++---- tests/helpers.py | 4 +- tests/preprocessors/further_reading_test.py | 36 +++++++------- tests/preprocessors/include_header_test.py | 8 ++-- tests/tree/node_test.py | 6 +-- 35 files changed, 255 insertions(+), 262 deletions(-) diff --git a/src/builder/builder.py b/src/builder/builder.py index 25f9ee9..abcdfe2 100644 --- a/src/builder/builder.py +++ b/src/builder/builder.py @@ -32,7 +32,7 @@ def build(self): def make_build_dir(self): dest_dir = self.config.dest_dir - print(f'- Prepare a build dir: {dest_dir}') + print(f"- Prepare a build dir: {dest_dir}") fs.rm_dir(dest_dir) fs.make_dir(dest_dir) @@ -40,17 +40,17 @@ def copy_assets(self): assets_dir = self.config.assets_dir assets_dest_dir = self.blog.config.assets_dest_dir fs.make_dir(assets_dest_dir) - print(f'- Copy assets from {assets_dir} to {assets_dest_dir}') + print(f"- Copy assets from {assets_dir} to {assets_dest_dir}") fs.copy_dir(assets_dir, assets_dest_dir) def render_all(self): for entity in self.vault.page_types: - print(f'# Render {entity}:') + print(f"# Render {entity}:") tic = time.perf_counter() pages = getattr(self.vault, entity) for page in pages: - print(f'- {page.data.title}') + print(f"- {page.data.title}") if page.data.is_private: print( f"- [SKIP]: '{page.data.title}' is private, add `published: True` attribute to the frontmetter to publish it" @@ -62,26 +62,26 @@ def render_all(self): toc = time.perf_counter() - print('') + print("") print( - f'{len(pages)} {entity} have been rendered in {toc-tic:0.4f} seconds\n' + f"{len(pages)} {entity} have been rendered in {toc-tic:0.4f} seconds\n" ) def render(self, page): dest_dir = self.config.dest_dir dest = os.path.join(dest_dir, page.data.slug) - ctx = self.create_context({'self': page.data}) + ctx = self.create_context({"self": page.data}) html = page.render(ctx) layout = self.get_layout(page) if layout is not None: - ctx.update({'content': html}) + ctx.update({"content": html}) html = layout.render(ctx) fs.write_file(dest, html) def get_layout(self, node): - layout_name = node.data.meta.get('layout') or 'main' + layout_name = node.data.meta.get("layout") or "main" return self.blog.layouts[layout_name] def process_assets(self, page): @@ -91,7 +91,7 @@ def process_assets(self, page): if not issubclass(type(content_data), ContentData): continue - if content_data.ext == '.md': + if content_data.ext == ".md": continue if validators.url(content_data.filename): @@ -100,15 +100,15 @@ def process_assets(self, page): try: public_dir = self.config.public_dir assets_dest_dir = self.config.assets_dest_dir - dest_filename = f'{content_data.id}{content_data.ext}' + dest_filename = f"{content_data.id}{content_data.ext}" frm = content_data.filename - to = f'{assets_dest_dir}/{dest_filename}' + to = f"{assets_dest_dir}/{dest_filename}" url = os.path.join(public_dir, dest_filename) fs.copyfile(frm, to) content_data.filename = url - print(f' - [COPY ASSET]: {frm} to {to}') + print(f" - [COPY ASSET]: {frm} to {to}") except: # FIXME: Should skip abs paths and urls @@ -116,15 +116,15 @@ def process_assets(self, page): def preprocess_content(self, page): for processor in self.preprocessors: - if hasattr(processor, 'process_page') and callable( - getattr(processor, 'process_page') + if hasattr(processor, "process_page") and callable( + getattr(processor, "process_page") ): processor.process_page(page) for entity in page.data.entities: for processor in self.preprocessors: - if hasattr(processor, 'process_entity') and callable( - getattr(processor, 'process_entity') + if hasattr(processor, "process_entity") and callable( + getattr(processor, "process_entity") ): processor.process_entity(entity) @@ -133,10 +133,10 @@ def create_context(self, local_ctx=None): local_ctx = {} global_ctx = { - 'config': self.config, - 'layouts': self.blog.layouts, - 'pages': self.vault.pages, - 'posts': self.vault.posts, + "config": self.config, + "layouts": self.blog.layouts, + "pages": self.vault.pages, + "posts": self.vault.posts, } global_ctx.update(local_ctx) return global_ctx diff --git a/src/cli.py b/src/cli.py index a4bfe80..390928a 100644 --- a/src/cli.py +++ b/src/cli.py @@ -27,19 +27,19 @@ --version Show version. """ -version = pkg_resources.get_distribution('obsidian-blog').version +version = pkg_resources.get_distribution("obsidian-blog").version def main(): args = docopt(doc, version=version) - serve = args['--serve'] - watch = args['--watch'] + serve = args["--serve"] + watch = args["--watch"] config.override( { - 'port': int(args['--port']), - 'blog_title': args['--title'], - 'drafts': args['--drafts'], + "port": int(args["--port"]), + "blog_title": args["--title"], + "drafts": args["--drafts"], } ) config.load_dotenv() @@ -63,5 +63,5 @@ def main(): print(e) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/src/converters/markdown.py b/src/converters/markdown.py index a8daacc..70c2149 100644 --- a/src/converters/markdown.py +++ b/src/converters/markdown.py @@ -2,15 +2,15 @@ md_parser = Markdown( extensions=[ - 'fenced_code', - 'markdown_link_attr_modifier', - 'attr_list', + "fenced_code", + "markdown_link_attr_modifier", + "attr_list", ], extension_configs={ - 'markdown_link_attr_modifier': { - 'new_tab': 'on', - 'no_referrer': 'external_only', - 'auto_title': 'on', + "markdown_link_attr_modifier": { + "new_tab": "on", + "no_referrer": "external_only", + "auto_title": "on", }, }, ) diff --git a/src/dataclasses/asset_data.py b/src/dataclasses/asset_data.py index 497adec..522c295 100644 --- a/src/dataclasses/asset_data.py +++ b/src/dataclasses/asset_data.py @@ -8,9 +8,9 @@ class AssetData: """Basic image class""" - filename: str = '' - placeholder: str = '' - alt: str = '' + filename: str = "" + placeholder: str = "" + alt: str = "" key: Optional[str] = None @property diff --git a/src/dataclasses/config_data.py b/src/dataclasses/config_data.py index e6e86c6..bb0f287 100644 --- a/src/dataclasses/config_data.py +++ b/src/dataclasses/config_data.py @@ -5,16 +5,16 @@ @dataclass class ConfigData: drafts: bool = False - blog_title: str = 'My Blog' - dest_dir: str = '.build' - source_dir: str = '.blog' - posts_dir: str = 'Posts' - pages_dir: str = 'Pages' - layouts_dir: str = '.blog/_layouts' - assets_dir: str = '.blog/_assets' - assets_dest_dir: str = '.build/static' - public_dir: str = '/static' - default_layout: str = 'main' + blog_title: str = "My Blog" + dest_dir: str = ".build" + source_dir: str = ".blog" + posts_dir: str = "Posts" + pages_dir: str = "Pages" + layouts_dir: str = ".blog/_layouts" + assets_dir: str = ".blog/_assets" + assets_dest_dir: str = ".build/static" + public_dir: str = "/static" + default_layout: str = "main" port: int = 4200 def override(self, config: dict): @@ -24,7 +24,7 @@ def override(self, config: dict): setattr(self, i.name, config[i.name]) def load_dotenv(self): - self.override(dotenv_values('.env')) + self.override(dotenv_values(".env")) config = ConfigData() diff --git a/src/dataclasses/content_data.py b/src/dataclasses/content_data.py index 7bddf80..edfc909 100644 --- a/src/dataclasses/content_data.py +++ b/src/dataclasses/content_data.py @@ -7,26 +7,26 @@ from src.lib.fs import basename from slugify.slugify import slugify -TITLE_DELIMETER = ' - ' +TITLE_DELIMETER = " - " DEFAULT_DATE = datetime.fromtimestamp(0) @dataclass class ContentData: - filename: str = '' + filename: str = "" placeholder: Optional[str] = None meta: dict = field(default_factory=dict) - content: str = '' + content: str = "" entities: list = field(default_factory=list) match: dict = field(default_factory=dict) @property def title(self): # If it was explicitly redefined, return it - if 'title' in self.match and self.match['title'] is not None: - return self.match['title'] + if "title" in self.match and self.match["title"] is not None: + return self.match["title"] - meta_title = self.meta.get('title') + meta_title = self.meta.get("title") if isinstance(meta_title, str): return meta_title title, _ = os.path.splitext(basename(self.filename)) @@ -37,10 +37,10 @@ def title(self): @property def date(self): - meta_date = self.meta.get('date') + meta_date = self.meta.get("date") if isinstance(meta_date, date): - return datetime.strptime(meta_date.strftime('%Y%m%d'), '%Y%m%d') + return datetime.strptime(meta_date.strftime("%Y%m%d"), "%Y%m%d") return DEFAULT_DATE @@ -49,12 +49,12 @@ def __lt__(self, other): @property def slug(self): - meta_slug = self.meta.get('slug') + meta_slug = self.meta.get("slug") if isinstance(meta_slug, str): - return f'{meta_slug}.html' + return f"{meta_slug}.html" file, _ = os.path.splitext(self.filename) slug = slugify(os.path.basename(file)) - return f'{slug}.html' + return f"{slug}.html" @property def id(self): @@ -69,9 +69,9 @@ def ext(self): @property def is_private(self): - if config.drafts and self.meta.get('draft'): + if config.drafts and self.meta.get("draft"): return False - if self.meta.get('published'): + if self.meta.get("published"): return False return True @@ -80,11 +80,9 @@ def _placeholder_title(self): if not self.placeholder: return None - [title] = re.findall( - r'\[\[([\d\s\w\-&|]*)\]\]', self.placeholder or '' - ) - if not '|' in title: + [title] = re.findall(r"\[\[([\d\s\w\-&|]*)\]\]", self.placeholder or "") + if not "|" in title: return None - _, title = title.split('|') + _, title = title.split("|") return title.strip() diff --git a/src/entities/image.py b/src/entities/image.py index 4047de2..401dee4 100644 --- a/src/entities/image.py +++ b/src/entities/image.py @@ -10,5 +10,5 @@ class Image: def render(self, data): content = data.content - rendered_image = f'![{self.data.title}]({self.data.filename})' + rendered_image = f"![{self.data.title}]({self.data.filename})" return content.replace(self.data.placeholder, rendered_image) diff --git a/src/entities/inline_image.py b/src/entities/inline_image.py index 91741a0..d087248 100644 --- a/src/entities/inline_image.py +++ b/src/entities/inline_image.py @@ -3,7 +3,7 @@ from src.dataclasses.asset_data import AssetData from src.entities.image import Image -INLINE_IMG_RE = r'(\!\[(.*?)\]\((.*?)\))' +INLINE_IMG_RE = r"(\!\[(.*?)\]\((.*?)\))" class InlineImage(Image): @@ -12,7 +12,7 @@ def get_all(cls, entity): if not isinstance(entity.data, ContentData): return [] - if entity.data.ext is '.md': + if entity.data.ext is ".md": return [] imgs = [] diff --git a/src/entities/markdown_image.py b/src/entities/markdown_image.py index 9244e36..7209656 100644 --- a/src/entities/markdown_image.py +++ b/src/entities/markdown_image.py @@ -28,9 +28,9 @@ def get_all(cls, entity): @staticmethod def get_matches(content): - print('content', content) + print("content", content) markdown = markdownFabric(renderer=ASTRenderer) ast = markdown(content) - res = get_all_of_types(['obsidian_embed'], ast) + res = get_all_of_types(["obsidian_embed"], ast) breakpoint() return res diff --git a/src/entities/obsidian_embed.py b/src/entities/obsidian_embed.py index 6b658ff..a05e4b3 100644 --- a/src/entities/obsidian_embed.py +++ b/src/entities/obsidian_embed.py @@ -14,9 +14,9 @@ def __init__(self, data: ContentData): def render(self, data): _, ext = os.path.splitext(self.data.filename) - if ext in ['.png', '.jpg', '.gif']: + if ext in [".png", ".jpg", ".gif"]: return self.render_image(data) - if ext in ['.md']: + if ext in [".md"]: return self.render_markdown(data) def render_markdown(self, data: ContentData): @@ -25,14 +25,14 @@ def render_markdown(self, data: ContentData): def render_image(self, data: ContentData): content = data.content - template = f'![{self.title}]({self.data.filename})' + template = f"![{self.title}]({self.data.filename})" return content.replace(self.data.placeholder, template) @staticmethod def get_matches(content): markdown = markdownFabric(renderer=ASTRenderer) ast = markdown(content) - return get_all_of_types(['obsidian_embed'], ast) + return get_all_of_types(["obsidian_embed"], ast) @classmethod def get_all(cls, entity): @@ -43,8 +43,8 @@ def get_all(cls, entity): matches = cls.get_matches(entity.data.content) for match in matches: - placeholder = match['placeholder'] - target = match['target'] + placeholder = match["placeholder"] + target = match["target"] # TODO: Duplication filename = target @@ -53,13 +53,13 @@ def get_all(cls, entity): if ext: filename = target else: - filename = f'{target}.md' + filename = f"{target}.md" try: - path = fs.find_one_by_glob(f'**/{filename}') + path = fs.find_one_by_glob(f"**/{filename}") _, ext = os.path.splitext(filename) - if ext == '.md': + if ext == ".md": _, meta, content = fs.load(path) embed = ContentData( @@ -76,13 +76,13 @@ def get_all(cls, entity): embed = ContentData( placeholder=placeholder, filename=path, - content='', + content="", match=match, ) entity = ObsidianEmbed(embed) entities.append(entity) - print(f'- [PARSED]: Include: {placeholder}') + print(f"- [PARSED]: Include: {placeholder}") except Exception as e: print(f'- [NOT FOUND] "{placeholder}" {e}') diff --git a/src/entities/obsidian_link.py b/src/entities/obsidian_link.py index 906d254..7eeee51 100644 --- a/src/entities/obsidian_link.py +++ b/src/entities/obsidian_link.py @@ -22,11 +22,11 @@ def id(self): def get_matches(content): markdown = markdownFabric(renderer=ASTRenderer) ast = markdown(content) - return get_all_of_types(['obsidian_link'], ast) + return get_all_of_types(["obsidian_link"], ast) def render(self, data): content = data.content - not_found = self.data.meta.get('not_found') + not_found = self.data.meta.get("not_found") if not_found: return content.replace(self.data.placeholder, self.title) @@ -43,8 +43,8 @@ def get_all(cls, entity): matches = cls.get_matches(entity.data.content) for match in matches: - placeholder = match['placeholder'] - target = match['target'] + placeholder = match["placeholder"] + target = match["target"] # TODO: Duplication filename = target @@ -53,23 +53,21 @@ def get_all(cls, entity): if ext: filename = target else: - filename = f'{target}.md' + filename = f"{target}.md" try: _, ext = os.path.splitext(filename) - if ext != '.md': + if ext != ".md": continue - filename = fs.find_one_by_glob(f'**/{filename}') + filename = fs.find_one_by_glob(f"**/{filename}") _, meta, _ = fs.load(filename) - url = meta.get('link') + url = meta.get("link") if not url: - meta['not_found'] = True - print( - f'- [LINK NOT FOUND] Link is not defined for {placeholder}' - ) + meta["not_found"] = True + print(f"- [LINK NOT FOUND] Link is not defined for {placeholder}") data = ContentData( placeholder=placeholder, @@ -81,7 +79,7 @@ def get_all(cls, entity): include = cls(data) includes.append(include) - print(f'- [PARSED]: Link: {placeholder}, {url}') + print(f"- [PARSED]: Link: {placeholder}, {url}") except Exception as e: print(f'- [LINK NOT FOUND] "{placeholder}" {e}') diff --git a/src/entities/parser.py b/src/entities/parser.py index 1e185a4..afc437c 100644 --- a/src/entities/parser.py +++ b/src/entities/parser.py @@ -2,7 +2,7 @@ class ObsidianLink(inline.InlineElement): - pattern = r'\[\[\s*(.+?)\s*(?:\|\s*(.+?)\s*)?]\]' + pattern = r"\[\[\s*(.+?)\s*(?:\|\s*(.+?)\s*)?]\]" parse_children = True def __init__(self, match): @@ -12,7 +12,7 @@ def __init__(self, match): class ObsidianEmbed(inline.InlineElement): - pattern = r'\!\[\[\s*(.+?)\s*(?:\|\s*(.+?)\s*)?]\]' + pattern = r"\!\[\[\s*(.+?)\s*(?:\|\s*(.+?)\s*)?]\]" parse_children = True def __init__(self, match): @@ -24,13 +24,15 @@ def __init__(self, match): class Obsidian: elements = [ObsidianEmbed, ObsidianLink] + def markdownFabric(*args, **kwargs): markdown = Markdown(*args, **kwargs) markdown.use(Obsidian) return markdown + def traverse(head, cb): - key = 'children' + key = "children" if not head: return @@ -41,12 +43,13 @@ def traverse(head, cb): for child in head.get(key): traverse(child, cb) -def get_all_of_types(element_types, ast): + +def get_all_of_types(element_types, ast): nodes = [] traverse(ast, lambda n: nodes.append(n)) return list( filter( - lambda n: n.get('element') in element_types, + lambda n: n.get("element") in element_types, nodes, ) ) diff --git a/src/entities/reference_image.py b/src/entities/reference_image.py index 319715c..16bdea6 100644 --- a/src/entities/reference_image.py +++ b/src/entities/reference_image.py @@ -3,7 +3,7 @@ from src.entities.image import Image from src.lib.fs import normalize_path -REFERENCE_IMG_RE = r'(\!\[(.*)]\[(.*)\])' +REFERENCE_IMG_RE = r"(\!\[(.*)]\[(.*)\])" class ReferenceImage(Image): @@ -19,7 +19,7 @@ def get_all(entity): for match in matches: placeholder, alt, key = match - link_re = re.compile('\\[' + key + '\\]:\\s(.*)') + link_re = re.compile("\\[" + key + "\\]:\\s(.*)") filename = re.findall(link_re, content)[0] data = ContentData( @@ -27,6 +27,6 @@ def get_all(entity): filename=normalize_path(filename), ) imgs.append(ReferenceImage(data=data)) - print(f'- [PARSED]: Image: {filename}') + print(f"- [PARSED]: Image: {filename}") return imgs diff --git a/src/lib/http_server.py b/src/lib/http_server.py index 9b09ed3..f777db1 100644 --- a/src/lib/http_server.py +++ b/src/lib/http_server.py @@ -9,10 +9,8 @@ def __init__(self, port: int, directory: str) -> None: self.start() def start(self): - with socketserver.TCPServer( - ('', self.port), self.create_handler() - ) as httpd: - print(f'Start server at {self.port} port') + with socketserver.TCPServer(("", self.port), self.create_handler()) as httpd: + print(f"Start server at {self.port} port") httpd.serve_forever() def create_handler(self): @@ -22,7 +20,7 @@ def _init(self, *args, **kwargs): ) return type( - f'HandlerFrom<{self.directory}>', + f"HandlerFrom<{self.directory}>", (http.server.SimpleHTTPRequestHandler,), - {'__init__': _init, 'directory': self.directory}, + {"__init__": _init, "directory": self.directory}, ) diff --git a/src/obsidian/vault.py b/src/obsidian/vault.py index 7a97cbf..8e7c447 100644 --- a/src/obsidian/vault.py +++ b/src/obsidian/vault.py @@ -5,7 +5,7 @@ class ObsidianVault: """ObsidianVault handles posts and pages look up""" - page_types = ['pages', 'posts'] + page_types = ["pages", "posts"] def __init__(self, config: ConfigData): self.config = config diff --git a/src/preprocessors/further_reading.py b/src/preprocessors/further_reading.py index 4d53274..f17fa2f 100644 --- a/src/preprocessors/further_reading.py +++ b/src/preprocessors/further_reading.py @@ -13,37 +13,35 @@ def process_entity(cls, entity): if not cls.is_supported_content(data): return - links = data.meta.get('links', None) + links = data.meta.get("links", None) if links is None: return if type(links) is not list: print( - f' - [FURTHER READING PREPROCESS] meta links are not valid. Should be a list' + f" - [FURTHER READING PREPROCESS] meta links are not valid. Should be a list" ) - further_reading_md = '\n**Further Reading**:\n\n' + further_reading_md = "\n**Further Reading**:\n\n" for link in links: if type(link) is not dict: return - link_name = link.get('name') - link_url = link.get('url') - link_md = f'- [{link_name}]({link_url})' - further_reading_md += f'{link_md}\n' + link_name = link.get("name") + link_url = link.get("url") + link_md = f"- [{link_name}]({link_url})" + further_reading_md += f"{link_md}\n" - data.content = f'{data.content}\n{further_reading_md}' - print( - f' - [PREPROCESS] Rendered further reading section for "{data.title}"' - ) + data.content = f"{data.content}\n{further_reading_md}" + print(f' - [PREPROCESS] Rendered further reading section for "{data.title}"') @classmethod def is_supported_content(cls, data: ContentData): if not isinstance(data, ContentData): return False - if data.content == '': + if data.content == "": return False return True diff --git a/src/preprocessors/include_header.py b/src/preprocessors/include_header.py index 63cac60..44567e5 100644 --- a/src/preprocessors/include_header.py +++ b/src/preprocessors/include_header.py @@ -8,7 +8,7 @@ def process_entity(entity): if not isinstance(data, ContentData): return - if data.content == '': + if data.content == "": return header = f"""\ @@ -18,6 +18,6 @@ def process_entity(entity): """ - data.content = f'{header}\n{data.content}' + data.content = f"{header}\n{data.content}" print(f' - [PREPROCESS] Rendered header for "{data.title}"') diff --git a/src/preprocessors/note_delimeters.py b/src/preprocessors/note_delimeters.py index 4a56e78..231601d 100644 --- a/src/preprocessors/note_delimeters.py +++ b/src/preprocessors/note_delimeters.py @@ -8,11 +8,11 @@ def process_entity(entity): if not isinstance(data, ContentData): return - if data.content == '': + if data.content == "": return - delimeter = '---' + delimeter = "---" - data.content = f'{data.content}\n\n{delimeter}\n' + data.content = f"{data.content}\n\n{delimeter}\n" print(f' - [PREPROCESS] Rendered delimeter for "{data.title}"') diff --git a/src/tasks/builder.py b/src/tasks/builder.py index ae3f90c..d0732e3 100644 --- a/src/tasks/builder.py +++ b/src/tasks/builder.py @@ -22,6 +22,6 @@ def run(config=ConfigData): builder.build() toc = time.perf_counter() - print('---\n') - print(f'The build has been finished in {toc - tic:0.4f} seconds\n') + print("---\n") + print(f"The build has been finished in {toc - tic:0.4f} seconds\n") lock = False diff --git a/src/tasks/preflight_check.py b/src/tasks/preflight_check.py index c73051c..4529b86 100644 --- a/src/tasks/preflight_check.py +++ b/src/tasks/preflight_check.py @@ -20,5 +20,5 @@ def validate_directory_exists(cls, directory): if not os.path.isdir(directory): raise Exception( - f'Directory {directory} not found. Are you in a properly configured vault?' + f"Directory {directory} not found. Are you in a properly configured vault?" ) diff --git a/src/tasks/watcher.py b/src/tasks/watcher.py index e82fa0c..2182e08 100644 --- a/src/tasks/watcher.py +++ b/src/tasks/watcher.py @@ -20,7 +20,7 @@ def callback(self): def start_watcher(self, ignore_dir): Handler = self.create_handler(ignore_dir, self.callback) - self.watcher = Watcher(Handler, path='.') + self.watcher = Watcher(Handler, path=".") self.watcher.run() def create_handler(self, ignore_dir, callback): diff --git a/src/tree/node.py b/src/tree/node.py index 33cda78..2359010 100644 --- a/src/tree/node.py +++ b/src/tree/node.py @@ -31,5 +31,5 @@ def flat_children(self): return entities @staticmethod - def unwrap(node: 'TreeNode'): + def unwrap(node: "TreeNode"): return node.data diff --git a/tests/blog/layout_test.py b/tests/blog/layout_test.py index e97048e..eb296c1 100644 --- a/tests/blog/layout_test.py +++ b/tests/blog/layout_test.py @@ -6,7 +6,7 @@ def test_layout_parsing(): cwd = os.getcwd() - fixture_path = get_fixture_path('layouts') + fixture_path = get_fixture_path("layouts") os.chdir(fixture_path) layouts = Layout.get_all(fixture_path) @@ -17,25 +17,25 @@ def test_layout_parsing(): @pytest.mark.parametrize( - 'layout_name', + "layout_name", [ - ('index'), - ('main'), - ('another'), + ("index"), + ("main"), + ("another"), ], ) def test_layout_rendering(layout_name): cwd = os.getcwd() - fixture_path = get_fixture_path('layouts') + fixture_path = get_fixture_path("layouts") os.chdir(fixture_path) - data = 'Hello World' - context = {'data': data} + data = "Hello World" + context = {"data": data} layouts = Layout.get_all(fixture_path) layout = layouts[layout_name] res = layout.render(context) - assert res == f'

{layout_name}

\n
{data}
\n' + assert res == f"

{layout_name}

\n
{data}
\n" os.chdir(cwd) diff --git a/tests/dataclasses/asset_data_test.py b/tests/dataclasses/asset_data_test.py index 04a0a74..68308ab 100644 --- a/tests/dataclasses/asset_data_test.py +++ b/tests/dataclasses/asset_data_test.py @@ -2,10 +2,10 @@ def test_content_data_id(): - data = AssetData(filename='/a/b/c.png') - assert data.id == 'a-b-c' + data = AssetData(filename="/a/b/c.png") + assert data.id == "a-b-c" def test_content_data_ext(): - data = AssetData(filename='/a/b/c.jpg') - assert data.ext == '.jpg' + data = AssetData(filename="/a/b/c.jpg") + assert data.ext == ".jpg" diff --git a/tests/dataclasses/config_data_test.py b/tests/dataclasses/config_data_test.py index eb5a3e8..df45e47 100644 --- a/tests/dataclasses/config_data_test.py +++ b/tests/dataclasses/config_data_test.py @@ -6,22 +6,22 @@ def test_config_data_override(): config = ConfigData() - config.override({'blog_title': 'abc'}) - assert config.blog_title == 'abc' + config.override({"blog_title": "abc"}) + assert config.blog_title == "abc" - config.override({'blog_title': 'def'}) - assert config.blog_title == 'def' + config.override({"blog_title": "def"}) + assert config.blog_title == "def" def test_config_data_dotenv(): cwd = os.getcwd() - fixture_path = get_fixture_path('config_data') + fixture_path = get_fixture_path("config_data") os.chdir(fixture_path) config = ConfigData() config.load_dotenv() - assert config.blog_title == 'Dotenv' - assert config.default_layout == 'dotenv' + assert config.blog_title == "Dotenv" + assert config.default_layout == "dotenv" os.chdir(cwd) diff --git a/tests/dataclasses/content_data_test.py b/tests/dataclasses/content_data_test.py index 934aa38..a704af9 100644 --- a/tests/dataclasses/content_data_test.py +++ b/tests/dataclasses/content_data_test.py @@ -2,40 +2,40 @@ def test_content_data_ext(): - data = ContentData(filename='test.hbs') - assert data.ext == '.hbs' + data = ContentData(filename="test.hbs") + assert data.ext == ".hbs" - data = ContentData(filename='test.md') - assert data.ext == '.md' + data = ContentData(filename="test.md") + assert data.ext == ".md" def test_content_data_slug(): - data = ContentData(filename='test.hbs') - assert data.slug == 'test.html' + data = ContentData(filename="test.hbs") + assert data.slug == "test.html" - data = ContentData(filename='test.hbs', meta={'slug': 'abc'}) - assert data.slug == 'abc.html' + data = ContentData(filename="test.hbs", meta={"slug": "abc"}) + assert data.slug == "abc.html" def test_content_data_title(): - data = ContentData(filename='Test.md') - assert data.title == 'Test' + data = ContentData(filename="Test.md") + assert data.title == "Test" - data = ContentData(filename='Parent - Child.md') - assert data.title == 'Child' + data = ContentData(filename="Parent - Child.md") + assert data.title == "Child" - data = ContentData(filename='Parent - Children - Child.md') - assert data.title == 'Child' + data = ContentData(filename="Parent - Children - Child.md") + assert data.title == "Child" - data = ContentData(meta={'title': 'Title'}) - assert data.title == 'Title' + data = ContentData(meta={"title": "Title"}) + assert data.title == "Title" def test_content_data_is_private(): - data = ContentData(meta={'published': True}) + data = ContentData(meta={"published": True}) assert data.is_private == False - data = ContentData(meta={'published': False}) + data = ContentData(meta={"published": False}) assert data.is_private == True data = ContentData(meta={}) @@ -43,24 +43,24 @@ def test_content_data_is_private(): def test_content_data_id(): - data = ContentData(filename='/a/b/c.md') - assert data.id == 'a-b-c' + data = ContentData(filename="/a/b/c.md") + assert data.id == "a-b-c" def test_content_data_sorting(): arr = [ ContentData( meta={ - 'date': '2022-01-01', - 'title': '1', + "date": "2022-01-01", + "title": "1", } ), - ContentData(meta={'date': '2022-01-02', 'title': '2'}), + ContentData(meta={"date": "2022-01-02", "title": "2"}), ] arr_sorted = sorted(arr, reverse=True) - assert list(map(lambda i: i.title, arr_sorted)) == ['1', '2'] + assert list(map(lambda i: i.title, arr_sorted)) == ["1", "2"] # TODO: It's handled by marko @@ -68,9 +68,9 @@ def xtest_content_data_placeholder_title(): data = ContentData( placeholder='[[Prometheus | Prometheus]], meta={ "title": "Zeus" }' ) - assert data.title == 'Prometheus' + assert data.title == "Prometheus" data = ContentData( placeholder='[[Prometheus | Epimetheus]], meta={ "title": "Zeus" }' ) - assert data.title == 'Epimetheus' + assert data.title == "Epimetheus" diff --git a/tests/entities/inline_image_test.py b/tests/entities/inline_image_test.py index 636dea9..c971244 100644 --- a/tests/entities/inline_image_test.py +++ b/tests/entities/inline_image_test.py @@ -4,26 +4,26 @@ def test_markdown_image_parsing(): - placeholder = '![a](b.png)' - page = create_page(content=placeholder, filename='page.md') + placeholder = "![a](b.png)" + page = create_page(content=placeholder, filename="page.md") entity = InlineImage.get_all(page)[0] assert entity.data.placeholder == placeholder - assert entity.data.title == 'b' - assert entity.data.filename == 'b.png' + assert entity.data.title == "b" + assert entity.data.filename == "b.png" def test_inline_image_rendering(): - placeholder = '![a](b.png)' - page = create_page(content=placeholder, filename='page.md') + placeholder = "![a](b.png)" + page = create_page(content=placeholder, filename="page.md") asset_data = ContentData( placeholder=placeholder, - filename='d.png', + filename="d.png", ) entity = InlineImage(data=asset_data) res = entity.render(page.data) - assert res == '![d](d.png)' + assert res == "![d](d.png)" diff --git a/tests/entities/obsidian_embed_test.py b/tests/entities/obsidian_embed_test.py index 07cd604..80e4b29 100644 --- a/tests/entities/obsidian_embed_test.py +++ b/tests/entities/obsidian_embed_test.py @@ -7,11 +7,11 @@ from tests.helpers import create_page, get_fixture_path -@pytest.mark.parametrize('fixture_name', [('mediawiki_include')]) +@pytest.mark.parametrize("fixture_name", [("mediawiki_include")]) def test_obsidian_embed(snapshot, fixture_name): cwd = os.getcwd() fixture_path = get_fixture_path(fixture_name) - page_path = f'{fixture_path}/page.md' + page_path = f"{fixture_path}/page.md" os.chdir(fixture_path) filename, meta, content = fs.load(page_path) @@ -20,36 +20,36 @@ def test_obsidian_embed(snapshot, fixture_name): assert len(entities) == 1 entity = entities[0] - snapshot.assert_match(yaml.dump(entity.data), f'{fixture_name}.yml') + snapshot.assert_match(yaml.dump(entity.data), f"{fixture_name}.yml") os.chdir(cwd) def test_obsidian_embed_markdown_rendering(): - placeholder = '![[include]]' + placeholder = "![[include]]" page = create_page(content=placeholder) content_data = ContentData( - filename='include.md', + filename="include.md", placeholder=placeholder, - content='abc', + content="abc", ) entity = ObsidianEmbed(data=content_data) res = entity.render(page.data) - assert res == 'abc' + assert res == "abc" def test_obsidian_embed_image_rendering(): - placeholder = '![[include.png]]' + placeholder = "![[include.png]]" page = create_page(content=placeholder) content_data = ContentData( - filename='include.png', + filename="include.png", placeholder=placeholder, ) entity = ObsidianEmbed(data=content_data) res = entity.render(page.data) - assert res == '![include](include.png)' + assert res == "![include](include.png)" diff --git a/tests/entities/obsidian_link_test.py b/tests/entities/obsidian_link_test.py index ab17798..f8fb237 100644 --- a/tests/entities/obsidian_link_test.py +++ b/tests/entities/obsidian_link_test.py @@ -6,18 +6,18 @@ from tests.helpers import create_page, get_fixture_path -@pytest.mark.parametrize('fixture_name', [('mediawiki_links')]) +@pytest.mark.parametrize("fixture_name", [("mediawiki_links")]) def test_obsidian_link(snapshot, fixture_name): cwd = os.getcwd() fixture_path = get_fixture_path(fixture_name) os.chdir(fixture_path) - page_path = f'{fixture_path}/page.md' + page_path = f"{fixture_path}/page.md" filename, meta, content = fs.load(page_path) page = create_page(filename=filename, meta=meta, content=content) entities = ObsidianLink.get_all(page) assert len(entities) == 3 - snapshot.assert_match(yaml.dump(page.render()), f'{fixture_name}.yml') + snapshot.assert_match(yaml.dump(page.render()), f"{fixture_name}.yml") os.chdir(cwd) diff --git a/tests/entities/parser_test.py b/tests/entities/parser_test.py index 17f21d7..cff2318 100644 --- a/tests/entities/parser_test.py +++ b/tests/entities/parser_test.py @@ -20,43 +20,43 @@ def test_entities_parser(): traverse(ast, lambda n: nodes.append(n)) nodes = list( filter( - lambda n: n.get('element') in ['obsidian_link', 'obsidian_embed'], + lambda n: n.get("element") in ["obsidian_link", "obsidian_embed"], nodes, ) ) node = nodes[0] - assert node['placeholder'] == '![[Hello]]' - assert node['title'] == None - assert node['target'] == 'Hello' - assert node['element'] == 'obsidian_embed' + assert node["placeholder"] == "![[Hello]]" + assert node["title"] == None + assert node["target"] == "Hello" + assert node["element"] == "obsidian_embed" node = nodes[1] - assert node['placeholder'] == '![[Hello | World]]' - assert node['title'] == 'World' - assert node['target'] == 'Hello' - assert node['element'] == 'obsidian_embed' + assert node["placeholder"] == "![[Hello | World]]" + assert node["title"] == "World" + assert node["target"] == "Hello" + assert node["element"] == "obsidian_embed" node = nodes[2] - assert node['placeholder'] == '[[Hello]]' - assert node['title'] == None - assert node['target'] == 'Hello' - assert node['element'] == 'obsidian_link' + assert node["placeholder"] == "[[Hello]]" + assert node["title"] == None + assert node["target"] == "Hello" + assert node["element"] == "obsidian_link" node = nodes[3] - assert node['placeholder'] == '[[Hello | World]]' - assert node['title'] == 'World' - assert node['target'] == 'Hello' - assert node['element'] == 'obsidian_link' + assert node["placeholder"] == "[[Hello | World]]" + assert node["title"] == "World" + assert node["target"] == "Hello" + assert node["element"] == "obsidian_link" node = nodes[4] - assert node['placeholder'] == '[[One | Two]]' - assert node['title'] == 'Two' - assert node['target'] == 'One' - assert node['element'] == 'obsidian_link' + assert node["placeholder"] == "[[One | Two]]" + assert node["title"] == "Two" + assert node["target"] == "One" + assert node["element"] == "obsidian_link" node = nodes[5] - assert node['placeholder'] == '[[Three | Four]]' - assert node['title'] == 'Four' - assert node['target'] == 'Three' - assert node['element'] == 'obsidian_link' + assert node["placeholder"] == "[[Three | Four]]" + assert node["title"] == "Four" + assert node["target"] == "Three" + assert node["element"] == "obsidian_link" diff --git a/tests/entities/reference_image_test.py b/tests/entities/reference_image_test.py index 147eae7..a7bce58 100644 --- a/tests/entities/reference_image_test.py +++ b/tests/entities/reference_image_test.py @@ -4,27 +4,27 @@ def test_reference_image_parsing(): - placeholder = '![alt][image_id]' - reference = '[image_id]: http://example.com' - page = create_page(content=f'{placeholder}\n{reference}') + placeholder = "![alt][image_id]" + reference = "[image_id]: http://example.com" + page = create_page(content=f"{placeholder}\n{reference}") entity = ReferenceImage.get_all(page)[0] assert entity.data.placeholder == placeholder - assert entity.data.filename == 'http://example.com' + assert entity.data.filename == "http://example.com" def test_reference_image_rendering(): - placeholder = '![alt][image_id]' - reference = '![image_id]: image.png' - page = create_page(content=f'{placeholder}\n{reference}') + placeholder = "![alt][image_id]" + reference = "![image_id]: image.png" + page = create_page(content=f"{placeholder}\n{reference}") content_data = ContentData( placeholder=placeholder, - filename='new-image.png', + filename="new-image.png", ) entity = ReferenceImage(data=content_data) res = entity.render(page.data) - assert res == f'![new-image](new-image.png)\n{reference}' + assert res == f"![new-image](new-image.png)\n{reference}" diff --git a/tests/helpers.py b/tests/helpers.py index 8109ddb..d14441e 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -2,14 +2,14 @@ from src.dataclasses.content_data import ContentData from src.obsidian.page import Page -fixtures_path = os.path.join(os.path.dirname(__file__), '__fixtures__') +fixtures_path = os.path.join(os.path.dirname(__file__), "__fixtures__") def get_fixture_path(name: str): return os.path.join(fixtures_path, name) -def create_page(filename='page.md', meta=None, content=None): +def create_page(filename="page.md", meta=None, content=None): content_data = ContentData(filename=filename, meta=meta, content=content) return Page(data=content_data) diff --git a/tests/preprocessors/further_reading_test.py b/tests/preprocessors/further_reading_test.py index 9ed38dd..822efc5 100644 --- a/tests/preprocessors/further_reading_test.py +++ b/tests/preprocessors/further_reading_test.py @@ -5,15 +5,15 @@ def test_further_reading_preprocessor(snapshot): content_data = ContentData( - filename='a.md', + filename="a.md", meta={ - 'links': [ - {'name': 'name.a', 'url': 'url.a'}, - {'name': 'name.b', 'url': 'url.b'}, - {'name': 'name.c', 'url': 'url.c'}, + "links": [ + {"name": "name.a", "url": "url.a"}, + {"name": "name.b", "url": "url.b"}, + {"name": "name.c", "url": "url.c"}, ] }, - content='content', + content="content", ) entity = DummyInclude(content_data) @@ -21,14 +21,14 @@ def test_further_reading_preprocessor(snapshot): entity.data.content - snapshot.assert_match(content_data.content, f'further_reading_test.html') + snapshot.assert_match(content_data.content, f"further_reading_test.html") def test_further_reading_preprocessor_no_links(snapshot): content_data = ContentData( - filename='a.md', + filename="a.md", meta={}, - content='content', + content="content", ) entity = DummyInclude(content_data) @@ -36,22 +36,20 @@ def test_further_reading_preprocessor_no_links(snapshot): entity.data.content - snapshot.assert_match( - content_data.content, f'further_reading_no_links_test.html' - ) + snapshot.assert_match(content_data.content, f"further_reading_no_links_test.html") def test_further_reading_preprocessor_empty_content(snapshot): content_data = ContentData( - filename='a.md', + filename="a.md", meta={ - 'links': [ - {'name': 'name.a', 'url': 'url.a'}, - {'name': 'name.b', 'url': 'url.b'}, - {'name': 'name.c', 'url': 'url.c'}, + "links": [ + {"name": "name.a", "url": "url.a"}, + {"name": "name.b", "url": "url.b"}, + {"name": "name.c", "url": "url.c"}, ] }, - content='', + content="", ) entity = DummyInclude(content_data) @@ -61,5 +59,5 @@ def test_further_reading_preprocessor_empty_content(snapshot): # Shoudn't render anything snapshot.assert_match( - content_data.content, f'further_reading_empty_content_test.html' + content_data.content, f"further_reading_empty_content_test.html" ) diff --git a/tests/preprocessors/include_header_test.py b/tests/preprocessors/include_header_test.py index 8867d7a..7c33a76 100644 --- a/tests/preprocessors/include_header_test.py +++ b/tests/preprocessors/include_header_test.py @@ -5,9 +5,9 @@ def test_include_header_preprocessor(snapshot): content_data = ContentData( - filename='a.md', - meta={'title': 'abc'}, - content='content', + filename="a.md", + meta={"title": "abc"}, + content="content", ) entity = DummyInclude(content_data) @@ -15,4 +15,4 @@ def test_include_header_preprocessor(snapshot): entity.data.content - snapshot.assert_match(content_data.content, f'include_header_test.html') + snapshot.assert_match(content_data.content, f"include_header_test.html") diff --git a/tests/tree/node_test.py b/tests/tree/node_test.py index aef7158..96f4fed 100644 --- a/tests/tree/node_test.py +++ b/tests/tree/node_test.py @@ -2,7 +2,7 @@ def test_tree_node(): - data = 'head node' + data = "head node" head = TreeNode(data) assert head.data == data @@ -61,7 +61,7 @@ def test_tree_node_recursive_flat(): def test_tree_node_unwrap(): - node = TreeNode('content') + node = TreeNode("content") res = TreeNode.unwrap(node) - assert res == 'content' + assert res == "content" From 55f7e9f86f4b1efa1a83b05e282299ec3b787816 Mon Sep 17 00:00:00 2001 From: Anton Shuvalov Date: Sun, 31 Jul 2022 17:36:36 +0700 Subject: [PATCH 2/2] Bump to 0.2.1 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 337cf2e..49c9485 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "obsidian-blog" -version = "0.2.0" +version = "0.2.1" description = "Feature rich static site generator for obsidian.md" authors = ["'Anton Shuvalov' "] license = "Commons Clause"