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!fHshell_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: raise 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.7.1.dist-info/entry_points.txtN+I/N.,()/L-Hɉ/-)փYAļ.$(s2 PK! J*//#shell_utils-0.7.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-0.7.1.dist-info/WHEEL A н#Z@Z|Jl~6蓅 Λ MU4[PYBpYD*Mͯ#ڪ/̚?ݭ'%nPK!H]#C $shell_utils-0.7.1.dist-info/METADATAXk۸_rd7M$4ni#*Is/%YL3AH"}}otP j7\>IjouYN`J/G97r|O4R5T ֖~"Kspv>/NOkmf:nvYٽo-0m2]y}jϛV]oU%2ߵ dT)T NIޛhi\9[;Cwy€S66 tW=9ޗ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