-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add AnkiConnect plugin support #29
Open
MarkoSagadin
wants to merge
3
commits into
Mochitto:main
Choose a base branch
from
MarkoSagadin:feature/ankiconnect
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,72 @@ | ||
import frontmatter | ||
from jsonschema import validate | ||
from jsonschema.exceptions import ValidationError | ||
|
||
from markdown2anki.utils import common_types as Types | ||
|
||
|
||
# Note: Keep MarkdownMetadata and metadata_schema in sync when changing. | ||
class MarkdownMetadata: | ||
def __init__( | ||
self, | ||
deck_name: str, | ||
note_type_basic: str, | ||
note_type_cloze: str, | ||
tags: list[str] | None = None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be useful to add a This should be easy to add as "default" and have the incoming list append to it |
||
no_tabs: bool = False, | ||
) -> None: | ||
self.deck_name = deck_name | ||
self.note_type_basic = note_type_basic | ||
self.note_type_cloze = note_type_cloze | ||
self.tags = tags | ||
self.no_tabs = no_tabs | ||
|
||
|
||
metadata_schema = { | ||
"type": "object", | ||
"properties": { | ||
"deck_name": {"type": "string"}, | ||
"note_type_basic": {"type": "string"}, | ||
"note_type_cloze": {"type": "string"}, | ||
"tags": {"type": "array", "items": {"type": "string"}}, | ||
"no_tabs": {"type": "boolean"}, | ||
}, | ||
"required": [ | ||
"deck_name", | ||
"note_type_basic", | ||
"note_type_cloze", | ||
], | ||
"optional": ["tags", "no_tabs"], | ||
"additionalProperties": False, | ||
} | ||
|
||
|
||
class MarkdownHandler: | ||
def __init__(self, path: Types.PathString) -> None: | ||
self.filepath = path | ||
self._PostObject = frontmatter.load(path) | ||
self.content = self._PostObject.content | ||
self.metadata = self._PostObject.metadata | ||
""" | ||
From given path to markdown file create a MarkdownHandler object. | ||
|
||
Both content and metadata are extracted from the file and stored in the object. | ||
Metadata is validated against a schema. | ||
""" | ||
with open(path) as f: | ||
self.metadata, self.content = frontmatter.parse(f.read()) | ||
|
||
if not self.metadata: | ||
raise Exception("No metadata found in file.") | ||
|
||
try: | ||
validate(instance=self.metadata, schema=metadata_schema) | ||
except ValidationError as e: | ||
raise Exception(f"Invalid metadata schema: {e}") | ||
|
||
# Unpack unstructred metadata and pass it through the MarkdownMetadata class to | ||
# get the structured metadata and set defaults for optional fields, then convert | ||
# it back to a dict. | ||
self.metadata = MarkdownMetadata(**self.metadata).__dict__ | ||
|
||
def get_frontmatter_text(self): | ||
def get_frontmatter_text(self) -> str: | ||
"""Return frontmatter text.""" | ||
yaml_text = frontmatter.YAMLHandler().export(self.metadata) | ||
frontmatter_text = "---\n" + yaml_text + "\n---\n\n" | ||
return frontmatter_text |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
import pytest | ||
from markdown2anki.markdown_handler import MarkdownHandler | ||
|
||
# NOTE: In all below strings it is important that the string starts in the same line as | ||
# the triple quotes. Otherwise, the frontmatter will not be detected due to the extra | ||
# newline. | ||
|
||
|
||
content_0 = """Some dummy content, no frontmatter.""" | ||
|
||
|
||
def test_given_file_with_no_frontmatter_raises_exception(temp_md_file): | ||
with pytest.raises(Exception): | ||
_ = MarkdownHandler(temp_md_file(content_0)) | ||
|
||
|
||
content_1 = """--- | ||
invalid_frontmatter | ||
--- | ||
|
||
Some dummy content | ||
""" | ||
|
||
|
||
def test_given_file_with_invalid_yaml_raises_exception(temp_md_file): | ||
with pytest.raises(Exception): | ||
_ = MarkdownHandler(temp_md_file(content_1)) | ||
|
||
|
||
content_2 = """--- | ||
deck_name: deck | ||
note_type_basic: basic | ||
note_type_cloze: cloze | ||
--- | ||
|
||
Some dummy content | ||
""" | ||
|
||
|
||
def test_given_file_with_valid_yaml_succeeds(temp_md_file): | ||
handle = MarkdownHandler(temp_md_file(content_2)) | ||
|
||
assert handle.metadata["deck_name"] == "deck" | ||
assert handle.metadata["note_type_basic"] == "basic" | ||
assert handle.metadata["note_type_cloze"] == "cloze" | ||
|
||
|
||
content_3 = """--- | ||
some_wrong_key: deck | ||
note_type_basic: basic | ||
note_type_cloze: cloze | ||
--- | ||
|
||
Some dummy content | ||
""" | ||
|
||
|
||
def test_given_file_with_invalid_yaml_schema_raises_exception(temp_md_file): | ||
with pytest.raises(Exception): | ||
_ = MarkdownHandler(temp_md_file(content_3)) | ||
|
||
|
||
content_4 = """--- | ||
deck_name: deck | ||
note_type_basic: basic | ||
note_type_cloze: cloze | ||
tags: | ||
- tag1 | ||
- tag2 | ||
--- | ||
|
||
Some dummy content | ||
""" | ||
|
||
|
||
def test_given_file_with_optional_tags_succeeds(temp_md_file): | ||
handle = MarkdownHandler(temp_md_file(content_4)) | ||
|
||
assert handle.metadata["tags"] == ["tag1", "tag2"] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo