Skip to content
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

Chore: Add ruff linting #191

Merged
merged 7 commits into from
Oct 10, 2024
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
24 changes: 24 additions & 0 deletions .github/workflows/pr_linting.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: 📇 Code Linting

on:
push:
branches: [ develop ]
pull_request:
branches: [ develop ]

workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number}}
cancel-in-progress: true

permissions:
contents: read
pull-requests: write

jobs:
linting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
10 changes: 5 additions & 5 deletions automated_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
for module_name in ("requests", "unidecode"):
sys.modules[module_name] = object()

import ayon_api
from ayon_api import ServerAPI
import ayon_api # noqa: E402
from ayon_api import ServerAPI # noqa: E402

EXCLUDED_METHODS = {
"get_default_service_username",
Expand Down Expand Up @@ -52,7 +52,7 @@ def prepare_init_without_api(init_filepath):
with open(init_filepath, "r") as stream:
content = stream.read()

api_regex = re.compile("from \._api import \((?P<functions>[^\)]*)\)")
api_regex = re.compile(r"from \._api import \((?P<functions>[^\)]*)\)")
api_imports = api_regex.search(content)
start, end = api_imports.span()
api_imports_text = content[start:end]
Expand All @@ -66,7 +66,7 @@ def prepare_init_without_api(init_filepath):
f'"{name}"' for name in function_names
}

all_regex = re.compile("__all__ = \([^\)]*\)")
all_regex = re.compile(r"__all__ = \([^\)]*\)")
all_content = all_regex.search(content)
start, end = all_content.span()
all_content_text = content[start:end]
Expand Down Expand Up @@ -224,7 +224,7 @@ def main():
print(new_content, file=stream)

# find all functions and classes available in '_api.py'
func_regex = re.compile("^(def|class) (?P<name>[^\(]*)(\(|:).*")
func_regex = re.compile(r"^(def|class) (?P<name>[^\(]*)(\(|:).*")
func_names = []
for line in new_content.split("\n"):
result = func_regex.search(line)
Expand Down
11 changes: 6 additions & 5 deletions ayon_api/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,8 +783,8 @@ def dispatch_event(*args, **kwargs):
depends_on (Optional[str]): Add dependency to another event.
username (Optional[str]): Username which triggered event.
description (Optional[str]): Description of event.
summary (Optional[dict[str, Any]]): Summary of event that can be used
for simple filtering on listeners.
summary (Optional[dict[str, Any]]): Summary of event that can
be used for simple filtering on listeners.
payload (Optional[dict[str, Any]]): Full payload of event data with
all details.
finished (Optional[bool]): Mark event as finished on dispatch.
Expand Down Expand Up @@ -875,7 +875,8 @@ def download_file_to_stream(*args, **kwargs):

Args:
endpoint (str): Endpoint or URL to file that should be downloaded.
stream (Union[io.BytesIO, BinaryIO]): Stream where output will be stored.
stream (Union[io.BytesIO, BinaryIO]): Stream where output will
be stored.
chunk_size (Optional[int]): Size of chunks that are received
in single loop.
progress (Optional[TransferProgress]): Object that gives ability
Expand Down Expand Up @@ -2392,8 +2393,8 @@ def get_folders(*args, **kwargs):
"""Query folders from server.

Todos:
Folder name won't be unique identifier, so we should add folder path
filtering.
Folder name won't be unique identifier, so we should add
folder path filtering.

Notes:
Filter 'active' don't have direct filter in GraphQl.
Expand Down
43 changes: 23 additions & 20 deletions ayon_api/entity_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@
import copy
import collections
from abc import ABC, abstractmethod
import typing

from ._api import get_server_api_connection
from .utils import create_entity_id, convert_entity_id, slugify_string

if typing.TYPE_CHECKING:
from typing import Literal

StatusState = Literal["not_started", "in_progress", "done", "blocked"]
EntityType = Literal["project", "folder", "task"]


class _CustomNone(object):
def __init__(self, name=None):
Expand Down Expand Up @@ -44,7 +51,7 @@ class EntityHub(object):
key on entities. This is not recommended as 'data' may be use for
secure information and would also slow down server queries. Content
of 'data' key can't be received only GraphQl.

"""

