Skip to content

Commit c4cf878

Browse files
committed
pre-commit checks
1 parent a2f68da commit c4cf878

File tree

6 files changed

+90
-59
lines changed

6 files changed

+90
-59
lines changed

gateway/sds_gateway/static/js/dataset/DatasetEditingHandler.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ class DatasetEditingHandler {
486486
markFileForRemoval(fileId) {
487487
const file = this.filesSearchHandler?.selectedFiles.get(fileId);
488488

489-
if (!file){
489+
if (!file) {
490490
console.warn(`File ${fileId} not found for removal`);
491491
return;
492492
}

gateway/sds_gateway/static/js/dataset/__tests__/DatasetEditingHandler.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -324,17 +324,17 @@ describe("DatasetEditingHandler", () => {
324324
},
325325
);
326326
});
327-
327+
328328
describe("Cancel Button Functionality", () => {
329329
beforeEach(() => {
330330
editingHandler = new DatasetEditingHandler(mockConfig);
331-
331+
332332
// Mock required DOM elements for cancel operations
333333
const pendingCapturesList = document.createElement("tbody");
334334
pendingCapturesList.id = "pending-captures-list";
335335
const pendingFilesList = document.createElement("tbody");
336336
pendingFilesList.id = "pending-files-list";
337-
337+
338338
document.getElementById = jest.fn((id) => {
339339
if (id === "pending-captures-list") return pendingCapturesList;
340340
if (id === "pending-files-list") return pendingFilesList;

gateway/sds_gateway/static/js/dataset/__tests__/DatasetModeManager.test.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ describe("DatasetModeManager", () => {
259259
}).toThrow();
260260
});
261261
});
262-
262+
263263
describe("Public/Private Dataset Management", () => {
264264
beforeEach(() => {
265265
modeManager = new DatasetModeManager(mockConfig);
@@ -274,10 +274,10 @@ describe("DatasetModeManager", () => {
274274
...mockConfig,
275275
existingDatasetIsPublic: false,
276276
};
277-
277+
278278
const publicManager = new DatasetModeManager(publicConfig);
279279
const privateManager = new DatasetModeManager(privateConfig);
280-
280+
281281
expect(publicManager.isExistingPublicDataset()).toBe(true);
282282
expect(privateManager.isExistingPublicDataset()).toBe(false);
283283
});
@@ -287,11 +287,11 @@ describe("DatasetModeManager", () => {
287287
publicOption.id = "public-option";
288288
publicOption.type = "radio";
289289
publicOption.checked = true;
290-
290+
291291
const statusField = document.createElement("input");
292292
statusField.id = "id_status";
293293
statusField.value = "final";
294-
294+
295295
document.getElementById = jest.fn((id) => {
296296
if (id === "public-option") return publicOption;
297297
if (id === "id_status") return statusField;
@@ -300,11 +300,11 @@ describe("DatasetModeManager", () => {
300300

301301
expect(modeManager.isCurrentSessionPublicDataset()).toBe(true);
302302
expect(modeManager.isCurrentSessionFinalDataset()).toBe(true);
303-
303+
304304
// Test draft/private combination
305305
publicOption.checked = false;
306306
statusField.value = "draft";
307-
307+
308308
expect(modeManager.isCurrentSessionPublicDataset()).toBe(false);
309309
expect(modeManager.isCurrentSessionFinalDataset()).toBe(false);
310310
});

gateway/sds_gateway/static/js/search/AssetSearchHandler.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,7 @@ class AssetSearchHandler {
298298
// Normalize for generic table_rows template
299299
const rows = capturesData.map((capture) => ({
300300
data_attrs: { "capture-id": capture.id },
301-
cells: [
302-
{ value: capture.type },
303-
{ value: capture.directory },
304-
],
301+
cells: [{ value: capture.type }, { value: capture.directory }],
305302
actions: [
306303
{
307304
label: "Remove",
@@ -993,10 +990,10 @@ class AssetSearchHandler {
993990
const row = document.createElement("tr");
994991
const filePath = this.getRelativePath(file, currentPath);
995992
const isSelected = this.selectedFiles.has(file.id);
996-
993+
997994
// Check if file is already in the dataset (edit mode only)
998-
const isExistingFile = this.isEditMode &&
999-
this.formHandler?.currentFiles?.has(file.id);
995+
const isExistingFile =
996+
this.isEditMode && this.formHandler?.currentFiles?.has(file.id);
1000997
row.innerHTML = `
1001998
<td>
1002999
<input type="checkbox" class="form-check-input" name="files" value="${file.id}"

gateway/sds_gateway/static/js/search/__tests__/AssetSearchHandler.test.js

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ describe("AssetSearchHandler", () => {
282282
expect(searchHandler.currentFilters.type).toBe("spectrum");
283283
});
284284
});
285-
285+
286286
describe("Checkbox Disabling for Existing Files", () => {
287287
let editModeHandler;
288288
let createModeHandler;
@@ -296,10 +296,7 @@ describe("AssetSearchHandler", () => {
296296
formHandler: {
297297
setSearchHandler: jest.fn(),
298298
currentFiles: new Map([
299-
[
300-
"existing-file-1",
301-
{ id: "existing-file-1", name: "existing.h5" },
302-
],
299+
["existing-file-1", { id: "existing-file-1", name: "existing.h5" }],
303300
]),
304301
},
305302
};
@@ -315,7 +312,7 @@ describe("AssetSearchHandler", () => {
315312
// Mock target element for rendering
316313
mockTargetElement = document.createElement("tbody");
317314
mockTargetElement.id = "file-tree-table-body";
318-
315+
319316
// Mock DOMUtils.formatFileSize
320317
global.window.DOMUtils.formatFileSize = jest.fn((size) => size || "0 B");
321318
});

gateway/sds_gateway/users/views.py

Lines changed: 72 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1700,7 +1700,7 @@ class GroupCapturesView(
17001700
# ========== Helper Methods ==========
17011701

17021702
def _parse_dataset_uuid(
1703-
self, dataset_uuid_str: str, raise_on_error: bool = False
1703+
self, dataset_uuid_str: str, *, raise_on_error: bool = False
17041704
) -> UUID | None:
17051705
"""
17061706
Parse dataset UUID string with consistent error handling.
@@ -1717,10 +1717,10 @@ def _parse_dataset_uuid(
17171717
"""
17181718
try:
17191719
return UUID(dataset_uuid_str)
1720-
except ValueError:
1720+
except ValueError as err:
17211721
if raise_on_error:
17221722
msg = "Invalid dataset UUID."
1723-
raise Http404(msg)
1723+
raise Http404(msg) from err
17241724
return None
17251725

17261726
def _parse_comma_separated_ids(self, value: str) -> list[str]:
@@ -1738,7 +1738,10 @@ def _parse_comma_separated_ids(self, value: str) -> list[str]:
17381738
return [item_id.strip() for item_id in value.split(",") if item_id.strip()]
17391739

17401740
def _get_error_response(
1741-
self, message: str | None = None, errors: dict | None = None, status_code: int = 400
1741+
self,
1742+
message: str | None = None,
1743+
errors: dict | None = None,
1744+
status_code: int = 400,
17421745
) -> JsonResponse:
17431746
"""
17441747
Create standardized error response.
@@ -1770,7 +1773,7 @@ def _get_error_response(
17701773
)
17711774

17721775
def _get_dataset(
1773-
self, dataset_uuid: UUID, user: User | None = None, raise_404: bool = True
1776+
self, dataset_uuid: UUID, user: User | None = None, *, raise_404: bool = True
17741777
) -> Dataset | None:
17751778
"""
17761779
Safely retrieve a dataset with consistent error handling.
@@ -1801,7 +1804,7 @@ def _get_dataset(
18011804
return None
18021805

18031806
def _get_capture(
1804-
self, capture_id: str, user: User | None = None, require_owner: bool = False
1807+
self, capture_id: str, user: User | None = None, *, require_owner: bool = False
18051808
) -> Capture | None:
18061809
"""
18071810
Safely retrieve a capture with consistent error handling.
@@ -1818,17 +1821,15 @@ def _get_capture(
18181821
filters = {"uuid": capture_id, "is_deleted": False}
18191822
if require_owner and user:
18201823
filters["owner"] = user
1821-
capture = Capture.objects.get(**filters)
18221824
# Additional check if user provided but require_owner is False
1823-
if user and not require_owner and capture.owner != user:
1824-
# Still allow if user has access (for shared captures)
1825-
pass
1826-
return capture
1825+
# Still allow if user has access (for shared captures)
18271826
except Capture.DoesNotExist:
18281827
return None
1828+
else:
1829+
return Capture.objects.get(**filters)
18291830

18301831
def _get_file(
1831-
self, file_id: str, user: User | None = None, require_owner: bool = False
1832+
self, file_id: str, user: User | None = None, *, require_owner: bool = False
18321833
) -> File | None:
18331834
"""
18341835
Safely retrieve a file with consistent error handling.
@@ -1899,8 +1900,10 @@ def _get_permission_cache(
18991900
"can_remove_assets": UserSharePermission.user_can_remove_assets(
19001901
user, dataset_uuid, ItemType.DATASET
19011902
),
1902-
"can_remove_others_assets": UserSharePermission.user_can_remove_others_assets(
1903-
user, dataset_uuid, ItemType.DATASET
1903+
"can_remove_others_assets": (
1904+
UserSharePermission.user_can_remove_others_assets(
1905+
user, dataset_uuid, ItemType.DATASET
1906+
)
19041907
),
19051908
}
19061909

@@ -2041,7 +2044,9 @@ def get_context_data(self, **kwargs):
20412044
dataset_uuid = None
20422045

20432046
if dataset_uuid_str:
2044-
dataset_uuid = self._parse_dataset_uuid(dataset_uuid_str, raise_on_error=True)
2047+
dataset_uuid = self._parse_dataset_uuid(
2048+
dataset_uuid_str, raise_on_error=True
2049+
)
20452050
if not dataset_uuid:
20462051
msg = "Invalid dataset UUID."
20472052
raise Http404(msg)
@@ -2161,7 +2166,9 @@ def post(self, request, *args, **kwargs):
21612166

21622167
if dataset_uuid_str:
21632168
# Get dataset UUID format
2164-
dataset_uuid = self._parse_dataset_uuid(dataset_uuid_str, raise_on_error=False)
2169+
dataset_uuid = self._parse_dataset_uuid(
2170+
dataset_uuid_str, raise_on_error=False
2171+
)
21652172
if not dataset_uuid:
21662173
return self._get_error_response(
21672174
message="Invalid dataset UUID.", status_code=400
@@ -2175,7 +2182,7 @@ def post(self, request, *args, **kwargs):
21752182
except (DatabaseError, IntegrityError) as e:
21762183
log.exception("Database error in dataset creation")
21772184
return self._get_error_response(message=str(e), status_code=500)
2178-
except ValueError as e:
2185+
except ValueError:
21792186
# Handle UUID parsing errors
21802187
return self._get_error_response(
21812188
message="Invalid dataset UUID.", status_code=400
@@ -2191,7 +2198,9 @@ def _validate_dataset_form(
21912198
# Check if this is an edit operation first
21922199

21932200
if dataset_uuid_str:
2194-
dataset_uuid = self._parse_dataset_uuid(dataset_uuid_str, raise_on_error=False)
2201+
dataset_uuid = self._parse_dataset_uuid(
2202+
dataset_uuid_str, raise_on_error=False
2203+
)
21952204
if not dataset_uuid:
21962205
messages.error(request, "Invalid dataset UUID.")
21972206
return redirect("users:dataset_list")
@@ -2202,7 +2211,9 @@ def _validate_dataset_form(
22022211
)
22032212

22042213
if not permission_level:
2205-
return self._get_error_response(message="Access denied.", status_code=403)
2214+
return self._get_error_response(
2215+
message="Access denied.", status_code=403
2216+
)
22062217

22072218
# Only validate form if user can edit metadata
22082219
can_edit = UserSharePermission.user_can_edit_dataset(
@@ -2268,7 +2279,9 @@ def _handle_dataset_creation(
22682279
{"success": True, "redirect_url": reverse("users:dataset_list")},
22692280
)
22702281

2271-
def _handle_dataset_edit(self, request, dataset_form: DatasetInfoForm, dataset_uuid: UUID) -> JsonResponse:
2282+
def _handle_dataset_edit(
2283+
self, request, dataset_form: DatasetInfoForm, dataset_uuid: UUID
2284+
) -> JsonResponse:
22722285
"""Handle dataset editing with asset management."""
22732286

22742287
# Get dataset
@@ -2319,7 +2332,7 @@ def _parse_asset_changes(self, request) -> dict:
23192332

23202333
return changes
23212334

2322-
def _apply_asset_changes(
2335+
def _apply_asset_changes( # noqa: C901
23232336
self,
23242337
dataset: Dataset,
23252338
changes: dict,
@@ -2335,12 +2348,14 @@ def _apply_asset_changes(
23352348
("files", File, dataset.files),
23362349
]
23372350

2338-
for asset_type_name, asset_model, asset_relation in asset_types:
2351+
for asset_type_name, _asset_model, asset_relation in asset_types:
23392352
# Add assets
23402353
if permissions["can_add_assets"]:
23412354
for asset_id in changes[asset_type_name]["add"]:
23422355
if asset_type_name == "captures":
2343-
asset = self._get_capture(asset_id, user=user, require_owner=True)
2356+
asset = self._get_capture(
2357+
asset_id, user=user, require_owner=True
2358+
)
23442359
else:
23452360
asset = self._get_file(asset_id, user=user, require_owner=True)
23462361

@@ -2351,7 +2366,9 @@ def _apply_asset_changes(
23512366
if permissions["can_remove_assets"]:
23522367
for asset_id in changes[asset_type_name]["remove"]:
23532368
if asset_type_name == "captures":
2354-
asset = self._get_capture(asset_id, user=None, require_owner=False)
2369+
asset = self._get_capture(
2370+
asset_id, user=None, require_owner=False
2371+
)
23552372
else:
23562373
asset = self._get_file(asset_id, user=None, require_owner=False)
23572374

@@ -2376,31 +2393,51 @@ def _apply_author_changes(self, authors: list, changes: dict) -> list:
23762393

23772394
# Apply modifications if any
23782395
if i in changes.get("modified", {}):
2379-
modified_author = author.copy() if isinstance(author, dict) else {"name": author, "orcid_id": ""}
2396+
modified_author = (
2397+
author.copy()
2398+
if isinstance(author, dict)
2399+
else {"name": author, "orcid_id": ""}
2400+
)
23802401
for field, change_data in changes["modified"][i].items():
2381-
modified_author[field] = change_data.get("new", modified_author.get(field, ""))
2402+
modified_author[field] = change_data.get(
2403+
"new", modified_author.get(field, "")
2404+
)
23822405
result.append(modified_author)
23832406
else:
23842407
result.append(author)
23852408

23862409
# Add new authors - only add those that aren't already in the result
2387-
# The 'added' array contains indices of newly added authors in the current authors array
2410+
# The 'added' array contains indices of newly added authors in the
2411+
# current authors array
23882412
added_indices = changes.get("added", [])
23892413
for i in added_indices:
23902414
if i < len(authors):
23912415
new_author = authors[i]
2392-
# Check if this author is already in result (shouldn't be, but safety check)
2416+
# Check if this author is already in result (shouldn't be,
2417+
# but safety check)
23932418
# Convert to comparable format
2394-
new_author_name = new_author.get("name", "") if isinstance(new_author, dict) else str(new_author)
2395-
new_author_orcid = new_author.get("orcid_id", "") if isinstance(new_author, dict) else ""
2396-
2419+
new_author_name = (
2420+
new_author.get("name", "")
2421+
if isinstance(new_author, dict)
2422+
else str(new_author)
2423+
)
2424+
new_author_orcid = (
2425+
new_author.get("orcid_id", "")
2426+
if isinstance(new_author, dict)
2427+
else ""
2428+
)
2429+
23972430
# Only add if not already present (by name and orcid)
23982431
is_duplicate = any(
2399-
(isinstance(a, dict) and a.get("name") == new_author_name and a.get("orcid_id") == new_author_orcid) or
2400-
(not isinstance(a, dict) and str(a) == new_author_name)
2432+
(
2433+
isinstance(a, dict)
2434+
and a.get("name") == new_author_name
2435+
and a.get("orcid_id") == new_author_orcid
2436+
)
2437+
or (not isinstance(a, dict) and str(a) == new_author_name)
24012438
for a in result
24022439
)
2403-
2440+
24042441
if not is_duplicate:
24052442
result.append(new_author)
24062443

@@ -2631,7 +2668,7 @@ def _build_order_by(self, sort_by: str, sort_order: str) -> str:
26312668
order_prefix = "-" if sort_order == "desc" else ""
26322669
return f"{order_prefix}{sort_by}"
26332670

2634-
return "-created_at" # Default sorting
2671+
return "-created_at"
26352672

26362673
def _get_owned_datasets(self, user: User, order_by: str) -> QuerySet[Dataset]:
26372674
"""Get datasets owned by the user."""

0 commit comments

Comments
 (0)