Skip to content

Commit

Permalink
Apply lint auto fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
peytondmurray committed Oct 30, 2024
1 parent 38d8597 commit 3d3f8d3
Show file tree
Hide file tree
Showing 14 changed files with 36 additions and 54 deletions.
16 changes: 11 additions & 5 deletions conda-store-server/conda_store_server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

import platformdirs

if typing.TYPE_CHECKING:
from ._internal.orm import Build
from .app import CondaStore


__version__ = "2024.11.1-dev"

Expand Down Expand Up @@ -39,15 +43,15 @@ class BuildKey:

_version3_experimental_hash_size = 32

def _version1_fmt(build: "Build") -> str: # noqa: F821
def _version1_fmt(build: Build) -> str: # noqa: F821
datetime_format = "%Y%m%d-%H%M%S-%f"
hash = build.specification.sha256
timestamp = build.scheduled_on.strftime(datetime_format)
id = build.id
name = build.specification.name
return f"{hash}-{timestamp}-{id}-{name}"

def _version2_fmt(build: "Build") -> str: # noqa: F821
def _version2_fmt(build: Build) -> str: # noqa: F821
tzinfo = datetime.timezone.utc
hash = build.specification.sha256[: BuildKey._version2_hash_size]
timestamp = int(build.scheduled_on.replace(tzinfo=tzinfo).timestamp())
Expand All @@ -56,7 +60,7 @@ def _version2_fmt(build: "Build") -> str: # noqa: F821
return f"{hash}-{timestamp}-{id}-{name}"

# Warning: this is an experimental version and can be changed at any time
def _version3_experimental_fmt(build: "Build") -> str: # noqa: F821
def _version3_experimental_fmt(build: Build) -> str: # noqa: F821
# Caches the hash value for faster lookup later
if build.hash is not None:
return build.hash
Expand Down Expand Up @@ -113,14 +117,16 @@ def versions(cls) -> typing.Tuple[int]:
return tuple(cls._fmt.keys())

@classmethod
def get_build_key(cls, build: "Build") -> str: # noqa: F821
def get_build_key(cls, build: Build) -> str: # noqa: F821
"""Returns build key for this build"""
cls._check_version(build.build_key_version)
return cls._fmt.get(build.build_key_version)(build)

@classmethod
def parse_build_key(
cls, conda_store: "CondaStore", build_key: str # noqa: F821
cls,
conda_store: CondaStore,
build_key: str, # noqa: F821
) -> int:
"""Returns build id from build key"""
# This import is here to avoid cyclic imports
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import sys
import tempfile
import warnings

from typing import Union

import yaml
Expand Down Expand Up @@ -54,7 +53,7 @@ def write_file(filename, s):
warnings.warn(
"Installer generation requires constructor: https://github.com/conda/constructor"
)
return
return None

# pip dependencies are not directly supported by constructor, they will be
# installed via the post_install script:
Expand Down
8 changes: 4 additions & 4 deletions conda-store-server/conda_store_server/_internal/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import os
import re
import sys

from typing import Any, Callable, Dict, List, Optional, TypeAlias, Union

from conda_lock.lockfile.v1.models import Lockfile
Expand All @@ -19,7 +18,7 @@


def _datetime_factory(offset: datetime.timedelta):
"""utcnow datetime + timezone as string"""
"""Utcnow datetime + timezone as string"""
return datetime.datetime.utcnow() + offset


Expand All @@ -41,7 +40,8 @@ def _datetime_factory(offset: datetime.timedelta):


class Permissions(enum.Enum):
"Permissions map to conda-store actions"
"""Permissions map to conda-store actions"""

ENVIRONMENT_CREATE = "environment:create"
ENVIRONMENT_READ = "environment::read"
ENVIRONMENT_UPDATE = "environment::update"
Expand Down Expand Up @@ -528,7 +528,7 @@ def __str__(self):


def _docker_datetime_factory():
"""utcnow datetime + timezone as string"""
"""Utcnow datetime + timezone as string"""
return datetime.datetime.utcnow().astimezone().isoformat()


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
import posixpath
import sys
import time

from enum import Enum
from threading import Thread

import uvicorn

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
Expand All @@ -34,7 +32,6 @@
from traitlets.config import Application, catch_config_error

import conda_store_server

from conda_store_server import __version__, storage
from conda_store_server._internal import dbutil, orm
from conda_store_server._internal.server import views
Expand Down Expand Up @@ -167,9 +164,7 @@ def _default_templates(self):
def _validate_config_file(self, proposal):
if not os.path.isfile(proposal.value):
print(
"ERROR: Failed to find specified config file: {}".format(
proposal.value
),
f"ERROR: Failed to find specified config file: {proposal.value}",
file=sys.stderr,
)
sys.exit(1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Optional

import yaml

from fastapi import APIRouter, Depends, Request
from fastapi.responses import RedirectResponse

Expand All @@ -16,7 +15,6 @@
from conda_store_server._internal.schema import Permissions
from conda_store_server.server import dependencies


router_ui = APIRouter(tags=["ui"])


Expand All @@ -38,7 +36,7 @@ async def ui_create_get_environment(
)

def sort_namespace(n):
"Default namespace always first, then alphabetical"
"""Default namespace always first, then alphabetical"""
if n.name == default_namespace:
return f"0{n.name}"
return f"1{n.name}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ class CondaStoreWorker(Application):
def _validate_config_file(self, proposal):
if not os.path.isfile(proposal.value):
print(
"ERROR: Failed to find specified config file: {}".format(
proposal.value
),
f"ERROR: Failed to find specified config file: {proposal.value}",
file=sys.stderr,
)
sys.exit(1)
Expand Down Expand Up @@ -85,7 +83,6 @@ def logger_to_celery_logging_level(self, logging_level):
return logging_to_celery_level_map[logging_level]

def start(self):

argv = [
"worker",
f"--loglevel={self.logger_to_celery_logging_level(self.log_level)}",
Expand Down
5 changes: 1 addition & 4 deletions conda-store-server/conda_store_server/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from __future__ import annotations

import re

from typing import Any, Dict, List, Union

from sqlalchemy import distinct, func, null, or_
Expand Down Expand Up @@ -569,9 +568,7 @@ def get_build_lockfile_legacy(db, build_id: int):
return """#platform: {0}
@EXPLICIT
{1}
""".format(
conda_utils.conda_platform(), "\n".join(packages)
)
""".format(conda_utils.conda_platform(), "\n".join(packages))


def get_build_artifact_types(db, build_id: int):
Expand Down
3 changes: 0 additions & 3 deletions conda-store-server/conda_store_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
import datetime
import os
import sys

from contextlib import contextmanager
from typing import Any, Dict

import pydantic

from celery import Celery, group
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.pool import QueuePool
Expand Down Expand Up @@ -624,7 +622,6 @@ def register_environment(
is_lockfile: bool = False,
):
"""Register a given specification to conda store with given namespace/name."""

settings = self.get_settings(db)

namespace = namespace or settings.default_namespace
Expand Down
6 changes: 1 addition & 5 deletions conda-store-server/hatch_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@
import tarfile
import tempfile
import urllib.request

from pathlib import Path
from typing import Any, Dict, List

from hatchling.builders.hooks.plugin.interface import BuildHookInterface


CONDA_STORE_UI_VERSION = "2024.10.1"
CONDA_STORE_UI_URL = f"https://registry.npmjs.org/@conda-store/conda-store-ui/-/conda-store-ui-{CONDA_STORE_UI_VERSION}.tgz"

Expand Down Expand Up @@ -89,7 +87,6 @@ def get_ui_release(self, ui_version: str) -> None:
ui_version (str): conda-store-ui version to download, must be a
valid npm release
"""

with tempfile.TemporaryDirectory() as tmp_dir:
tmp_dir = Path(tmp_dir)
tmp_filename = tmp_dir / "conda-store-ui.tgz"
Expand All @@ -114,7 +111,6 @@ def copy_ui_files(self, source_directory: str) -> None:
Args:
source_directory (str): path to the directory containing the UI files
"""

server_build_static_assets = Path(self.root) / SERVER_UI_ASSETS
server_build_static_assets.mkdir(parents=True, exist_ok=True)

Expand All @@ -133,6 +129,6 @@ def copy_ui_files(self, source_directory: str) -> None:
f"Copied files: {[p.name for p in server_build_static_assets.glob('*')]}"
)

except (IOError, OSError) as e:
except OSError as e:
print(f"Error copying files: {e}")
raise
1 change: 1 addition & 0 deletions conda-store-server/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ line-length = 88
[tool.isort]
lines_between_types = 1
lines_after_imports = 2
profile = 'black'

[tool.ruff]
line-length = 88
Expand Down
4 changes: 2 additions & 2 deletions conda-store-server/tests/_internal/server/views/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import pytest
import traitlets
import yaml

from fastapi.testclient import TestClient

from conda_store_server import CONDA_STORE_DIR, __version__
Expand Down Expand Up @@ -1047,7 +1046,8 @@ def test_put_global_settings_auth_in_namespace_environment(
testclient, authenticate, route
):
"""This is a test that you cannot set a global setting at the
namespace or environment settings level"""
namespace or environment settings level
"""
response = testclient.put(
route,
json={
Expand Down
16 changes: 7 additions & 9 deletions conda-store-server/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@

import pytest
import yaml

from fastapi.testclient import TestClient
from sqlalchemy.orm import Session

from conda_store_server import api, app, storage


from conda_store_server._internal import ( # isort:skip
action,
dbutil,
Expand Down Expand Up @@ -105,7 +103,7 @@ def conda_store_server(conda_store_config):

ResultModelBase.metadata.create_all(db.get_bind())

yield _conda_store_server
return _conda_store_server


@pytest.fixture
Expand Down Expand Up @@ -188,7 +186,7 @@ def conda_store(conda_store_config):

ResultModelBase.metadata.create_all(db.get_bind())

yield _conda_store
return _conda_store


@pytest.fixture
Expand All @@ -199,7 +197,7 @@ def db(conda_store):

@pytest.fixture
def simple_specification():
yield schema.CondaSpecification(
return schema.CondaSpecification(
name="test",
channels=["main"],
dependencies=["zlib"],
Expand All @@ -208,7 +206,7 @@ def simple_specification():

@pytest.fixture
def simple_specification_with_pip():
yield schema.CondaSpecification(
return schema.CondaSpecification(
name="test",
channels=["main"],
dependencies=[
Expand All @@ -234,7 +232,7 @@ def simple_conda_lock_with_pip():

@pytest.fixture
def simple_lockfile_specification(simple_conda_lock):
yield schema.LockfileSpecification.parse_obj(
return schema.LockfileSpecification.parse_obj(
{
"name": "test",
"description": "simple lockfile specification",
Expand All @@ -245,7 +243,7 @@ def simple_lockfile_specification(simple_conda_lock):

@pytest.fixture
def simple_lockfile_specification_with_pip(simple_conda_lock_with_pip):
yield schema.LockfileSpecification.parse_obj(
return schema.LockfileSpecification.parse_obj(
{
"name": "test",
"description": "simple lockfile specification with pip",
Expand Down Expand Up @@ -279,7 +277,7 @@ def conda_prefix(conda_store, tmp_path, request):
specification=specification,
conda_prefix=conda_prefix,
)
yield conda_prefix
return conda_prefix


def _seed_conda_store(
Expand Down
7 changes: 3 additions & 4 deletions conda-store-server/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
# license that can be found in the LICENSE file.

import pytest

from sqlalchemy.exc import IntegrityError

from conda_store_server import api
from conda_store_server._internal.orm import NamespaceRoleMapping
from conda_store_server._internal.utils import BuildPathError


@pytest.fixture()
@pytest.fixture
def populated_db(db):
"""A database fixture populated with 4 envs in 3 namespaces."""
description = "Hello World"
Expand Down Expand Up @@ -352,11 +351,11 @@ def test_get_set_keyvaluestore(db):

# test updating a prefix
api.set_kvstore_key_values(db, "pytest", setting_2)
assert {**setting_1, **setting_2} == api.get_kvstore_key_values(db, "pytest")
assert api.get_kvstore_key_values(db, "pytest") == {**setting_1, **setting_2}

# test updating a prefix
api.set_kvstore_key_values(db, "pytest", {"c": 999, "d": 999}, update=False)
assert {**setting_1, **setting_2} == api.get_kvstore_key_values(db, "pytest")
assert api.get_kvstore_key_values(db, "pytest") == {**setting_1, **setting_2}


def test_build_path_too_long(db, conda_store, simple_specification):
Expand Down
Loading

0 comments on commit 3d3f8d3

Please sign in to comment.