Skip to content

shellfish.fs.is_dir(fspath: FsPath) -> bool ⚓︎

Return True if the given path is a directory; alias for isdir

Source code in libs/shellfish/src/shellfish/fs/__init__.py
128
129
130
def is_dir(fspath: FsPath) -> bool:
    """Return True if the given path is a directory; alias for isdir"""
    return isdir(fspath)

shellfish ⚓︎

shellfish ~ shell and file-system utils

Classes⚓︎

shellfish.Done(*args: Any, **kwargs: _VT) ⚓︎

Bases: JsonBaseModel

PRun => 'ProcessRun' for finished processes

Source code in libs/jsonbourne/src/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Attributes⚓︎
shellfish.Done.__property_fields__: Set[str] property ⚓︎

Returns a set of property names for the class that have a setter

Functions⚓︎
shellfish.Done.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/src/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
shellfish.Done.__ge__(filepath: FsPath) -> 'Done' ⚓︎

Operator overload for writing stderr to fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath of location to write stderr

required

Returns:

Type Description
'Done'

Done object; self

Source code in libs/shellfish/src/shellfish/sh.py
658
659
660
661
662
663
664
665
666
667
668
669
def __ge__(self, filepath: FsPath) -> "Done":
    """Operator overload for writing stderr to fspath

    Args:
        filepath: Filepath of location to write stderr

    Returns:
        Done object; self

    """
    self.write_stderr(filepath)
    return self
shellfish.Done.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/src/jsonbourne/core.py
1067
1068
1069
1070
1071
1072
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
shellfish.Done.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/src/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
shellfish.Done.__gt__(filepath: FsPath) -> None ⚓︎

Operator overload for writing a stdout to a fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath to write stdout to

required
Source code in libs/shellfish/src/shellfish/sh.py
649
650
651
652
653
654
655
656
def __gt__(self, filepath: FsPath) -> None:
    """Operator overload for writing a stdout to a fspath

    Args:
        filepath: Filepath to write stdout to

    """
    self.write_stdout(filepath)
shellfish.Done.__irshift__(filepath: FsPath) -> 'Done' ⚓︎

Operator overload for appending stderr to fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath of location to write stderr

required

Returns:

Type Description
'Done'

Done object; self

Source code in libs/shellfish/src/shellfish/sh.py
680
681
682
683
684
685
686
687
688
689
690
691
def __irshift__(self, filepath: FsPath) -> "Done":
    """Operator overload for appending stderr to fspath

    Args:
        filepath: Filepath of location to write stderr

    Returns:
        Done object; self

    """
    self.write_stderr(filepath, append=True)
    return self
shellfish.Done.__post_init__() -> None ⚓︎

Write the stdout/stdout to sys.stdout/sys.stderr post object init

Source code in libs/shellfish/src/shellfish/sh.py
537
538
539
540
def __post_init__(self) -> None:
    """Write the stdout/stdout to sys.stdout/sys.stderr post object init"""
    if self.verbose:
        self.sys_print()
shellfish.Done.__rshift__(filepath: FsPath) -> None ⚓︎

Operator overload for appending stdout to fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath to write stdout to

required
Source code in libs/shellfish/src/shellfish/sh.py
671
672
673
674
675
676
677
678
def __rshift__(self, filepath: FsPath) -> None:
    """Operator overload for appending stdout to fspath

    Args:
        filepath: Filepath to write stdout to

    """
    self.write_stdout(filepath, append=True)
shellfish.Done.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/src/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
shellfish.Done.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/src/jsonbourne/core.py
893
894
895
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
shellfish.Done.check(ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0) -> None ⚓︎

Check returncode and stderr

Raises:

Type Description
DoneError

If return code is non-zero and stderr is not None

Source code in libs/shellfish/src/shellfish/sh.py
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def check(
    self,
    ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0,
) -> None:
    """Check returncode and stderr

    Raises:
        DoneError: If return code is non-zero and stderr is not None

    """
    if isinstance(ok_code, int):
        if self.returncode != ok_code and self.stderr:
            raise DoneError(done=self)
    else:
        if self.returncode not in ok_code:
            raise DoneError(done=self)
shellfish.Done.completed_process() -> CompletedProcess[str] ⚓︎

Return subprocess.CompletedProcess object

Source code in libs/shellfish/src/shellfish/sh.py
630
631
632
633
634
635
636
637
def completed_process(self) -> CompletedProcess[str]:
    """Return subprocess.CompletedProcess object"""
    return CompletedProcess(
        args=self.args,
        returncode=self.returncode,
        stdout=self.stdout,
        stderr=self.stderr,
    )
shellfish.Done.defaults_dict() -> Dict[str, Any] classmethod ⚓︎

Return a dictionary of non-required keys -> default value(s)

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary of non-required keys -> default value

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@classmethod
def defaults_dict(cls) -> Dict[str, Any]:
    """Return a dictionary of non-required keys -> default value(s)

    Returns:
        Dict[str, Any]: Dictionary of non-required keys -> default value

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})
        >>> t.defaults_dict()
        {'a': 1, 'b': 'herm'}

    """
    return {
        k: v.default for k, v in cls.model_fields.items() if not v.is_required()
    }
shellfish.Done.dict(*args: Any, **kwargs: Any) -> Dict[str, Any] ⚓︎

Alias for model_dump

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
118
119
120
def dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
    """Alias for `model_dump`"""
    return self.model_dump(*args, **kwargs)
shellfish.Done.done_dict() -> DoneDict ⚓︎

Return Done object as typed-dict

Source code in libs/shellfish/src/shellfish/sh.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def done_dict(self) -> DoneDict:
    """Return Done object as typed-dict"""
    return DoneDict(
        args=self.args,
        returncode=self.returncode,
        stdout=self.stdout,
        stderr=self.stderr,
        ti=self.ti,
        tf=self.tf,
        dt=self.dt,
        hrdt=self.hrdt_dict(),
        stdin=self.stdin,
        async_proc=self.async_proc,
        verbose=self.verbose,
    )
shellfish.Done.done_obj() -> DoneObj ⚓︎

Return Done object typed dict

Source code in libs/shellfish/src/shellfish/sh.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
def done_obj(self) -> DoneObj:
    """Return Done object typed dict"""
    return DoneObj(
        args=self.args,
        returncode=self.returncode,
        stdout=self.stdout,
        stderr=self.stderr,
        ti=self.ti,
        tf=self.tf,
        dt=self.dt,
        hrdt=self.hrdt_obj(),
        stdin=self.stdin,
        async_proc=self.async_proc,
        verbose=self.verbose,
    )
shellfish.Done.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/src/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """
    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
shellfish.Done.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/src/jsonbourne/core.py
762
763
764
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
shellfish.Done.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/src/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
shellfish.Done.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/src/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
shellfish.Done.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/src/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
shellfish.Done.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/src/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
shellfish.Done.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/core.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
shellfish.Done.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/src/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
shellfish.Done.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/src/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
shellfish.Done.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/src/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
shellfish.Done.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/src/jsonbourne/core.py
897
898
899
900
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
shellfish.Done.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT classmethod ⚓︎

Create class from dict filtering keys not in (sub)class' fields

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
278
279
280
281
282
283
284
@classmethod
def from_dict_filtered(
    cls: Type[JsonBaseModelT], dictionary: Dict[str, Any]
) -> JsonBaseModelT:
    """Create class from dict filtering keys not in (sub)class' fields"""
    attr_names: Set[str] = set(cls._cls_field_names())
    return cls(**{k: v for k, v in dictionary.items() if k in attr_names})
shellfish.Done.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/src/jsonbourne/core.py
902
903
904
905
906
907
908
909
910
911
912
913
914
915
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
shellfish.Done.grep(string: str) -> List[str] ⚓︎

Return lines in stdout that have

Parameters:

Name Type Description Default
string str

String to search for

required

Returns:

Type Description
List[str]

List[str]: List of strings of stdout lines containing the given search string

Source code in libs/shellfish/src/shellfish/sh.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def grep(self, string: str) -> List[str]:
    """Return lines in stdout that have

    Args:
        string (str): String to search for

    Returns:
        List[str]: List of strings of stdout lines containing the given
            search string

    """
    return [
        line for line in self.stdout.splitlines(keepends=False) if string in line
    ]
shellfish.Done.has_required_fields() -> bool classmethod ⚓︎

Return True/False if the (sub)class has any fields that are required

Returns:

Name Type Description
bool bool

True if any fields for a (sub)class are required

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
286
287
288
289
290
291
292
293
294
@classmethod
def has_required_fields(cls) -> bool:
    """Return True/False if the (sub)class has any fields that are required

    Returns:
        bool: True if any fields for a (sub)class are required

    """
    return any(val.is_required() for val in cls.model_fields.values())
shellfish.Done.is_default() -> bool ⚓︎

Check if the object is equal to the default value for its fields

Returns:

Type Description
bool

True if object is equal to the default value for all fields; False otherwise

Examples:

>>> class Thing(JsonBaseModel):
...    a: int = 1
...    b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def is_default(self) -> bool:
    """Check if the object is equal to the default value for its fields

    Returns:
        True if object is equal to the default value for all fields; False otherwise

    Examples:
        >>> class Thing(JsonBaseModel):
        ...    a: int = 1
        ...    b: str = 'b'
        ...
        >>> t = Thing()
        >>> t.is_default()
        True
        >>> t = Thing(a=2)
        >>> t.is_default()
        False

    """
    if self.has_required_fields():
        return False
    return all(
        mfield.default == self[fname] for fname, mfield in self.model_fields.items()
    )
shellfish.Done.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
shellfish.Done.json(*args: Any, **kwargs: Any) -> str ⚓︎

Alias for model_dumps

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
122
123
124
def json(self, *args: Any, **kwargs: Any) -> str:
    """Alias for `model_dumps`"""
    return self.model_dump_json(*args, **kwargs)
