Skip to content

Commit

Permalink
chore(pre-commit): formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
shakefu committed Dec 2, 2023
1 parent 396dc1d commit 517ddf0
Show file tree
Hide file tree
Showing 18 changed files with 843 additions and 714 deletions.
1 change: 0 additions & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ 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.

5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ Python Standard Library.

Pytool is compatible with and tested against Python 3.8 and higher. End of life Python versions are not supported.

> [!NOTE]
> *Note*: Python 2 and `<3.8` is now [End of
> [!NOTE] > _Note_: Python 2 and `<3.8` is now [End of
> Life](https://www.python.org/doc/sunset-python-2/) and support in Pytool
> is deprecated and will be removed in Pytool 4.x.
Expand All @@ -30,7 +29,7 @@ Docs](https://readthedocs.org)!

Pytool is available on PyPI for your installation ease.

``` bash
```bash
pip install pytool
```

Expand Down
3 changes: 1 addition & 2 deletions docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Here you'll find a record of the changes in each version of :mod:`pytool`.

- Implement a instance-descriptor read-only protocol for
:class:`pytool.lang.Namespace` objects. This means you can assign descriptor
instances to Namespace instances, and their values can be read, but not set.
instances to Namespace instances, and their values can be read, but not set.

This differs from normal python descriptor behavior, where the descriptor
instance must be present in the class rather than the instance.
Expand Down Expand Up @@ -149,4 +149,3 @@ Pre-2.0.0
---------

Sorry, I was lazy and didn't keep a Changelog until 2.0. Apologies!

1 change: 0 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,3 @@ Indices and tables
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

4 changes: 1 addition & 3 deletions docs/pytool.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ issue <https://github.com/shakefu/pytool/issues>`_.
:class:`pytool.cmd.Command`
---------------------------

.. autoclass:: pytool.cmd.Command
.. autoclass:: pytool.cmd.Command
:members:

:mod:`pytool.json`: JSON helpers
Expand Down Expand Up @@ -234,5 +234,3 @@ issue <https://github.com/shakefu/pytool/issues>`_.

.. autoclass:: ListProxy
:members:


28 changes: 14 additions & 14 deletions pytool/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@
"""
from pytool import (
cmd,
json,
lang,
proxy,
text,
time,
)
cmd,
json,
lang,
proxy,
text,
time,
)

__all__ = [
'cmd',
'json',
'lang',
'proxy',
'text',
'time',
]
"cmd",
"json",
"lang",
"proxy",
"text",
"time",
]
116 changes: 61 additions & 55 deletions pytool/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
# Handle the optional configargparse lib
try:
import configargparse as argparse

DefaultFormatter = argparse.ArgumentDefaultsRawHelpFormatter
HAS_CAP = True
except ImportError:
import argparse

DefaultFormatter = argparse.RawDescriptionHelpFormatter
HAS_CAP = False

import pytool.text

try:
import pyconfig
except ImportError:
Expand All @@ -40,10 +43,10 @@


__all__ = [
'RELOAD_SIGNAL',
'STOP_SIGNAL',
'Command',
]
"RELOAD_SIGNAL",
"STOP_SIGNAL",
"Command",
]


try:
Expand Down Expand Up @@ -135,59 +138,59 @@ def run(self):
refer to that documentation for more information.
"""

def __init__(self):
self.parser = argparse.ArgumentParser(add_help=False,
**self.parser_opts())
self.parser = argparse.ArgumentParser(add_help=False, **self.parser_opts())
self.subparsers = None
self.set_opts()
self.opt('--help', action='help', help='display this help and exit')
self.opt("--help", action="help", help="display this help and exit")

def parser_opts(self):
""" Subclasses should override this method to return a dictionary of
additional arguments to the parser instance.
**Example**::
class MyCommand(Command):
def parser_opts(self):
return dict(
description="Manual description for cmd.",
add_env_var_help=True,
auto_env_var_prefix='mycmd_',
)
"""Subclasses should override this method to return a dictionary of
additional arguments to the parser instance.
**Example**::
class MyCommand(Command):
def parser_opts(self):
return dict(
description="Manual description for cmd.",
add_env_var_help=True,
auto_env_var_prefix='mycmd_',
)
"""
return dict()

def set_opts(self):
""" Subclasses should override this method to configure the command
line arguments and options.
"""Subclasses should override this method to configure the command
line arguments and options.
**Example**::
**Example**::
class MyCommand(Command):
def set_opts(self):
self.opt('--verbose', '-v', action='store_true',
help="be more verbose")
class MyCommand(Command):
def set_opts(self):
self.opt('--verbose', '-v', action='store_true',
help="be more verbose")
def run(self):
if self.args.verbose:
print "I'm verbose."
def run(self):
if self.args.verbose:
print "I'm verbose."
"""
pass

def opt(self, *args, **kwargs):
""" Add an option to this command. This takes the same arguments as
:meth:`ArgumentParser.add_argument`.
"""Add an option to this command. This takes the same arguments as
:meth:`ArgumentParser.add_argument`.
"""
self.parser.add_argument(*args, **kwargs)

def run(self):
""" Subclasses should override this method to start the command
process. In other words, this is where the magic happens.
"""Subclasses should override this method to start the command
process. In other words, this is where the magic happens.
.. versionchanged:: 3.15.0
.. versionchanged:: 3.15.0
By default, this will just print help and exit.
By default, this will just print help and exit.
"""
self.parser.print_help()
Expand Down Expand Up @@ -269,34 +272,34 @@ def run(self):
"""
if not self.subparsers:
self.subparsers = self.parser.add_subparsers(title='subcommands',
dest='command')
self.subparsers = self.parser.add_subparsers(
title="subcommands", dest="command"
)

if opt_func is None:
opt_func = getattr(self, name.replace('-', '_') + '_opts', None)
opt_func = getattr(self, name.replace("-", "_") + "_opts", None)

if run_func is None:
run_func = getattr(self, name.replace('-', '_'),
self.parser.print_help)
run_func = getattr(self, name.replace("-", "_"), self.parser.print_help)

# Map help text to command descriptions for extra convenience
if 'help' in kwargs and 'description' not in kwargs:
kwargs['description'] = kwargs['help']
if "help" in kwargs and "description" not in kwargs:
kwargs["description"] = kwargs["help"]

# Provide good wrapping
if 'description' in kwargs:
kwargs['description'] = pytool.text.wrap(kwargs['description'])
kwargs.setdefault('formatter_class', CommandFormatter)
if "description" in kwargs:
kwargs["description"] = pytool.text.wrap(kwargs["description"])
kwargs.setdefault("formatter_class", CommandFormatter)

# Propagate environment variable prefix settings
prefix = getattr(self.parser, '_auto_env_var_prefix', UNSET)
prefix = getattr(self.parser, "_auto_env_var_prefix", UNSET)
if prefix is not UNSET:
kwargs.setdefault('auto_env_var_prefix', prefix)
kwargs.setdefault("auto_env_var_prefix", prefix)

# Propagate environment variable help settings
add_help = getattr(self.parser, '_add_env_var_help', UNSET)
add_help = getattr(self.parser, "_add_env_var_help", UNSET)
if add_help is not UNSET:
kwargs.setdefault('add_env_var_help', add_help)
kwargs.setdefault("add_env_var_help", add_help)

parser = self.subparsers.add_parser(name, *args, **kwargs)
parser.set_defaults(func=run_func)
Expand All @@ -313,13 +316,13 @@ def run(self):

@classmethod
def console_script(cls):
""" Method used to start the command when launched from a distutils
console script.
"""Method used to start the command when launched from a distutils
console script.
"""
cls().start(sys.argv[1:])

def start(self, args):
""" Starts a command and registers single handlers. """
"""Starts a command and registers single handlers."""
if six.PY3 and sys.version_info >= (3, 7):
# Unfortunately this doesn't work and I don't know why... will fix
# it later.
Expand Down Expand Up @@ -362,10 +365,11 @@ class CommandFormatter(DefaultFormatter):
command, which makes it much more readable.
"""

def __init__(self, *args, **kwargs):
width = pytool.text.columns()
max_help_position = max(40, int(width / 2))
kwargs['max_help_position'] = max_help_position
kwargs["max_help_position"] = max_help_position
super(CommandFormatter, self).__init__(*args, **kwargs)


Expand Down Expand Up @@ -395,7 +399,7 @@ def listen_opts(self):
"""
if args:
name = 'opt_' + args[0].lstrip('-')
name = "opt_" + args[0].lstrip("-")

def opt(self):
self.opt(*args, **kwargs)
Expand All @@ -418,13 +422,15 @@ def run(self):
...
"""

@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as err:
sys.stderr.write(str(err))
sys.stderr.write('\n')
sys.stderr.write("\n")
sys.stderr.flush()
sys.exit(1)

return wrapper
20 changes: 10 additions & 10 deletions pytool/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,27 @@
from datetime import datetime

import simplejson as json

# Conditionally handle bson import so we don't have to depend on pymongo
try:
import bson
except ImportError:
# Make a mock bson module (as a class object)
bson = type('bson', (object,),
{'ObjectId': type('ObjectId', (object,), {})})
bson = type("bson", (object,), {"ObjectId": type("ObjectId", (object,), {})})


__all__ = [
'as_json',
'from_json',
"as_json",
"from_json",
]


def _default(obj):
""" Handle encoding of an object which isn't JSON serializable by the
regular encoder. """
"""Handle encoding of an object which isn't JSON serializable by the
regular encoder."""
# Datetime objects get encoded according to the ISO standard
if isinstance(obj, datetime):
return obj.strftime('%a %b %d %Y %H:%M:%S %z').strip()
return obj.strftime("%a %b %d %Y %H:%M:%S %z").strip()
# BSON ObjectId types get encoded as their hex string
if isinstance(obj, bson.ObjectId):
return str(obj)
Expand Down Expand Up @@ -78,10 +78,10 @@ def as_json(obj, **kwargs):


def from_json(value):
""" Decodes a JSON string into an object.
"""Decodes a JSON string into an object.
:param str value: String to decode
:returns: Decoded JSON object
:param str value: String to decode
:returns: Decoded JSON object
"""
return json.loads(value)
Loading

0 comments on commit 517ddf0

Please sign in to comment.