Skip to content

Commit

Permalink
refactor: use f-strings for string formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
nejch authored and JohnVillalovos committed Nov 6, 2021
1 parent f51d9be commit 7925c90
Show file tree
Hide file tree
Showing 40 changed files with 206 additions and 227 deletions.
10 changes: 3 additions & 7 deletions gitlab/base.py
Expand Up @@ -115,17 +115,13 @@ def __setattr__(self, name: str, value: Any) -> None:
def __str__(self) -> str:
data = self._attrs.copy()
data.update(self._updated_attrs)
return "%s => %s" % (type(self), data)
return f"{type(self)} => {data}"

def __repr__(self) -> str:
if self._id_attr:
return "<%s %s:%s>" % (
self.__class__.__name__,
self._id_attr,
self.get_id(),
)
return f"<{self.__class__.__name__} {self._id_attr}:{self.get_id()}>"
else:
return "<%s>" % self.__class__.__name__
return f"<{self.__class__.__name__}>"

def __eq__(self, other: object) -> bool:
if not isinstance(other, RESTObject):
Expand Down
8 changes: 4 additions & 4 deletions gitlab/cli.py
Expand Up @@ -85,8 +85,8 @@ def wrapped_f(*args: Any, **kwargs: Any) -> Any:

def die(msg: str, e: Optional[Exception] = None) -> None:
if e:
msg = "%s (%s)" % (msg, e)
sys.stderr.write(msg + "\n")
msg = f"{msg} ({e})"
sys.stderr.write(f"{msg}\n")
sys.exit(1)


Expand Down Expand Up @@ -172,7 +172,7 @@ def _parse_value(v: Any) -> Any:
with open(v[1:]) as fl:
return fl.read()
except Exception as e:
sys.stderr.write("%s\n" % e)
sys.stderr.write(f"{e}\n")
sys.exit(1)

return v
Expand Down Expand Up @@ -209,7 +209,7 @@ def main() -> None:
sys.exit(e)
# We only support v4 API at this time
if config.api_version not in ("4",):
raise ModuleNotFoundError(name="gitlab.v%s.cli" % config.api_version)
raise ModuleNotFoundError(name=f"gitlab.v{config.api_version}.cli")