shellfish.Done.json_parse(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any ⚓︎

Return json parsed stdout

Source code in libs/shellfish/src/shellfish/sh.py
705
706
707
708
709
710
711
712
713
714
715
716
717
def json_parse(
    self,
    stderr: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
) -> Any:
    """Return json parsed stdout"""
    return (
        self.json_parse_stdout(jsonc=jsonc, jsonl=jsonl, ndjson=ndjson)
        if not stderr
        else self.json_parse_stderr(jsonc=jsonc, jsonl=jsonl, ndjson=ndjson)
    )
shellfish.Done.json_parse_stderr(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any ⚓︎

Return json parsed stderr

Source code in libs/shellfish/src/shellfish/sh.py
699
700
701
702
703
def json_parse_stderr(
    self, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False
) -> Any:
    """Return json parsed stderr"""
    return JSON.loads(self.stderr, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson)
shellfish.Done.json_parse_stdout(jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any ⚓︎

Return json parsed stdout

Source code in libs/shellfish/src/shellfish/sh.py
693
694
695
696
697
def json_parse_stdout(
    self, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False
) -> Any:
    """Return json parsed stdout"""
    return JSON.loads(self.stdout, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson)
shellfish.Done.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
shellfish.Done.parse_json(stderr: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False) -> Any ⚓︎

Return json parsed stdout (alias bc I keep flip-flopping the fn name)

Source code in libs/shellfish/src/shellfish/sh.py
719
720
721
722
723
724
725
726
727
def parse_json(
    self,
    stderr: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
) -> Any:
    """Return json parsed stdout (alias bc I keep flip-flopping the fn name)"""
    return self.json_parse(stderr=stderr, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson)
shellfish.Done.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/src/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
shellfish.Done.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/src/jsonbourne/core.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
shellfish.Done.sys_print() -> None ⚓︎

Write self.stdout to sys.stdout and self.stderr to sys.stderr

Source code in libs/shellfish/src/shellfish/sh.py
615
616
617
618
def sys_print(self) -> None:
    """Write self.stdout to sys.stdout and self.stderr to sys.stderr"""
    sys.stdout.write(self.stdout)
    sys.stderr.write(self.stderr)
shellfish.Done.to_dict() -> Dict[str, Any] ⚓︎

Eject and return object as plain jane dictionary

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
255
256
257
def to_dict(self) -> Dict[str, Any]:
    """Eject and return object as plain jane dictionary"""
    return self.eject()
shellfish.Done.to_dict_filter_defaults() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def to_dict_filter_defaults(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})

    """
    defaults = self.defaults_dict()
    return {
        k: v
        for k, v in self.model_dump().items()
        if k not in defaults or v != defaults[k]
    }
shellfish.Done.to_dict_filter_none() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> from typing import Optional
>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...     c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def to_dict_filter_none(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> from typing import Optional
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...     c: Optional[str] = None
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm', c=None)
        >>> t.to_dict_filter_none()
        {'a': 1, 'b': 'herm'}
        >>> t.to_json_obj_filter_none()
        JsonObj(**{'a': 1, 'b': 'herm'})

    """
    return {k: v for k, v in self.model_dump().items() if v is not None}
shellfish.Done.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/src/jsonbourne/core.py
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
shellfish.Done.to_json_dict() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def to_json_dict(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return self.to_json_obj()
shellfish.Done.to_json_obj() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def to_json_obj(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return JsonObj(
        {
            k: v if not isinstance(v, JsonBaseModel) else v.to_json_dict()
            for k, v in self.__dict__.items()
        }
    )
shellfish.Done.to_json_obj_filter_defaults() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values equal to (sub)class' default

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
210
211
212
def to_json_obj_filter_defaults(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values equal to (sub)class' default"""
    return JsonObj(self.to_dict_filter_defaults())
shellfish.Done.to_json_obj_filter_none() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values where the value is None

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
214
215
216
def to_json_obj_filter_none(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values where the value is None"""
    return JsonObj(self.to_dict_filter_none())
shellfish.Done.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
1062
1063
1064
1065
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)
shellfish.Done.write_stderr(filepath: FsPath, *, append: bool = False) -> None ⚓︎

Write stderr as a string to a fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath of location to write stderr

required
append bool

Flag to append to file or plain write to file

False
Source code in libs/shellfish/src/shellfish/sh.py
639
640
641
642
643
644
645
646
647
def write_stderr(self, filepath: FsPath, *, append: bool = False) -> None:
    """Write stderr as a string to a fspath

    Args:
        filepath: Filepath of location to write stderr
        append (bool): Flag to append to file or plain write to file

    """
    fs.wstring(Path(filepath), self.stderr, append=append)
shellfish.Done.write_stdout(filepath: FsPath, *, append: bool = False) -> None ⚓︎

Write stdout as a string to a fspath

Parameters:

Name Type Description Default
filepath FsPath

Filepath to write stdout to

required
append bool

Flag to append to file or plain write to file

False
Source code in libs/shellfish/src/shellfish/sh.py
620
621
622
623
624
625
626
627
628
def write_stdout(self, filepath: FsPath, *, append: bool = False) -> None:
    """Write stdout as a string to a fspath

    Args:
        filepath: Filepath to write stdout to
        append (bool): Flag to append to file or plain write to file

    """
    fs.wstring(Path(filepath), self.stdout, append=append)

shellfish.DoneError(done: Done) ⚓︎

Bases: SubprocessError

Error raised when a process returns a non-zero/ok exit status

Attributes:

Name Type Description
cmd str

command that was run

returncode int

exit status of the process

stdout str

standard output (stdout) of the process

stderr str

standard error (stderr) of the process

Source code in libs/shellfish/src/shellfish/sh.py
461
462
463
464
465
466
467
def __init__(self, done: Done) -> None:
    self.returncode = done.returncode
    self.cmd = done.args
    self.stderr = done.stderr
    self.stdout = done.stdout
    self.cmd = done.args
    self.done = done

shellfish.DoneObj ⚓︎

Bases: TypedDict

Todo

deprecate this in favor of DoneDict

shellfish.Flag ⚓︎

Flag obj

Examples:

>>> Flag.__help
'--help'
>>> Flag._v
'-v'

shellfish.FlagMeta ⚓︎

Bases: type

Meta class

Functions⚓︎
shellfish.FlagMeta.attr2flag(string: str) -> str cached staticmethod ⚓︎

Convert and return attr to string

Source code in libs/shellfish/src/shellfish/sh.py
355
356
357
358
359
@staticmethod
@lru_cache(maxsize=None)
def attr2flag(string: str) -> str:
    """Convert and return attr to string"""
    return string.replace("_", "-")

shellfish.HrTime(*args: Any, **kwargs: _VT) ⚓︎

Bases: JsonBaseModel

High resolution time

Source code in libs/jsonbourne/src/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Attributes⚓︎
shellfish.HrTime.__property_fields__: Set[str] property ⚓︎

Returns a set of property names for the class that have a setter

Functions⚓︎
shellfish.HrTime.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/src/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
shellfish.HrTime.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/src/jsonbourne/core.py
1067
1068
1069
1070
1071
1072
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
shellfish.HrTime.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/src/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
shellfish.HrTime.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
98
99
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
shellfish.HrTime.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/src/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
shellfish.HrTime.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/src/jsonbourne/core.py
893
894
895
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
shellfish.HrTime.defaults_dict() -> Dict[str, Any] classmethod ⚓︎

Return a dictionary of non-required keys -> default value(s)

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary of non-required keys -> default value

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@classmethod
def defaults_dict(cls) -> Dict[str, Any]:
    """Return a dictionary of non-required keys -> default value(s)

    Returns:
        Dict[str, Any]: Dictionary of non-required keys -> default value

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})
        >>> t.defaults_dict()
        {'a': 1, 'b': 'herm'}

    """
    return {
        k: v.default for k, v in cls.model_fields.items() if not v.is_required()
    }
shellfish.HrTime.dict(*args: Any, **kwargs: Any) -> Dict[str, Any] ⚓︎

Alias for model_dump

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
118
119
120
def dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
    """Alias for `model_dump`"""
    return self.model_dump(*args, **kwargs)
shellfish.HrTime.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/src/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """
    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
shellfish.HrTime.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/src/jsonbourne/core.py
762
763
764
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
shellfish.HrTime.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/src/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
shellfish.HrTime.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/src/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
shellfish.HrTime.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/src/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
shellfish.HrTime.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/src/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
shellfish.HrTime.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/core.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
shellfish.HrTime.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/src/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
shellfish.HrTime.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/src/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
shellfish.HrTime.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/src/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
shellfish.HrTime.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/src/jsonbourne/core.py
897
898
899
900
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
shellfish.HrTime.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT classmethod ⚓︎

Create class from dict filtering keys not in (sub)class' fields

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
278
279
280
281
282
283
284
@classmethod
def from_dict_filtered(
    cls: Type[JsonBaseModelT], dictionary: Dict[str, Any]
) -> JsonBaseModelT:
    """Create class from dict filtering keys not in (sub)class' fields"""
    attr_names: Set[str] = set(cls._cls_field_names())
    return cls(**{k: v for k, v in dictionary.items() if k in attr_names})
shellfish.HrTime.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/src/jsonbourne/core.py
902
903
904
905
906
907
908
909
910
911
912
913
914
915
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
shellfish.HrTime.from_seconds(seconds: float) -> 'HrTime' classmethod ⚓︎

Return HrTime object from seconds

Parameters:

Name Type Description Default
seconds float

number of seconds

required

Returns:

Type Description
'HrTime'

HrTime object

Source code in libs/shellfish/src/shellfish/sh.py
417
418
419
420
421
422
423
424
425
426
427
428
429
@classmethod
def from_seconds(cls, seconds: float) -> "HrTime":
    """Return HrTime object from seconds

    Args:
        seconds (float): number of seconds

    Returns:
        HrTime object

    """
    _sec, _ns = seconds2hrtime(seconds)
    return cls(sec=_sec, ns=_ns)
shellfish.HrTime.has_required_fields() -> bool classmethod ⚓︎

Return True/False if the (sub)class has any fields that are required

Returns:

Name Type Description
bool bool

True if any fields for a (sub)class are required

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
286
287
288
289
290
291
292
293
294
@classmethod
def has_required_fields(cls) -> bool:
    """Return True/False if the (sub)class has any fields that are required

    Returns:
        bool: True if any fields for a (sub)class are required

    """
    return any(val.is_required() for val in cls.model_fields.values())
shellfish.HrTime.is_default() -> bool ⚓︎

Check if the object is equal to the default value for its fields

Returns:

Type Description
bool

True if object is equal to the default value for all fields; False otherwise

Examples:

>>> class Thing(JsonBaseModel):
...    a: int = 1
...    b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def is_default(self) -> bool:
    """Check if the object is equal to the default value for its fields

    Returns:
        True if object is equal to the default value for all fields; False otherwise

    Examples:
        >>> class Thing(JsonBaseModel):
        ...    a: int = 1
        ...    b: str = 'b'
        ...
        >>> t = Thing()
        >>> t.is_default()
        True
        >>> t = Thing(a=2)
        >>> t.is_default()
        False

    """
    if self.has_required_fields():
        return False
    return all(
        mfield.default == self[fname] for fname, mfield in self.model_fields.items()
    )
shellfish.HrTime.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
shellfish.HrTime.json(*args: Any, **kwargs: Any) -> str ⚓︎

Alias for model_dumps

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
122
123
124
def json(self, *args: Any, **kwargs: Any) -> str:
    """Alias for `model_dumps`"""
    return self.model_dump_json(*args, **kwargs)
shellfish.HrTime.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
shellfish.HrTime.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/src/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
shellfish.HrTime.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/src/jsonbourne/core.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
shellfish.HrTime.to_dict() -> Dict[str, Any] ⚓︎

Eject and return object as plain jane dictionary

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
255
256
257
def to_dict(self) -> Dict[str, Any]:
    """Eject and return object as plain jane dictionary"""
    return self.eject()
shellfish.HrTime.to_dict_filter_defaults() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def to_dict_filter_defaults(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})

    """
    defaults = self.defaults_dict()
    return {
        k: v
        for k, v in self.model_dump().items()
        if k not in defaults or v != defaults[k]
    }
shellfish.HrTime.to_dict_filter_none() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> from typing import Optional
>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...     c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def to_dict_filter_none(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> from typing import Optional
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...     c: Optional[str] = None
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm', c=None)
        >>> t.to_dict_filter_none()
        {'a': 1, 'b': 'herm'}
        >>> t.to_json_obj_filter_none()
        JsonObj(**{'a': 1, 'b': 'herm'})

    """
    return {k: v for k, v in self.model_dump().items() if v is not None}
shellfish.HrTime.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/src/jsonbourne/core.py
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
shellfish.HrTime.to_json_dict() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def to_json_dict(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return self.to_json_obj()
shellfish.HrTime.to_json_obj() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def to_json_obj(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return JsonObj(
        {
            k: v if not isinstance(v, JsonBaseModel) else v.to_json_dict()
            for k, v in self.__dict__.items()
        }
    )
shellfish.HrTime.to_json_obj_filter_defaults() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values equal to (sub)class' default

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
210
211
212
def to_json_obj_filter_defaults(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values equal to (sub)class' default"""
    return JsonObj(self.to_dict_filter_defaults())
shellfish.HrTime.to_json_obj_filter_none() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values where the value is None

Source code in libs/jsonbourne/src/jsonbourne/pydantic.py
214
215
216
def to_json_obj_filter_none(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values where the value is None"""
    return JsonObj(self.to_dict_filter_none())
shellfish.HrTime.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/src/jsonbourne/core.py
1062
1063
1064
1065
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)

shellfish.LIN ⚓︎

Bases: LIN

Linux (and Mac) shell commands/methods container

Functions⚓︎

Make a directory symlink

Parameters:

Name Type Description Default
linkpath str

Path to the link to be made

required
targetpath str

Path to the target of the link to be made

required
exist_ok str

Allow link to exist

False
Source code in libs/shellfish/src/shellfish/osfs.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@staticmethod
def link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None:
    """Make a directory symlink

    Args:
        linkpath (str): Path to the link to be made
        targetpath (str): Path to the target of the link to be made
        exist_ok (str): Allow link to exist

    """
    try:
        symlink(targetpath, linkpath)
    except FileExistsError as fee:
        if not exist_ok:
            raise fee

Make multiple directory symlinks

Parameters:

Name Type Description Default
link_target_tuples List[Tuple[str, str]]

Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target.

required
exist_ok bool

Allow link to exist

False
Source code in libs/shellfish/src/shellfish/osfs.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@staticmethod
def link_dirs(
    link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False
) -> None:
    """Make multiple directory symlinks

    Args:
        link_target_tuples: Iterable of tuples of the form: (link, target)
            or a dictionary mapping with key => value pairs of the form
            link => target.
        exist_ok (bool): Allow link to exist

    """
    for link, target in link_target_tuples:
        LIN.link_dir(link, target, exist_ok=exist_ok)

Make a file symlink

Parameters:

Name Type Description Default
linkpath str

Path to the link to be made

required
targetpath str

Path to the target of the link to be made

required
exist_ok bool

Allow links to already exist

False
Source code in libs/shellfish/src/shellfish/osfs.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@staticmethod
def link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None:
    """Make a file symlink

    Args:
        linkpath (str): Path to the link to be made
        targetpath (str): Path to the target of the link to be made
        exist_ok (bool): Allow links to already exist

    """
    makedirs(path.split(linkpath)[0], exist_ok=True)
    try:
        symlink(targetpath, linkpath)
    except FileExistsError as fee:
        if not exist_ok:
            raise fee

Make multiple file symlinks

Parameters:

Name Type Description Default
exist_ok bool

Allow links to already exist

False
link_target_tuples List[Tuple[str, str]]

Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target.

required
Source code in libs/shellfish/src/shellfish/osfs.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@staticmethod
def link_files(
    link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False
) -> None:
    """Make multiple file symlinks

    Args:
        exist_ok (bool): Allow links to already exist
        link_target_tuples: Iterable of tuples of the form: (link, target)
            or a dictionary mapping with key => value pairs of the form
            link => target.

    """
    for link, target in link_target_tuples:
        LIN.link_file(link, target, exist_ok=exist_ok)
shellfish.LIN.rsync(src: str, dest: str, delete: bool = False, mkdirs: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> Done staticmethod ⚓︎

Run an rsync subprocess

Parameters:

Name Type Description Default
mkdirs bool

Make destination directories if they do not already exist; defaults to False.

False
src str

Source directory path

required
dest str

Destination directory path

required
delete bool

Delete files/directories in destination if they do exist in source

False
exclude Optional[IterableStr]

Strings/patterns to exclude

None
include Optional[IterableStr]

Strings/patterns to include

None
dry_run bool

Perform operation as a dry run

False

Returns:

Name Type Description
Done Done

Done object containing the info for the rsync run

Rsync return codes::

- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested  action not supported: an attempt was made to
  manipulate 64-bit files on a platform that cannot support them;
  or an option was specified that is supported by the client and
  not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/src/shellfish/sh.py
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
@staticmethod
def rsync(
    src: str,
    dest: str,
    delete: bool = False,
    mkdirs: bool = False,
    dry_run: bool = False,
    exclude: Optional[IterableStr] = None,
    include: Optional[IterableStr] = None,
) -> Done:
    """Run an `rsync` subprocess

    Args:
        mkdirs (bool): Make destination directories if they do not already
            exist; defaults to False.
        src (str): Source directory path
        dest (str): Destination directory path
        delete (bool): Delete files/directories in destination if they do
            exist in source
        exclude: Strings/patterns to exclude
        include: Strings/patterns to include
        dry_run (bool): Perform operation as a dry run

    Returns:
        Done: Done object containing the info for the rsync run

    Rsync return codes::

        - 0 == Success
        - 1 == Syntax or usage error
        - 2 == Protocol incompatibility
        - 3 == Errors selecting input/output files, dirs
        - 4 == Requested  action not supported: an attempt was made to
          manipulate 64-bit files on a platform that cannot support them;
          or an option was specified that is supported by the client and
          not the server.
        - 5 == Error starting client-server protocol
        - 6 == Daemon unable to append to log-file
        - 10 == Error in socket I/O
        - 11 == Error in file I/O
        - 12 == Error in rsync protocol data stream
        - 13 == Errors with program diagnostics
        - 14 == Error in IPC code
        - 20 == Received SIGUSR1 or SIGINT
        - 21 == Some error returned by waitpid()
        - 22 == Error allocating core memory buffers
        - 23 == Partial transfer due to error
        - 24 == Partial transfer due to vanished source files
        - 25 == The --max-delete limit stopped deletions
        - 30 == Timeout in data send2viewserver/receive
        - 35 == Timeout waiting for daemon connection

    """
    if exclude is None:
        exclude = []
    if include is None:
        include = []
    if mkdirs and not dry_run:
        makedirs(dest, exist_ok=True)
    rsync_args = LIN.rsync_args(
        src, dest, delete=delete, exclude=exclude, include=include, dry_run=dry_run
    )

    done = do(args=list(filter(None, rsync_args)))
    return done
shellfish.LIN.rsync_args(src: str, dest: str, delete: bool = False, dry_run: bool = False, exclude: Optional[IterableStr] = None, include: Optional[IterableStr] = None) -> List[str] staticmethod ⚓︎

Return args for rsync command on linux/mac

Parameters:

Name Type Description Default
src str

path to remote (raid) tdir

required
dest str

path to local tdir

required
delete bool

Flag that will do a 'hard sync'

False
exclude Optional[IterableStr]

Strings/patterns to exclude

None
include Optional[IterableStr]

Strings/patterns to include

None
dry_run bool

Perform operation as a dry run

False

Returns:

Type Description
List[str]

subprocess return code from rsync

Rsync return codes::

- 0 == Success
- 1 == Syntax or usage error
- 2 == Protocol incompatibility
- 3 == Errors selecting input/output files, dirs
- 4 == Requested  action not supported: an attempt was made to
  manipulate 64-bit files on a platform that cannot support them;
  or an option was specified that is supported by the client and
  not the server.
- 5 == Error starting client-server protocol
- 6 == Daemon unable to append to log-file
- 10 == Error in socket I/O
- 11 == Error in file I/O
- 12 == Error in rsync protocol data stream
- 13 == Errors with program diagnostics
- 14 == Error in IPC code
- 20 == Received SIGUSR1 or SIGINT
- 21 == Some error returned by waitpid()
- 22 == Error allocating core memory buffers
- 23 == Partial transfer due to error
- 24 == Partial transfer due to vanished source files
- 25 == The --max-delete limit stopped deletions
- 30 == Timeout in data send2viewserver/receive
- 35 == Timeout waiting for daemon connection
Source code in libs/shellfish/src/shellfish/sh.py
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
@staticmethod
def rsync_args(
    src: str,
    dest: str,
    delete: bool = False,
    dry_run: bool = False,
    exclude: Optional[IterableStr] = None,
    include: Optional[IterableStr] = None,
) -> List[str]:
    """Return args for rsync command on linux/mac

    Args:
        src: path to remote (raid) tdir
        dest: path to local tdir
        delete: Flag that will do a 'hard sync'
        exclude: Strings/patterns to exclude
        include: Strings/patterns to include
        dry_run (bool): Perform operation as a dry run

    Returns:
        subprocess return code from rsync

    Rsync return codes::

        - 0 == Success
        - 1 == Syntax or usage error
        - 2 == Protocol incompatibility
        - 3 == Errors selecting input/output files, dirs
        - 4 == Requested  action not supported: an attempt was made to
          manipulate 64-bit files on a platform that cannot support them;
          or an option was specified that is supported by the client and
          not the server.
        - 5 == Error starting client-server protocol
        - 6 == Daemon unable to append to log-file
        - 10 == Error in socket I/O
        - 11 == Error in file I/O
        - 12 == Error in rsync protocol data stream
        - 13 == Errors with program diagnostics
        - 14 == Error in IPC code
        - 20 == Received SIGUSR1 or SIGINT
        - 21 == Some error returned by waitpid()
        - 22 == Error allocating core memory buffers
        - 23 == Partial transfer due to error
        - 24 == Partial transfer due to vanished source files
        - 25 == The --max-delete limit stopped deletions
        - 30 == Timeout in data send2viewserver/receive
        - 35 == Timeout waiting for daemon connection


    """
    if exclude is None:
        exclude = []
    if include is None:
        include = []

    if not dest.endswith("/"):
        dest = f"{dest}/"
    if not src.endswith("/"):
        src = f"{src}/"
    _args: List[Union[str, None]] = [
        "rsync",
        "-a",
        "-O",
        "--no-o",
        "--no-g",
        "--no-p",
        "--delete" if delete else None,
        *(f'--exclude="{pattern}"' for pattern in exclude),
        *(f'--include="{pattern}"' for pattern in include),
        *(("--dry-run", "-i") if dry_run else (None,)),
        src,
        dest,
    ]
    return list(filter(None, _args))

Unlink a directory symlink given a path to the symlink

Parameters:

Name Type Description Default
link str

path to the symlink

required
Source code in libs/shellfish/src/shellfish/osfs.py
133
134
135
136
137
138
139
140
141
@staticmethod
def unlink_dir(link: str) -> None:
    """Unlink a directory symlink given a path to the symlink

    Args:
        link: path to the symlink

    """
    unlink(str(link))

Unlink directory symlinks given the paths the links

Parameters:

Name Type Description Default
links IterableStr

Iterable of paths to links

required
Source code in libs/shellfish/src/shellfish/osfs.py
143
144
145
146
147
148
149
150
151
152
@staticmethod
def unlink_dirs(links: IterableStr) -> None:
    """Unlink directory symlinks given the paths the links

    Args:
        links: Iterable of paths to links

    """
    for link in links:
        LIN.unlink_dir(link)

Unlink a file symlink given a path to the symlink

Parameters:

Name Type Description Default
link str

path to the symlink

required
Source code in libs/shellfish/src/shellfish/osfs.py
154
155
156
157
158
159
160
161
162
@staticmethod
def unlink_file(link: str) -> None:
    """Unlink a file symlink given a path to the symlink

    Args:
        link: path to the symlink

    """
    unlink(str(link))

Unlink directory symlinks given the paths the links

Parameters:

Name Type Description Default
links IterableStr

Iterable of paths to links

required
Source code in libs/shellfish/src/shellfish/osfs.py
164
165
166
167
168
169
170
171
172
173
@staticmethod
def unlink_files(links: IterableStr) -> None:
    """Unlink directory symlinks given the paths the links

    Args:
        links: Iterable of paths to links

    """
    for link in links:
        LIN.unlink_file(link)

shellfish.Stdio ⚓︎

Bases: IntEnum

Standard-io enum object

shellfish.WIN ⚓︎

Bases: WIN

Windows shell commands/methods container

Functions⚓︎

Make a directory symlink

Parameters:

Name Type Description Default
linkpath str

Path to the link to be made

required
targetpath str

Path to the target of the link to be made

required
exist_ok bool

If True, do not raise an exception if the link exists

False
Source code in libs/shellfish/src/shellfish/osfs.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@staticmethod
def link_dir(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None:
    """Make a directory symlink

    Args:
        linkpath (str): Path to the link to be made
        targetpath (str): Path to the target of the link to be made
        exist_ok (bool): If True, do not raise an exception if the link exists

    """
    makedirs(path.split(linkpath)[0], exist_ok=True)
    try:
        symlink(targetpath, linkpath, target_is_directory=True)
    except OSError:
        batman.MKLINK(
            linkpath,
            targetpath,
            D=True,
        )

Make multiple directory symlinks

Parameters:

Name Type Description Default
link_target_tuples List[Tuple[str, str]]

Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target.

required
exist_ok bool

If True, do not raise an exception if the link(s) exist

False
Source code in libs/shellfish/src/shellfish/osfs.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@staticmethod
def link_dirs(
    link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False
) -> None:
    """Make multiple directory symlinks

    Args:
        link_target_tuples: Iterable of tuples of the form: (link, target)
            or a dictionary mapping with key => value pairs of the form
            link => target.
        exist_ok (bool): If True, do not raise an exception if the link(s) exist

    """
    try:
        for link, target in link_target_tuples:
            WIN.link_dir(link, target, exist_ok=exist_ok)
    except OSError:
        args = [
            batman.MKLINK_ARGS(link, target, D=True)
            for link, target in link_target_tuples
            if WIN._check_link_target_dirs(link, target)
        ]
        batman.run_cmds_as_bat_file(commands=[" ".join(el) for el in args])

Make a file symlink

Parameters:

Name Type Description Default
linkpath str

Path to the link to be made

required
targetpath str

Path to the target of the link to be made

required
exist_ok bool

If True, don't raise an exception if the link exists

False
Source code in libs/shellfish/src/shellfish/osfs.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
@staticmethod
def link_file(linkpath: str, targetpath: str, *, exist_ok: bool = False) -> None:
    """Make a file symlink

    Args:
        linkpath (str): Path to the link to be made
        targetpath (str): Path to the target of the link to be made
        exist_ok (bool): If True, don't raise an exception if the link exists

    """
    try:
        symlink(targetpath, linkpath)
    except OSError:
        makedirs(path.split(linkpath)[0], exist_ok=True)
        batman.MKLINK(
            linkpath,
            targetpath,
        )

Make multiple file symlinks

Parameters:

Name Type Description Default
link_target_tuples List[Tuple[str, str]]

Iterable of tuples of the form: (link, target) or a dictionary mapping with key => value pairs of the form link => target.

required
exist_ok bool

If True, don't raise an exception if the link exists

False
Source code in libs/shellfish/src/shellfish/osfs.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
@staticmethod
def link_files(
    link_target_tuples: List[Tuple[str, str]], *, exist_ok: bool = False
) -> None:
    """Make multiple file symlinks

    Args:
        link_target_tuples: Iterable of tuples of the form: (link, target)
            or a dictionary mapping with key => value pairs of the form
            link => target.
        exist_ok (bool): If True, don't raise an exception if the link exists

    """
    try:
        for link, target in link_target_tuples:
            WIN.link_file(link, target, exist_ok=exist_ok)
    except OSError:
        link_target_tuples = list(link_target_tuples)
        _args = [
            batman.MKLINK_ARGS(link, target, D=False)
            for link, target in link_target_tuples
            if WIN._check_link_target_files(link, target)
        ]
        batman.run_cmds_as_bat_file(commands=[" ".join(el) for el in _args])
shellfish.WIN.robocopy(src: str, dest: str, *, mkdirs: bool = True, delete: bool = False, exclude_files: Optional[Iterable[str]] = None, exclude_dirs: Optional[Iterable[str]] = None, dry_run: bool = False) -> Done staticmethod ⚓︎

Robocopy wrapper function (crude in that it opens a subprocess)

Parameters:

Name Type Description Default
src str

path to source directory

required
dest str

path to destination directory

required
delete bool

Delete files in the destination directory if they do not exist in the source directory

False
exclude_files Optional[Iterable[str]]

Strings/patterns with which to exclude files

None
exclude_dirs Optional[Iterable[str]]

Strings/patterns with which to exclude directories

None
dry_run bool

Do the operation as a dry run

False
mkdirs bool

Flag to make destinaation directories if they do not already exist

True

Returns:

Type Description
Done

subprocess return code from robocopy

Robocopy return codes::

0. No files were copied. No failure was encountered. No files were
   mismatched. The files already exist in the destination
   directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
   that are not present in the source directory. No files were
   copied.
3. Some files were copied. Additional files were present. No
   failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
   was encountered.
6. Additional files and mismatched files exist. No files were
   copied and no failures were encountered. This means that the
   files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
   files were present.
8. Several files did not copy.
Source code in libs/shellfish/src/shellfish/sh.py
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
@staticmethod
def robocopy(
    src: str,
    dest: str,
    *,
    mkdirs: bool = True,
    delete: bool = False,
    exclude_files: Optional[Iterable[str]] = None,
    exclude_dirs: Optional[Iterable[str]] = None,
    dry_run: bool = False,
) -> Done:  # pragma: nocov
    """Robocopy wrapper function (crude in that it opens a subprocess)

    Args:
        src (str): path to source directory
        dest (str): path to destination directory
        delete (bool): Delete files in the destination directory if they do
            not exist in the source directory
        exclude_files: Strings/patterns with which to exclude files
        exclude_dirs: Strings/patterns with which to exclude directories
        dry_run (bool): Do the operation as a dry run
        mkdirs (bool): Flag to make destinaation directories if they do
            not already exist

    Returns:
        subprocess return code from robocopy

    Robocopy return codes::

        0. No files were copied. No failure was encountered. No files were
           mismatched. The files already exist in the destination
           directory; therefore, the copy operation was skipped.
        1. All files were copied successfully.
        2. There are some additional files in the destination directory
           that are not present in the source directory. No files were
           copied.
        3. Some files were copied. Additional files were present. No
           failure was encountered.
        5. Some files were copied. Some files were mismatched. No failure
           was encountered.
        6. Additional files and mismatched files exist. No files were
           copied and no failures were encountered. This means that the
           files already exist in the destination directory.
        7. Files were copied, a file mismatch was present, and additional
           files were present.
        8. Several files did not copy.

    """
    _exclude_files = [] if exclude_files is None else list(exclude_files)
    _exclude_dirs = [] if exclude_dirs is None else list(exclude_dirs)
    if mkdirs and not dry_run:
        makedirs(dest, exist_ok=True)
    _args = WIN.robocopy_args(
        src=src,
        dest=dest,
        delete=delete,
        exclude_files=_exclude_files,
        exclude_dirs=_exclude_dirs,
        dry_run=dry_run,
    )
    return do(args=_args)
shellfish.WIN.robocopy_args(src: str, dest: str, *, delete: bool = False, exclude_files: Optional[List[str]] = None, exclude_dirs: Optional[List[str]] = None, dry_run: bool = False) -> List[str] staticmethod ⚓︎

Return list of robocopy command args

Parameters:

Name Type Description Default
src str

path to source directory

required
dest str

path to destination directory

required
delete bool

Delete files in the destination directory if they do not exist in the source directory

False
exclude_files Optional[List[str]]

Strings/patterns with which to exclude files

None
exclude_dirs Optional[List[str]]

Strings/patterns with which to exclude directories

None
dry_run bool

Do the operation as a dry run

False

Returns:

Type Description
List[str]

subprocess return code from robocopy

Robocopy return codes::

0. No files were copied. No failure was encountered. No files were
   mismatched. The files already exist in the destination
   directory; therefore, the copy operation was skipped.
1. All files were copied successfully.
2. There are some additional files in the destination directory
   that are not present in the source directory. No files were
   copied.
3. Some files were copied. Additional files were present. No
   failure was encountered.
5. Some files were copied. Some files were mismatched. No failure
   was encountered.
6. Additional files and mismatched files exist. No files were
   copied and no failures were encountered. This means that the
   files already exist in the destination directory.
7. Files were copied, a file mismatch was present, and additional
   files were present.
8. Several files did not copy.
Source code in libs/shellfish/src/shellfish/sh.py
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
@staticmethod
def robocopy_args(
    src: str,
    dest: str,
    *,
    delete: bool = False,
    exclude_files: Optional[List[str]] = None,
    exclude_dirs: Optional[List[str]] = None,
    dry_run: bool = False,
) -> List[str]:
    """Return list of robocopy command args

    Args:
        src (str): path to source directory
        dest (str): path to destination directory
        delete (bool): Delete files in the destination directory if they do
            not exist in the source directory
        exclude_files: Strings/patterns with which to exclude files
        exclude_dirs: Strings/patterns with which to exclude directories
        dry_run (bool): Do the operation as a dry run

    Returns:
        subprocess return code from robocopy

    Robocopy return codes::

        0. No files were copied. No failure was encountered. No files were
           mismatched. The files already exist in the destination
           directory; therefore, the copy operation was skipped.
        1. All files were copied successfully.
        2. There are some additional files in the destination directory
           that are not present in the source directory. No files were
           copied.
        3. Some files were copied. Additional files were present. No
           failure was encountered.
        5. Some files were copied. Some files were mismatched. No failure
           was encountered.
        6. Additional files and mismatched files exist. No files were
           copied and no failures were encountered. This means that the
           files already exist in the destination directory.
        7. Files were copied, a file mismatch was present, and additional
           files were present.
        8. Several files did not copy.

    """
    if exclude_files is None:
        exclude_files = []
    if exclude_dirs is None:
        exclude_dirs = []
    _args = [
        "robocopy",
        src,
        dest,
        "/MIR" if delete else "/E",
        "/mt",
        "/W:1",
        "/R:1",
    ]
    if exclude_dirs:
        _args.extend(["/XD", *exclude_dirs])
    if exclude_files:
        _args.extend(["/XF", *exclude_files])
    if dry_run:
        _args.append("/L")
    return list(filter(None, _args))

Unlink a directory symlink given a path to the symlink

Parameters:

Name Type Description Default
link str

path to the symlink

required
Source code in libs/shellfish/src/shellfish/osfs.py
269
270
271
272
273
274
275
276
277
278
279
280
@staticmethod
def unlink_dir(link: str) -> None:
    """Unlink a directory symlink given a path to the symlink

    Args:
        link: path to the symlink

    """
    try:
        unlink(link)
    except OSError:
        batman.RD(link)

Unlink directory symlinks given the paths the links

Parameters:

Name Type Description Default
links IterableStr

Iterable of paths to links

required
Source code in libs/shellfish/src/shellfish/osfs.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
@staticmethod
def unlink_dirs(links: IterableStr) -> None:
    """Unlink directory symlinks given the paths the links

    Args:
        links: Iterable of paths to links

    """
    try:
        for link in links:
            WIN.unlink_dir(link)
    except OSError:
        batman.run_cmds_as_bat_file(
            commands=[batman.RD_ARGS(link) for link in links]
        )

Unlink a file symlink given a path to the symlink

Parameters:

Name Type Description Default
link str

path to the symlink

required
Source code in libs/shellfish/src/shellfish/osfs.py
298
299
300
301
302
303
304
305
306
307
308
309
@staticmethod
def unlink_file(link: str) -> None:
    """Unlink a file symlink given a path to the symlink

    Args:
        link (str): path to the symlink

    """
    try:
        unlink(link)
    except OSError:
        batman.DEL(link)

Unlink directory symlinks given the paths the links

Parameters:

Name Type Description Default
links IterableStr

Iterable of paths to links

required
Source code in libs/shellfish/src/shellfish/osfs.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
@staticmethod
def unlink_files(links: IterableStr) -> None:
    """Unlink directory symlinks given the paths the links

    Args:
        links: Iterable of paths to links

    """
    try:
        for link in links:
            WIN.unlink_file(link)
    except OSError:
        batman.run_cmds_as_bat_file(
            [batman.DEL_ARGS(link) for link in links],
        )

Functions⚓︎

shellfish.basename(fspath: FsPath) -> str ⚓︎

Return the basename of given path; alias of os.path.dirname

Parameters:

Name Type Description Default
fspath FsPath

File-system path

required

Returns:

Name Type Description
str str

basename of path

Source code in libs/shellfish/src/shellfish/sh.py
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
def basename(fspath: FsPath) -> str:
    """Return the basename of given path; alias of os.path.dirname

    Args:
        fspath: File-system path

    Returns:
        str: basename of path

    """
    return path.basename(str(fspath))

shellfish.cd(dirpath: FsPath) -> None ⚓︎

Change directory to given dirpath; alias for os.chdir

Parameters:

Name Type Description Default
dirpath FsPath

Directory fspath

required
Source code in libs/shellfish/src/shellfish/sh.py
1885
1886
1887
1888
1889
1890
1891
1892
def cd(dirpath: FsPath) -> None:
    """Change directory to given dirpath; alias for `os.chdir`

    Args:
        dirpath: Directory fspath

    """
    chdir(str(dirpath))

shellfish.chmod(fspath: FsPath, mode: int) -> None ⚓︎

Change the access permissions of a file

Parameters:

Name Type Description Default
fspath FsPath

Path to file to chmod

required
mode int

Permissions mode as an int

required
Source code in libs/shellfish/src/shellfish/fs/__init__.py
1403
1404
1405
1406
1407
1408
1409
1410
1411
def chmod(fspath: FsPath, mode: int) -> None:
    """Change the access permissions of a file

    Args:
        fspath (FsPath): Path to file to chmod
        mode (int): Permissions mode as an int

    """
    return _chmod(path=str(fspath), mode=mode)

shellfish.copy_file(src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False) -> Tuple[str, str] ⚓︎

Copy a file given a source-path and a destination-path

Parameters:

Name Type Description Default
src str

Source fspath

required
dest str

Destination fspath

required
dryrun bool

Do not copy file if True just return the src and dest

False
mkdirp bool

Create parent directories if they do not exist

False
Source code in libs/shellfish/src/shellfish/fs/__init__.py
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
def copy_file(
    src: FsPath, dest: FsPath, *, dryrun: bool = False, mkdirp: bool = False
) -> Tuple[str, str]:
    """Copy a file given a source-path and a destination-path

    Args:
        src (str): Source fspath
        dest (str): Destination fspath
        dryrun (bool): Do not copy file if True just return the src and dest
        mkdirp (bool): Create parent directories if they do not exist

    """
    _dest = Path(dest)
    if not dryrun and mkdirp:
        _dest.parent.mkdir(parents=mkdirp, exist_ok=True)
    elif not _dest.parent.exists() or not _dest.parent.is_dir():
        raise FileNotFoundError(f"Destination directory {_dest.parent} does not exist")
    if not dryrun:
        wbytes_gen(dest, lbytes_gen(src, blocksize=2**18))
        _copystat(src, dest, follow_symlinks=True)
    return (str(src), str(dest))

shellfish.cp(src: FsPath, dest: FsPath, *, force: bool = True, recursive: bool = False, r: bool = False, f: bool = True) -> None ⚓︎

Copy the directory/file src to the directory/file dest

Parameters:

Name Type Description Default
src str

Source directory/file to copy

required
dest FsPath

Destination directory/file to copy

required
force bool

Force the copy (like -f flag for cp in shell)

True
recursive bool

Recursive copy (like -r flag for cp in shell)

False
r bool

alias for recursive

False
f bool

alias for force

True

Raises:

Type Description
ValueError

If src is a directory and recursive and r are both False

Source code in libs/shellfish/src/shellfish/fs/__init__.py
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
def cp(
    src: FsPath,
    dest: FsPath,
    *,
    force: bool = True,
    recursive: bool = False,
    r: bool = False,
    f: bool = True,
) -> None:
    """Copy the directory/file src to the directory/file dest

    Args:
        src (str): Source directory/file to copy
        dest: Destination directory/file to copy
        force: Force the copy (like -f flag for cp in shell)
        recursive: Recursive copy (like -r flag for cp in shell)
        r: alias for recursive
        f: alias for force

    Raises:
        ValueError: If src is a directory and recursive and r are both `False`

    """
    _recursive = recursive or r
    _force = force or f
    for _src in iglob(_fspath(src), recursive=True):
        _dest = dest
        if (path.exists(dest) and not _force) or _src == dest:
            return
        if path.isdir(_src) and not _recursive:
            raise ValueError("Source ({}) is directory; use r=True")
        if path.isfile(_src) and path.isdir(dest):
            _dest = path.join(dest, path.basename(_src))
        if path.isfile(_src) or path.islink(src):
            copy_file(_src, _dest)
        if path.isdir(_src):
            if not path.exists(dest):
                _makedirs(dest)
            copytree(src, dest, dirs_exist_ok=True)

shellfish.decode_stdio_bytes(stdio_bytes: Union[str, bytes], lf: bool = True) -> str ⚓︎

Return Stdio bytes from stdout/stderr as a string

Args:
    stdio_bytes (bytes): STDOUT/STDERR bytes
    lf (bool): Replace `

line endings with `

Returns:
    str: decoded stdio bytes
Source code in libs/shellfish/src/shellfish/sh.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def decode_stdio_bytes(stdio_bytes: Union[str, bytes], lf: bool = True) -> str:
    """Return Stdio bytes from stdout/stderr as a string

    Args:
        stdio_bytes (bytes): STDOUT/STDERR bytes
        lf (bool): Replace `\r\n` line endings with `\n`

    Returns:
        str: decoded stdio bytes

    """
    if isinstance(stdio_bytes, str):
        return stdio_bytes
    if lf:
        return decode_stdio_bytes(stdio_bytes, lf=False).replace("\r\n", "\n")
    try:
        return str(stdio_bytes.decode())
    except AttributeError:
        return ""
    except Exception:
        pass

    try:
        return str(stdio_bytes.decode("utf-8"))
    except UnicodeDecodeError:
        pass
    return str(stdio_bytes.decode("latin-1"))

shellfish.dir_exists(fspath: FsPath) -> bool ⚓︎

Return True if the given path exists; False otherwise; alias for isdir

Source code in libs/shellfish/src/shellfish/fs/__init__.py
123
124
125
def dir_exists(fspath: FsPath) -> bool:
    """Return True if the given path exists; False otherwise; alias for isdir"""
    return isdir(fspath)

shellfish.dir_exists_async(fspath: FsPath) -> bool async ⚓︎

Return True if the directory exists; False otherwise

Source code in libs/shellfish/src/shellfish/fs/_async.py
128
129
130
async def dir_exists_async(fspath: FsPath) -> bool:
    """Return True if the directory exists; False otherwise"""
    return await aios.path.isdir(_fspath(fspath))

shellfish.dirname(fspath: FsPath) -> str ⚓︎

Return dirname/parent-dir of given path; alias of os.path.dirname

Parameters:

Name Type Description Default
fspath FsPath

File-system path

required

Returns:

Name Type Description
str str

basename of path

Source code in libs/shellfish/src/shellfish/sh.py
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
def dirname(fspath: FsPath) -> str:
    """Return dirname/parent-dir of given path; alias of os.path.dirname

    Args:
        fspath: File-system path

    Returns:
        str: basename of path

    """
    return path.dirname(_fspath(fspath))

shellfish.dirpath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path] ⚓︎

Yield all dirpaths as pathlib.Path objects beneath a dirpath

Source code in libs/shellfish/src/shellfish/fs/__init__.py
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
def dirpath_gen(
    dirpath: FsPath = ".",
    *,
    abspath: bool = False,
    topdown: bool = True,
    onerror: Optional[Callable[[OSError], Any]] = None,
    followlinks: bool = False,
    check: bool = True,
) -> Iterator[Path]:
    r"""Yield all dirpaths as pathlib.Path objects beneath a dirpath"""
    return (
        Path(el)
        for el in dirs_gen(
            dirpath=dirpath,
            abspath=abspath,
            topdown=topdown,
            onerror=onerror,
            followlinks=followlinks,
            check=check,
        )
    )

shellfish.dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[str] ⚓︎

Yield directory-paths beneath a dirpath (defaults to os.getcwd())

Parameters:

Name Type Description Default
dirpath FsPath

Directory path to walk down/through.

'.'
abspath bool

Yield the absolute path

True
onerror Optional[Callable[[OSError], Any]]

Function called on OSError

None
topdown bool

Not applicable

True
followlinks bool

Follow links

False
check bool

Check that dir exists

True

Returns:

Type Description
Iterator[str]

Generator object that yields directory paths (absolute or relative)

Examples:

>>> tmpdir = 'dirs_gen.doctest'
>>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
>>> filepath_parts = [
...     ("dir", "file1.txt"),
...     ("dir", "file2.txt"),
...     ("dir", "file3.txt"),
...     ("dir", "dir2", "file1.txt"),
...     ("dir", "dir2", "file2.txt"),
...     ("dir", "dir2", "file3.txt"),
...     ("dir", "dir2a", "file1.txt"),
...     ("dir", "dir2a", "file2.txt"),
...     ("dir", "dir2a", "file3.txt"),
... ]
>>> from shellfish.fs import touch
>>> expected_dirs = []
>>> expected_files = []
>>> for f in filepath_parts:
...     fspath = path.join(*f)
...     fspath = path.join(tmpdir, fspath)
...     dirpath = path.dirname(fspath)
...     expected_files.append(fspath)
...     expected_dirs.append(dirpath)
...     _makedirs(dirpath, exist_ok=True)
...     touch(fspath)
>>> expected_dirs = list(sorted(set(expected_dirs)))
>>> from pprint import pprint
>>> expected_files = [el.replace('\\', '/') for el in expected_files]
>>> pprint(expected_files)
['dirs_gen.doctest/dir/file1.txt',
 'dirs_gen.doctest/dir/file2.txt',
 'dirs_gen.doctest/dir/file3.txt',
 'dirs_gen.doctest/dir/dir2/file1.txt',
 'dirs_gen.doctest/dir/dir2/file2.txt',
 'dirs_gen.doctest/dir/dir2/file3.txt',
 'dirs_gen.doctest/dir/dir2a/file1.txt',
 'dirs_gen.doctest/dir/dir2a/file2.txt',
 'dirs_gen.doctest/dir/dir2a/file3.txt']
>>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
>>> pprint(expected_dirs)
['dirs_gen.doctest/dir',
 'dirs_gen.doctest/dir/dir2',
 'dirs_gen.doctest/dir/dir2a']
>>> _files = list(files_gen(tmpdir))
>>> _dirs = list(dirs_gen(tmpdir))
>>> files_n_dirs_list = list(sorted(_files + _dirs))
>>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
>>> pprint(files_n_dirs_list)
['dirs_gen.doctest',
 'dirs_gen.doctest/dir',
 'dirs_gen.doctest/dir/dir2',
 'dirs_gen.doctest/dir/dir2/file1.txt',
 'dirs_gen.doctest/dir/dir2/file2.txt',
 'dirs_gen.doctest/dir/dir2/file3.txt',
 'dirs_gen.doctest/dir/dir2a',
 'dirs_gen.doctest/dir/dir2a/file1.txt',
 'dirs_gen.doctest/dir/dir2a/file2.txt',
 'dirs_gen.doctest/dir/dir2a/file3.txt',
 'dirs_gen.doctest/dir/file1.txt',
 'dirs_gen.doctest/dir/file2.txt',
 'dirs_gen.doctest/dir/file3.txt']
>>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
>>> expected = [el.replace('\\', '/') for el in expected]
>>> pprint(expected)
['dirs_gen.doctest',
 'dirs_gen.doctest/dir',
 'dirs_gen.doctest/dir/dir2',
 'dirs_gen.doctest/dir/dir2/file1.txt',
 'dirs_gen.doctest/dir/dir2/file2.txt',
 'dirs_gen.doctest/dir/dir2/file3.txt',
 'dirs_gen.doctest/dir/dir2a',
 'dirs_gen.doctest/dir/dir2a/file1.txt',
 'dirs_gen.doctest/dir/dir2a/file2.txt',
 'dirs_gen.doctest/dir/dir2a/file3.txt',
 'dirs_gen.doctest/dir/file1.txt',
 'dirs_gen.doctest/dir/file2.txt',
 'dirs_gen.doctest/dir/file3.txt']
>>> files_n_dirs_list == expected
True
>>> from shutil import rmtree
>>> rmtree(tmpdir)
Source code in libs/shellfish/src/shellfish/fs/__init__.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
def dirs_gen(
    dirpath: FsPath = ".",
    *,
    abspath: bool = True,
    topdown: bool = True,
    onerror: Optional[Callable[[OSError], Any]] = None,
    followlinks: bool = False,
    check: bool = True,
) -> Iterator[str]:
    r"""Yield directory-paths beneath a dirpath (defaults to os.getcwd())

    Args:
        dirpath: Directory path to walk down/through.
        abspath (bool): Yield the absolute path
        onerror: Function called on OSError
        topdown: Not applicable
        followlinks: Follow links
        check: Check that dir exists

    Returns:
        Generator object that yields directory paths (absolute or relative)

    Examples:
        >>> tmpdir = 'dirs_gen.doctest'
        >>> from os import makedirs; _makedirs(tmpdir, exist_ok=True)
        >>> filepath_parts = [
        ...     ("dir", "file1.txt"),
        ...     ("dir", "file2.txt"),
        ...     ("dir", "file3.txt"),
        ...     ("dir", "dir2", "file1.txt"),
        ...     ("dir", "dir2", "file2.txt"),
        ...     ("dir", "dir2", "file3.txt"),
        ...     ("dir", "dir2a", "file1.txt"),
        ...     ("dir", "dir2a", "file2.txt"),
        ...     ("dir", "dir2a", "file3.txt"),
        ... ]
        >>> from shellfish.fs import touch
        >>> expected_dirs = []
        >>> expected_files = []
        >>> for f in filepath_parts:
        ...     fspath = path.join(*f)
        ...     fspath = path.join(tmpdir, fspath)
        ...     dirpath = path.dirname(fspath)
        ...     expected_files.append(fspath)
        ...     expected_dirs.append(dirpath)
        ...     _makedirs(dirpath, exist_ok=True)
        ...     touch(fspath)
        >>> expected_dirs = list(sorted(set(expected_dirs)))
        >>> from pprint import pprint
        >>> expected_files = [el.replace('\\', '/') for el in expected_files]
        >>> pprint(expected_files)
        ['dirs_gen.doctest/dir/file1.txt',
         'dirs_gen.doctest/dir/file2.txt',
         'dirs_gen.doctest/dir/file3.txt',
         'dirs_gen.doctest/dir/dir2/file1.txt',
         'dirs_gen.doctest/dir/dir2/file2.txt',
         'dirs_gen.doctest/dir/dir2/file3.txt',
         'dirs_gen.doctest/dir/dir2a/file1.txt',
         'dirs_gen.doctest/dir/dir2a/file2.txt',
         'dirs_gen.doctest/dir/dir2a/file3.txt']
        >>> expected_dirs = [el.replace('\\', '/') for el in expected_dirs]
        >>> pprint(expected_dirs)
        ['dirs_gen.doctest/dir',
         'dirs_gen.doctest/dir/dir2',
         'dirs_gen.doctest/dir/dir2a']
        >>> _files = list(files_gen(tmpdir))
        >>> _dirs = list(dirs_gen(tmpdir))
        >>> files_n_dirs_list = list(sorted(_files + _dirs))
        >>> files_n_dirs_list = [el.replace('\\', '/') for el in files_n_dirs_list]
        >>> pprint(files_n_dirs_list)
        ['dirs_gen.doctest',
         'dirs_gen.doctest/dir',
         'dirs_gen.doctest/dir/dir2',
         'dirs_gen.doctest/dir/dir2/file1.txt',
         'dirs_gen.doctest/dir/dir2/file2.txt',
         'dirs_gen.doctest/dir/dir2/file3.txt',
         'dirs_gen.doctest/dir/dir2a',
         'dirs_gen.doctest/dir/dir2a/file1.txt',
         'dirs_gen.doctest/dir/dir2a/file2.txt',
         'dirs_gen.doctest/dir/dir2a/file3.txt',
         'dirs_gen.doctest/dir/file1.txt',
         'dirs_gen.doctest/dir/file2.txt',
         'dirs_gen.doctest/dir/file3.txt']
        >>> expected = sorted(set(expected_files + expected_dirs + [tmpdir]))
        >>> expected = [el.replace('\\', '/') for el in expected]
        >>> pprint(expected)
        ['dirs_gen.doctest',
         'dirs_gen.doctest/dir',
         'dirs_gen.doctest/dir/dir2',
         'dirs_gen.doctest/dir/dir2/file1.txt',
         'dirs_gen.doctest/dir/dir2/file2.txt',
         'dirs_gen.doctest/dir/dir2/file3.txt',
         'dirs_gen.doctest/dir/dir2a',
         'dirs_gen.doctest/dir/dir2a/file1.txt',
         'dirs_gen.doctest/dir/dir2a/file2.txt',
         'dirs_gen.doctest/dir/dir2a/file3.txt',
         'dirs_gen.doctest/dir/file1.txt',
         'dirs_gen.doctest/dir/file2.txt',
         'dirs_gen.doctest/dir/file3.txt']
        >>> files_n_dirs_list == expected
        True
        >>> from shutil import rmtree
        >>> rmtree(tmpdir)

    """
    if check and not isdir(dirpath):
        raise NotADirectoryError(dirpath)
    return (
        dirpath if abspath else str(dirpath).replace(dirpath, "").strip(sep)
        for dirpath in (
            pwd
            for pwd, dirs, files in walk(
                str(dirpath),
                onerror=onerror,
                topdown=topdown,
                followlinks=followlinks,
            )
        )
    )

shellfish.do(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[FsPath] = None, shell: bool = False, check: bool = False, tee: bool = False, verbose: bool = False, input: STDIN = None, timeout: Optional[Union[float, int]] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done ⚓︎

Run a subprocess synchronously

Parameters:

Name Type Description Default
*popenargs PopenArgs

Args given as *args; Cannot use both *popenargs and args

()
args Optional[PopenArgs]

Args as strings for the subprocess

None
env Optional[Dict[str, str]]

Environment variables as a dictionary (Default value = None)

None
extenv bool

Extend the environment with the current environment (Default value = True)

True
cwd Optional[FsPath]

Current working directory (Default value = None)

None
shell bool

Run in shell or sub-shell

False
check bool

Check the outputs (generally useless)

False
input STDIN

Stdin to give to the subprocess

None
tee bool

Flag to tee the subprocess stdout and stderr to sys.stdout/stderr

False
verbose bool

Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr

False
timeout Optional[int]

Timeout in seconds for the process if not None

None
ok_code Union[int, List[int], Tuple[int, ...], Set[int]]

Return code(s) to check against

0
dryrun bool

Don't run the subprocess

False

Returns:

Type Description
Done

Finished PRun object which is a dictionary, so a dictionary

Raises:

Type Description
ValueError

if args and *popenargs are both given

Source code in libs/shellfish/src/shellfish/sh.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
def do(
    *popenargs: PopenArgs,
    args: Optional[PopenArgs] = None,
    env: Optional[Dict[str, str]] = None,
    extenv: bool = True,
    cwd: Optional[FsPath] = None,
    shell: bool = False,
    check: bool = False,
    tee: bool = False,
    verbose: bool = False,
    input: STDIN = None,
    timeout: Optional[Union[float, int]] = None,
    ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0,
    dryrun: bool = False,
) -> Done:
    """Run a subprocess synchronously

    Args:
        *popenargs: Args given as `*args`; Cannot use both *popenargs and args
        args: Args as strings for the subprocess
        env: Environment variables as a dictionary (Default value = None)
        extenv: Extend the environment with the current environment (Default value = True)
        cwd: Current working directory (Default value = None)
        shell: Run in shell or sub-shell
        check: Check the outputs (generally useless)
        input: Stdin to give to the subprocess
        tee (bool): Flag to tee the subprocess stdout and stderr to sys.stdout/stderr
        verbose (bool): Flag to write the subprocess stdout and stderr to
            sys.stdout and sys.stderr
        timeout (Optional[int]): Timeout in seconds for the process if not None
        ok_code: Return code(s) to check against
        dryrun: Don't run the subprocess

    Returns:
        Finished PRun object which is a dictionary, so a dictionary

    Raises:
        ValueError: if args and *popenargs are both given

    """
    if args and popenargs:
        raise ValueError("Cannot give *popenargs and `args` kwargs")
    args = validate_popen_args([*args]) if args else validate_popen_args(popenargs)
    if is_win():
        args = validate_popen_args_windows(args, env)
    _input = validate_stdin(input)
    return _do(
        args=args,
        env=env,
        extenv=extenv,
        cwd=cwd,
        shell=shell,
        check=check,
        verbose=verbose,
        input=_input,
        timeout=timeout,
        ok_code=ok_code,
        dryrun=dryrun,
        tee=tee,
    )

shellfish.do_async(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done async ⚓︎

Run a subprocess and await its completion

Parameters:

Name Type Description Default
*popenargs PopenArgs

Args given as *args; Cannot use both *popenargs and args

()
args Optional[PopenArgs]

Args as strings for the subprocess

None
check bool

Check the result returncode

False
env Optional[Dict[str, str]]

Environment variables as a dictionary (Default value = None)

None
extenv bool

Extend environment with the current environment (Default value = True)

True
cwd Optional[str]

Current working directory (Default value = None)

None
shell bool

Run in shell or sub-shell

False
input STDIN

Stdin to give to the subprocess

None
verbose bool

Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr

False
timeout Optional[int]

Timeout in seconds for the process if not None

None
ok_code Union[int, List[int], Tuple[int, ...], Set[int]]

Return code(s) that are considered OK (Default value = 0)

0
dryrun bool

Flag to not run the subprocess but return a Done object

False

Returns:

Type Description
Done

Finished PRun object which is a dictionary, so a dictionary

Raises:

Type Description
ValueError

If both *popenargs and args are given

Source code in libs/shellfish/src/shellfish/sh.py
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
async def do_async(
    *popenargs: PopenArgs,
    args: Optional[PopenArgs] = None,
    env: Optional[Dict[str, str]] = None,
    extenv: bool = True,
    cwd: Optional[str] = None,
    shell: bool = False,
    verbose: bool = False,
    input: STDIN = None,
    check: bool = False,
    timeout: Optional[float] = None,
    ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0,
    dryrun: bool = False,
) -> Done:
    """Run a subprocess and await its completion

    Args:
        *popenargs: Args given as `*args`; Cannot use both *popenargs and args
        args: Args as strings for the subprocess
        check (bool): Check the result returncode
        env: Environment variables as a dictionary (Default value = None)
        extenv: Extend environment with the current environment (Default value = True)
        cwd: Current working directory (Default value = None)
        shell: Run in shell or sub-shell
        input: Stdin to give to the subprocess
        verbose (bool): Flag to write the subprocess stdout and stderr to
            sys.stdout and sys.stderr
        timeout (Optional[int]): Timeout in seconds for the process if not None
        ok_code: Return code(s) that are considered OK (Default value = 0)
        dryrun (bool): Flag to not run the subprocess but return a Done object

    Returns:
        Finished PRun object which is a dictionary, so a dictionary

    Raises:
        ValueError: If both *popenargs and args are given

    """
    if args and popenargs:
        raise ValueError("Cannot give *args and args-keyword-argument")
    args = validate_popen_args([*args]) if args else validate_popen_args(popenargs)
    if is_win() and sys.version_info < (3, 8):
        done = await do_asyncify(
            args=args,
            env=env,
            extenv=extenv,
            cwd=cwd,
            shell=shell,
            verbose=verbose,
            input=input,
            check=check,
            timeout=timeout,
            ok_code=ok_code,
            dryrun=dryrun,
        )
        done.async_proc = True
        return done
    if not shell and is_win():
        args = validate_popen_args_windows(args, env)
    return await _do_async(
        args=args,
        env=env,
        extenv=extenv,
        cwd=cwd,
        shell=shell,
        verbose=verbose,
        input=input,
        check=check,
        timeout=timeout,
        ok_code=ok_code,
        dryrun=dryrun,
    )

shellfish.doa(*popenargs: PopenArgs, args: Optional[PopenArgs] = None, env: Optional[Dict[str, str]] = None, extenv: bool = True, cwd: Optional[str] = None, shell: bool = False, verbose: bool = False, input: STDIN = None, check: bool = False, timeout: Optional[float] = None, ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0, dryrun: bool = False) -> Done async ⚓︎

Run a subprocess and await its completion

Alias for sh.do_async

Parameters:

Name Type Description Default
*popenargs PopenArgs

Args given as *args; Cannot use both *popenargs and args

()
args Optional[PopenArgs]

Args as strings for the subprocess

None
check bool

Check the result returncode

False
env Optional[Dict[str, str]]

Environment variables as a dictionary (Default value = None)

None
cwd Optional[str]

Current working directory (Default value = None)

None
shell bool

Run in shell or sub-shell

False
input STDIN

Stdin to give to the subprocess

None
verbose bool

Flag to write the subprocess stdout and stderr to sys.stdout and sys.stderr

False
timeout Optional[int]

Timeout in seconds for the process if not None

None
ok_code Union[int, List[int], Tuple[int, ...], Set[int]]

Return code(s) that are considered OK (Default value = 0)

0
dryrun bool

Flag to not run the subprocess but return a Done object

False
extenv bool

Extend environment with the current environment (Default value = True)

True

Returns:

Type Description
Done

Finished PRun object which is a dictionary, so a dictionary

Source code in libs/shellfish/src/shellfish/sh.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
async def doa(
    *popenargs: PopenArgs,
    args: Optional[PopenArgs] = None,
    env: Optional[Dict[str, str]] = None,
    extenv: bool = True,
    cwd: Optional[str] = None,
    shell: bool = False,
    verbose: bool = False,
    input: STDIN = None,
    check: bool = False,
    timeout: Optional[float] = None,
    ok_code: Union[int, List[int], Tuple[int, ...], Set[int]] = 0,
    dryrun: bool = False,
) -> Done:
    """Run a subprocess and await its completion

    Alias for sh.do_async

    Args:
        *popenargs: Args given as `*args`; Cannot use both *popenargs and args
        args: Args as strings for the subprocess
        check (bool): Check the result returncode
        env: Environment variables as a dictionary (Default value = None)
        cwd: Current working directory (Default value = None)
        shell: Run in shell or sub-shell
        input: Stdin to give to the subprocess
        verbose (bool): Flag to write the subprocess stdout and stderr to
            sys.stdout and sys.stderr
        timeout (Optional[int]): Timeout in seconds for the process if not None
        ok_code: Return code(s) that are considered OK (Default value = 0)
        dryrun (bool): Flag to not run the subprocess but return a Done object
        extenv: Extend environment with the current environment (Default value = True)

    Returns:
        Finished PRun object which is a dictionary, so a dictionary

    """
    return await do_async(
        *popenargs,
        args=args,
        env=env,
        extenv=extenv,
        cwd=cwd,
        shell=shell,
        verbose=verbose,
        input=input,
        check=check,
        timeout=timeout,
        ok_code=ok_code,
        dryrun=dryrun,
    )

shellfish.exists(fspath: FsPath) -> bool ⚓︎

Return True if the given path exists; False otherwise

Source code in libs/shellfish/src/shellfish/fs/__init__.py
113
114
115
def exists(fspath: FsPath) -> bool:
    """Return True if the given path exists; False otherwise"""
    return path.exists(_fspath(fspath))

shellfish.export(key: str, val: Optional[str] = None) -> Tuple[str, str] ⚓︎

Export/Set an environment variable

Parameters:

Name Type Description Default
key str

environment variable name/key

required
val str

environment variable value

None

Raises:

Type Description
ValueError

if unable to parse key/val

Source code in libs/shellfish/src/shellfish/sh.py
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
def export(key: str, val: Optional[str] = None) -> Tuple[str, str]:
    """Export/Set an environment variable

    Args:
        key (str): environment variable name/key
        val (str): environment variable value

    Raises:
        ValueError: if unable to parse key/val

    """
    if val:
        environ[key] = val
        return (key, val)
    if "=" in key:
        _key = key.split("=")[0]
        return export(_key, key[len(_key) + 1 :])
    raise ValueError(
        f"Unable to parse env variable - key: {str(key)}, value: {str(val)}"
    )

shellfish.extension(fspath: str, *, period: bool = False) -> str ⚓︎

Return the extension for a fspath

Examples:

>>> from shellfish.fs import extension
>>> extension("foo.bar")
'bar'
>>> extension("foo.tar.gz")
'tar.gz'
>>> extension("foo.tar.gz", period=True)
'.tar.gz'
Source code in libs/shellfish/src/shellfish/fs/__init__.py
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
def extension(fspath: str, *, period: bool = False) -> str:
    """Return the extension for a fspath

    Examples:
        >>> from shellfish.fs import extension
        >>> extension("foo.bar")
        'bar'
        >>> extension("foo.tar.gz")
        'tar.gz'
        >>> extension("foo.tar.gz", period=True)
        '.tar.gz'

    """
    if period:
        return "".join(Path(fspath).suffixes)
    return "".join(Path(fspath).suffixes).lstrip(".")

shellfish.file_exists(fspath: FsPath) -> bool ⚓︎

Return True if the given path exists; False otherwise; alias for isfile

Source code in libs/shellfish/src/shellfish/fs/__init__.py
118
119
120
def file_exists(fspath: FsPath) -> bool:
    """Return True if the given path exists; False otherwise; alias for isfile"""
    return isfile(fspath)

shellfish.file_exists_async(fspath: FsPath) -> bool async ⚓︎

Return True if the file exists; False otherwise

Source code in libs/shellfish/src/shellfish/fs/_async.py
123
124
125
async def file_exists_async(fspath: FsPath) -> bool:
    """Return True if the file exists; False otherwise"""
    return await aios.path.isfile(_fspath(fspath))

shellfish.file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str] ⚓︎

Yield lines from a given fspath

Parameters:

Name Type Description Default
filepath FsPath

File to yield lines from

required
keepends bool

Flag to keep the ends of the file lines

True

Yields:

Type Description
Iterable[str]

Lines from the given fspath

Examples:

>>> string = '\n'.join(str(i) for i in range(1, 10))
>>> string
'1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> fspath = "file_lines_gen.doctest.txt"
>>> from shellfish.fs import wstring
>>> wstring(fspath, string)
17
>>> for file_line in file_lines_gen(fspath):
...     file_line
'1\n'
'2\n'
'3\n'
'4\n'
'5\n'
'6\n'
'7\n'
'8\n'
'9'
>>> for file_line in file_lines_gen(fspath, keepends=False):
...     file_line
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
>>> import os; os.remove(fspath)
Source code in libs/shellfish/src/shellfish/fs/__init__.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
def file_lines_gen(filepath: FsPath, keepends: bool = True) -> Iterable[str]:
    r"""Yield lines from a given fspath

    Args:
        filepath: File to yield lines from
        keepends: Flag to keep the ends of the file lines

    Yields:
        Lines from the given fspath

    Examples:
        >>> string = '\n'.join(str(i) for i in range(1, 10))
        >>> string
        '1\n2\n3\n4\n5\n6\n7\n8\n9'
        >>> fspath = "file_lines_gen.doctest.txt"
        >>> from shellfish.fs import wstring
        >>> wstring(fspath, string)
        17
        >>> for file_line in file_lines_gen(fspath):
        ...     file_line
        '1\n'
        '2\n'
        '3\n'
        '4\n'
        '5\n'
        '6\n'
        '7\n'
        '8\n'
        '9'
        >>> for file_line in file_lines_gen(fspath, keepends=False):
        ...     file_line
        '1'
        '2'
        '3'
        '4'
        '5'
        '6'
        '7'
        '8'
        '9'
        >>> import os; os.remove(fspath)


    """
    with open(filepath) as f:
        if keepends:
            yield from (line for line in f)
        else:
            yield from (line.rstrip("\n").rstrip("\r\n") for line in f)

shellfish.filecmp(left: FsPath, right: FsPath, *, shallow: bool = True, blocksize: int = 65536) -> bool ⚓︎

Compare 2 files for equality given their filepaths

Parameters:

Name Type Description Default
left FsPath

Filepath 1

required
right FsPath

Filepath 2

required
shallow bool

Check only size and modification time if True

True
blocksize int

Chunk size to read files

65536

Returns:

Type Description
bool

True if files are equal, False otherwise

Source code in libs/shellfish/src/shellfish/fs/__init__.py
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
def filecmp(
    left: FsPath,
    right: FsPath,
    *,
    shallow: bool = True,
    blocksize: int = 65536,
) -> bool:
    """Compare 2 files for equality given their filepaths

    Args:
        left (FsPath): Filepath 1
        right (FsPath): Filepath 2
        shallow (bool): Check only size and modification time if True
        blocksize (int): Chunk size to read files

    Returns:
        True if files are equal, False otherwise

    """
    left_stat = stat(left)
    right_stat = stat(right)
    if (
        shallow
        and left_stat.st_size == right_stat.st_size
        and left_stat.st_mtime == right_stat.st_mtime
    ):
        return True
    if left_stat.st_size != right_stat.st_size:
        return False
    return not any(
        left_chunk != right_chunk
        for left_chunk, right_chunk in zip(
            rbytes_gen(left, blocksize=blocksize),
            rbytes_gen(right, blocksize=blocksize),
        )
    )

shellfish.filepath_gen(dirpath: FsPath = '.', *, abspath: bool = False, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Iterator[Path] ⚓︎

Yield all filepaths as pathlib.Path objects beneath a dirpath

Source code in libs/shellfish/src/shellfish/fs/__init__.py
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
def filepath_gen(
    dirpath: FsPath = ".",
    *,
    abspath: bool = False,
    topdown: bool = True,
    onerror: Optional[Callable[[OSError], Any]] = None,
    followlinks: bool = False,
    check: bool = True,
) -> Iterator[Path]:
    r"""Yield all filepaths as pathlib.Path objects beneath a dirpath"""
    return (
        Path(el)
        for el in files_gen(
            dirpath=dirpath,
            abspath=abspath,
            topdown=topdown,
            onerror=onerror,
            followlinks=followlinks,
            check=check,
        )
    )

shellfish.filepath_mtimedelta_sec(filepath: FsPath) -> float ⚓︎

Return the seconds since the file(path) was last modified

Source code in libs/shellfish/src/shellfish/fs/__init__.py
378
379
380
def filepath_mtimedelta_sec(filepath: FsPath) -> float:
    """Return the seconds since the file(path) was last modified"""
    return time() - path.getmtime(_fspath(filepath))

shellfish.files_dirs_gen(dirpath: FsPath = '.', *, abspath: bool = True, topdown: bool = True, onerror: Optional[Callable[[OSError], Any]] = None, followlinks: bool = False, check: bool = True) -> Tuple[Iterator[str], Iterator[str]] ⚓︎

Return a files_gen() and a dirs_gen() in one swell-foop

Parameters:

Name Type Description Default
dirpath FsPath

Directory path to walk down/through.

'.'
abspath bool

Yield the absolute path

True
onerror Optional[Callable[[OSError], Any]]

Function called on OSError

None
topdown bool

Not applicable

True
followlinks bool

Follow links

False
check bool

Check if dirpath is a directory

True

Returns:

Type Description
Tuple[Iterator[str], Iterator[str]]

A tuple of two generators (files_gen(), dirs_gen())

Examples:

>>> tmpdir = 'files_dirs_gen.doctest'
>>> from os import makedirs;