Skip to content

Commit 2a038b3

Browse files
committed
chore: use pathlib for path manipulations
This simplifies the code and allows use to simplify error handling.
1 parent 4c61c5c commit 2a038b3

File tree

9 files changed

+97
-111
lines changed

9 files changed

+97
-111
lines changed

examples/addfile.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,8 @@
2020
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2121
#
2222

23-
24-
import os
25-
import pathlib
2623
import sys
24+
from pathlib import Path
2725

2826
import gammu
2927

@@ -33,7 +31,8 @@ def main() -> None:
3331
print("This requires two parameters: file to upload and path!")
3432
sys.exit(1)
3533

36-
data = pathlib.Path(sys.argv[1]).read_bytes()
34+
test_file = Path(sys.argv[1])
35+
data = test_file.read_bytes()
3736

3837
state_machine = gammu.StateMachine()
3938
state_machine.ReadConfig()
@@ -43,7 +42,7 @@ def main() -> None:
4342
print("\n\nExpection: Put specified file onto Memorycard on phone")
4443
file_f = {
4544
"ID_FullName": sys.argv[2],
46-
"Name": os.path.basename(sys.argv[1]),
45+
"Name": test_file.name,
4746
"Buffer": data,
4847
"Protected": 0,
4948
"ReadOnly": 0,

examples/filesystem_test.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747

4848
import argparse
4949
import datetime
50-
import os
5150
import sys
5251
from pathlib import Path
5352

@@ -91,7 +90,7 @@ def main() -> None: # noqa: PLR0912, PLR0915, C901
9190
print("And even better, you should read the script before you run it.")
9291
sys.exit(1)
9392

94-
if not os.path.exists(args.testfile):
93+
if not Path(args.testfile).exists():
9594
print("You have to select file which will be used for testing!")
9695
sys.exit(1)
9796

@@ -120,8 +119,9 @@ def main() -> None: # noqa: PLR0912, PLR0915, C901
120119

121120
# Check AddFilePart
122121
print("\n\nExpectation: Put cgi.jpg onto Memorycard on phone")
123-
file_content = Path(args.testfile).read_bytes()
124-
file_stat = os.stat(args.testfile)
122+
file_object = Path(args.testfile)
123+
file_content = file_object.read_bytes()
124+
file_stat = file_object.stat()
125125
ttime = datetime.datetime.fromtimestamp(file_stat[8])
126126
file_f = {
127127
"ID_FullName": args.folder,
@@ -159,7 +159,7 @@ def main() -> None: # noqa: PLR0912, PLR0915, C901
159159
else:
160160
print("Files differ!")
161161

162-
os.remove("./test.jpg")
162+
Path("./test.jpg").unlink()
163163

164164
# Check GetNextRootFolder
165165
print("\n\nExpectation: Root Folder List")

examples/savesmspercontact.py

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,12 @@
2121
#
2222

2323

24-
import errno
25-
import os
2624
import re
25+
from pathlib import Path
2726

2827
import gammu
2928

3029

31-
def createFolderIfNotExist(path) -> None:
32-
try:
33-
os.makedirs(path)
34-
except OSError as exception:
35-
if exception.errno != errno.EEXIST:
36-
raise
37-
38-
3930
def getInternationalizedNumber(number):
4031
if not number:
4132
return "Unknown"
@@ -45,16 +36,14 @@ def getInternationalizedNumber(number):
4536
return number
4637

4738

48-
def getFilename(mydir, mysms):
39+
def getFilename(mydir: Path, mysms) -> str:
4940
if mysms[0]["DateTime"]:
5041
return mysms[0]["DateTime"].strftime("%Y-%m-%d-%Hh%Mm%Ss")
5142

5243
# no date available so calculate unknown number
53-
myfiles = os.listdir(mydir)
54-
5544
nextitem = 0
56-
for i in myfiles:
57-
match = re.match(r"^Unknown-([0-9]*)", i)
45+
for i in mydir.glob("Unknown-*"):
46+
match = re.match(r"^Unknown-([0-9]*)", i.name)
5847
if match and int(match.group(1)) > nextitem:
5948
nextitem = int(match.group(1))
6049

@@ -65,15 +54,17 @@ def saveSMS(mysms, all_contacts) -> None:
6554
my_number = getInternationalizedNumber(mysms[0]["Number"])
6655

6756
try:
68-
mydir = all_contacts[my_number]
57+
mydir = Path(all_contacts[my_number])
6958
except KeyError:
70-
mydir = my_number
59+
mydir = Path(my_number)
7160

72-
createFolderIfNotExist(mydir)
61+
mydir.mkdir(parents=True, exist_ok=True)
7362

7463
myfile = getFilename(mydir, mysms)
7564

76-
with open(os.path.join(mydir, myfile), "a", encoding="utf-8") as handle:
65+
outfile = mydir / myfile
66+
67+
with outfile.open("a", encoding="utf-8") as handle:
7768
handle.writelines(i["Text"] for i in mysms)
7869
handle.write("\n")
7970

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,6 @@ ignore = [
151151
"PERF203", # WONFIX: affects only old Python versions
152152
"PLR2004",
153153
"PLR6301",
154-
"PTH",
155154
"RUF012",
156155
"S607",
157156
"SIM115",

setup.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@
2121
#
2222
"""python-gammu - Phone communication library."""
2323

24-
import glob
2524
import os
2625
import platform
2726
import subprocess # noqa: S404
2827
import sys
28+
from pathlib import Path
29+
from typing import cast
2930

3031
from packaging.version import parse
3132
from setuptools import Extension, setup
@@ -40,7 +41,7 @@ def __init__(self) -> None:
4041
self.on_windows = platform.system() == "Windows"
4142
self.has_pkgconfig = self.check_pkconfig()
4243
self.has_env = "GAMMU_PATH" in os.environ
43-
self.path = self.lookup_path()
44+
self.path: Path = cast("Path", self.lookup_path())
4445
self.use_pkgconfig = self.has_pkgconfig and not self.has_env
4546

4647
def check_pkconfig(self) -> bool:
@@ -50,28 +51,29 @@ def check_pkconfig(self) -> bool:
5051
except (subprocess.CalledProcessError, OSError):
5152
return False
5253

53-
def config_path(self, base):
54-
return os.path.join(base, "include", "gammu", "gammu-config.h")
54+
def config_path(self, base: Path) -> Path:
55+
return base / "include" / "gammu" / "gammu-config.h"
5556

56-
def lookup_path(self):
57+
def lookup_path(self) -> Path | None:
58+
paths: list[Path]
5759
if self.has_env:
58-
paths = [os.environ["GAMMU_PATH"]]
60+
paths = [Path(os.environ["GAMMU_PATH"])]
5961
elif self.on_windows:
6062
paths = [
61-
"C:\\Gammu",
62-
"C:\\Program Files\\Gammu",
63-
"C:\\Program Files (x86)\\Gammu",
63+
Path("C:\\Gammu"),
64+
Path("C:\\Program Files\\Gammu"),
65+
Path("C:\\Program Files (x86)\\Gammu"),
6466
]
65-
paths += glob.glob("C:\\Program Files\\Gammu*")
66-
paths += glob.glob("C:\\Program Files (x86)\\Gammu*")
67+
paths += Path("C:\\Program Files").glob("Gammu*")
68+
paths += Path("C:\\Program Files (x86)").glob("Gammu*")
6769
else:
68-
paths = ["/usr/local/", "/usr/"]
69-
paths += glob.glob("/opt/gammu*")
70+
paths = [Path("/usr/local/"), Path("/usr/")]
71+
paths += Path("/opt").glob("gammu*")
7072

7173
for path in paths:
7274
include = self.config_path(path)
73-
if os.path.exists(include):
74-
return path
75+
if include.exists():
76+
return Path(path)
7577
return None
7678

7779
def check_version(self) -> None:
@@ -91,7 +93,7 @@ def check_version(self) -> None:
9193
print("Can not find supported Gammu version using pkg-config!")
9294
sys.exit(100)
9395

94-
if self.path is None:
96+
if not self.path:
9597
print("Failed to find Gammu!")
9698
print("Either it is not installed or not found.")
9799
print("After install Gammu ensure that setup finds it by any of:")
@@ -100,7 +102,7 @@ def check_version(self) -> None:
100102
sys.exit(101)
101103

102104
version = None
103-
with open(self.config_path(self.path), encoding="utf-8") as handle:
105+
with self.config_path(self.path).open(encoding="utf-8") as handle:
104106
for line in handle:
105107
if line.startswith("#define GAMMU_VERSION "):
106108
version = parse(line.split('"')[1])
@@ -109,7 +111,7 @@ def check_version(self) -> None:
109111
print("Too old Gammu version, please upgrade!")
110112
sys.exit(100)
111113

112-
def get_libs(self):
114+
def get_libs(self) -> list[str]:
113115
if self.use_pkgconfig:
114116
output = subprocess.check_output(
115117
["pkg-config", "--libs-only-l", "gammu", "gammu-smsd"]
@@ -122,7 +124,7 @@ def get_libs(self):
122124
libs.append("m")
123125
return libs
124126

125-
def get_cflags(self):
127+
def get_cflags(self) -> str:
126128
if self.use_pkgconfig:
127129
return (
128130
subprocess.check_output(
@@ -131,9 +133,9 @@ def get_cflags(self):
131133
.decode("utf-8")
132134
.strip()
133135
)
134-
return "-I{}".format(os.path.join(self.path, "include", "gammu"))
136+
return "-I{}".format((self.path / "include" / "gammu").as_posix())
135137

136-
def get_ldflags(self):
138+
def get_ldflags(self) -> str:
137139
if self.use_pkgconfig:
138140
return (
139141
subprocess.check_output(
@@ -143,8 +145,8 @@ def get_ldflags(self):
143145
.strip()
144146
)
145147
if self.on_windows:
146-
return "/LIBPATH:{}".format(os.path.join(self.path, "lib"))
147-
return "-L{}".format(os.path.join(self.path, "lib"))
148+
return "/LIBPATH:{}".format(self.path / "lib")
149+
return "-L{}".format((self.path / "lib").as_posix())
148150

149151

150152
def get_module():

test/test_backup.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,21 @@
1818
# with this program; if not, write to the Free Software Foundation, Inc.,
1919
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2020
#
21-
import glob
22-
import os
23-
import os.path
2421
import tempfile
2522
import unittest
23+
from pathlib import Path
2624

2725
import gammu
2826

29-
TEST_DIR = os.path.join(os.path.dirname(__file__), "data")
30-
TEST_FILES_CALENDAR = glob.glob(os.path.join(TEST_DIR, "*.ics")) + glob.glob(
31-
os.path.join(TEST_DIR, "*.vcs")
32-
)
33-
TEST_FILES_CONTACTS = glob.glob(os.path.join(TEST_DIR, "*.vcf"))
27+
TEST_DIR = Path(__file__).parent / "data"
28+
TEST_FILES_CALENDAR = [*TEST_DIR.glob("*.ics"), *TEST_DIR.glob("*.vcs")]
29+
TEST_FILES_CONTACTS = TEST_DIR.glob("*.vcf")
3430
TEST_CONTACTS = (".lmb", ".vcf", ".backup")
3531
TEST_CALENDAR = (".vcs", ".ics", ".backup")
3632

3733

3834
class BackupTest(unittest.TestCase):
39-
def perform_test(self, filename, extensions) -> None:
35+
def perform_test(self, filename: Path, extensions: tuple[str, ...]) -> None:
4036
out_files = [
4137
tempfile.NamedTemporaryFile(suffix=extension, delete=False)
4238
for extension in extensions
@@ -47,7 +43,7 @@ def perform_test(self, filename, extensions) -> None:
4743
handle.close()
4844
out_backup.close()
4945
try:
50-
backup = gammu.ReadBackup(filename)
46+
backup = gammu.ReadBackup(filename.as_posix())
5147
for out in out_files:
5248
# Save to new format
5349
gammu.SaveBackup(out.name, backup)
@@ -69,8 +65,8 @@ def perform_test(self, filename, extensions) -> None:
6965
gammu.SaveBackup(out_backup.name, backup)
7066
finally:
7167
for handle in out_files:
72-
os.unlink(handle.name)
73-
os.unlink(out_backup.name)
68+
Path(handle.name).unlink()
69+
Path(out_backup.name).unlink()
7470

7571
def test_convert_contacts(self) -> None:
7672
for filename in TEST_FILES_CONTACTS:
@@ -81,7 +77,7 @@ def test_convert_calendar(self) -> None:
8177
self.perform_test(filename, TEST_CALENDAR)
8278

8379
def test_calendar(self) -> None:
84-
entry = gammu.ReadBackup(os.path.join(TEST_DIR, "rrule.ics"))["Calendar"][0]
80+
entry = gammu.ReadBackup((TEST_DIR / "rrule.ics").as_posix())["Calendar"][0]
8581

8682
# Convert it to vCard
8783
vc_entry = gammu.EncodeVCALENDAR(entry)
@@ -94,7 +90,7 @@ def test_calendar(self) -> None:
9490
assert entry2["Type"] == entry3["Type"]
9591

9692
def test_todo(self) -> None:
97-
entry = gammu.ReadBackup(os.path.join(TEST_DIR, "02.vcs"))["ToDo"][0]
93+
entry = gammu.ReadBackup((TEST_DIR / "02.vcs").as_posix())["ToDo"][0]
9894

9995
# Convert it to vCard
10096
vt_entry = gammu.EncodeVTODO(entry)
@@ -107,7 +103,7 @@ def test_todo(self) -> None:
107103
assert entry2["Type"] == entry3["Type"]
108104

109105
def test_contact(self) -> None:
110-
entry = gammu.ReadBackup(os.path.join(TEST_DIR, "gammu.vcf"))["PhonePhonebook"][
106+
entry = gammu.ReadBackup((TEST_DIR / "gammu.vcf").as_posix())["PhonePhonebook"][
111107
0
112108
]
113109

test/test_config.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
# with this program; if not, write to the Free Software Foundation, Inc.,
1919
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2020
#
21-
import pathlib
2221
import tempfile
2322
import unittest
23+
from pathlib import Path
2424

2525
import pytest
2626

@@ -103,19 +103,19 @@ def check_operation(self, filename, handle=None) -> None:
103103
if handle:
104104
handle.close()
105105
if filename is not None:
106-
content = pathlib.Path(filename).read_text(encoding="utf-8")
106+
content = Path(filename).read_text(encoding="utf-8")
107107
assert "SMS type: Status report" in content
108108

109109
def test_file(self) -> None:
110110
testfile = tempfile.NamedTemporaryFile(suffix=".debug", delete=False)
111111
testfile.close()
112112
try:
113-
handle = pathlib.Path(testfile.name).open("w", encoding="utf-8")
113+
handle = Path(testfile.name).open("w", encoding="utf-8")
114114
gammu.SetDebugFile(handle)
115115
self.check_operation(testfile.name, handle)
116116
finally:
117117
gammu.SetDebugFile(None)
118-
pathlib.Path(testfile.name).unlink()
118+
Path(testfile.name).unlink()
119119

120120
def test_filename(self) -> None:
121121
testfile = tempfile.NamedTemporaryFile(suffix=".debug", delete=False)
@@ -125,7 +125,7 @@ def test_filename(self) -> None:
125125
self.check_operation(testfile.name)
126126
finally:
127127
gammu.SetDebugFile(None)
128-
pathlib.Path(testfile.name).unlink()
128+
Path(testfile.name).unlink()
129129

130130
def test_none(self) -> None:
131131
gammu.SetDebugFile(None)
@@ -138,8 +138,8 @@ def test_nothing(self) -> None:
138138
try:
139139
gammu.SetDebugFile(testfile.name)
140140
self.check_operation(None)
141-
content = pathlib.Path(testfile.name).read_text(encoding="utf-8")
141+
content = Path(testfile.name).read_text(encoding="utf-8")
142142
assert not content
143143
finally:
144144
gammu.SetDebugFile(None)
145-
pathlib.Path(testfile.name).unlink()
145+
Path(testfile.name).unlink()

0 commit comments

Comments
 (0)