Skip to content

Commit

Permalink
Merge pull request #33 from pepkit/dev
Browse files Browse the repository at this point in the history
v0.6.2
  • Loading branch information
nsheff committed Nov 4, 2021
2 parents 771ffbf + abe2ef3 commit 1d79b7c
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 96 deletions.
5 changes: 5 additions & 0 deletions docs/changelog.md
Expand Up @@ -2,6 +2,11 @@

This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) format.

## [0.6.2] - 2021-01-28

### Fixed
- `is_url` function; [Issue 32](https://github.com/pepkit/ubiquerg/issues/32)

## [0.6.1] - 2020-07-01

### Changed
Expand Down
22 changes: 9 additions & 13 deletions setup.py
Expand Up @@ -8,29 +8,23 @@

def read_reqs(reqs_name):
depsfile = os.path.join(REQDIR, "requirements-{}.txt".format(reqs_name))
with open(depsfile, 'r') as f:
with open(depsfile, "r") as f:
return [l.strip() for l in f if l.strip()]


with open(os.path.join(PKG, "_version.py"), 'r') as versionfile:
with open(os.path.join(PKG, "_version.py"), "r") as versionfile:
version = versionfile.readline().split()[-1].strip("\"'\n")

# Handle the pypi README (long description) formatting.
try:
import pypandoc
long_description = pypandoc.convert_file("README.md", 'rst')
print("Pandoc conversion succeeded")
except(IOError, ImportError, OSError):
print("Warning: pandoc conversion failed!")
long_description = open("README.md").read()

with open("README.md") as f:
long_description = f.read()

setup(
name=PKG,
packages=[PKG],
version=version,
description="Various utility functions",
long_description=long_description,
long_description_content_type='text/markdown',
long_description_content_type="text/markdown",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: BSD License",
Expand All @@ -46,5 +40,7 @@ def read_reqs(reqs_name):
include_package_data=True,
test_suite="tests",
tests_require=read_reqs("dev"),
setup_requires=(["pytest-runner"] if {"test", "pytest", "ptr"} & set(sys.argv) else []),
setup_requires=(
["pytest-runner"] if {"test", "pytest", "ptr"} & set(sys.argv) else []
),
)
19 changes: 19 additions & 0 deletions tests/test_web.py
@@ -0,0 +1,19 @@
""" Tests for web """

import pytest
from ubiquerg.web import is_url


@pytest.mark.parametrize("s", ["https://www.github.com",
"https://www.youtube.com"]
)
def test_is_url_tests_positive(s):
assert is_url(s)


@pytest.mark.parametrize("s", ["www.github.com",
"test: string spaces",
"j%2vv@::https://test.com"]
)
def test_is_url_tests_negative(s):
assert not is_url(s)
2 changes: 1 addition & 1 deletion ubiquerg/_version.py
@@ -1 +1 @@
__version__ = "0.6.1"
__version__ = "0.6.2"
87 changes: 57 additions & 30 deletions ubiquerg/cli_tools.py
@@ -1,29 +1,39 @@
""" Functions for working with command-line interaction """

from .collection import is_collection_like, merge_dicts
from argparse import ArgumentParser, _SubParsersAction, _HelpAction, \
_VersionAction, SUPPRESS
from argparse import (
ArgumentParser,
_SubParsersAction,
_HelpAction,
_VersionAction,
SUPPRESS,
)
import sys

__classes__ = ["VersionInHelpParser"]
__all__ = __classes__ + ["build_cli_extra", "query_yes_no", "convert_value"]


class VersionInHelpParser(ArgumentParser):

def __init__(self, version=None, **kwargs):
""" Overwrites the inherited init. Saves the version as an object
attribute for further use. """
"""Overwrites the inherited init. Saves the version as an object
attribute for further use."""
super(VersionInHelpParser, self).__init__(**kwargs)
self.version = version
if self.version is not None:
self.add_argument('--version', action='version',
version='%(prog)s {}'.format(self.version))
self.add_argument(
"--version",
action="version",
version="%(prog)s {}".format(self.version),
)

def format_help(self):
""" Add version information to help text. """
help_string = "version: {}\n".format(str(self.version)) \
if self.version is not None else ""
help_string = (
"version: {}\n".format(str(self.version))
if self.version is not None
else ""
)
return help_string + super(VersionInHelpParser, self).format_help()

def subparsers(self):
Expand All @@ -34,8 +44,7 @@ def subparsers(self):
"""
subs = [a for a in self._actions if isinstance(a, _SubParsersAction)]
if len(subs) != 1:
raise ValueError(
"Expected exactly 1 subparser, got {}".format(len(subs)))
raise ValueError("Expected exactly 1 subparser, got {}".format(len(subs)))
return subs[0]

def top_level_args(self):
Expand Down Expand Up @@ -73,10 +82,16 @@ def dests_by_subparser(self, subcommand=None, top_level=False):
return dest_list

if subcommand is not None and subcommand not in self.subcommands():
raise ValueError("'{}' not found in this parser commands: {}".
format(subcommand, str(self.subcommands())))
subs = self.subparsers().choices if subcommand is None \
raise ValueError(
"'{}' not found in this parser commands: {}".format(
subcommand, str(self.subcommands())
)
)
subs = (
self.subparsers().choices
if subcommand is None
else {subcommand: self.subparsers().choices[subcommand]}
)
dests = {}
for subcmd, sub in subs.items():
dest_list = []
Expand Down Expand Up @@ -121,10 +136,16 @@ def arg_defaults(self, subcommand=None, unique=False, top_level=False):
return defaults_dict

if subcommand is not None and subcommand not in self.subcommands():
raise ValueError("'{}' not found in this parser commands: {}".
format(subcommand, str(self.subcommands())))
subs = self.subparsers().choices if subcommand is None \
raise ValueError(
"'{}' not found in this parser commands: {}".format(
subcommand, str(self.subcommands())
)
)
subs = (
self.subparsers().choices
if subcommand is None
else {subcommand: self.subparsers().choices[subcommand]}
)
defaults = {}
for subcmd, sub in subs.items():
defaults_dict = {}
Expand Down Expand Up @@ -159,8 +180,7 @@ def build_cli_extra(optargs):

def render(k, v):
if not isinstance(k, str):
raise TypeError(
"Option name isn't a string: {} ({})".format(k, type(k)))
raise TypeError("Option name isn't a string: {} ({})".format(k, type(k)))
if v is None:
return k
if is_collection_like(v):
Expand All @@ -183,12 +203,16 @@ def query_yes_no(question, default="no"):
:param str default: the presumed answer if the user just hits <Enter>.
:return bool: True for "yes" or False for "no"
"""

def parse(ans):
return {"yes": True, "y": True, "ye": True,
"no": False, "n": False}[ans.lower()]
return {"yes": True, "y": True, "ye": True, "no": False, "n": False}[
ans.lower()
]

try:
prompt = {None: "[y/n]", "yes": "[Y/n]",
"no": "[y/N]"}[None if default is None else default.lower()]
prompt = {None: "[y/n]", "yes": "[Y/n]", "no": "[y/N]"}[
None if default is None else default.lower()
]
except (AttributeError, KeyError):
raise ValueError("invalid default answer: {}".format(default))
msg = "{q} {p} ".format(q=question, p=prompt)
Expand All @@ -197,8 +221,7 @@ def parse(ans):
try:
return parse(_read_from_user() or default)
except KeyError:
sys.stdout.write(
"Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")


def convert_value(val):
Expand All @@ -214,17 +237,19 @@ def convert_value(val):
try:
val = str(val)
except:
raise ValueError("The input has to be of type convertible to 'str',"
" got '{}'".format(type(val)))
raise ValueError(
"The input has to be of type convertible to 'str',"
" got '{}'".format(type(val))
)

if isinstance(val, bool):
return val
if isinstance(val, str):
if val == 'None':
if val == "None":
return None
if val.lower() == 'true':
if val.lower() == "true":
return True
if val.lower() == 'false':
if val.lower() == "false":
return False
try:
float(val)
Expand All @@ -241,7 +266,9 @@ def convert_value(val):

def _read_from_user():
import sys

if sys.version_info.major < 3:
from __builtin__ import raw_input

return raw_input()
return input()
29 changes: 18 additions & 11 deletions ubiquerg/collection.py
Expand Up @@ -3,6 +3,7 @@
import itertools
import sys
from warnings import warn

if sys.version_info < (3, 3):
from collections import Iterable
else:
Expand Down Expand Up @@ -72,21 +73,27 @@ def powerset(items, min_items=None, include_full_pop=True, nonempty=False):
min_items = 1 if nonempty else 0
else:
if not isinstance(min_items, int):
raise TypeError("Min items count for each subset isn't an integer: "
"{} ({})".format(min_items, type(min_items)))
raise TypeError(
"Min items count for each subset isn't an integer: "
"{} ({})".format(min_items, type(min_items))
)
if nonempty and min_items < 1:
raise ValueError("When minimum item count is {}, nonempty subsets "
"cannot be guaranteed.".format(min_items))
raise ValueError(
"When minimum item count is {}, nonempty subsets "
"cannot be guaranteed.".format(min_items)
)
# Account for iterable burn possibility; besides, collection should be
# relatively small if building the powerset.
items = list(items)
n = len(items)
if n == 0 or n < min_items:
return []
max_items = len(items) + 1 if include_full_pop else len(items)
return list(itertools.chain.from_iterable(
itertools.combinations(items, k)
for k in range(min_items, max_items)))
return list(
itertools.chain.from_iterable(
itertools.combinations(items, k) for k in range(min_items, max_items)
)
)


def asciify_dict(data):
Expand All @@ -96,7 +103,7 @@ def _asciify_list(lst):
ret = []
for item in lst:
if isinstance(item, unicode):
item = item.encode('utf-8')
item = item.encode("utf-8")
elif isinstance(item, list):
item = _asciify_list(item)
elif isinstance(item, dict):
Expand All @@ -111,12 +118,12 @@ def _asciify_list(lst):
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = key.encode('utf-8')
key = key.encode("utf-8")
if isinstance(value, unicode):
value = value.encode('utf-8')
value = value.encode("utf-8")
elif isinstance(value, list):
value = _asciify_list(value)
elif isinstance(value, dict):
value = asciify_dict(value)
ret[key] = value
return ret
return ret
6 changes: 4 additions & 2 deletions ubiquerg/environment.py
Expand Up @@ -10,12 +10,14 @@

class TmpEnv(object):
""" Temporary environment variable setting. """

def __init__(self, overwrite=False, **kwargs):
if not overwrite:
already_set = [k for k, v in kwargs.items() if os.getenv(k, v) != v]
if already_set:
msg = "{} variable(s) already set: {}".\
format(len(already_set), ", ".join(already_set))
msg = "{} variable(s) already set: {}".format(
len(already_set), ", ".join(already_set)
)
raise ValueError(msg)
self._kvs = kwargs

Expand Down

0 comments on commit 1d79b7c

Please sign in to comment.