Skip to content

Commit e61afed

Browse files
committed
type(fs): add type annotations and fix toml_dump return
1 parent 511edf0 commit e61afed

File tree

1 file changed

+33
-52
lines changed

1 file changed

+33
-52
lines changed

stdl/fs.py

Lines changed: 33 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -179,14 +179,14 @@ def yaml_dump(data: Any, path: str | PathLike, encoding: str = "utf-8") -> None:
179179
yaml.safe_dump(data, f)
180180

181181

182-
def toml_load(path: str | PathLike, encoding: str = "utf-8"):
182+
def toml_load(path: str | PathLike, encoding: str = "utf-8") -> dict[str, Any]:
183183
with open(path, encoding=encoding) as f:
184184
return toml.load(f)
185185

186186

187-
def toml_dump(data, path: str | PathLike, encoding: str = "utf-8") -> str:
187+
def toml_dump(data: dict[str, Any], path: str | PathLike, encoding: str = "utf-8") -> None:
188188
with open(path, "w", encoding=encoding) as f:
189-
return toml.dump(data, f)
189+
toml.dump(data, f)
190190

191191

192192
def get_dir_size(directory: str | PathLike, *, readable: bool = False) -> str | int:
@@ -360,7 +360,7 @@ def mkdirs(dest: str | Path, names: list[str]) -> None:
360360

