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

Sourcery Starbot ⭐ refactored Alc-Alc/starlite #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

SourceryAI
Copy link

Thanks for starring sourcery-ai/sourcery ✨ 🌟 ✨

Here's your pull request refactoring your most popular Python repo.

If you want Sourcery to refactor all your Python repos and incoming pull requests install our bot.

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch https://github.com/sourcery-ai-bot/starlite main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Copy link
Author

@SourceryAI SourceryAI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

response = jwt_auth.login(identifier=str(data.id), response_body=data)

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

return response
return jwt_auth.login(identifier=str(data.id), response_body=data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function login_handler refactored with the following changes:

This removes the following comments ( why? ):

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

response = jwt_cookie_auth.login(identifier=str(data.id), response_body=data)

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

return response
return jwt_cookie_auth.login(identifier=str(data.id), response_body=data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function login_handler refactored with the following changes:

This removes the following comments ( why? ):

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

# if we do not define a response body, the login process will return a standard OAuth2 login response. Note the `Response[OAuth2Login]` return type.
response = oauth2_auth.login(identifier=str(data.id))

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

return response
return oauth2_auth.login(identifier=str(data.id))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function login_handler refactored with the following changes:

This removes the following comments ( why? ):

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)
# if we do not define a response body, the login process will return a standard OAuth2 login response.  Note the `Response[OAuth2Login]` return type.

Comment on lines -64 to +58
# If you'd like to define a custom response body, use the `response_body` parameter. Note the `Response[User]` return type.
response = oauth2_auth.login(identifier=str(data.id), response_body=data)

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)

