Skip to content

Commit

Permalink
Add ruff config to pre-commit (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
anneschuth authored Sep 5, 2024
2 parents 5130bf2 + 285088b commit 4758bd6
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 42 deletions.
17 changes: 17 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Ruff settings: https://docs.astral.sh/ruff/configuration/
[tool.ruff]
line-length = 120
target-version = "py311"
src = ["script"]

[tool.ruff.format]
line-ending = "lf"

[tool.ruff.lint]
select = ["I", "SIM", "B", "UP", "F", "E", "S", "C90", "DTZ", "LOG", "PIE", "PT", "ERA", "W", "C", "TRY", "RUF"]
fixable = ["ALL"]
task-tags = ["TODO"]
ignore = ["TRY003", "ANN101"]

[tool.ruff.lint.mccabe]
max-complexity = 12
39 changes: 13 additions & 26 deletions script/inject_definitions_in_decision_tree.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,25 @@
# !/usr/bin/env python3

import yaml
import re
import json
import re

import yaml

# Load the decision-tree.yaml file
with open("decision-tree.yaml", "r") as file:
with open("decision-tree.yaml") as file:
decision_tree = yaml.safe_load(file)

# Load the definitions.yaml file
with open("definitions.yaml", "r") as file:
with open("definitions.yaml") as file:
definitions = yaml.safe_load(file)

# Create a dictionary to lookup terms
term_dict = {
definition["term"]: (
f"<dfn><abbr title=\"{definition['definition']}\">{definition['term']}</abbr></dfn>"
)
definition["term"]: (f"<dfn><abbr title=\"{definition['definition']}\">{definition['term']}</abbr></dfn>")
for definition in definitions["definitions"]
}

pattern = re.compile(
"|".join(
[re.escape(term) for term in sorted(term_dict.keys(), key=len, reverse=True)]
)
)
pattern = re.compile("|".join([re.escape(term) for term in sorted(term_dict.keys(), key=len, reverse=True)]))


def replace_terms_callback(match):
Expand All @@ -37,8 +32,8 @@ def replace_terms_callback(match):

def replace_terms(text, term_dict):
"""
Replace all occurrences of terms in the text with their corresponding <dfn><abbr title=""></abbr></dfn> wrapped terms.
Uses a regular expression with a callback function to ensure the longest term is replaced first.
Replace all occurrences of terms in the text with their corresponding <dfn><abbr title=""></abbr></dfn> wrapped
terms. Uses a regular expression with a callback function to ensure the longest term is replaced first.
"""
return pattern.sub(replace_terms_callback, text)

Expand All @@ -58,22 +53,16 @@ def process_question_or_conclusion(text, term_dict):
q["question"] = process_question_or_conclusion(q.get("question", ""), term_dict)

if "description" in q:
q["description"] = process_question_or_conclusion(
q.get("description", ""), term_dict
)
q["description"] = process_question_or_conclusion(q.get("description", ""), term_dict)

for a in q.get("answers", []):
a["answer"] = process_question_or_conclusion(a.get("answer", ""), term_dict)

if "subresult" in a:
a["subresult"] = process_question_or_conclusion(
a.get("subresult", ""), term_dict
)
a["subresult"] = process_question_or_conclusion(a.get("subresult", ""), term_dict)

if "answerComment" in a:
a["answerComment"] = process_question_or_conclusion(
a.get("answerComment", ""), term_dict
)
a["answerComment"] = process_question_or_conclusion(a.get("answerComment", ""), term_dict)

# Process conclusions
for c in decision_tree.get("conclusions", []):
Expand All @@ -82,9 +71,7 @@ def process_question_or_conclusion(text, term_dict):
c["obligation"] = process_question_or_conclusion(c.get("obligation", ""), term_dict)

if "conclusionComment" in c:
c["conclusionComment"] = process_question_or_conclusion(
c.get("conclusionComment", ""), term_dict
)
c["conclusionComment"] = process_question_or_conclusion(c.get("conclusionComment", ""), term_dict)

# Save the modified decision_tree back to a YAML file
with open("frontend/src/assets/decision-tree.json", "w+") as file:
Expand Down
13 changes: 5 additions & 8 deletions script/json2yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
questions = []


def parse_question(data, id="0"):
def parse_question(data, id="0") -> None:
global questions

if isinstance(data, list): # all lists are 1 length. why is it like this?
Expand Down Expand Up @@ -65,20 +65,18 @@ def parse_question(data, id="0"):


def read_json(file: str) -> dict:
with open(file, "r") as f:
with open(file) as f:
json_str = f.read()
data = json.loads(json_str)
return data


def write_yaml(dict: dict, file: str):
def write_yaml(dict: dict, file: str) -> None:
with open(file, "w") as f:
yaml.dump(
dict, f, default_flow_style=False, sort_keys=False, width=float("inf")
)
yaml.dump(dict, f, default_flow_style=False, sort_keys=False, width=float("inf"))


def change_answer_id(questions, old, new):
def change_answer_id(questions, old, new) -> None:
for question in questions:
for answer in question.get("answers"):
if answer.get("nextQuestionId") == old:
Expand Down Expand Up @@ -108,7 +106,6 @@ def remove_duplicates():
index = q.index(hashed)
change_answer_id(new_questions, duplicate_id, ids[index])

pass
else:
new_questions.append(question)
q.append(hashed)
Expand Down
15 changes: 7 additions & 8 deletions script/validate
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env python3

import argparse
import json
import sys
import argparse

import jsonschema
import yaml
Expand All @@ -21,23 +21,21 @@ args = parser.parse_args()


# Function to validate a single pair
def validate_pair(schema_file, yaml_file):
def validate_pair(schema_file, yaml_file) -> None:
# Load the JSON schema
with open(schema_file, "r") as sf:
with open(schema_file) as sf:
schema = json.load(sf)

# Load the YAML file
with open(yaml_file, "r") as yf:
with open(yaml_file) as yf:
data = yaml.safe_load(yf)

# Validate the data
try:
validate(instance=data, schema=schema)
print(f"Validation of '{yaml_file}' against '{schema_file}' successful.")
except jsonschema.exceptions.ValidationError as err:
print(
f"Validation error in '{yaml_file}' against '{schema_file}': {err.message}"
)
print(f"Validation error in '{yaml_file}' against '{schema_file}': {err.message}")
sys.exit(1)


Expand All @@ -48,6 +46,7 @@ if args.file_pairs:
validate_pair(schema_file, yaml_file)
else:
print(
"Error: Please provide either --schema_file and --yaml_file for a single validation, or --file_pairs for multiple validations."
"Error: Please provide either --schema_file and --yaml_file for a single validation, or --file_pairs for "
"multiple validations."
)
sys.exit(1)

0 comments on commit 4758bd6

Please sign in to comment.