Skip to content

Commit

Permalink
chore: Format all code
Browse files Browse the repository at this point in the history
  • Loading branch information
SilverRainZ committed Aug 18, 2024
1 parent 24e0a5f commit 5792c40
Show file tree
Hide file tree
Showing 14 changed files with 405 additions and 304 deletions.
59 changes: 31 additions & 28 deletions src/sphinxnotes/snippet/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""
sphinxnotes.snippet
~~~~~~~~~~~~~~~~~~~
sphinxnotes.snippet
~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2020 Shengyu Zhang
:license: BSD, see LICENSE for details.
:copyright: Copyright 2020 Shengyu Zhang
:license: BSD, see LICENSE for details.
"""

from __future__ import annotations
Expand All @@ -14,44 +14,45 @@

__version__ = '1.1.1'


class Snippet(object):
"""
Snippet is base class of reStructuredText snippet.
:param nodes: Document nodes that make up this snippet
:param nodes: Document nodes that make up this snippet
"""

#: Source file path of snippet
file:str
file: str

#: Line number range of snippet, in the source file which is left closed
#: and right opened.
lineno:Tuple[int,int]
lineno: Tuple[int, int]

#: The original reStructuredText of snippet
rst:List[str]
rst: List[str]

#: The possible identifier key of snippet, which is picked from nodes'
#: (or nodes' parent's) `ids attr`_.
#:
#: .. _ids attr: https://docutils.sourceforge.io/docs/ref/doctree.html#ids
refid:Optional[str]
refid: Optional[str]

def __init__(self, *nodes:nodes.Node) -> None:
def __init__(self, *nodes: nodes.Node) -> None:
assert len(nodes) != 0

self.file = nodes[0].source

lineno = [float('inf'), -float('inf')]
for node in nodes:
if not node.line:
continue # Skip node that have None line, I dont know why
continue # Skip node that have None line, I dont know why
lineno[0] = min(lineno[0], _line_of_start(node))
lineno[1] = max(lineno[1], _line_of_end(node))
self.lineno = lineno

lines = []
with open(self.file, "r") as f:
with open(self.file, 'r') as f:
start = self.lineno[0] - 1
stop = self.lineno[1] - 1
for line in itertools.islice(f, start, stop):
Expand All @@ -73,61 +74,60 @@ def __init__(self, *nodes:nodes.Node) -> None:
break



class Text(Snippet):
#: Text of snippet
text:str
text: str

def __init__(self, node:nodes.Node) -> None:
def __init__(self, node: nodes.Node) -> None:
super().__init__(node)
self.text = node.astext()


class CodeBlock(Text):
#: Language of code block
language:str
language: str
#: Caption of code block
caption:Optional[str]
caption: Optional[str]

def __init__(self, node:nodes.literal_block) -> None:
def __init__(self, node: nodes.literal_block) -> None:
assert isinstance(node, nodes.literal_block)
super().__init__(node)
self.language = node['language']
self.caption = node.get('caption')


class WithCodeBlock(object):
code_blocks:List[CodeBlock]
code_blocks: List[CodeBlock]

def __init__(self, nodes:nodes.Nodes) -> None:
def __init__(self, nodes: nodes.Nodes) -> None:
self.code_blocks = []
for n in nodes.traverse(nodes.literal_block):
self.code_blocks.append(self.CodeBlock(n))


class Title(Text):
def __init__(self, node:nodes.title) -> None:
def __init__(self, node: nodes.title) -> None:
assert isinstance(node, nodes.title)
super().__init__(node)


class WithTitle(object):
title:Optional[Title]
title: Optional[Title]

def __init__(self, node:nodes.Node) -> None:
def __init__(self, node: nodes.Node) -> None:
title_node = node.next_node(nodes.title)
self.title = Title(title_node) if title_node else None


class Section(Snippet, WithTitle):
def __init__(self, node:nodes.section) -> None:
def __init__(self, node: nodes.section) -> None:
assert isinstance(node, nodes.section)
Snippet.__init__(self, node)
WithTitle.__init__(self, node)


class Document(Section):
def __init__(self, node:nodes.document) -> None:
def __init__(self, node: nodes.document) -> None:
assert isinstance(node, nodes.document)
super().__init__(node.next_node(nodes.section))

Expand All @@ -136,7 +136,8 @@ def __init__(self, node:nodes.document) -> None:
# Nodes helper #
################

def _line_of_start(node:nodes.Node) -> int:

def _line_of_start(node: nodes.Node) -> int:
assert node.line
if isinstance(node, nodes.title):
if isinstance(node.parent.parent, nodes.document):
Expand All @@ -155,7 +156,7 @@ def _line_of_start(node:nodes.Node) -> int:
return node.line


def _line_of_end(node:nodes.Node) -> Optional[int]:
def _line_of_end(node: nodes.Node) -> Optional[int]:
next_node = node.next_node(descend=False, siblings=True, ascend=True)
while next_node:
if next_node.line:
Expand All @@ -166,7 +167,9 @@ def _line_of_end(node:nodes.Node) -> Optional[int]:
descend=True,
# If node and its children have not valid line attr, try use line
# of next node
ascend=True, siblings=True)
ascend=True,
siblings=True,
)
# No line found, return the max line of source file
if node.source:
with open(node.source) as f:
Expand Down
70 changes: 36 additions & 34 deletions src/sphinxnotes/snippet/cache.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
""" sphinxnotes.snippet.cache
~~~~~~~~~~~~~~~~~~~~~~~~~
"""sphinxnotes.snippet.cache
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2021 Shengyu Zhang
:license: BSD, see LICENSE for details.
:copyright: Copyright 2021 Shengyu Zhang
:license: BSD, see LICENSE for details.
"""