return response
return oauth2_auth.login(identifier=str(data.id), response_body=data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function login_custom_response_handler refactored with the following changes:

This removes the following comments ( why? ):

# you can do whatever you want to update the response instance here
# e.g. response.set_cookie(...)
# If you'd like to define a custom response body, use the `response_body` parameter.  Note the `Response[User]` return type.

if not (token == VALID_TOKEN and cookie == VALID_COOKIE_VALUE):
if token != VALID_TOKEN or cookie != VALID_COOKIE_VALUE:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_user refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

Comment on lines -90 to +97
field_definitions: Dict[str, Tuple[Any, None]] = {}
for field_name, field_type in get_type_hints(item).items():
if is_classvar(field_type):
continue
if not isinstance(field_type, GenericAlias) or NoneType not in field_type.__args__:
field_definitions[field_name] = (Optional[field_type], None)
else:
field_definitions[field_name] = (field_type, None)

field_definitions: Dict[str, Tuple[Any, None]] = {
field_name: (Optional[field_type], None)
if not isinstance(field_type, GenericAlias)
or NoneType not in field_type.__args__
else (field_type, None)
for field_name, field_type in get_type_hints(item).items()
if not is_classvar(field_type)
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Partial._create_partial_pydantic_model refactored with the following changes:

Comment on lines -88 to +92
is_mount = hasattr(route, "route_handler") and getattr(route.route_handler, "is_mount", False) # pyright: ignore
has_path_parameters = bool(route.path_parameters)

if is_mount: # pyright: ignore
if is_mount := hasattr(route, "route_handler") and getattr(
route.route_handler, "is_mount", False
):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function add_route_to_trie refactored with the following changes:

This removes the following comments ( why? ):

# pyright: ignore

Comment on lines -146 to +148
if not mount_node.children or not any(sub_route in path for sub_route in mount_node.children): # type: ignore
if not mount_node.children or all(
sub_route not in path for sub_route in mount_node.children
): # type: ignore
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_path_to_route refactored with the following changes:

v
for v in chain.from_iterable(
chain.from_iterable(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function validate_node refactored with the following changes:

Comment on lines -456 to +460
used_reserved_kwargs = {*parameter_names, *path_parameters, *dependency_keys}.intersection(RESERVED_KWARGS)
if used_reserved_kwargs:
if used_reserved_kwargs := {
*parameter_names,
*path_parameters,
*dependency_keys,
}.intersection(RESERVED_KWARGS):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function KwargsModel._validate_raw_kwargs refactored with the following changes:

Comment on lines -63 to +65
and (default_value is None and not (signature_field.is_optional or signature_field.is_any)),
and default_value is None
and not signature_field.is_optional
and not signature_field.is_any,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_parameter_definition refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

@@ -12,7 +12,6 @@
if TYPE_CHECKING:
from starlite.plugins import OpenAPISchemaPluginProtocol

if TYPE_CHECKING:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-15 refactored with the following changes:

Comment on lines -161 to +160
if len(items) > 1:
schema.items = Schema(one_of=items)
else:
schema.items = items[0]
schema.items = Schema(one_of=items) if len(items) > 1 else items[0]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_collection_constrained_field_schema refactored with the following changes:

Comment on lines -53 to +60
if not allow_quoted and not (value[0].isalpha() or value[0] in {"_", "$"}):
if (
not allow_quoted
and not value[0].isalpha()
and value[0] not in {"_", "$"}
):
raise ValueError(f"invalid typescript namespace {value}")
if allow_quoted:
if allowed_key_re.fullmatch(value):
return value
return f'"{value}"'
return value if allowed_key_re.fullmatch(value) else f'"{value}"'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function normalize_typescript_namespace refactored with the following changes:

Comment on lines -27 to +32
return '"' + value + '"'
return f'"{value}"'

if isinstance(value, bool):
return "true" if value else "false"

if value is None:
return "null"

return str(value)
return "null" if value is None else str(value)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _as_string refactored with the following changes:

Comment on lines -121 to -127
spec: dict[str, Any] = {}
for key, value in location.items():
if value:
spec[key] = value
if not spec:
if spec := {key: value for key, value in location.items() if value}:
return {HTMXHeaders.LOCATION.value: encode_json(spec).decode()}
else:
raise ValueError("redirect_to is required parameter.")
return {HTMXHeaders.LOCATION.value: encode_json(spec).decode()}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_location_headers refactored with the following changes:

Comment on lines -151 to +149
response = htmx_headers_dict[key](value)
return response
return htmx_headers_dict[key](value)
if value is not None:
response = htmx_headers_dict[key](value)
header.update(response)
header |= response
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_headers refactored with the following changes:

if value and self.request.headers.get(name + "-URI-AutoEncoded") == "true":
if value and self.request.headers.get(f"{name}-URI-AutoEncoded") == "true":
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function HTMXDetails._get_header_value refactored with the following changes:

Comment on lines -76 to +77
if self._model_has_updated and do_created:
data.created = now # type:ignore[attr-defined]
if do_created:
data.created = now # type:ignore[attr-defined]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GenericMockRepository._update_audit_attributes refactored with the following changes:

return bool(existing > 0)
return existing > 0
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SQLAlchemyRepository.exists refactored with the following changes:

if column_type.asdecimal:
return Decimal
return float
return Decimal if column_type.asdecimal else float
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SQLAlchemyPlugin.handle_numeric_type refactored with the following changes:

if key == "max_age":
if updated_key == "max_age":
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cookie.simple_cookie refactored with the following changes:

Comment on lines -212 to +217
indices = self._find_indices(key)
if not indices:
self.headers.append((name_encoded, value_encoded))
else:
if indices := self._find_indices(key):
for i in indices[1:]:
del self.headers[i]
self.headers[indices[0]] = (name_encoded, value_encoded)
else:
self.headers.append((name_encoded, value_encoded))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function MutableScopeHeaders.__setitem__ refactored with the following changes:

Comment on lines -310 to +317
cc_items = []
for key, value in self.dict(
exclude_unset=True, exclude_none=True, by_alias=True, exclude={"documentation_only"}
).items():
cc_items.append(key if isinstance(value, bool) else f"{key}={value}")

cc_items = [
key if isinstance(value, bool) else f"{key}={value}"
for key, value in self.dict(
exclude_unset=True,
exclude_none=True,
by_alias=True,
exclude={"documentation_only"},
).items()
]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CacheControlHeader._get_header_value refactored with the following changes:

Comment on lines -364 to +366
if self.weak:
return f"W/{value}"
return value
return f"W/{value}" if self.weak else value
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ETag._get_header_value refactored with the following changes:

Comment on lines -315 to +326
resolved_response_headers.update(
{name: ResponseHeader(name=name, value=value) for name, value in layer_response_headers.items()}
)
resolved_response_headers |= {
name: ResponseHeader(name=name, value=value)
for name, value in layer_response_headers.items()
}
else:
resolved_response_headers.update({h.name: h for h in layer_response_headers})
for extra_header in ("cache_control", "etag"):
header_model: Header | None = getattr(layer, extra_header, None)
if header_model:
if header_model := getattr(layer, extra_header, None):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function HTTPRouteHandler.resolve_response_headers refactored with the following changes:

Comment on lines -60 to +67
if exclude_path_pattern and exclude_path_pattern.findall(
scope["path"] if not getattr(scope.get("route_handler", {}), "is_mount", False) else scope["raw_path"].decode()
):
return True
return False
return bool(
exclude_path_pattern
and exclude_path_pattern.findall(
scope["path"]
if not getattr(scope.get("route_handler", {}), "is_mount", False)
else scope["raw_path"].decode()
)
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function should_bypass_middleware refactored with the following changes:

Comment on lines -45 to +49
redirect_domains: set[str] = {
host.replace("www.", "") for host in config.allowed_hosts if host.startswith("www.")
}
if redirect_domains:
if redirect_domains := {
host.replace("www.", "")
for host in config.allowed_hosts
if host.startswith("www.")
}:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AllowedHostsMiddleware.__init__ refactored with the following changes:

Comment on lines -67 to +77
host = headers.get("host", headers.get("x-forwarded-host", "")).split(":")[0]

if host:
if host := headers.get("host", headers.get("x-forwarded-host", "")).split(
":"
)[0]:
if self.allowed_hosts_regex.fullmatch(host):
await self.app(scope, receive, send)
return

if self.redirect_domains is not None and self.redirect_domains.fullmatch(host):
url = URL.from_scope(scope)
redirect_url = url.with_replacements(netloc="www." + url.netloc)
redirect_url = url.with_replacements(netloc=f"www.{url.netloc}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function AllowedHostsMiddleware.__call__ refactored with the following changes:

Comment on lines -44 to 49
origin = headers.get("origin")

if not origin:
await self.app(scope, receive, send)
else:
if origin := headers.get("origin"):
await self.app(scope, receive, self.send_wrapper(send=send, origin=origin, has_cookie="cookie" in headers))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CORSMiddleware.__call__ refactored with the following changes:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant