Skip to content

chore: reduce usage of 'from mod_foo import class_foo' #2872

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
17 changes: 7 additions & 10 deletions gitlab/_backends/requests_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
from typing import Any, BinaryIO, Dict, Optional, TYPE_CHECKING, Union

import requests
from requests import PreparedRequest
from requests.auth import AuthBase
from requests.structures import CaseInsensitiveDict
from requests_toolbelt.multipart.encoder import MultipartEncoder # type: ignore

from . import protocol
Expand All @@ -17,24 +14,24 @@ def __init__(self, token: str):
self.token = token


class OAuthTokenAuth(TokenAuth, AuthBase):
def __call__(self, r: PreparedRequest) -> PreparedRequest:
class OAuthTokenAuth(TokenAuth, requests.auth.AuthBase):
def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest:
r.headers["Authorization"] = f"Bearer {self.token}"
r.headers.pop("PRIVATE-TOKEN", None)
r.headers.pop("JOB-TOKEN", None)
return r


class PrivateTokenAuth(TokenAuth, AuthBase):
def __call__(self, r: PreparedRequest) -> PreparedRequest:
class PrivateTokenAuth(TokenAuth, requests.auth.AuthBase):
def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest:
r.headers["PRIVATE-TOKEN"] = self.token
r.headers.pop("JOB-TOKEN", None)
r.headers.pop("Authorization", None)
return r


class JobTokenAuth(TokenAuth, AuthBase):
def __call__(self, r: PreparedRequest) -> PreparedRequest:
class JobTokenAuth(TokenAuth, requests.auth.AuthBase):
def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest:
r.headers["JOB-TOKEN"] = self.token
r.headers.pop("PRIVATE-TOKEN", None)
r.headers.pop("Authorization", None)
Expand Down Expand Up @@ -68,7 +65,7 @@ def status_code(self) -> int:
return self._response.status_code

@property
def headers(self) -> CaseInsensitiveDict[str]:
def headers(self) -> requests.structures.CaseInsensitiveDict[str]:
return self._response.headers

@property
Expand Down
4 changes: 2 additions & 2 deletions gitlab/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
Union,
)

from requests.structures import CaseInsensitiveDict
import requests

import gitlab.config
from gitlab.base import RESTObject
Expand Down Expand Up @@ -107,7 +107,7 @@ def die(msg: str, e: Optional[Exception] = None) -> None:
def gitlab_resource_to_cls(
gitlab_resource: str, namespace: ModuleType
) -> Type[RESTObject]:
classes = CaseInsensitiveDict(namespace.__dict__)
classes = requests.structures.CaseInsensitiveDict(namespace.__dict__)
lowercase_class = gitlab_resource.replace("-", "")
class_type = classes[lowercase_class]
if TYPE_CHECKING:
Expand Down
14 changes: 7 additions & 7 deletions gitlab/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import re
import time
import urllib
from typing import (
Any,
BinaryIO,
Expand All @@ -15,7 +16,6 @@
TYPE_CHECKING,
Union,
)
from urllib import parse

import requests

Expand Down Expand Up @@ -517,10 +517,10 @@ def _set_auth_info(self) -> None:
)

def enable_debug(self, mask_credentials: bool = True) -> None:
import http.client
import logging
from http import client

client.HTTPConnection.debuglevel = 1
http.client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
Expand All @@ -538,7 +538,7 @@ def enable_debug(self, mask_credentials: bool = True) -> None:
def print_as_log(*args: Any) -> None:
httpclient_log.log(logging.DEBUG, " ".join(args))

setattr(client, "print", print_as_log)
setattr(http.client, "print", print_as_log)

if not mask_credentials:
return
Expand Down Expand Up @@ -684,11 +684,11 @@ def http_request(
raw_url = self._build_url(path)

# parse user-provided URL params to ensure we don't add our own duplicates
parsed = parse.urlparse(raw_url)
params = parse.parse_qs(parsed.query)
parsed = urllib.parse.urlparse(raw_url)
params = urllib.parse.parse_qs(parsed.query)
utils.copy_dict(src=query_data, dest=params)

url = parse.urlunparse(parsed._replace(query=""))
url = urllib.parse.urlunparse(parsed._replace(query=""))

# Deal with kwargs: by default a user uses kwargs to send data to the
# gitlab server, but this generates problems (python keyword conflicts
Expand Down
14 changes: 8 additions & 6 deletions gitlab/config.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import configparser
import os
import pathlib
import shlex
import subprocess
from os.path import expanduser, expandvars
from pathlib import Path
from typing import List, Optional, Union

from gitlab.const import USER_AGENT

_DEFAULT_FILES: List[str] = [
"/etc/python-gitlab.cfg",
str(Path.home() / ".python-gitlab.cfg"),
str(pathlib.Path.home() / ".python-gitlab.cfg"),
]

HELPER_PREFIX = "helper:"
Expand All @@ -20,8 +19,8 @@
_CONFIG_PARSER_ERRORS = (configparser.NoOptionError, configparser.NoSectionError)


def _resolve_file(filepath: Union[Path, str]) -> str:
resolved = Path(filepath).resolve(strict=True)
def _resolve_file(filepath: Union[pathlib.Path, str]) -> str:
resolved = pathlib.Path(filepath).resolve(strict=True)
return str(resolved)


Expand Down Expand Up @@ -269,7 +268,10 @@ def _get_values_from_helper(self) -> None:
continue

helper = value[len(HELPER_PREFIX) :].strip()
commmand = [expanduser(expandvars(token)) for token in shlex.split(helper)]
commmand = [
os.path.expanduser(os.path.expandvars(token))
for token in shlex.split(helper)
]

try:
value = (
Expand Down
6 changes: 3 additions & 3 deletions gitlab/const.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from enum import Enum, IntEnum
import enum

from gitlab._version import __title__, __version__


class GitlabEnum(str, Enum):
class GitlabEnum(str, enum.Enum):
"""An enum mixed in with str to make it JSON-serializable."""


# https://gitlab.com/gitlab-org/gitlab/-/blob/e97357824bedf007e75f8782259fe07435b64fbb/lib/gitlab/access.rb#L12-18
class AccessLevel(IntEnum):
class AccessLevel(enum.IntEnum):
NO_ACCESS: int = 0
MINIMAL_ACCESS: int = 5
GUEST: int = 10
Expand Down
4 changes: 2 additions & 2 deletions gitlab/v4/objects/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
https://docs.gitlab.com/ee/user/packages/generic_packages/
"""

from pathlib import Path
import pathlib
from typing import (
Any,
BinaryIO,
Expand Down Expand Up @@ -57,7 +57,7 @@ def upload(
package_name: str,
package_version: str,
file_name: str,
path: Optional[Union[str, Path]] = None,
path: Optional[Union[str, pathlib.Path]] = None,
select: Optional[str] = None,
data: Optional[Union[bytes, BinaryIO]] = None,
**kwargs: Any,
Expand Down
Loading