Skip to content

refactor: improve types readability + CI job for formatting #51

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

Merged
merged 5 commits into from
Mar 21, 2023
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
20 changes: 20 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,23 @@ jobs:
with:
name: reference-docs
path: ./docs/build/

format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install dependencies
run: |
python3.10 -m venv venv
source venv/bin/activate
pip3 install --upgrade pip
python3.10 -m pip install -r requirements.txt
python3.10 setup.py install
- name: Check Formatting
run: |
source venv/bin/activate
yapf -d -r -p .
24 changes: 14 additions & 10 deletions docs/theme/devsite_translator/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@

from sphinx.writers import html


_DESCTYPE_NAMES = {'class': 'Classes',
'data': 'Constants',
'function': 'Functions',
'method': 'Methods',
'attribute': 'Attributes',
'exception': 'Exceptions'}
_DESCTYPE_NAMES = {
'class': 'Classes',
'data': 'Constants',
'function': 'Functions',
'method': 'Methods',
'attribute': 'Attributes',
'exception': 'Exceptions'
}

# Use the default translator for these node types
_RENDER_WITH_DEFAULT = ['method', 'staticmethod', 'attribute']
Expand All @@ -48,12 +49,14 @@ def visit_desc(self, node):
if node.parent.tagname == 'section':
self.insert_header = True
if node['desctype'] != self.current_section:
self.body.append(f"<h2>{_DESCTYPE_NAMES[node['desctype']]}</h2>")
self.body.append(
f"<h2>{_DESCTYPE_NAMES[node['desctype']]}</h2>")
self.current_section = node['desctype']
if node['desctype'] in _RENDER_WITH_DEFAULT:
html.HTMLTranslator.visit_desc(self, node)
else:
self.body.append(self.starttag(node, 'table', CLASS=node['objtype']))
self.body.append(self.starttag(node, 'table',
CLASS=node['objtype']))

def depart_desc(self, node):
if node['desctype'] in _RENDER_WITH_DEFAULT:
Expand All @@ -68,7 +71,8 @@ def visit_desc_signature(self, node):
self.body.append('<tr>')
self.body.append(self.starttag(node, 'th'))
if self.insert_header:
self.body.append(f"<h3 class=\"sphinx-hidden\">{node['fullname']}</h3>")
self.body.append(
f"<h3 class=\"sphinx-hidden\">{node['fullname']}</h3>")
self.insert_header = False