# Now we build the entire set of subcommands and do the complete parsing
parser = _get_parser()
Expand Down
10 changes: 5 additions & 5 deletions gitlab/client.py
Expand Up @@ -80,7 +80,7 @@ def __init__(
self._server_version: Optional[str] = None
self._server_revision: Optional[str] = None
self._base_url = self._get_base_url(url)
self._url = "%s/api/v%s" % (self._base_url, api_version)
self._url = f"{self._base_url}/api/v{api_version}"
#: Timeout to use for requests to gitlab server
self.timeout = timeout
self.retry_transient_errors = retry_transient_errors
Expand All @@ -106,7 +106,7 @@ def __init__(

# We only support v4 API at this time
if self._api_version not in ("4",):
raise ModuleNotFoundError(name="gitlab.v%s.objects" % self._api_version)
raise ModuleNotFoundError(name=f"gitlab.v{self._api_version}.objects")
# NOTE: We must delay import of gitlab.v4.objects until now or
# otherwise it will cause circular import errors
import gitlab.v4.objects
Expand Down Expand Up @@ -196,7 +196,7 @@ def __setstate__(self, state: Dict[str, Any]) -> None:
self.__dict__.update(state)
# We only support v4 API at this time
if self._api_version not in ("4",):
raise ModuleNotFoundError(name="gitlab.v%s.objects" % self._api_version)
raise ModuleNotFoundError(name=f"gitlab.v{self._api_version}.objects")
# NOTE: We must delay import of gitlab.v4.objects until now or
# otherwise it will cause circular import errors
import gitlab.v4.objects
Expand Down Expand Up @@ -409,7 +409,7 @@ def _set_auth_info(self) -> None:
self.headers.pop("JOB-TOKEN", None)

if self.oauth_token:
self.headers["Authorization"] = "Bearer %s" % self.oauth_token
self.headers["Authorization"] = f"Bearer {self.oauth_token}"
self.headers.pop("PRIVATE-TOKEN", None)
self.headers.pop("JOB-TOKEN", None)

Expand Down Expand Up @@ -465,7 +465,7 @@ def _build_url(self, path: str) -> str:
if path.startswith("http://") or path.startswith("https://"):
return path
else:
return "%s%s" % (self._url, path)
return f"{self._url}{path}"

def _check_redirects(self, result: requests.Response) -> None:
# Check the requests history to detect 301/302 redirections.
Expand Down
8 changes: 4 additions & 4 deletions gitlab/config.py
Expand Up @@ -95,8 +95,8 @@ def __init__(
self.url = self._config.get(self.gitlab_id, "url")
except Exception as e:
raise GitlabDataError(
"Impossible to get gitlab informations from "
"configuration (%s)" % self.gitlab_id
"Impossible to get gitlab details from "
f"configuration ({self.gitlab_id})"
) from e

self.ssl_verify: Union[bool, str] = True
Expand Down Expand Up @@ -173,7 +173,7 @@ def __init__(
except Exception:
pass
if self.api_version not in ("4",):
raise GitlabDataError("Unsupported API version: %s" % self.api_version)
raise GitlabDataError(f"Unsupported API version: {self.api_version}")

self.per_page = None
for section in ["global", self.gitlab_id]:
Expand All @@ -182,7 +182,7 @@ def __init__(
except Exception:
pass
if self.per_page is not None and not 0 <= self.per_page <= 100:
raise GitlabDataError("Unsupported per_page number: %s" % self.per_page)
raise GitlabDataError(f"Unsupported per_page number: {self.per_page}")

self.pagination = None
try:
Expand Down
2 changes: 1 addition & 1 deletion gitlab/const.py
Expand Up @@ -55,4 +55,4 @@
# specific project scope
SEARCH_SCOPE_PROJECT_NOTES: str = "notes"

USER_AGENT: str = "{}/{}".format(__title__, __version__)
USER_AGENT: str = f"{__title__}/{__version__}"
4 changes: 2 additions & 2 deletions gitlab/exceptions.py
Expand Up @@ -46,9 +46,9 @@ def __init__(

def __str__(self) -> str:
if self.response_code is not None:
return "{0}: {1}".format(self.response_code, self.error_message)
return f"{self.response_code}: {self.error_message}"
else:
return "{0}".format(self.error_message)
return f"{self.error_message}"


class GitlabAuthenticationError(GitlabError):
Expand Down
46 changes: 23 additions & 23 deletions gitlab/mixins.py
Expand Up @@ -101,7 +101,7 @@ def get(
"""
if not isinstance(id, int):
id = utils.clean_str_id(id)
path = "%s/%s" % (self.path, id)
path = f"{self.path}/{id}"
if TYPE_CHECKING:
assert self._obj_cls is not None
if lazy is True:
Expand Down Expand Up @@ -173,7 +173,7 @@ def refresh(self, **kwargs: Any) -> None:
GitlabGetError: If the server cannot perform the request
"""
if self._id_attr:
path = "%s/%s" % (self.manager.path, self.id)
path = f"{self.manager.path}/{self.id}"
else:
if TYPE_CHECKING:
assert self.manager.path is not None
Expand Down Expand Up @@ -273,7 +273,7 @@ def _check_missing_create_attrs(self, data: Dict[str, Any]) -> None:
missing.append(attr)
continue
if missing:
raise AttributeError("Missing attributes: %s" % ", ".join(missing))
raise AttributeError(f"Missing attributes: {', '.join(missing)}")

@exc.on_http_error(exc.GitlabCreateError)
def create(
Expand Down Expand Up @@ -349,7 +349,7 @@ def _check_missing_update_attrs(self, data: Dict[str, Any]) -> None:
missing.append(attr)
continue
if missing:
raise AttributeError("Missing attributes: %s" % ", ".join(missing))
raise AttributeError(f"Missing attributes: {', '.join(missing)}")

def _get_update_method(
self,
Expand All @@ -370,7 +370,7 @@ def update(
self,
id: Optional[Union[str, int]] = None,
new_data: Optional[Dict[str, Any]] = None,
**kwargs: Any
**kwargs: Any,
) -> Dict[str, Any]:
"""Update an object on the server.
Expand All @@ -391,7 +391,7 @@ def update(
if id is None:
path = self.path
else:
path = "%s/%s" % (self.path, id)
path = f"{self.path}/{id}"

self._check_missing_update_attrs(new_data)
files = {}
Expand Down Expand Up @@ -444,7 +444,7 @@ def set(self, key: str, value: str, **kwargs: Any) -> base.RESTObject:
Returns:
obj: The created/updated attribute
"""
path = "%s/%s" % (self.path, utils.clean_str_id(key))
path = f"{self.path}/{utils.clean_str_id(key)}"
data = {"value": value}
server_data = self.gitlab.http_put(path, post_data=data, **kwargs)
if TYPE_CHECKING:
Expand Down Expand Up @@ -479,7 +479,7 @@ def delete(self, id: Union[str, int], **kwargs: Any) -> None:
else:
if not isinstance(id, int):
id = utils.clean_str_id(id)
path = "%s/%s" % (self.path, id)
path = f"{self.path}/{id}"
self.gitlab.http_delete(path, **kwargs)


Expand Down Expand Up @@ -598,7 +598,7 @@ def user_agent_detail(self, **kwargs: Any) -> Dict[str, Any]:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server cannot perform the request
"""
path = "%s/%s/user_agent_detail" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/user_agent_detail"
result = self.manager.gitlab.http_get(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(result, requests.Response)
Expand Down Expand Up @@ -631,7 +631,7 @@ def approve(
GitlabUpdateError: If the server fails to perform the request
"""

path = "%s/%s/approve" % (self.manager.path, self.id)
path = f"{self.manager.path}/{self.id}/approve"
data = {"access_level": access_level}
server_data = self.manager.gitlab.http_put(path, post_data=data, **kwargs)
if TYPE_CHECKING:
Expand All @@ -654,7 +654,7 @@ def download(
streamed: bool = False,
action: Optional[Callable] = None,
chunk_size: int = 1024,
**kwargs: Any
**kwargs: Any,
) -> Optional[bytes]:
"""Download the archive of a resource export.
Expand All @@ -674,7 +674,7 @@ def download(
Returns:
str: The blob content if streamed is False, None otherwise
"""
path = "%s/download" % (self.manager.path)
path = f"{self.manager.path}/download"
result = self.manager.gitlab.http_get(
path, streamed=streamed, raw=True, **kwargs
)
Expand Down Expand Up @@ -705,7 +705,7 @@ def subscribe(self, **kwargs: Any) -> None:
GitlabAuthenticationError: If authentication is not correct
GitlabSubscribeError: If the subscription cannot be done
"""
path = "%s/%s/subscribe" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/subscribe"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(server_data, requests.Response)
Expand All @@ -725,7 +725,7 @@ def unsubscribe(self, **kwargs: Any) -> None:
GitlabAuthenticationError: If authentication is not correct
GitlabUnsubscribeError: If the unsubscription cannot be done
"""
path = "%s/%s/unsubscribe" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/unsubscribe"
server_data = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(server_data, requests.Response)
Expand All @@ -752,7 +752,7 @@ def todo(self, **kwargs: Any) -> None:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the todo cannot be set
"""
path = "%s/%s/todo" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/todo"
self.manager.gitlab.http_post(path, **kwargs)


Expand Down Expand Up @@ -781,7 +781,7 @@ def time_stats(self, **kwargs: Any) -> Dict[str, Any]:
if "time_stats" in self.attributes:
return self.attributes["time_stats"]

path = "%s/%s/time_stats" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/time_stats"
result = self.manager.gitlab.http_get(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(result, requests.Response)
Expand All @@ -800,7 +800,7 @@ def time_estimate(self, duration: str, **kwargs: Any) -> Dict[str, Any]:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done
"""
path = "%s/%s/time_estimate" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/time_estimate"
data = {"duration": duration}
result = self.manager.gitlab.http_post(path, post_data=data, **kwargs)
if TYPE_CHECKING:
Expand All @@ -819,7 +819,7 @@ def reset_time_estimate(self, **kwargs: Any) -> Dict[str, Any]:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done
"""
path = "%s/%s/reset_time_estimate" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/reset_time_estimate"
result = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(result, requests.Response)
Expand All @@ -838,7 +838,7 @@ def add_spent_time(self, duration: str, **kwargs: Any) -> Dict[str, Any]:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done
"""
path = "%s/%s/add_spent_time" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/add_spent_time"
data = {"duration": duration}
result = self.manager.gitlab.http_post(path, post_data=data, **kwargs)
if TYPE_CHECKING:
Expand All @@ -857,7 +857,7 @@ def reset_spent_time(self, **kwargs: Any) -> Dict[str, Any]:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done
"""
path = "%s/%s/reset_spent_time" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/reset_spent_time"
result = self.manager.gitlab.http_post(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(result, requests.Response)
Expand Down Expand Up @@ -893,7 +893,7 @@ def participants(self, **kwargs: Any) -> Dict[str, Any]:
RESTObjectList: The list of participants
"""

path = "%s/%s/participants" % (self.manager.path, self.get_id())
path = f"{self.manager.path}/{self.get_id()}/participants"
result = self.manager.gitlab.http_get(path, **kwargs)
if TYPE_CHECKING:
assert not isinstance(result, requests.Response)
Expand All @@ -920,7 +920,7 @@ def render(self, link_url: str, image_url: str, **kwargs: Any) -> Dict[str, Any]
Returns:
dict: The rendering properties
"""
path = "%s/render" % self.path
path = f"{self.path}/render"
data = {"link_url": link_url, "image_url": image_url}
result = self.gitlab.http_get(path, data, **kwargs)
if TYPE_CHECKING:
Expand Down Expand Up @@ -967,7 +967,7 @@ def promote(self, **kwargs: Any) -> Dict[str, Any]:
dict: The updated object data (*not* a RESTObject)
"""

path = "%s/%s/promote" % (self.manager.path, self.id)
path = f"{self.manager.path}/{self.id}/promote"
http_method = self._get_update_method()
result = http_method(path, **kwargs)
if TYPE_CHECKING:
Expand Down
2 changes: 1 addition & 1 deletion gitlab/types.py
Expand Up @@ -61,4 +61,4 @@ def get_file_name(self, attr_name: Optional[str] = None) -> Optional[str]:

class ImageAttribute(FileAttribute):
def get_file_name(self, attr_name: Optional[str] = None) -> str:
return "%s.png" % attr_name if attr_name else "image.png"
return f"{attr_name}.png" if attr_name else "image.png"
2 changes: 1 addition & 1 deletion gitlab/utils.py
Expand Up @@ -51,7 +51,7 @@ def copy_dict(dest: Dict[str, Any], src: Dict[str, Any]) -> None:
# custom_attributes: {'foo', 'bar'} =>
# "custom_attributes['foo']": "bar"
for dict_k, dict_v in v.items():
dest["%s[%s]" % (k, dict_k)] = dict_v
dest[f"{k}[{dict_k}]"] = dict_v
else:
dest[k] = v

Expand Down

0 comments on commit 7925c90

Please sign in to comment.