Skip to content

Commit

Permalink
Refine code after running flake8.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ken Kundert authored and Ken Kundert committed Mar 29, 2019
1 parent d1a0d9c commit d26eb86
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 11 deletions.
9 changes: 7 additions & 2 deletions shlib/extended_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def _is_readable(path):

PosixPath.is_readable = _is_readable


# is_writable {{{1
def _is_writable(path):
"""
Expand All @@ -53,6 +54,7 @@ def _is_writable(path):

PosixPath.is_writable = _is_writable


# is_executable {{{1
def _is_executable(path):
"""
Expand All @@ -66,6 +68,7 @@ def _is_executable(path):

PosixPath.is_executable = _is_executable


# is_hidden {{{1
def _is_hidden(path):
"""
Expand All @@ -75,10 +78,11 @@ def _is_hidden(path):
False
"""
return path.exists() and str(path).startswith('.')
return path.exists() and path.name.startswith('.')

PosixPath.is_hidden = _is_hidden


# path_from {{{1
def _path_from(path, start):
"""
Expand All @@ -94,6 +98,7 @@ def _path_from(path, start):

PosixPath.path_from = _path_from


# sans_ext {{{1
def _sans_ext(path):
"""
Expand All @@ -108,6 +113,7 @@ def _sans_ext(path):
"""
return path.parent / path.stem


PosixPath.sans_ext = _sans_ext

# Python 3.5 extensions {{{1
Expand Down Expand Up @@ -173,4 +179,3 @@ def _expanduser(self):
return self

PosixPath.expanduser = _expanduser

49 changes: 41 additions & 8 deletions shlib/shlib.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# shlib -- Scripting utilities
#
# A light-weight package with few dependencies that allows users to do
# A light-weight package with few dependencies that allows users to do
# shell-script like things relatively easily in Python.

# License {{{1
Expand All @@ -27,12 +27,11 @@
from .extended_pathlib import Path
except ImportError:
from pathlib import Path
from six import string_types
import itertools
import shlex
import shutil
import errno
import os
import sys

# Parameters {{{1
PREFERENCES = dict(
Expand All @@ -43,11 +42,11 @@

# Utilities {{{1
# is_str {{{2
from six import string_types
def is_str(obj):
"""Identifies strings in all their various guises."""
return isinstance(obj, string_types)


# is_iterable {{{2
def is_iterable(obj):
"""Identifies objects that can be iterated over, including strings."""
Expand All @@ -58,18 +57,21 @@ def is_iterable(obj):
from collections import Iterable
return isinstance(obj, Iterable)


# is_collection {{{2
def is_collection(obj):
"""Identifies objects that can be iterated over, excluding strings."""
return is_iterable(obj) and not is_str(obj)


# to_path {{{2
def to_path(*args):
try:
return Path(*args).expanduser()
except AttributeError:
return Path(*args)


# to_paths {{{2
def to_paths(args):
"Iterate through up to two levels of arguments, converting them to paths"
Expand All @@ -80,12 +82,14 @@ def to_paths(args):
else:
yield to_path(arg)


# to_str {{{2
def to_str(path):
# first convert to path to assure ~ expansion is done, then convert back to
# string.
return str(to_path(path))


# raise_os_error {{{2
# Raise an error based on the errno.
def raise_os_error(errno, filename=None):
Expand All @@ -94,11 +98,13 @@ def raise_os_error(errno, filename=None):
else:
raise OSError(errno, os.strerror(errno))


# split_cmd {{{2
def split_cmd(cmd):
from shlex import split
return split(cmd)


# quote_arg {{{2
def quote_arg(arg):
"""Return a shell-escaped version of the string *arg*."""
Expand All @@ -117,12 +123,14 @@ def quote(arg):
return "'" + arg.replace("'", "'\"'\"'") + "'"
return quote(str(arg))


# _use_log {{{2
def _use_log(log):
if log is None:
return PREFERENCES['log_cmd']
return log


# Preferences {{{1
def set_prefs(**kwargs):
"""Set ShLib preferences
Expand Down Expand Up @@ -150,6 +158,7 @@ def set_state(state):
PREFERENCES = state
return old_state


# File system utility functions (cp, mv, rm, ln, touch, mkdir, ls, etc.) {{{1
# cp {{{2
def cp(*paths):
Expand All @@ -176,6 +185,7 @@ def cp(*paths):
else:
shutil.copy2(to_str(src), to_str(dest))


# mv {{{2
def mv(*paths):
"Move file or directory (supports moves across filesystems)"
Expand Down Expand Up @@ -204,6 +214,7 @@ def mv(*paths):
shutil.move(to_str(src), to_str(dest))



# rm {{{2
def rm(*paths):
"Remove files or directories (equivalent to rm -rf)"
Expand All @@ -221,12 +232,14 @@ def rm(*paths):
if err.errno != errno.ENOENT:
raise


# ln {{{2
def ln(src, dest):
"Create symbolic link."
dest = to_path(dest)
dest.symlink_to(src)


