PK!?1shell_utils/__init__.py# -*- coding: utf-8 -*- """Top-level package for shell-utils.""" from shell_utils.shell_utils import * from shell_utils.notify import notify, notice PK!o:++shell_utils/cli.py""" Usage: [OPTIONS] COMMAND [ARGS]... A cli for shell-utils. Options: --help Show this message and exit. """ import sys import subprocess as sp from pathlib import Path from shell_utils import shell import click @click.group() def cli(): """A cli for shell_utils.""" pass @cli.command() def generate_runner(): """Generate a run.py script in the current directory.""" from shell_utils import runner runner_path = Path('run.py') if runner_path.exists(): raise EnvironmentError('run.py already exists in current directory') click.secho('writing content to run.py', fg='yellow') runner_path.write_text(Path(runner.__file__).read_text()) shell('chmod +x run.py') def invoke_runner(): """ This invokes the run.py script in the current directory. """ if not Path(Path(), 'run.py').exists(): raise SystemExit( click.secho('run.py not found in current directory', fg='red') ) sp.run(['python3', 'run.py'] + sys.argv[1:]) if __name__ == "__main__": cli() PK!2f f shell_utils/notify.pyimport subprocess as sp import typing as typ import logging import shlex import sys from functools import wraps import click def notify(message: str, title=None, subtitle=None, sound=None): """ Send a Mac OS notification. Args: message: the notification body title: the title of the notification subtitle: the subtitle of the notification sound: the sound the notification makes see https://apple.stackexchange.com/questions/57412/how-can-i-trigger-a-notification-center-notification-from-an-applescript-or-shel/115373#115373 """ if title is None: title = 'heads up' if subtitle is None: subtitle = 'something happened' if sys.platform != 'darwin': logging.warning('This function is designed to work on Mac OS') # There is probably a less hacky way to escape single quotes safely # but I haven't gotten to it message = message.replace("'", '') command = f"""osascript -e 'display notification "{message}" with title "{title}" subtitle "{subtitle}" sound name "{sound}"' """ sp.run(shlex.split(command), check=False) def notice(message: typ.Optional[str] = None, title=None, subtitle=None, sound=None): """ Returns a decorator that allows you to be notified when a function returns. Args: message: the notification body title: the title of the notification subtitle: the subtitle of the notification sound: the sound the notification makes Returns: a function """ def decorator(func): """ Send notification that task has finished. Especially useful for long-running tasks """ @wraps(func) def inner(*args, **kwargs): nonlocal message, title, subtitle, sound title = getattr(func, '__name__') + ' finished' if title is None else title subtitle = 'Success!' if subtitle is None else subtitle result = None try: _result = func(*args, **kwargs) if isinstance(_result, str): result = _result except: subtitle = 'Failure' raise finally: if message is not None: pass elif result is not None: message = result else: message = '' notify(message, title=title, subtitle=subtitle, sound=sound) return inner return decorator @click.command() @click.argument('message') @click.option('--title', help='the notification title') @click.option('--subtitle', help='the notification subtitle') @click.option('--sound', help='the notification sound') def notify_command(message, title, subtitle, sound): """Notification cli tool.""" notify(message, title=title, subtitle=subtitle, sound=sound) PK! bool: """ Return True if return code is zero else false. Args: self: sp.CompletedProcess Returns: True or False """ return self.returncode == 0 def shell(command: str, check=True, capture=False, silent=False, dedent=True, strip=True, **kwargs ) -> sp.CompletedProcess: """ Run the command in a shell. !!! Make sure you trust the input to this command !!! Args: command: the command to be run check: raise exception if return code not zero capture: if set to True, captures stdout and stderr, making them available as stdout and stderr attributes on the returned CompletedProcess. This also means the command's stdout and stderr won't be piped to FD 1 and 2 by default silent: disable the printing of the command that's being run prior to execution dedent: de-dent command string; useful if it's a bash script written within a function in your module strip: strip ends of command string of newlines and whitespace prior to execution kwargs: passed to subprocess.run as-is Returns: Completed Process """ user = click.style(getuser(), fg='green') hostname = click.style(gethostname(), fg='blue') command = textwrap.dedent(command) if dedent else command command = command.strip() if strip else command if not silent: print(f'{user}@{hostname}', click.style('executing...', fg='yellow') ) print(command) print( click.style( ('-' * max(len(l) for l in command.splitlines()) if command else ''), fg='magenta' ) ) print() process = sp.run( command, check=check, shell=True, stdout=sp.PIPE if capture else None, stderr=sp.PIPE if capture else None, **kwargs ) # override bool dunder method process._bool = types.MethodType(_bool, process) process.__class__.__bool__ = process._bool if capture: # decode stderr and stdout # keep bytes as raw_{stream} process.raw_stdout: bytes = process.stdout process.raw_stderr: bytes = process.stderr process.stdout: str = process.stdout.decode() process.stderr: str = process.stderr.decode() return process @contextmanager def cd(path_: Pathy): """Change the current working directory.""" cwd = os.getcwd() os.chdir(os.path.expanduser(path_)) yield os.chdir(cwd) @contextmanager def env(**kwargs) -> T.Iterator[os._Environ]: """Set environment variables and yield new environment dict.""" original_environment = copy.deepcopy(os.environ) for key, value in kwargs.items(): os.environ[key] = value yield os.environ os.environ = original_environment @contextmanager def path(*paths: Pathy, prepend=False, expand_user=True) -> T.Iterator[ T.List[str]]: """ Add the paths to $PATH and yield the new $PATH as a list. Args: prepend: prepend paths to $PATH else append expand_user: expands home if ~ is used in path strings """ paths_list: T.List[Pathy] = list(paths) paths_str_list: T.List[str] = [] for index, _path in enumerate(paths_list): if not isinstance(_path, str): print(f'index: {index}') paths_str_list.append(_path.__fspath__()) elif expand_user: paths_str_list.append(os.path.expanduser(_path)) original_path = os.environ['PATH'].split(':') paths_str_list = paths_str_list + \ original_path if prepend else original_path + paths_str_list with env(PATH=':'.join(paths_str_list)): yield paths_str_list @contextmanager def quiet(): """ Suppress stdout and stderr. https://stackoverflow.com/questions/11130156/suppress-stdout-stderr-print-from-python-functions """ # open null file descriptors null_file_descriptors = ( os.open(os.devnull, os.O_RDWR), os.open(os.devnull, os.O_RDWR) ) # save stdout and stderr stdout_and_stderr = (os.dup(1), os.dup(2)) # assign the null pointers to stdout and stderr null_fd1, null_fd2 = null_file_descriptors os.dup2(null_fd1, 1) os.dup2(null_fd2, 2) yield # re-assign the real stdout/stderr back to (1) and (2) stdout, stderr = stdout_and_stderr os.dup2(stdout, 1) os.dup2(stderr, 2) # close all file descriptors. for fd in null_file_descriptors + stdout_and_stderr: os.close(fd) # alias bash bash = shell __all__ = [ 'shell', 'bash', 'cd', 'env', 'path', 'quiet', ] PK!HRR~,shell_utils-2.2.1.dist-info/entry_points.txtN+I/N.,()/L-Hɉ/-)փYAļ<U9Vye٩@".$Y @PK! J*//#shell_utils-2.2.1.dist-info/LICENSECopyright 2018 Stephan Fitzpatrick Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.PK!HMWX!shell_utils-2.2.1.dist-info/WHEEL A н#Z@Z|Jl~6蓅 Λ MU4[PYBpYD*Mͯ#ڪ/̚?ݭ'%nPK!HCT$shell_utils-2.2.1.dist-info/METADATAXm۸_KXR\o.mܢm MK[ITIjp I&m?4%29oyI'JD7i͜ȞsnwΩʲ6 \uu-aίHZ8puegR7 kIUi3F2mwεv[v:+t4zob8cwW7d;Q8Dܿ[*n^*k9?5jKj$D'|>?4ѭQH9' Qת l;'|7#5^>V>}Ʒ8cꔑ6=WyQ|ŷgo\¨~'^Zɏ.$oJo{G]$_y8-=VPU[oU)-@&'7N6;HY=%/qB5dBtB\5$Zmwk^i{`H;Yw80kJGpЭՌ4 X?@eW!$FG.zS΅#`3n`t!]Snܓeh^uOD)93dݺgxd*IL>Kq'Mn¯67if|kpVWZOPOX2Fn!Od*@DC}IQ~HhLQ DO] IkӆBZ0.#uW3̅!e[ilEx#jW wx|7qttWmڗun6`Qip̥|2u0 \vO((yPmtU=5NKI {UYU6dnR-]w8˗8f@Zarg# L1^l6l'SV ǭLsɓ's m .س{C d04Sa;o/ ːʺRwUZ ฿W`ו3$/}0Jb El E\ k0c N/t`Bg>3$:){gz='r-lRiRa4[Qp4ޫ1W j1z;[u+aR~KcgF-TGsV!)USߵU?o# @ESXSQ =BI\l̿DkvG-qn alJ^Ƥ}N/>X躊:%Z:'BWÍmE;3|x<{v 1W;mdzfHp =aY (v-)E_186 `(:CӃ,GX{0Ӵ0zd_^l_z瑺{ھA4_D#cÐ2s-adt+qG݆x.^2&Zt*Oj{$O32c'jCnZyDJT|Q`=?oBeO4^kq?䟡PK!HXt!"shell_utils-2.2.1.dist-info/RECORDι@἟l 76ť,"U3`d7iUUES0=(J]1S~U>BXC}[F(lbq|u#.TfȗgD%W@{F \Į.fU[SjnH;&:ճ ;LXbFvݱ˖f\rp7IH9cR&d@+)A83xh>vSnp84{OuMNt(%ʅ-1Yq{EWʋؾޣjq:L-B|\C-q#H'}Cs|PK!?1shell_utils/__init__.pyPK!o:++shell_utils/cli.pyPK!2f f 'shell_utils/notify.pyPK!