Skip to content

Commit

Permalink
Merge pull request #35 from A/release-0.2.1
Browse files Browse the repository at this point in the history
Release 0.2.1
  • Loading branch information
A committed Jul 31, 2022
2 parents ffd1740 + 55f7e9f commit a6c59fc
Show file tree
Hide file tree
Showing 36 changed files with 256 additions and 263 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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' <[email protected]>"]
license = "Commons Clause"
Expand Down
42 changes: 21 additions & 21 deletions src/builder/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,25 +32,25 @@ 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)

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"
Expand All @@ -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):
Expand All @@ -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):
Expand All @@ -100,31 +100,31 @@ 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
pass

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)

Expand All @@ -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
14 changes: 7 additions & 7 deletions src/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -63,5 +63,5 @@ def main():
print(e)


if __name__ == '__main__':
if __name__ == "__main__":
main()
14 changes: 7 additions & 7 deletions src/converters/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
},
)
Expand Down
6 changes: 3 additions & 3 deletions src/dataclasses/asset_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 11 additions & 11 deletions src/dataclasses/config_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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()
34 changes: 16 additions & 18 deletions src/dataclasses/content_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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

Expand All @@ -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):
Expand All @@ -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

Expand All @@ -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()
2 changes: 1 addition & 1 deletion src/entities/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
4 changes: 2 additions & 2 deletions src/entities/inline_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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 = []
Expand Down
4 changes: 2 additions & 2 deletions src/entities/markdown_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading

0 comments on commit a6c59fc

Please sign in to comment.