Skip to content

Commit 8751402

Browse files
committed
feat(files): allow decoding project files directly to string
1 parent 0ecf3bb commit 8751402

File tree

3 files changed

+27
-6
lines changed

3 files changed

+27
-6
lines changed

docs/gl_objects/projects.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,9 +434,12 @@ Get a file::
434434
# get the base64 encoded content
435435
print(f.content)
436436

437-
# get the decoded content
437+
# get the decoded content as bytes
438438
print(f.decode())
439439

440+
# get the decoded content as a string
441+
print(f.decode("utf-8"))
442+
440443
Get file details from headers, without fetching its entire content::
441444

442445
headers = project.files.head('README.rst', ref='main')

gitlab/v4/objects/files.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
Iterator,
88
List,
99
Optional,
10+
overload,
1011
TYPE_CHECKING,
1112
Union,
1213
)
@@ -41,13 +42,30 @@ class ProjectFile(SaveMixin, ObjectDeleteMixin, RESTObject):
4142
file_path: str
4243
manager: "ProjectFileManager"
4344

45+
@overload
4446
def decode(self) -> bytes:
47+
...
48+
49+
@overload
50+
def decode(self, encoding: None) -> bytes:
51+
...
52+
53+
@overload
54+
def decode(self, encoding: str) -> str:
55+
...
56+
57+
def decode(self, encoding: Optional[str] = None) -> Union[bytes, str]:
4558
"""Returns the decoded content of the file.
4659
4760
Returns:
48-
The decoded content.
61+
The decoded content as bytes.
62+
The decoded content as string if a valid encoding is provided.
4963
"""
50-
return base64.b64decode(self.content)
64+
decoded_bytes = base64.b64decode(self.content)
65+
66+
if encoding is not None:
67+
return decoded_bytes.decode(encoding)
68+
return decoded_bytes
5169

5270
# NOTE(jlvillal): Signature doesn't match SaveMixin.save() so ignore
5371
# type error

tests/functional/api/test_repository.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ def test_repository_files(project):
3636
}
3737
)
3838
readme = project.files.get(file_path="README.rst", ref="main")
39-
# The first decode() is the ProjectFile method, the second one is the bytes
40-
# object method
41-
assert readme.decode().decode() == "Initial content"
39+
40+
assert readme.decode() == b"Initial content"
41+
assert readme.decode("utf-8") == "Initial content"
4242

4343
headers = project.files.head("README.rst", ref="main")
4444
assert headers["X-Gitlab-File-Path"] == "README.rst"

0 commit comments

Comments
 (0)