Skip to content

Commit 99893cd

Browse files
committed
[OMCPath] add more functionality and docstrings
1 parent 676e278 commit 99893cd

File tree

1 file changed

+120
-5
lines changed

1 file changed

+120
-5
lines changed

OMPython/OMCSession.py

Lines changed: 120 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -287,23 +287,138 @@ def __init__(self, *path, session: OMCSessionZMQ):
287287
self._session = session
288288

289289
def with_segments(self, *pathsegments):
290-
# overwrite this function of PurePosixPath to ensure session is set
290+
"""
291+
Create a new OMCPath object with the given path segments.
292+
293+
The original definition of Path is overridden to ensure session is set.
294+
"""
291295
return type(self)(*pathsegments, session=self._session)
292296

293297
def is_file(self) -> bool:
298+
"""
299+
Check if the path is a regular file.
300+
"""
294301
return self._session.sendExpression(f'regularFileExists("{self.as_posix()}")')
295302

296303
def is_dir(self) -> bool:
304+
"""
305+
Check if the path is a directory.
306+
"""
297307
return self._session.sendExpression(f'directoryExists("{self.as_posix()}")')
298308

299-
def read_text(self) -> str:
309+
def read_text(self, encoding=None, errors=None) -> str:
310+
"""
311+
Read the content of the file represented by this path as text.
312+
313+
The additional arguments `encoding` and `errors` are only defined for compatibility with Path() definitions.
314+
"""
300315
return self._session.sendExpression(f'readFile("{self.as_posix()}")')
301316

302-
def write_text(self, data: str) -> bool:
317+
def write_text(self, data: str, encoding=None, errors=None, newline=None) -> bool:
318+
"""
319+
Write text data to the file represented by this path.
320+
321+
The additional arguments `encoding`, `errors`, and `newline` are only defined for compatibility with Path()
322+
definitions.
323+
"""
324+
if not isinstance(data, str):
325+
raise TypeError('data must be str, not %s' %
326+
data.__class__.__name__)
327+
303328
return self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data}", false)')
304329

305-
def unlink(self) -> bool:
306-
return self._session.sendExpression(f'deleteFile("{self.as_posix()}")')
330+
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
331+
"""
332+
Create a directory at the path represented by this OMCPath object.
333+
334+
The additional arguments `mode`, and `parents` are only defined for compatibility with Path() definitions.
335+
"""
336+
if self.is_dir() and not exist_ok:
337+
raise FileExistsError(f"Directory {self.as_posix()} already exists!")
338+
339+
return self._session.sendExpression(f'mkdir("{self.as_posix()}")')
340+
341+
def cwd(self):
342+
"""
343+
Returns the current working directory as an OMCPath object.
344+
"""
345+
cwd_str = self._session.sendExpression('cd()')
346+
return OMCPath(cwd_str, session=self._session)
347+
348+
def unlink(self, missing_ok: bool = False) -> bool:
349+
"""
350+
Unlink (delete) the file or directory represented by this path.
351+
"""
352+
res = self._session.sendExpression(f'deleteFile("{self.as_posix()}")')
353+
if not res and not missing_ok:
354+
raise FileNotFoundError(f"Cannot delete file {self.as_posix()} - it does not exists!")
355+
return res
356+
357+
def resolve(self, strict: bool = False) -> OMCPath:
358+
"""
359+
Resolve the path to an absolute path. This is done based on available OMC functions.
360+
"""
361+
if strict and not (self.is_file() or self.is_dir()):
362+
raise OMCSessionException(f"Path {self.as_posix()} does not exist!")
363+
364+
if self.is_file():
365+
omcpath = self._omc_resolve(self.parent.as_posix()) / self.name
366+
elif self.is_dir():
367+
omcpath = self._omc_resolve(self.as_posix())
368+
else:
369+
raise OMCSessionException(f"Path {self.as_posix()} is neither a file nor a directory!")
370+
371+
return omcpath
372+
373+
def _omc_resolve(self, pathstr: str) -> OMCPath:
374+
"""
375+
Internal function to resolve the path of the OMCPath object using OMC functions *WITHOUT* changing the cwd
376+
within OMC.
377+
"""
378+
expression = ('omcpath_cwd := cd(); '
379+
f'omcpath_check := cd("{pathstr}"); ' # check requested pathstring
380+
'cd(omcpath_cwd)')
381+
382+
try:
383+
result = self._session.sendExpression(expression)
384+
result_parts = result.split('\n')
385+
pathstr_resolved = result_parts[1]
386+
pathstr_resolved = pathstr_resolved[1:-1] # remove quotes
387+
388+
omcpath_resolved = self._session.omcpath(pathstr_resolved)
389+
except OMCSessionException as ex:
390+
raise OMCSessionException(f"OMCPath resolve failed for {pathstr}!") from ex
391+
392+
if not omcpath_resolved.is_file() and not omcpath_resolved.is_dir():
393+
raise OMCSessionException(f"OMCPath resolve failed for {pathstr} - path does not exist!")
394+
395+
return omcpath_resolved
396+
397+
def absolute(self) -> OMCPath:
398+
"""
399+
Resolve the path to an absolute path. This is done by calling resolve() as it is the best we can do
400+
using OMC functions.
401+
"""
402+
return self.resolve(strict=True)
403+
404+
def exists(self) -> bool:
405+
"""
406+
Semi replacement for pathlib.Path.exists().
407+
"""
408+
return self.is_file() or self.is_dir()
409+
410+
def size(self) -> int:
411+
"""
412+
Get the size of the file in bytes - this is a extra function and the best we can do using OMC.
413+
"""
414+
if not self.is_file():
415+
raise OMCSessionException(f"Path {self.as_posix()} is not a file!")
416+
417+
res = self._session.sendExpression(f'stat("{self.as_posix()}")')
418+
if res[0]:
419+
return int(res[1])
420+
421+
raise OMCSessionException(f"Error reading file size for path {self.as_posix()}!")
307422

308423
# TODO: implement needed methods from pathlib._abc.PathBase:
309424
# OK - is_dir()

0 commit comments

Comments
 (0)