from __future__ import annotations
Expand All @@ -12,38 +12,41 @@
from . import Snippet
from .utils.pdict import PDict


@dataclass(frozen=True)
class Item(object):
""" Item of snippet cache. """
snippet:Snippet
tags:List[str]
excerpt:str
titlepath:List[str]
keywords:List[str]
"""Item of snippet cache."""

snippet: Snippet
tags: List[str]
excerpt: str
titlepath: List[str]
keywords: List[str]


DocID = Tuple[str, str] # (project, docname)
IndexID = str # UUID
Index = Tuple[str, str, List[str], List[str]] # (tags, excerpt, titlepath, keywords)

DocID = Tuple[str,str] # (project, docname)
IndexID = str # UUID
Index = Tuple[str,str,List[str],List[str]] # (tags, excerpt, titlepath, keywords)

class Cache(PDict):
"""A DocID -> List[Item] Cache."""
indexes:Dict[IndexID,Index]
index_id_to_doc_id:Dict[IndexID,Tuple[DocID,int]]
doc_id_to_index_ids:Dict[DocID,List[IndexID]]
num_snippets_by_project:Dict[str,int]
num_snippets_by_docid:Dict[DocID,int]

def __init__(self, dirname:str) -> None:
indexes: Dict[IndexID, Index]
index_id_to_doc_id: Dict[IndexID, Tuple[DocID, int]]
doc_id_to_index_ids: Dict[DocID, List[IndexID]]
num_snippets_by_project: Dict[str, int]
num_snippets_by_docid: Dict[DocID, int]

def __init__(self, dirname: str) -> None:
self.indexes = {}
self.index_id_to_doc_id = {}
self.doc_id_to_index_ids = {}
self.num_snippets_by_project= {}
self.num_snippets_by_project = {}
self.num_snippets_by_docid = {}
super().__init__(dirname)


def post_dump(self, key:DocID, items:List[Item]) -> None:
def post_dump(self, key: DocID, items: List[Item]) -> None:
"""Overwrite PDict.post_dump."""

# Remove old indexes and index IDs if exists
Expand All @@ -54,10 +57,12 @@ def post_dump(self, key:DocID, items:List[Item]) -> None:
# Add new index to every where
for i, item in enumerate(items):
index_id = self.gen_index_id()
self.indexes[index_id] = (item.tags,
item.excerpt,
item.titlepath,
item.keywords)
self.indexes[index_id] = (
item.tags,
item.excerpt,
item.titlepath,
item.keywords,
)
self.index_id_to_doc_id[index_id] = (key, i)
self.doc_id_to_index_ids[key].append(index_id)

Expand All @@ -69,8 +74,7 @@ def post_dump(self, key:DocID, items:List[Item]) -> None:
self.num_snippets_by_docid[key] = 0
self.num_snippets_by_docid[key] += len(items)


def post_purge(self, key:DocID, items:List[Item]) -> None:
def post_purge(self, key: DocID, items: List[Item]) -> None:
"""Overwrite PDict.post_purge."""

# Purge indexes
Expand All @@ -86,21 +90,19 @@ def post_purge(self, key:DocID, items:List[Item]) -> None:
if self.num_snippets_by_docid[key] == 0:
del self.num_snippets_by_docid[key]


def get_by_index_id(self, key:IndexID) -> Optional[Item]:
def get_by_index_id(self, key: IndexID) -> Optional[Item]:
"""Like get(), but use IndexID as key."""
doc_id, item_index = self.index_id_to_doc_id.get(key, (None,None))
doc_id, item_index = self.index_id_to_doc_id.get(key, (None, None))
if not doc_id:
return None
return self[doc_id][item_index]


def gen_index_id(self) -> str:
"""Generate unique ID for index."""
import uuid
return uuid.uuid4().hex[:7]

return uuid.uuid4().hex[:7]

def stringify(self, key:DocID, items:List[Item]) -> str:
def stringify(self, key: DocID, items: List[Item]) -> str:
"""Overwrite PDict.stringify."""
return key[1]
Loading

0 comments on commit 5792c40

Please sign in to comment.