Skip to content

Commit a46a790

Browse files
author
Nabil Freij
authored
save_file now cleans the filename, expands user and returns the full file path (#84)
1 parent 716a5ec commit a46a790

File tree

7 files changed

+71
-25
lines changed

7 files changed

+71
-25
lines changed

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ repos:
55
- id: docformatter
66
args: [--in-place, --pre-summary-newline, --make-summary-multi]
77
- repo: https://github.com/myint/autoflake
8-
rev: v1.5.3
8+
rev: v1.7.6
99
hooks:
1010
- id: autoflake
1111
args: ['--in-place', '--remove-all-unused-imports', '--remove-unused-variable']
1212
exclude: ".*(.fits|.fts|.fit|.txt|tca.*|extern.*|.rst|.md|__init__.py)$"
1313
- repo: https://github.com/psf/black
14-
rev: 22.8.0
14+
rev: 22.10.0
1515
hooks:
1616
- id: black
1717
exclude: ".*(.fits|.fts|.fit|.txt|.csv)$"
@@ -34,7 +34,7 @@ repos:
3434
- id: check-yaml
3535
- id: debug-statements
3636
- repo: https://github.com/pre-commit/mirrors-mypy
37-
rev: 'v0.971'
37+
rev: 'v0.982'
3838
hooks:
3939
- id: mypy
4040
additional_dependencies: [types-requests==2.28.0]

CHANGELOG.rst

Lines changed: 0 additions & 5 deletions
This file was deleted.

docs/index.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,8 @@ You need to install the development version of the package in order to make and
3030
See the :ref:`obtaining_the_source` section for details.
3131

3232
You may also want to familiarize yourself with the :ref:`dev_guide` for ``hvpy``.
33+
34+
Changelog
35+
---------
36+
37+
The changelog for ``hvpy`` is available on the `GitHub releases page <https://github.com/Helioviewer-Project/python-api/releases>`__.

hvpy/helpers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,12 @@ def createMovie(
122122
filename = f"{title}.{format}"
123123
else:
124124
filename = f"{filename}.{format}"
125-
save_file(
125+
filename = save_file(
126126
data=binary_data,
127127
filename=filename,
128128
overwrite=overwrite,
129129
)
130-
return Path(filename)
130+
return filename
131131

132132

133133
@_add_shared_docstring(takeScreenshotInputParameters)
@@ -203,9 +203,9 @@ def createScreenshot(
203203
filename = f"{res['id']}_{date.date()}.png"
204204
else:
205205
filename = f"{filename}.png"
206-
save_file(
206+
filename = save_file(
207207
data=binary_data,
208208
filename=filename,
209209
overwrite=overwrite,
210210
)
211-
return Path(filename)
211+
return filename

hvpy/tests/test_helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def test_createMovie(start_time, end_time, tmp_path):
3838
assert result == tmp_path / "movie.mp4"
3939

4040

41-
def test_createMovie_with_none_filename(start_time, end_time):
41+
def test_createMovie_with_no_filename(start_time, end_time):
4242
result = createMovie(
4343
startTime=start_time,
4444
endTime=end_time,

hvpy/tests/test_utils.py

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from pathlib import Path
12
from datetime import datetime
23

34
import pytest
@@ -71,7 +72,7 @@ def test_create_events_string():
7172

7273

7374
def test_save_file(tmp_path):
74-
f1 = tmp_path / "test.png"
75+
filename = tmp_path / "test.png"
7576
res = takeScreenshot(
7677
date=datetime.today(),
7778
imageScale=2.44,
@@ -82,13 +83,47 @@ def test_save_file(tmp_path):
8283
height=1200,
8384
display=True,
8485
)
85-
save_file(res, f1, overwrite=False)
86-
assert f1.exists()
86+
saved_file = save_file(res, filename, overwrite=False)
87+
assert saved_file == filename
8788
with pytest.raises(FileExistsError, match="already exists"):
88-
save_file(res, f1, overwrite=False)
89-
save_file(res, f1, overwrite=True)
90-
assert f1.exists()
89+
save_file(res, filename, overwrite=False)
90+
save_file(res, filename, overwrite=True)
9191

92-
f2 = tmp_path / "test2.png"
93-
save_file(res, str(f2), overwrite=False)
94-
assert f2.exists()
92+
93+
def test_save_file_cleans(tmp_path):
94+
# Clean the filename for Windows filepaths
95+
filename = tmp_path / ":test.png"
96+
clean_filename = str(filename).replace(":test.png", "_test.png")
97+
res = takeScreenshot(
98+
date=datetime.today(),
99+
imageScale=2.44,
100+
layers="[10,1,100]",
101+
x0=0,
102+
y0=0,
103+
width=1920,
104+
height=1200,
105+
display=True,
106+
)
107+
saved_file = save_file(res, str(filename))
108+
assert not filename.exists()
109+
assert saved_file == Path(clean_filename)
110+
111+
112+
def test_save_file_expands():
113+
# Check that ~/ expands
114+
filename = "~/:test.png"
115+
clean_filename = str(filename).replace(":", "_")
116+
res = takeScreenshot(
117+
date=datetime.today(),
118+
imageScale=2.44,
119+
layers="[10,1,100]",
120+
x0=0,
121+
y0=0,
122+
width=1920,
123+
height=1200,
124+
display=True,
125+
)
126+
saved_file = save_file(res, filename)
127+
saved_file.unlink()
128+
assert not Path(filename).exists()
129+
assert saved_file == Path(clean_filename).expanduser().resolve()

hvpy/utils.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import os
2+
import re
13
from typing import Any, List, Union, Callable
24
from pathlib import Path
35
from datetime import datetime
@@ -151,7 +153,7 @@ def create_events(events: List[Union[EventType, str, tuple]]) -> str:
151153
return constructed_events[:-1]
152154

153155

154-
def save_file(data: bytearray, filename: Union[Path, str], overwrite: bool = False) -> None:
156+
def save_file(data: bytearray, filename: Union[Path, str], overwrite: bool = False) -> Path:
155157
"""
156158
Saves a file to the specified path.
157159
@@ -164,9 +166,18 @@ def save_file(data: bytearray, filename: Union[Path, str], overwrite: bool = Fal
164166
overwrite
165167
Whether to overwrite the file if it already exists.
166168
Default is `False`.
169+
170+
Returns
171+
-------
172+
`~pathlib.Path`
173+
The path to the saved file.
167174
"""
168-
if isinstance(filename, str):
169-
filename = Path(filename)
175+
filepath, filename = os.path.split(filename)
176+
filename = re.sub(r"[^\w\-_\. ]", "_", filename)
177+
filename = Path(filepath) / Path(filename)
178+
filename = Path(filename).expanduser().resolve().absolute()
179+
# Sanitize the filename - Only works for strings
170180
if filename.exists() and not overwrite:
171181
raise FileExistsError(f"{filename} already exists. Use overwrite=True to overwrite.")
172182
filename.write_bytes(data)
183+
return filename

0 commit comments

Comments
 (0)