def depart_desc_signature(self, node):
Expand Down
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,12 @@ pythonpath = [

[tool.coverage.report]
skip_empty = true
[tool.yapf]
based_on_style = "google"
indent_width = 4
[tool.yapfignore]
ignore_patterns = [
"venv",
"build",
"dist",
]
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ pylint>=2.16.1
pytest-cov>=3.0.0
mypy>=1.0.0
sphinx>=6.1.3
sphinxcontrib-napoleon>=0.7
sphinxcontrib-napoleon>=0.7
yapf>=0.32.0
toml>=0.10.2
2 changes: 0 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Setup for Firebase Functions Python.
"""
Expand Down
2 changes: 0 additions & 2 deletions src/firebase_functions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Firebase Functions for Python.
"""
3 changes: 0 additions & 3 deletions src/firebase_functions/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Public code that is shared across modules.
"""
Expand Down Expand Up @@ -64,4 +62,3 @@ class CloudEvent(_typing.Generic[T]):
"""
The resource, provided by source, that this event relates to
"""

10 changes: 5 additions & 5 deletions src/firebase_functions/https_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ class HttpsError(Exception):
determines the HTTP status code of the response.
"""

details: _typing.Optional[_typing.Any] = None
details: _typing.Any | None = None
"""
Extra data to be converted to JSON and included in the error response.
"""
Expand All @@ -247,7 +247,7 @@ def __init__(
self,
code: FunctionsErrorCode,
message: str,
details: _typing.Optional[_typing.Any] = None,
details: _typing.Any | None = None,
):
self.code = code
self.message = message
Expand Down Expand Up @@ -326,17 +326,17 @@ class CallableRequest(_typing.Generic[_core.T]):
The raw request handled by the callable.
"""

app: _typing.Optional[AppCheckData] = None
app: AppCheckData | None = None
"""
The result of decoding and verifying a Firebase AppCheck token.
"""

auth: _typing.Optional[AuthData] = None
auth: AuthData | None = None
""""
The result of decoding and verifying a Firebase Auth ID token.
"""

instance_id_token: _typing.Optional[str] = None
instance_id_token: str | None = None
"""
An unverified token for a Firebase Instance ID.
"""
Expand Down
8 changes: 4 additions & 4 deletions src/firebase_functions/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ class PubSubOptions(RuntimeOptions):
Internal use only.
"""

retry: _typing.Optional[bool] = None
retry: bool | None = None
"""
Whether failed executions should be delivered again.
"""
Expand Down Expand Up @@ -364,7 +364,7 @@ class StorageOptions(RuntimeOptions):
Internal use only.
"""

bucket: _typing.Optional[str] = None
bucket: str | None = None
"""
The name of the bucket to watch for Storage events.
"""
Expand Down Expand Up @@ -416,7 +416,7 @@ class DatabaseOptions(RuntimeOptions):
Examples: '/foo/bar', '/foo/{bar}'
"""

instance: _typing.Optional[str] = None
instance: str | None = None
"""
Specify the handler to trigger on a database instance(s).
If present, this value can either be a single instance or a pattern.
Expand Down Expand Up @@ -471,7 +471,7 @@ class HttpsOptions(RuntimeOptions):
Invoker to set access control on https functions.
"""

cors: _typing.Optional[CorsOptions] = None
cors: CorsOptions | None = None
"""
Optionally set CORS options for Https functions.
"""
Expand Down
25 changes: 12 additions & 13 deletions src/firebase_functions/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ class SelectOptions(_typing.Generic[_T]):
value: _T
"""The value of the option."""

label: _typing.Optional[str] = None
label: str | None = None
"""The displayed label for the option."""


Expand All @@ -127,18 +127,18 @@ class TextInput:
validation_regex, if present, will be retried.
"""

example: _typing.Optional[str] = None
example: str | None = None
"""
An example of the input required that will be displayed alongside the input prompt.
"""

validation_regex: _typing.Optional[str] = None
validation_regex: str | None = None
"""
Validation regex for the input.
Input that does not match this regex, if present, will be retried.
"""

validation_error_message: _typing.Optional[str] = None
validation_error_message: str | None = None
"""
An error message that is displayed to the user if validation_regex fails.
"""
Expand Down Expand Up @@ -169,29 +169,28 @@ class Param(Expression[_T]):
The environment variable of this parameter. Must be upper case.
"""

default: _typing.Optional[_T] = None
default: _T | None = None
"""
The default value to assign to this param if none provided.
"""

label: _typing.Optional[str] = None
label: str | None = None
"""
A label that is displayed to the user for this param.
"""

description: _typing.Optional[str] = None
description: str | None = None
"""
Description of this param that is displayed to the user.
"""

immutable: _typing.Optional[bool] = None
immutable: bool | None = None
"""
Whether the value of this parameter can change between function
deployments.
"""

input: _typing.Union[TextInput, ResourceInput,
SelectInput[_T]] = TextInput()
input: TextInput | ResourceInput | SelectInput[_T] = TextInput()
"""
The type of input that is required for this param, e.g. TextInput.
"""
Expand Down Expand Up @@ -233,17 +232,17 @@ class SecretParam(Expression[str]):
The environment variable of this parameter. Must be upper case.
"""

label: _typing.Optional[str] = None
label: str | None = None
"""
A label that is displayed to the user for this param.
"""

description: _typing.Optional[str] = None
description: str | None = None
"""
Description of this param that is displayed to the user.
"""

immutable: _typing.Optional[bool] = None
immutable: bool | None = None
"""
Whether the value of this parameter can change between function
deployments.
Expand Down
2 changes: 0 additions & 2 deletions src/firebase_functions/private/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""
Firebase Functions for Python - Private/Internals
"""
29 changes: 14 additions & 15 deletions src/firebase_functions/private/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,29 +94,28 @@ class VpcSettings(_typing.TypedDict):
class ManifestEndpoint:
"""A definition of a function as appears in the Manifest."""

entryPoint: _typing.Optional[str] = None
region: _typing.Optional[list[str]] = _dataclasses.field(
default_factory=list[str])
platform: _typing.Optional[str] = "gcfv2"
entryPoint: str | None = None
region: list[str] | None = _dataclasses.field(default_factory=list[str])
platform: str | None = "gcfv2"
availableMemoryMb: int | _params.Expression[
int] | _util.Sentinel | None = None
maxInstances: int | _params.Expression[int] | _util.Sentinel | None = None
minInstances: int | _params.Expression[int] | _util.Sentinel | None = None
concurrency: int | _params.Expression[int] | _util.Sentinel | None = None
serviceAccountEmail: _typing.Optional[str | _util.Sentinel] = None
serviceAccountEmail: str | _util.Sentinel | None = None
timeoutSeconds: int | _params.Expression[int] | _util.Sentinel | None = None
cpu: int | str | _util.Sentinel | None = None
vpc: _typing.Optional[VpcSettings] = None
labels: _typing.Optional[dict[str, str]] = None
ingressSettings: _typing.Optional[str] | _util.Sentinel = None
secretEnvironmentVariables: _typing.Optional[
list[SecretEnvironmentVariable] | _util.Sentinel] = _dataclasses.field(
vpc: VpcSettings | None = None
labels: dict[str, str] | None = None
ingressSettings: str | None | _util.Sentinel = None
secretEnvironmentVariables: list[
SecretEnvironmentVariable] | _util.Sentinel | None = _dataclasses.field(
default_factory=list[SecretEnvironmentVariable])
httpsTrigger: _typing.Optional[HttpsTrigger] = None
callableTrigger: _typing.Optional[CallableTrigger] = None
eventTrigger: _typing.Optional[EventTrigger] = None
scheduleTrigger: _typing.Optional[ScheduleTrigger] = None
blockingTrigger: _typing.Optional[BlockingTrigger] = None
httpsTrigger: HttpsTrigger | None = None
callableTrigger: CallableTrigger | None = None
eventTrigger: EventTrigger | None = None
scheduleTrigger: ScheduleTrigger | None = None
blockingTrigger: BlockingTrigger | None = None


class ManifestRequiredApi(_typing.TypedDict):
Expand Down
8 changes: 4 additions & 4 deletions src/firebase_functions/private/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def _on_call_valid_method(request: _Request) -> bool:

def _on_call_valid_content_type(request: _Request) -> bool:
"""Validate content"""
content_type: _typing.Optional[str] = request.headers.get("Content-Type")
content_type: str | None = request.headers.get("Content-Type")

if content_type is None:
_logging.warning("Request is missing Content-Type.", content_type)
Expand Down Expand Up @@ -159,9 +159,9 @@ class _OnCallTokenVerification:
"""

app: OnCallTokenState = OnCallTokenState.INVALID
app_token: _typing.Optional[dict[str, _typing.Any]] = None
app_token: dict[str, _typing.Any] | None = None
auth: OnCallTokenState = OnCallTokenState.INVALID
auth_token: _typing.Optional[dict] = None
auth_token: dict | None = None

def as_dict(self) -> dict:
"""Set dictionary"""
Expand Down Expand Up @@ -256,7 +256,7 @@ class FirebaseConfig():
initialize a firebase App.
"""

storage_bucket: _typing.Optional[str]
storage_bucket: str | None
"""
The name of the Google Cloud Storage bucket used for storing application data.
This is the bucket name without any prefixes or additions (without "gs://").
Expand Down
2 changes: 1 addition & 1 deletion src/firebase_functions/pubsub_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class Message(_typing.Generic[T]):
"""

@property
def json(self) -> _typing.Optional[T]:
def json(self) -> T | None:
try:
if self.data is not None:
return _json.loads(_base64.b64decode(self.data).decode("utf-8"))
Expand Down
Loading