Skip to content

Commit beb407b

Browse files
authored
[MAINT] switch to ruff (#338)
* apply ruff * fix * fix
1 parent 8f14d9a commit beb407b

11 files changed

Lines changed: 144 additions & 121 deletions

File tree

.flake8

Lines changed: 0 additions & 32 deletions
This file was deleted.

.pre-commit-config.yaml

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,12 @@ repos:
2020
- id: mixed-line-ending
2121
- id: trailing-whitespace
2222

23-
# Sorts Python imports alphabetically and by section with `isort`.
24-
- repo: https://github.com/pycqa/isort
25-
rev: 6.0.1
26-
hooks:
27-
- id: isort
28-
args: [--profile, black, --settings-path, pyproject.toml]
29-
3023
# Automatically upgrade syntax for newer versions of the language.
3124
- repo: https://github.com/asottile/pyupgrade
3225
rev: v3.20.0
3326
hooks:
3427
- id: pyupgrade
35-
args: [--py38-plus]
36-
37-
# Aplly black formatting to python code
38-
# https://github.com/psf/black
39-
- repo: https://github.com/psf/black-pre-commit-mirror
40-
rev: 25.1.0
41-
hooks:
42-
- id: black
43-
args: [--config, pyproject.toml]
28+
args: [--py310-plus]
4429

4530
# Checks for spelling errors
4631
- repo: https://github.com/codespell-project/codespell
@@ -84,15 +69,13 @@ repos:
8469
- id: prettier
8570
types_or: [css, html, json]
8671

87-
# Check that Python code complies with PEP8 guidelines
88-
# flake8 uses pydocstyle to check docstrings: https://flake8.pycqa.org/en/latest/
89-
# flake8-docstrings: https://pypi.org/project/flake8-docstrings/
90-
# flake8-use-fstring forces to use fstrings: https://pypi.org/project/flake8-use-fstring/
91-
# flake8-functions checks functions quality: https://pypi.org/project/flake8-functions/
92-
# flake8-bugbear detects some common bugs: https://github.com/PyCQA/flake8-bugbear
93-
- repo: https://github.com/pyCQA/flake8
94-
rev: 7.3.0
72+
- repo: https://github.com/astral-sh/ruff-pre-commit
73+
rev: v0.12.7
9574
hooks:
96-
- id: flake8
97-
args: [--config, .flake8, --verbose, ecobidas, tests, macros]
98-
additional_dependencies: [flake8-docstrings, flake8-use-fstring, flake8-functions, flake8-bugbear]
75+
# Run the linter.
76+
- id: ruff-check
77+
# args: [--statistics]
78+
args: [--fix, --show-fixes]
79+
# Run the formatter.
80+
- id: ruff-format
81+
# args: [--diff]

ecobidas/cli.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def cli(argv: Sequence[str] = sys.argv) -> None:
3232
args, unknowns = parser.parse_known_args(argv[1:])
3333
if unknowns:
3434
logger.error(f"The following arguments are unknown: {unknowns}")
35-
exit(1)
35+
sys.exit(1)
3636

3737
verbosity = args.verbosity
3838
set_verbosity(verbosity)
@@ -46,21 +46,20 @@ def cli(argv: Sequence[str] = sys.argv) -> None:
4646
if isinstance(output_dir, list):
4747
output_dir = output_dir[0]
4848
convert(schema, output_dir, repo, branch)
49-
exit(0)
49+
sys.exit(0)
5050

5151
if args.command in ["update"]:
5252
schema = args.schema[0]
5353
download_spreadsheet(schema=schema)
54-
exit(0)
54+
sys.exit(0)
5555

5656
if args.command in ["serve"]:
5757
folder = args.folder if args.folder is None else args.folder[0]
5858
serve(folder=folder)
59-
exit(0)
59+
sys.exit(0)
6060

6161

6262
def convert(schema: str, output_dir: str, repo: str, branch: str) -> None:
63-
6463
logger.debug(f"{schema=}, {output_dir=}, {repo=}, {branch=}")
6564

6665
spreadsheets_info = get_spreadsheets_info()
@@ -69,7 +68,7 @@ def convert(schema: str, output_dir: str, repo: str, branch: str) -> None:
6968

7069
if not schema_list:
7170
logger.error(
72-
f"No known schema for: {schema=}" f"Known schemas are: {list(spreadsheets_info.keys())}"
71+
f"No known schema for: {schema=}Known schemas are: {list(spreadsheets_info.keys())}"
7372
)
7473

7574
for this_schema in schema_list:

ecobidas/create_schema.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import math
2-
import os
32
from pathlib import Path
43

54
import pandas as pd
@@ -59,8 +58,8 @@ def create_schema(
5958
if debug:
6059
activities = [1]
6160

62-
for i, activity_idx in enumerate(activities):
63-
this_activity = df["activity_order"] == activities[i]
61+
for activity_idx in activities:
62+
this_activity = df["activity_order"] == activity_idx
6463
items = df[this_activity]
6564
included_items = items["include"] == 1
6665
items = items[included_items]
@@ -85,14 +84,14 @@ def create_schema(
8584

8685
item_info = get_item_info(this_item)
8786

88-
if "message" in item_info and item_info["message"]:
87+
if item_info.get("message"):
8988
activity.messages.append(item_info["message"])
9089

91-
print_item_info(activity_idx, item_idx, item_info)
90+
print_item_info(str(activity_idx), item_idx, item_info)
9291

9392
item = define_new_item(item_info)
9493

95-
item.write(os.path.join(activity_path, "items"))
94+
item.write(Path(activity_path) / "items")
9695

9796
activity.append_item(item)
9897

@@ -150,7 +149,7 @@ def initialize_activity(items: pd.DataFrame, output_dir: str | Path) -> tuple[Ac
150149

151150

152151
def get_activity_preamble(items: pd.DataFrame) -> str:
153-
if "preamble" not in items.keys():
152+
if "preamble" not in items:
154153
return ""
155154

156155
not_nan = items["preamble"].notna()
@@ -182,7 +181,7 @@ def create_response_options(
182181
print_info(
183182
"response options",
184183
schema_info["basename"],
185-
os.path.join(output_dir, response_options.at_id),
184+
str(Path(output_dir) / response_options.at_id),
186185
)
187186

188187

@@ -197,12 +196,12 @@ def make_preamble(schema_info: dict[str, str], items: pd.DataFrame) -> str:
197196
if not preamble:
198197
return preamble
199198

200-
info = dict(
201-
preamble=preamble,
202-
xls=schema_info["link"],
203-
repo="",
204-
citation="",
205-
)
199+
info = {
200+
"preamble": preamble,
201+
"xls": schema_info["link"],
202+
"repo": "",
203+
"citation": "",
204+
}
206205

207206
if schema_info["repo"]:
208207
info["repo"] = schema_info["repo"]

ecobidas/download_tsv.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python3
22
"""Download the content of the different google spreadsheet in the inputs folder."""
3+
34
import ast
45
import json
56
from pathlib import Path
@@ -12,8 +13,7 @@
1213

1314

1415
# Function to download spreadsheet
15-
def download_spreadsheet(schema: str, output_dir: Path = None) -> None:
16-
16+
def download_spreadsheet(schema: str, output_dir: Path | None = None) -> None:
1717
if output_dir is None:
1818
output_dir = get_input_dir()
1919

@@ -33,7 +33,6 @@ def download_spreadsheet(schema: str, output_dir: Path = None) -> None:
3333

3434
# Iterate through entries and download spreadsheets
3535
for google_id, subfolder, output_filename in zip(google_ids, subfolders, output_filenames):
36-
3736
output_folder = output_dir / subfolder
3837
output_folder.mkdir(exist_ok=True, parents=True)
3938
output_file = output_folder / f"{output_filename}.tsv"
@@ -48,7 +47,7 @@ def download_spreadsheet(schema: str, output_dir: Path = None) -> None:
4847
f"https://docs.google.com/spreadsheets/d/{google_id}/export?format=tsv"
4948
)
5049
if response.status_code == 200:
51-
with open(output_file, "wb") as tsv_file:
50+
with output_file.open("wb") as tsv_file:
5251
tsv_file.write(response.content)
5352
else:
5453
logger.error("Error downloading the spreadsheet.")
@@ -69,7 +68,7 @@ def validate_downloaded_file(file: str | Path) -> None:
6968
df = pd.read_csv(file, sep="\t")
7069

7170
data_dictionary_file = get_input_dir() / "data-dictionary.json"
72-
with open(data_dictionary_file) as f:
71+
with data_dictionary_file.open() as f:
7372
data_dictionary = json.load(f)
7473

7574
columns = {x for x in df.columns if "Unnamed:" not in x}
@@ -96,11 +95,8 @@ def validate_downloaded_file(file: str | Path) -> None:
9695
f"\nThe following columns are missing from the data dictionary: {sorted(extra_columns)}"
9796
)
9897

99-
invalid_vis = []
100-
visibility = df.visibility.values
101-
for vis in visibility:
102-
if not is_valid_python(vis):
103-
invalid_vis.append(vis)
98+
visibility = df.visibility.to_numpy()
99+
invalid_vis = [vis for vis in visibility if not is_valid_python(vis)]
104100
if invalid_vis:
105101
logger.warning(f"\nThe following visibility are not valid python:\n{invalid_vis}")
106102

ecobidas/item.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88

99

1010
def set_item_name(this_item: dict) -> str:
11-
if "item" not in this_item.keys():
12-
item_name = convert_to_str(this_item["item_pref_label"])
13-
elif isinstance(convert_to_str(this_item["item"]), float):
14-
item_name = convert_to_str(this_item["item_pref_label"])
15-
elif convert_to_str(this_item["item"]) == "":
11+
if (
12+
"item" not in this_item
13+
or isinstance(convert_to_str(this_item["item"]), float)
14+
or convert_to_str(this_item["item"]) == ""
15+
):
1616
item_name = convert_to_str(this_item["item_pref_label"])
1717
else:
1818
item_name = convert_to_str(this_item["item"])

ecobidas/macros.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,23 @@ def main(output_dir: Path | None = None) -> None:
2828
output_dir = Path() / "output"
2929
output_dir.mkdir(exist_ok=True, parents=True)
3030

31-
with open(output_dir / "preset_responses_table.md", "w") as out:
31+
with (output_dir / "preset_responses_table.md").open("w") as out:
3232
out.write(f"{table_preset_responses()}")
3333

34-
with open(output_dir / "apps_table.md", "w") as out:
34+
with (output_dir / "apps_table.md").open("w") as out:
3535
out.write(f"{table_apps()}")
3636

37-
with open(output_dir / "spreadsheets_table.md", "w") as out:
37+
with (output_dir / "spreadsheets_table.md").open("w") as out:
3838
out.write(f"{table_spreadsheets()}")
3939

40-
with open(output_dir / "data_dictionary_table.md", "w") as out:
40+
with (output_dir / "data_dictionary_table.md").open("w") as out:
4141
out.write(f"{table_data_dictionary()}")
4242

4343

4444
def table_data_dictionary() -> str:
4545
"""Create markdown table for list of apps."""
4646
data_dictionary_file = get_input_dir() / "data-dictionary.json"
47-
with open(data_dictionary_file) as f:
47+
with data_dictionary_file.open() as f:
4848
data_dictionary = list(json.load(f).values())
4949
data_dictionary = sorted(data_dictionary, key=itemgetter("VariableName"))
5050
for i, _ in enumerate(data_dictionary):
@@ -74,9 +74,9 @@ def table_spreadsheets() -> str:
7474
for i, value in enumerate(sheets):
7575
if "meeg" in value["dir"]:
7676
continue
77-
sheets[i][
78-
"preview"
79-
] = f"{PREVIEW_BASE}{BASE_RAW_URL}/{value['dir']}/activities/{value['basename']}/{value['basename']}_schema.jsonld"
77+
sheets[i]["preview"] = (
78+
f"{PREVIEW_BASE}{BASE_RAW_URL}/{value['dir']}/activities/{value['basename']}/{value['basename']}_schema.jsonld"
79+
)
8080

8181
TemplateManager.initialize()
8282
template = TemplateManager.env.get_template("spreadsheet_table.j2")
@@ -86,7 +86,7 @@ def table_spreadsheets() -> str:
8686
def table_apps() -> str:
8787
"""Create markdown table for spreadsheets that are not apps or preset responses."""
8888
spreadsheets_info = get_spreadsheets_info()
89-
apps = [value for key, value in spreadsheets_info.items() if spreadsheets_info[key]["app_link"]]
89+
apps = [value for key, value in spreadsheets_info.items() if value["app_link"]]
9090
apps = sorted(apps, key=itemgetter("basename"))
9191

9292
TemplateManager.initialize()

ecobidas/utils.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def get_output_dir(this_schema: str | Path, output_dir: str | Path) -> Path:
3232
@lru_cache
3333
def get_spreadsheets_info() -> dict[str, dict[str, str]]:
3434
"""Load info about all the spreadsheets."""
35-
with open(get_input_dir() / "spreadsheet_google_id.yml") as f:
35+
with (get_input_dir() / "spreadsheet_google_id.yml").open() as f:
3636
spreadsheets_info = yaml.load(f)
3737

3838
for key in spreadsheets_info:
@@ -87,7 +87,7 @@ def load_data(this_schema: str) -> pd.DataFrame:
8787
schema_info = get_schema_info(this_schema)
8888
input_file = get_input_file(schema_info)
8989

90-
logger.info(f"\nLoading: {str(input_file)}\n")
90+
logger.info(f"\nLoading: {input_file!s}\n")
9191

9292
return pd.read_csv(input_file, sep="\t")
9393

@@ -112,7 +112,9 @@ def print_info(type: str, pref_label: str, file: str) -> None:
112112

113113
def print_item_info(activity_idx: str, item_idx: str, item_info: dict[str, str]) -> None:
114114
logger.debug(
115-
f"Activity: {int(activity_idx)} Item: {int(item_idx)}\t{item_info['name']}\t{item_info['field_type']}\t{item_info['visibility']}"
115+
f"Activity: {int(activity_idx)} "
116+
f"Item: {int(item_idx)}\t{item_info['name']}"
117+
f"\t{item_info['field_type']}\t{item_info['visibility']}"
116118
)
117119

118120

macros/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
__all__ = [
1111
"define_env",
1212
"table_apps",
13+
"table_data_dictionary",
1314
"table_preset_responses",
1415
"table_spreadsheets",
15-
"table_data_dictionary",
1616
]

0 commit comments

Comments
 (0)