PK!EQ3shell_utils/__init__.py# -*- coding: utf-8 -*- """Top-level package for shell-utils.""" from shell_utils.shell_utils import shell, env, path, cd, quiet from shell_utils.notify import notify __all__ = [ 'shell', 'env', 'path', 'cd', 'quiet', 'notify', ] PK!d&shell_utils/cli.py""" Usage: [OPTIONS] COMMAND [ARGS]... A cli for shell-utils. Options: --help Show this message and exit. """ 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') if __name__ == "__main__": cli() PK!6shell_utils/notify.pyimport subprocess as sp import logging import types import shlex import sys from functools import singledispatch, wraps import click @singledispatch def notify(message: str, title=None, subtitle=None, sound=None): """ Wraps osascript. 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') command = f"""osascript -e 'display notification "{message}" with title "{title}" subtitle "{subtitle}" sound name "{sound}"' """ sp.run(shlex.split(command), check=False) @notify.register(types.FunctionType) def _(func): """ Send notification that task has finished. Especially useful for long-running tasks """ @wraps(func) def inner(*args, **kwargs): result = None message = 'Succeeded!' try: result = func(*args, **kwargs) except Exception: message = 'Failed' raise else: return result finally: notify(message, title=getattr(func, '__name__')) return inner @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!pzzshell_utils/runner.py#!/usr/bin/env python3 import os from pathlib import Path from shell_utils import shell, cd, env, path, quiet import click @click.group() def main(): """ Development tasks; programmatically generated """ # ensure we're running commands from project root root = Path(__file__).parent.absolute() cwd = Path().absolute() if root != cwd: click.secho(f'Navigating from {cwd} to {root}', fg='yellow') os.chdir(root) if root != cwd: click.secho(f'Navigating from {cwd} to {root}', fg='yellow') os.chdir(root) if __name__ == '__main__': main() PK!{Ishell_utils/shell_utils.py# -*- coding: utf-8 -*- """Main module.""" import copy import os import subprocess as sp import textwrap import typing as T from contextlib import contextmanager from getpass import getuser from socket import gethostname import click Pathy = T.Union[os.PathLike, str] def shell(command: str, check=True, capture=False, show_command=True, dedent=True, strip=True) -> 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 show_command: show command being run prefixed by user dedent: de-dent command string; useful if it's a bash script written within a function in your module strip: strip the command string of newlines and whitespace from the beginning and end Returns: Completed Process """ user = click.style(getuser(), fg='green') hostname = click.style(gethostname(), fg='blue') command = command.strip() if strip else command command = textwrap.dedent(command) if dedent else command print() if show_command: print(f'{user}@{hostname} executing...', end=os.linesep * 2) print(command, end=os.linesep * 2) try: process = sp.run(command, check=check, shell=True, stdout=sp.PIPE if capture else None, stderr=sp.PIPE if capture else None ) except sp.CalledProcessError as err: raise SystemExit(err) print() return process @contextmanager def cd(path_: Pathy): """Change the current working directory.""" cwd = os.getcwd() os.chdir(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) __all__ = [ 'shell', 'cd', 'env', 'path', 'quiet' ] PK!Hg@\,shell_utils-0.6.2.dist-info/entry_points.txtN+I/N.,()/L-Hɉ/-)փYAļ.$(s2 PK! J*//#shell_utils-0.6.2.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-0.6.2.dist-info/WHEEL A н#Z@Z|Jl~6蓅 Λ MU4[PYBpYD*Mͯ#ڪ/̚?ݭ'%nPK!HЗ$shell_utils-0.6.2.dist-info/METADATAXo۸/ ;kzkoknk,n0شDټHFRq߾%)YNr] [&~<~N‰_Js~dD%neYN[J_3vV09&.Z+@֥RJQάFܦ콮H:lQnۮLWZlmKڂ7whdo[V8lEܿn㷩*X NI֪BIJ|οw[ifWF7F!Df}W%xWmW("HݠpEKx"f2e`$8o3y/QPb M+tY5NsI!{լfVLwSU*ڲ x x<+ _ǯh3"'y;ұNcH7hf4f,8F=ɉ{J*uS|ߑ Q{NFŷT<{h=t\R,&bmu: 6xD{Y_-.噼Vf[=*ONm ,ڟ"染I7)6d/)ɸ'6Ͷ2#e -5mOKr!?/{ Qܓ ]v}5:kBwP&00 р: 47rk%ZX7`00Sd@jn'Ak楊<#1_RfؠiPh2BHI^ 6Yzo>G2ϑ5*Ө6 ° D>*oS$a.'lBzP\I Mrn=l`I+^u7ɨ8~ [=Û1nlq rʺ\Uo"Pm+ #}bEMd EXRӪ c N&O=S3oz3 :κ_.#JڊB!t*6u#a̓Li^@ŋ5ƾ nX/gd2;!9lùwzgD@]}oX>mSvw؎o'n\P a1xk r'T ӗ[H1*;cK, i()leN} 5/-=Җȃ7ѐW{ I< %4Y A;bc{[2SDkAxĦe7Woo!y/+ uKwCZ,Y?d)) /, /(.<  tc:x_Cpşȿ/q 9OO{l̓I<kd勽piM^$% v[DSS;aF-L76 Ljq]~b'KĞ\%]jߌ?=Zns/DeiҬ"ڦ