# touch {{{2
def touch(*paths):
"""
Expand All @@ -235,6 +248,7 @@ def touch(*paths):
for path in to_paths(paths):
path.touch()


# mkdir {{{2
def mkdir(*paths):
"""
Expand All @@ -254,6 +268,7 @@ def mkdir(*paths):
if err.errno != errno.EEXIST or path.is_file():
raise


# mount/umount {{{2
class mount:

Expand All @@ -274,9 +289,11 @@ def __exit__(self, exc_type, exc_value, exc_traceback):
def umount(path):
Run(['umount', path])


def is_mounted(path):
return Run(['mountpoint', '-q', path], '0,1').status == 0


# cd {{{2
class cd:
def __init__(self, path):
Expand All @@ -290,22 +307,26 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, exc_traceback):
os.chdir(to_str(self.starting_dir))


# cwd {{{2
def cwd():
"""Return current working directory as a pathlib path"""
return Path.cwd()


# chmod {{{2
def chmod(mode, *paths):
"Change the mode bits of one or more file or directory"
for path in to_paths(paths):
path.chmod(mode)


# getmod {{{2
def getmod(path):
"Return the permission bits for a file or directory"
return os.stat(str(path)).st_mode & 0o777


# ls {{{2
def ls(*paths, **kwargs):
"""
Expand All @@ -316,12 +337,12 @@ def ls(*paths, **kwargs):
Args:
paths: the paths to list ('.' if no paths given).
select: a returned path will match this glob string, use **/* to enable
select: a returned path will match this glob string, use **/* to enable
recursion
reject: a returned path will not match this glob string
only: specifies the type of returned paths, choose from 'file' or 'dir'
hidden (bool): specifies whether hidden files should be returned, if
not given hidden files are returned if select string starts with
hidden (bool): specifies whether hidden files should be returned, if
not given hidden files are returned if select string starts with
'.'
KSK: it is a bit weird that I allow paths to be a list, but not select or
Expand Down Expand Up @@ -378,6 +399,7 @@ def acceptable(path):
if acceptable(each):
yield each


# lsd {{{2
def lsd(*args, **kwargs):
"""
Expand Down Expand Up @@ -407,6 +429,7 @@ def lsd(*args, **kwargs):
for d in ls(*args, **kwargs):
yield d


# lsf {{{2
def lsf(*args, **kwargs):
"""
Expand All @@ -432,6 +455,7 @@ def lsf(*args, **kwargs):
for f in ls(*args, **kwargs):
yield f


# Path list functions (leaves, cartesian_product, brace_expand, etc.) {{{1
def _leaves(path, hidden, report):
try:
Expand All @@ -447,6 +471,7 @@ def _leaves(path, hidden, report):
if report:
report(e)


# leaves() {{{2
def leaves(path, hidden=False, report=None):
"""
Expand All @@ -464,10 +489,11 @@ def leaves(path, hidden=False, report=None):
for each in _leaves(Path(path), hidden, report):
yield each


# cartesian_product() {{{2
def cartesian_product(*fragments):
"""
Combine path fragments to to a path list. Each fragment must be a string or
Combine path fragments to to a path list. Each fragment must be a string or
path or an iterable that generates strings or paths.
"""
if not len(fragments):
Expand All @@ -476,6 +502,7 @@ def cartesian_product(*fragments):
*(f if is_collection(f) else (f,) for f in fragments)
)]


# brace_expand() {{{2
try:
from braceexpand import braceexpand
Expand All @@ -488,6 +515,7 @@ def brace_expand(pattern):
except ImportError:
pass


# Execution classes and functions (Cmd, Run, Sh, Start, run, bg, shbg, which) {{{1
# Command class {{{2
class Cmd(object):
Expand Down Expand Up @@ -540,6 +568,7 @@ def __init__(
self.option_args = option_args
self._interpret_modes(modes)


# _interpret_modes {{{3
def _interpret_modes(self, modes):
accept = ''
Expand Down Expand Up @@ -753,6 +782,7 @@ def __init__(
self._interpret_modes(modes)
self.run(stdin)


# Sh class (deprecated) {{{2
class Sh(Cmd):
"""Run a command immediately in the shell.
Expand Down Expand Up @@ -866,6 +896,7 @@ def run(cmd, stdin=None, accept=0, shell=False):
raise OSError(None, "unexpected exit status (%d)." % status)
return status


# sh (deprecated) {{{2
def sh(cmd, stdin=None, accept=0, shell=True):
"Execute a command with a shell without capturing its output"
Expand All @@ -883,6 +914,7 @@ def bg(cmd, stdin=None, shell=False):
process.stdin.close()
return process.pid


# shbg (deprecated) {{{2
def shbg(cmd, stdin=None, shell=True):
"Execute a command with a shell in the background without capturing its output."
Expand All @@ -901,6 +933,7 @@ def which(name, path=None, flags=os.X_OK):
result.append(p)
return result


# render_command {{{2
def render_command(cmd, option_args=None, width=70):
""" Render a command.
Expand Down
3 changes: 3 additions & 0 deletions tests/REF
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
line1
line2
line3
2 changes: 2 additions & 0 deletions tests/TEST
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
line1
line2
2 changes: 1 addition & 1 deletion tests/test_shlib.rst

0 comments on commit d26eb86

Please sign in to comment.