361361
def yield_files_in(
362362
directory: str | Path,
363-
ext: str | tuple | None = None,
363+
ext: str | tuple[str, ...] | None = None,
364364
*,
365365
recursive: bool = True,
366366
abs: bool = True,
@@ -420,7 +420,7 @@ def yield_files_in(
420420

421421
def get_files_in(
422422
directory: str | Path,
423-
ext: str | tuple | None = None,
423+
ext: str | tuple[str, ...] | None = None,
424424
*,
425425
recursive: bool = True,
426426
abs: bool = True,
@@ -498,7 +498,7 @@ def ensure_paths_exist(*args: str | PathLike | Iterable[str | PathLike]) -> None
498498
FileNotFoundError : if one of the provided paths does not exist.
499499
"""
500500

501-
def check_path(path: str | PathLike):
501+
def check_path(path: str | PathLike) -> None:
502502
if not os.path.exists(os.fspath(path)):
503503
raise FileNotFoundError(f"Path does not exist: '{path}'")
504504

@@ -521,7 +521,7 @@ def ensure_paths_dont_exist(*args: str | PathLike | Iterable[str | PathLike]) ->
521521
FileNotFoundError : if one of the provided paths exists.
522522
"""
523523

524-
def check_path(path: str | PathLike):
524+
def check_path(path: str | PathLike) -> None:
525525
if os.path.exists(os.fspath(path)):
526526
raise FileExistsError(f"Path already exists: '{path}'")
527527

@@ -555,7 +555,7 @@ def __init__(
555555
super().__init__(args, returncode, stdout, stderr)
556556
self.time_taken = time_taken
557557

558-
def __repr__(self):
558+
def __repr__(self) -> str:
559559
args = [
560560
f"args={self.args!r}",
561561
f"returncode={self.returncode!r}",
@@ -581,7 +581,7 @@ def stderr_lines(self) -> list[str]:
581581
return []
582582
return self.stderr.splitlines()
583583

584-
def dict(self) -> dict:
584+
def dict(self) -> dict[str, Any]:
585585
return {
586586
"args": self.args,
587587
"returncode": self.returncode,
@@ -602,7 +602,7 @@ def exec_cmd(
602602
stdout: IO | None = None, # type:ignore
603603
stderr: IO | None = None, # type:ignore
604604
input: str | None | bytes = None, # type:ignore
605-
env: dict | None = None, # type:ignore
605+
env: dict[str, str] | None = None, # type:ignore
606606
text: bool = True,
607607
*args,
608608
**kwargs,
@@ -705,21 +705,21 @@ def __init__(
705705
if abs:
706706
self.path = os.path.abspath(self.path)
707707

708-
def __fspath__(self):
708+
def __fspath__(self) -> str:
709709
return self.path
710710

711-
def __str__(self):
711+
def __str__(self) -> str:
712712
return self.path
713713

714-
def resolve(self, strict: bool = False):
714+
def resolve(self, strict: bool = False) -> PathBase:
715715
"""
716716
Make the path absolute, resolving any symlinks.
717717
718718
Args:
719719
strict: If True and path doesn't exist, raises FileNotFoundError. Defaults to False.
720720
721721
Returns:
722-
A new File object with resolved path.
722+
PathBase: The object with resolved path.
723723
"""
724724
self.path = os.path.realpath(self.path)
725725
if strict and not self.exists:
@@ -789,9 +789,6 @@ def rename(self, name: str):
789789
790790
Args:
791791
name (str): The new name.
792-
793-
Returns:
794-
PathBase: The updated object.
795792
"""
796793
new_path = os.path.join(self.parent.path, name)
797794
os.rename(self.path, new_path)
@@ -804,9 +801,6 @@ def chmod(self, mode: int):
804801
805802
Args:
806803
mode (int): The new permissions mode.
807-
808-
Returns:
809-
PathBase: The updated object.
810804
"""
811805
os.chmod(self.path, mode)
812806
return self
@@ -818,31 +812,18 @@ def chown(self, user: str, group: str):
818812
Args:
819813
user (str): The new owner.
820814
group (str): The new group.
821-
822-
Returns:
823-
PathBase: The updated object.
824815
"""
825816
shutil.chown(self.path, user, group)
826817
return self
827818

828819
def should_exist(self):
829-
"""
830-
Raise FileNotFoundError if the path does not exist.
831-
832-
Returns:
833-
PathBase: The object.
834-
"""
820+
"""Raise FileNotFoundError if the path does not exist."""
835821
if not self.exists:
836822
raise FileNotFoundError(f"No such path: '{self.path}'")
837823
return self
838824

839825
def should_not_exist(self):
840-
"""
841-
Raise FileExistsError if the path exists.
842-
843-
Returns:
844-
PathBase: The object.
845-
"""
826+
"""Raise FileExistsError if the path exists."""
846827
if self.exists:
847828
raise FileExistsError(f"Path already exists: '{self.path}'")
848829
return self
@@ -1096,7 +1077,7 @@ def suffix(self) -> str:
10961077
return ""
10971078

10981079
@property
1099-
def stem(self):
1080+
def stem(self) -> str:
11001081
"""The file's stem (base name without extension)."""
11011082
base = self.basename
11021083
if "." not in base:
@@ -1113,21 +1094,21 @@ def size_readable(self) -> str:
11131094
"""The file's size in a human-readable format if readable is set to True."""
11141095
return bytes_readable(self.size)
11151096

1116-
def create(self):
1097+
def create(self) -> File:
11171098
"""Create an empty file if it doesn't exist."""
11181099
if self.exists:
11191100
return self
11201101
open(self.path, "a", encoding=self.encoding).close()
11211102
return self
11221103

1123-
def remove(self):
1104+
def remove(self) -> File:
11241105
"""Remove the file."""
11251106
if not self.exists:
11261107
return self
11271108
os.remove(self.path)
11281109
return self
11291110

1130-
def clear(self):
1111+
def clear(self) -> File:
11311112
"""Clear the contents of a file if it exists."""
11321113
if not self.exists:
11331114
return self
@@ -1160,7 +1141,7 @@ def _write(self, data: str | bytes, mode: str, *, newline: bool = True) -> None:
11601141
if newline:
11611142
f.write("\n")
11621143

1163-
def _write_iter(self, data: Iterable, mode: str, sep: str = "\n") -> None:
1144+
def _write_iter(self, data: Iterable[Any], mode: str, sep: str = "\n") -> None:
11641145
with open(self.path, mode, encoding=self.encoding) as f:
11651146
for entry in data:
11661147
f.write(f"{entry}{sep}")
@@ -1225,7 +1206,7 @@ def open(self, mode: str = "r", encoding: str | None = None, **kwargs) -> IO:
12251206
encoding = self.encoding
12261207
return open(self.path, mode, encoding=encoding, **kwargs)
12271208

1228-
def write_iter(self, data: Iterable, sep="\n"):
1209+
def write_iter(self, data: Iterable[Any], sep: str = "\n") -> None:
12291210
"""
12301211
Write data from an iterable to a file, overwriting any existing data.
12311212
@@ -1235,7 +1216,7 @@ def write_iter(self, data: Iterable, sep="\n"):
12351216
"""
12361217
self._write_iter(data, "w", sep=sep)
12371218

1238-
def append_iter(self, data: Iterable, sep="\n"):
1219+
def append_iter(self, data: Iterable[Any], sep: str = "\n") -> None:
12391220
"""
12401221
Append data from an iterable to a file.
12411222
@@ -1260,7 +1241,7 @@ def move_to(
12601241
*,
12611242
mkdir: bool = False,
12621243
overwrite: bool = True,
1263-
):
1244+
) -> File:
12641245
"""
12651246
Move the file to a new directory.
12661247
@@ -1289,7 +1270,7 @@ def copy_to(
12891270
*,
12901271
mkdir: bool = False,
12911272
overwrite: bool = True,
1292-
):
1273+
) -> File:
12931274
"""
12941275
Copy the file to a new directory.
12951276
@@ -1311,15 +1292,15 @@ def copy_to(
13111292
self.path = shutil.copy2(self.path, directory)
13121293
return self
13131294

1314-
def with_dir(self, directory: str):
1295+
def with_dir(self, directory: str) -> File:
13151296
"""
13161297
Change the directory of the file object. This will not move the actual file to that directory.
13171298
Use File.move_to for that.
13181299
"""
13191300
self.path = f"{directory}{SEP}{self.basename}"
13201301
return self
13211302

1322-
def with_ext(self, ext: str):
1303+
def with_ext(self, ext: str) -> File:
13231304
"""
13241305
Change the extension of the file and return the new File object
13251306
@@ -1334,7 +1315,7 @@ def with_ext(self, ext: str):
13341315
self.path = f"{self.dirname}{SEP}{self.stem}{ext}"
13351316
return self
13361317

1337-
def with_suffix(self, suffix: str):
1318+
def with_suffix(self, suffix: str) -> File:
13381319
"""Add a suffix to the file's name and return the new File object."""
13391320
ext = self.ext
13401321
if ext:
@@ -1343,7 +1324,7 @@ def with_suffix(self, suffix: str):
13431324
self.path = f"{self.dirname}{SEP}{filename}"
13441325
return self
13451326

1346-
def with_prefix(self, prefix: str):
1327+
def with_prefix(self, prefix: str) -> File:
13471328
"""Add a prefix to the file's name and return the new File object."""
13481329
ext = self.ext
13491330
if ext:
@@ -1352,25 +1333,25 @@ def with_prefix(self, prefix: str):
13521333
self.path = f"{self.dirname}{SEP}{filename}"
13531334
return self
13541335

1355-
def rename(self, name: str):
1336+
def rename(self, name: str) -> File:
13561337
"""Rename the file and return the new File object."""
13571338
new_path = f"{self.dirname}{SEP}{name}"
13581339
os.rename(self.path, new_path)
13591340
self.path = new_path
13601341
return self
13611342

1362-
def link(self, target: str, follow_symlinks: bool = True):
1343+
def link(self, target: str, follow_symlinks: bool = True) -> File:
13631344
"""Create a hard link to the file."""
13641345
os.link(self.path, target, follow_symlinks=follow_symlinks)
13651346
return self
13661347

1367-
def symlink(self, target: str):
1348+
def symlink(self, target: str) -> File:
13681349
"""Create a symbolic link to the file."""
13691350
os.symlink(self.path, target)
13701351
return self
13711352

13721353
@classmethod
1373-
def rand(cls, prefix: str = "file", ext: str = ""):
1354+
def rand(cls, prefix: str = "file", ext: str = "") -> File:
13741355
"""
13751356
Create a new random file with a specified prefix and extension.
13761357

0 commit comments

Comments
 (0)