Skip to content

Add pre-commit hook #6

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

Merged
merged 4 commits into from
Mar 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 0 additions & 128 deletions .flake8

This file was deleted.

13 changes: 13 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Pre-commit hooks
# 1. Run ruff on all python files
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.9.4
hooks:
# Run the linter.
# - id: ruff
# Run the formatter.
- id: ruff
args: ["check", "--select", "I", "--fix"]
- id: ruff-format
13 changes: 10 additions & 3 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import os
import sys

import pytest


# This collects tests that aren't standard pytest tests
def pytest_collect_file(parent, file_path):
# Special handling for test_validation.py
if file_path.name == "test_validation.py":
return ValidationTestFile.from_parent(parent, path=file_path)
return None


class ValidationTestFile(pytest.File):
def collect(self):
# Create a special test item for test_validation.py
yield ValidationTestItem.from_parent(self, name="test_validation")


class ValidationTestItem(pytest.Item):
def runtest(self):
# Run the test_validation.py script with "schema" as the argument
import subprocess
print(f"\n{'-'*80}\nRunning test_validation.py with 'schema' argument...")

print(f"\n{'-' * 80}\nRunning test_validation.py with 'schema' argument...")

result = subprocess.run(
[sys.executable, str(self.fspath), "schema"],
Expand All @@ -34,22 +39,24 @@ def runtest(self):
if result.returncode != 0:
raise ValidationTestFailure(result.stdout, result.stderr)

print(f"test_validation.py completed successfully.\n{'-'*80}")
print(f"test_validation.py completed successfully.\n{'-' * 80}")

def reportinfo(self):
return self.fspath, 0, f"test_validation.py schema"


class ValidationTestFailure(Exception):
def __init__(self, stdout, stderr):
self.stdout = stdout
self.stderr = stderr
super().__init__(f"test_validation.py failed")


@pytest.hookimpl(tryfirst=True)
def pytest_exception_interact(node, call, report):
if isinstance(call.excinfo.value, ValidationTestFailure):
failure = call.excinfo.value
print(f"test_validation.py failed!")
if failure.stderr:
print(f"STDERR:\n{failure.stderr}")
print(f"{'-'*80}")
print(f"{'-' * 80}")
13 changes: 7 additions & 6 deletions jsondoc/bin/convert_jsondoc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import argparse
import sys

import pypandoc

from jsondoc.convert.html import html_to_jsondoc
Expand Down Expand Up @@ -81,9 +82,9 @@ def convert_to_jsondoc(

input_content = None
if input_file is None:
assert (
source_format is not None
), "Source format must be specified if input file is not provided"
assert source_format is not None, (
"Source format must be specified if input file is not provided"
)

# Read from stdin
input_content = sys.stdin.read()
Expand All @@ -103,9 +104,9 @@ def convert_to_jsondoc(

if source_format == "jsondoc":
assert target_format is not None, "Target format must be specified"
assert (
target_format == "markdown"
), "Currently can only convert from JSON-DOC to Markdown"
assert target_format == "markdown", (
"Currently can only convert from JSON-DOC to Markdown"
)

if input_content is None:
raise Exception(
Expand Down
10 changes: 4 additions & 6 deletions jsondoc/convert/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,16 +373,14 @@ def __init__(self, **options):
self.options.update(options)
if self.options["strip"] is not None and self.options["convert"] is not None:
raise ValueError(
"You may specify either tags to strip or tags to"
" convert, but not both."
"You may specify either tags to strip or tags to convert, but not both."
)

def convert(self, html: str | bytes) -> Page | BlockBase | List[BlockBase]:
soup = BeautifulSoup(html, "html.parser")
return self.convert_soup(soup)

def convert_soup(self, soup: BeautifulSoup) -> Page | BlockBase | List[BlockBase]:

children = self.process_tag(soup, convert_as_inline=False, children_only=True)
children = run_final_block_transformations(children)
is_page = self._is_soup_page(soup)
Expand Down Expand Up @@ -483,9 +481,9 @@ def is_nested_node(el):
# text = convert_fn(node, text, convert_as_inline)
# current_level_object = convert_fn(node, convert_as_inline)
convert_output = convert_fn(node, convert_as_inline)
assert isinstance(
convert_output, (ConvertOutput, NoneType)
), f"Convert function {convert_fn} must return a ConvertOutput or None"
assert isinstance(convert_output, (ConvertOutput, NoneType)), (
f"Convert function {convert_fn} must return a ConvertOutput or None"
)

if convert_output is not None:
current_level_object = convert_output.main_object
Expand Down
9 changes: 3 additions & 6 deletions jsondoc/convert/markdown.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import re
from typing import List, Union

from pydantic import validate_call

from jsondoc.convert.utils import get_rich_text_from_block
from jsondoc.models.block.base import BlockBase
from jsondoc.models.block.types.code import CodeBlock
Expand All @@ -19,7 +21,6 @@
from jsondoc.models.shared_definitions import Annotations
from jsondoc.serialize import load_jsondoc, load_page


convert_heading_re = re.compile(r"convert_heading_(\d+)")
line_beginning_re = re.compile(r"^", re.MULTILINE)
whitespace_re = re.compile(r"[\t ]+")
Expand Down Expand Up @@ -60,7 +61,6 @@ def chomp(text):


class JsonDocToMarkdownConverter(object):

class DefaultOptions:
autolinks = True
bullets = "*+-" # An iterable of bullet types.
Expand Down Expand Up @@ -90,8 +90,7 @@ def __init__(self, **options):
self.options.update(options)
if self.options["strip"] is not None and self.options["convert"] is not None:
raise ValueError(
"You may specify either tags to strip or tags to"
" convert, but not both."
"You may specify either tags to strip or tags to convert, but not both."
)

def __getattr__(self, attr):
Expand All @@ -111,7 +110,6 @@ def convert_tag(block, convert_as_inline):

@validate_call
def convert(self, obj: str | dict | BlockBase | List[BlockBase] | Page) -> str:

if isinstance(obj, (str, dict)):
jsondoc = load_jsondoc(obj)
else:
Expand Down Expand Up @@ -145,7 +143,6 @@ def _get_children_content(self, block: BlockBase, convert_as_inline: bool) -> st

@validate_call
def convert_block(self, block: BlockBase, convert_as_inline: bool) -> str:

type_ = block.type
convert_fn = getattr(self, f"convert_{type_}_block", None)

Expand Down
3 changes: 1 addition & 2 deletions jsondoc/convert/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from datetime import datetime, timezone
import re
from datetime import datetime, timezone
from typing import List, Literal, Optional, Type

from bs4 import Tag
Expand Down Expand Up @@ -109,7 +109,6 @@ def create_rich_text(
color: str | None = None,
annotations: Annotations | None = None,
) -> RichTextText | RichTextEquation:

if text is not None and equation is not None:
raise ValueError("Only one of text or equation must be provided")

Expand Down
36 changes: 18 additions & 18 deletions jsondoc/models/block/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,24 @@


class Type(Enum):
paragraph = 'paragraph'
to_do = 'to_do'
bulleted_list_item = 'bulleted_list_item'
numbered_list_item = 'numbered_list_item'
code = 'code'
column = 'column'
column_list = 'column_list'
divider = 'divider'
equation = 'equation'
heading_1 = 'heading_1'
heading_2 = 'heading_2'
heading_3 = 'heading_3'
image = 'image'
quote = 'quote'
equation_1 = 'equation'
table = 'table'
table_row = 'table_row'
toggle = 'toggle'
paragraph = "paragraph"
to_do = "to_do"
bulleted_list_item = "bulleted_list_item"
numbered_list_item = "numbered_list_item"
code = "code"
column = "column"
column_list = "column_list"
divider = "divider"
equation = "equation"
heading_1 = "heading_1"
heading_2 = "heading_2"
heading_3 = "heading_3"
image = "image"
quote = "quote"
equation_1 = "equation"
table = "table"
table_row = "table_row"
toggle = "toggle"


class Block(BlockBase):
Expand Down
Loading
Loading