Skip to content

fix: remove custom URL encoding #1816

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 1 commit into from
Jan 9, 2022
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
6 changes: 3 additions & 3 deletions gitlab/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def get(
GitlabGetError: If the server cannot perform the request
"""
if not isinstance(id, int):
id = utils.clean_str_id(id)
id = utils._url_encode(id)
path = f"{self.path}/{id}"
if TYPE_CHECKING:
assert self._obj_cls is not None
Expand Down Expand Up @@ -444,7 +444,7 @@ def set(self, key: str, value: str, **kwargs: Any) -> base.RESTObject:
Returns:
The created/updated attribute
"""
path = f"{self.path}/{utils.clean_str_id(key)}"
path = f"{self.path}/{utils._url_encode(key)}"
data = {"value": value}
server_data = self.gitlab.http_put(path, post_data=data, **kwargs)
if TYPE_CHECKING:
Expand Down Expand Up @@ -478,7 +478,7 @@ def delete(self, id: Union[str, int], **kwargs: Any) -> None:
path = self.path
else:
if not isinstance(id, int):
id = utils.clean_str_id(id)
id = utils._url_encode(id)
path = f"{self.path}/{id}"
self.gitlab.http_delete(path, **kwargs)

Expand Down
23 changes: 20 additions & 3 deletions gitlab/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import urllib.parse
from typing import Any, Callable, Dict, Optional
from urllib.parse import quote

import requests

Expand Down Expand Up @@ -56,8 +56,25 @@ def copy_dict(dest: Dict[str, Any], src: Dict[str, Any]) -> None:
dest[k] = v


def clean_str_id(id: str) -> str:
return quote(id, safe="")
def _url_encode(id: str) -> str:
"""Encode/quote the characters in the string so that they can be used in a path.

Reference to documentation on why this is necessary.

https://docs.gitlab.com/ee/api/index.html#namespaced-path-encoding

If using namespaced API requests, make sure that the NAMESPACE/PROJECT_PATH is
URL-encoded. For example, / is represented by %2F

https://docs.gitlab.com/ee/api/index.html#path-parameters

Path parameters that are required to be URL-encoded must be followed. If not, it
doesn’t match an API endpoint and responds with a 404. If there’s something in front
of the API (for example, Apache), ensure that it doesn’t decode the URL-encoded path
parameters.

"""
return urllib.parse.quote(id, safe="")


def remove_none_from_dict(data: Dict[str, Any]) -> Dict[str, Any]:
Expand Down
2 changes: 1 addition & 1 deletion gitlab/v4/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _process_from_parent_attrs(self) -> None:
if key not in self.args:
continue

self.parent_args[key] = gitlab.utils.clean_str_id(self.args[key])
self.parent_args[key] = gitlab.utils._url_encode(self.args[key])
# If we don't delete it then it will be added to the URL as a query-string
del self.args[key]

Expand Down
3 changes: 2 additions & 1 deletion gitlab/v4/objects/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ def set(
Returns:
The created/updated attribute
"""
path = f"{self.path}/{name.replace('/', '%2F')}"
name = utils._url_encode(name)
path = f"{self.path}/{name}"
data = {
"value": value,
"feature_group": feature_group,
Expand Down
15 changes: 8 additions & 7 deletions gitlab/v4/objects/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def save( # type: ignore
"""
self.branch = branch
self.commit_message = commit_message
self.file_path = self.file_path.replace("/", "%2F")
self.file_path = utils._url_encode(self.file_path)
super(ProjectFile, self).save(**kwargs)

@exc.on_http_error(exc.GitlabDeleteError)
Expand All @@ -76,7 +76,7 @@ def delete( # type: ignore
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
file_path = self.get_id().replace("/", "%2F")
file_path = utils._url_encode(self.get_id())
self.manager.delete(file_path, branch, commit_message, **kwargs)


Expand Down Expand Up @@ -144,7 +144,7 @@ def create(
assert data is not None
self._check_missing_create_attrs(data)
new_data = data.copy()
file_path = new_data.pop("file_path").replace("/", "%2F")
file_path = utils._url_encode(new_data.pop("file_path"))
path = f"{self.path}/{file_path}"
server_data = self.gitlab.http_post(path, post_data=new_data, **kwargs)
if TYPE_CHECKING:
Expand Down Expand Up @@ -173,7 +173,7 @@ def update( # type: ignore
"""
new_data = new_data or {}
data = new_data.copy()
file_path = file_path.replace("/", "%2F")
file_path = utils._url_encode(file_path)
data["file_path"] = file_path
path = f"{self.path}/{file_path}"
self._check_missing_update_attrs(data)
Expand Down Expand Up @@ -203,7 +203,8 @@ def delete( # type: ignore
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request
"""
path = f"{self.path}/{file_path.replace('/', '%2F')}"
file_path = utils._url_encode(file_path)
path = f"{self.path}/{file_path}"
data = {"branch": branch, "commit_message": commit_message}
self.gitlab.http_delete(path, query_data=data, **kwargs)

Expand Down Expand Up @@ -238,7 +239,7 @@ def raw(
Returns:
The file content
"""
file_path = file_path.replace("/", "%2F").replace(".", "%2E")
file_path = utils._url_encode(file_path)
path = f"{self.path}/{file_path}/raw"
query_data = {"ref": ref}
result = self.gitlab.http_get(
Expand All @@ -265,7 +266,7 @@ def blame(self, file_path: str, ref: str, **kwargs: Any) -> List[Dict[str, Any]]
Returns:
A list of commits/lines matching the file
"""
file_path = file_path.replace("/", "%2F").replace(".", "%2E")
file_path = utils._url_encode(file_path)
path = f"{self.path}/{file_path}/blame"
query_data = {"ref": ref}
result = self.gitlab.http_list(path, query_data, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion gitlab/v4/objects/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def update_submodule(
GitlabPutError: If the submodule could not be updated
"""

submodule = submodule.replace("/", "%2F") # .replace('.', '%2E')
submodule = utils._url_encode(submodule)
path = f"/projects/{self.get_id()}/repository/submodules/{submodule}"
data = {"branch": branch, "commit_sha": commit_sha}
if "commit_message" in kwargs:
Expand Down
8 changes: 6 additions & 2 deletions tests/functional/api/test_repository.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import os
import sys
import tarfile
import time
Expand All @@ -13,13 +14,13 @@
def test_repository_files(project):
project.files.create(
{
"file_path": "README",
"file_path": "README.md",
"branch": "main",
"content": "Initial content",
"commit_message": "Initial commit",
}
)
readme = project.files.get(file_path="README", ref="main")
readme = project.files.get(file_path="README.md", ref="main")
readme.content = base64.b64encode(b"Improved README").decode()

time.sleep(2)
Expand All @@ -42,6 +43,9 @@ def test_repository_files(project):
blame = project.files.blame(file_path="README.rst", ref="main")
assert blame

raw_file = project.files.raw(file_path="README.rst", ref="main")
assert os.fsdecode(raw_file) == "Initial content"


def test_repository_tree(project):
tree = project.repository_tree()
Expand Down
13 changes: 9 additions & 4 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,20 @@
from gitlab import utils


def test_clean_str_id():
def test_url_encode():
src = "nothing_special"
dest = "nothing_special"
assert dest == utils.clean_str_id(src)
assert dest == utils._url_encode(src)

src = "foo#bar/baz/"
dest = "foo%23bar%2Fbaz%2F"
assert dest == utils.clean_str_id(src)
assert dest == utils._url_encode(src)

src = "foo%bar/baz/"
dest = "foo%25bar%2Fbaz%2F"
assert dest == utils.clean_str_id(src)
assert dest == utils._url_encode(src)

# periods/dots should not be modified
src = "docs/README.md"
dest = "docs%2FREADME.md"
assert dest == utils._url_encode(src)