Skip to content

Commit d9a0286

Browse files
committed
[OMCPath] add more functionality and docstrings
1 parent 02dd0ff commit d9a0286

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
@@ -284,23 +284,138 @@ def __init__(self, *path, session: OMCSessionZMQ):
284284
self._session = session
285285

286286
def with_segments(self, *pathsegments):
287-
# overwrite this function of PurePosixPath to ensure session is set
287+
"""
288+
Create a new OMCPath object with the given path segments.
289+
290+
The original definition of Path is overridden to ensure session is set.
291+
"""
288292
return type(self)(*pathsegments, session=self._session)
289293

290294
def is_file(self) -> bool:
295+
"""
296+
Check if the path is a regular file.
297+
"""
291298
return self._session.sendExpression(f'regularFileExists("{self.as_posix()}")')
292299

293300
def is_dir(self) -> bool:
301+
"""
302+
Check if the path is a directory.
303+
"""
294304
return self._session.sendExpression(f'directoryExists("{self.as_posix()}")')
295305

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

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

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

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

0 commit comments

Comments
 (0)