def __init__(
Expand Down Expand Up @@ -129,8 +136,8 @@ def get_attributes_for_type(self, entity_type):
Use attribute schema to validate values on entities.

Args:
entity_type (Literal["project", "folder", "task"]): Entity type
for which should be attributes received.
entity_type (EntityType): Entity type for which should
be attributes received.

Returns:
Dict[str, Dict[str, Any]]: Attribute schemas that are available
Expand Down Expand Up @@ -259,8 +266,8 @@ def add_new_folder(self, *args, created=True, **kwargs):
Args:
folder_type (str): Type of folder. Folder type must be available in
config of project folder types.
entity_id (Union[str, None]): Id of the entity. New id is created if
not passed.
entity_id (Union[str, None]): Id of the entity. New id is created
if not passed.
parent_id (Union[str, None]): Id of parent entity.
name (str): Name of entity.
label (Optional[str]): Folder label.
Expand Down Expand Up @@ -289,8 +296,8 @@ def add_new_task(self, *args, created=True, **kwargs):
Args:
task_type (str): Type of task. Task type must be available in
config of project folder types.
entity_id (Union[str, None]): Id of the entity. New id is created if
not passed.
entity_id (Union[str, None]): Id of the entity. New id is created
if not passed.
parent_id (Union[str, None]): Id of parent entity.
name (str): Name of entity.
label (Optional[str]): Folder label.
Expand Down Expand Up @@ -734,8 +741,8 @@ def _pre_commit_types_changes(
Args:
project_changes (dict[str, Any]): Project changes.
orig_types (list[dict[str, Any]]): Original types.
changes_key (Literal[folderTypes, taskTypes]): Key of type changes
in project changes.
changes_key (Literal["folderTypes", "taskTypes"]): Key of type
changes in project changes.
post_changes (dict[str, Any]): An object where post changes will
be stored.

Expand Down Expand Up @@ -1247,7 +1254,7 @@ def entity_type(self):
"""Entity type coresponding to server.

Returns:
Literal[project, folder, task]: Entity type.
EntityType: Entity type.

"""
pass
Expand Down Expand Up @@ -1473,7 +1480,7 @@ def set_parent(self, parent):

Raises:
TypeError: If validation of parent does not pass.

"""
parent_id = None
if parent is not None:
Expand Down Expand Up @@ -1604,8 +1611,7 @@ class ProjectStatus:
Args:
name (str): Name of the status. e.g. 'In progress'
short_name (Optional[str]): Short name of the status. e.g. 'IP'
state (Optional[Literal[not_started, in_progress, done, blocked]]): A
state of the status.
state (Optional[StatusState]): A state of the status.
icon (Optional[str]): Icon of the status. e.g. 'play_arrow'.
color (Optional[str]): Color of the status. e.g. '#eeeeee'.
index (Optional[int]): Index of the status.
Expand Down Expand Up @@ -1864,8 +1870,7 @@ def get_state(self):
"""Get state of project status.

Return:
Literal[not_started, in_progress, done, blocked]: General
state of status.
StatusState: General state of status.

"""
return self._state
Expand All @@ -1874,8 +1879,7 @@ def set_state(self, state):
"""Set color of project status.

Args:
state (Literal[not_started, in_progress, done, blocked]): General
state of status.
state (StatusState): General state of status.

"""
if state not in self.valid_states:
Expand Down Expand Up @@ -2055,8 +2059,7 @@ def create(
Args:
name (str): Name of the status. e.g. 'In progress'
short_name (Optional[str]): Short name of the status. e.g. 'IP'
state (Optional[Literal[not_started, in_progress, done, blocked]]): A
state of the status.
state (Optional[StatusState]): A state of the status.
icon (Optional[str]): Icon of the status. e.g. 'play_arrow'.
color (Optional[str]): Color of the status. e.g. '#eeeeee'.

Expand Down Expand Up @@ -2795,7 +2798,7 @@ def __init__(
tags = []
else:
tags = list(tags)

if assignees is None:
assignees = []
else:
Expand Down
1 change: 0 additions & 1 deletion ayon_api/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def to_data(self):
"user": self.username,
"dependencies": copy.deepcopy(self.dependencies),
"description": self.description,
"description": self.description,
"summary": copy.deepcopy(self.summary),
"payload": self.payload,
"finished": self.finished,
Expand Down
2 changes: 1 addition & 1 deletion ayon_api/graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class GraphQlQuery:

Args:
name (str): Name of query.

"""
offset = 2

Expand Down
4 changes: 3 additions & 1 deletion ayon_api/graphql_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,9 @@ def representations_graphql_query(fields):
repre_ids_var = query.add_variable("representationIds", "[String!]")
repre_names_var = query.add_variable("representationNames", "[String!]")
version_ids_var = query.add_variable("versionIds", "[String!]")
has_links_var = query.add_variable("representationHasLinks", "HasLinksFilter")
has_links_var = query.add_variable(
"representationHasLinks", "HasLinksFilter"
)
statuses_var = query.add_variable(
"representationStatuses", "[String!]"
)
Expand Down
39 changes: 24 additions & 15 deletions ayon_api/server_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,11 @@ def _do_rest_request(self, function, url, **kwargs):
# Server may be restarting
new_response = RestApiResponse(
None,
{"detail": "Unable to connect the server. Connection refused"}
{
"detail": (
"Unable to connect the server. Connection refused"
)
}
)

except requests.exceptions.Timeout:
Expand All @@ -1296,7 +1300,11 @@ def _do_rest_request(self, function, url, **kwargs):

new_response = RestApiResponse(
None,
{"detail": "Unable to connect the server. Connection error"}
{
"detail": (
"Unable to connect the server. Connection error"
)
}
)

time.sleep(0.1)
Expand Down Expand Up @@ -1565,8 +1573,8 @@ def dispatch_event(
depends_on (Optional[str]): Add dependency to another event.
username (Optional[str]): Username which triggered event.
description (Optional[str]): Description of event.
summary (Optional[dict[str, Any]]): Summary of event that can be used
for simple filtering on listeners.
summary (Optional[dict[str, Any]]): Summary of event that can
be used for simple filtering on listeners.
payload (Optional[dict[str, Any]]): Full payload of event data with
all details.
finished (Optional[bool]): Mark event as finished on dispatch.
Expand Down Expand Up @@ -1633,7 +1641,7 @@ def enroll_event_job(
at least one unfinished event with target topic, when set to 'True'.
This helps when order of events matter and more than one process using
the same target is running at the same time.

Make sure the new event has updated status to '"finished"' status
when you're done with logic

Expand Down Expand Up @@ -1760,7 +1768,8 @@ def download_file_to_stream(

Args:
endpoint (str): Endpoint or URL to file that should be downloaded.
stream (Union[io.BytesIO, BinaryIO]): Stream where output will be stored.
stream (Union[io.BytesIO, BinaryIO]): Stream where output will
be stored.
chunk_size (Optional[int]): Size of chunks that are received
in single loop.
progress (Optional[TransferProgress]): Object that gives ability
Expand Down Expand Up @@ -1851,7 +1860,7 @@ def _upload_chunks_iter(file_stream, progress, chunk_size):

Yields:
bytes: Chunk of file.

"""
# Get size of file
file_stream.seek(0, io.SEEK_END)
Expand Down Expand Up @@ -1984,7 +1993,7 @@ def upload_file(

Returns:
requests.Response: Response object

"""
if progress is None:
progress = TransferProgress()
Expand Down Expand Up @@ -2204,7 +2213,7 @@ def get_attributes_for_type(self, entity_type):
"""Get attribute schemas available for an entity type.

Example::

```
# Example attribute schema
{
Expand Down Expand Up @@ -2855,7 +2864,7 @@ def get_bundles(self):
"""Server bundles with basic information.

This is example output::

{
"bundles": [
{
Expand Down Expand Up @@ -4188,8 +4197,8 @@ def get_folders(
"""Query folders from server.

Todos:
Folder name won't be unique identifier, so we should add folder path
filtering.
Folder name won't be unique identifier, so we should add
folder path filtering.

Notes:
Filter 'active' don't have direct filter in GraphQl.
Expand Down Expand Up @@ -6655,7 +6664,7 @@ def get_representations_parents(

def get_representation_parents(
self,
project_name,
project_name,
representation_id,
project_fields=None,
folder_fields=None,
Expand Down Expand Up @@ -6991,7 +7000,7 @@ def get_workfiles_info(
"attrib.{}".format(attr)
for attr in self.get_attributes_for_type("workfile")
}

if own_attributes is not _PLACEHOLDER:
warnings.warn(
(
Expand Down Expand Up @@ -8168,7 +8177,7 @@ def send_batch_operations(
body = json.loads(
json.dumps(operation, default=entity_data_json_default)
)
except:
except (TypeError, ValueError):
raise ValueError("Couldn't json parse body: {}".format(
json.dumps(
operation, indent=4, default=failed_json_default
Expand Down
Loading