Skip to content

pyupgrade @ py37 #745

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/_ext/aafig.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def get_basename(text, options, prefix="aafig"):
del options["format"]
hashkey = text + str(options)
id = sha(hashkey.encode("utf-8")).hexdigest()
return "%s-%s" % (prefix, id)
return f"{prefix}-{id}"


class AafigError(SphinxError):
Expand Down Expand Up @@ -135,7 +135,7 @@ def render_aafig_images(app, doctree):
img["uri"] = fname
# FIXME: find some way to avoid this hack in aafigure
if extra:
(width, height) = [x.split('"')[1] for x in extra.split()]
(width, height) = (x.split('"')[1] for x in extra.split())
if "width" not in img:
img["width"] = width
if "height" not in img:
Expand All @@ -151,7 +151,7 @@ def render_aafigure(app, text, options):
raise AafigError("aafigure module not installed")

fname = get_basename(text, options)
fname = "%s.%s" % (get_basename(text, options), options["format"])
fname = "{}.{}".format(get_basename(text, options), options["format"])
if app.builder.format == "html":
# HTML
imgpath = relative_uri(app.builder.env.docname, "_images")
Expand All @@ -177,7 +177,7 @@ def render_aafigure(app, text, options):
f = None
try:
try:
f = open(metadata_fname, "r")
f = open(metadata_fname)
extra = f.read()
except Exception:
raise AafigError()
Expand Down
14 changes: 7 additions & 7 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@
latex_documents = [
(
"index",
"{0}.tex".format(about["__package_name__"]),
"{0} Documentation".format(about["__title__"]),
"{}.tex".format(about["__package_name__"]),
"{} Documentation".format(about["__title__"]),
about["__author__"],
"manual",
)
Expand All @@ -111,7 +111,7 @@
(
"index",
about["__package_name__"],
"{0} Documentation".format(about["__title__"]),
"{} Documentation".format(about["__title__"]),
about["__author__"],
1,
)
Expand All @@ -120,8 +120,8 @@
texinfo_documents = [
(
"index",
"{0}".format(about["__package_name__"]),
"{0} Documentation".format(about["__title__"]),
"{}".format(about["__package_name__"]),
"{} Documentation".format(about["__title__"]),
about["__author__"],
about["__package_name__"],
about["__description__"],
Expand Down Expand Up @@ -196,14 +196,14 @@ def linkcode_resolve(domain, info): # NOQA: C901
fn = relpath(fn, start=dirname(tmuxp.__file__))

if "dev" in about["__version__"]:
return "%s/blob/master/%s/%s%s" % (
return "{}/blob/master/{}/{}{}".format(
about["__github__"],
about["__package_name__"],
fn,
linespec,
)
else:
return "%s/blob/v%s/%s/%s%s" % (
return "{}/blob/v{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
about["__package_name__"],
Expand Down
1 change: 0 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ def session(server):
"""
try:
server.switch_client(session.get("session_id"))
pass
except exc.LibTmuxException:
# server.attach_session(session.get('session_id'))
pass
Expand Down
6 changes: 3 additions & 3 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
from unittest.mock import MagicMock

import pytest

Expand Down Expand Up @@ -435,7 +435,7 @@ def test_load_log_file(cli_args, tmpdir, monkeypatch):
monkeypatch.setenv("HOME", str(tmpdir))

with tmpdir.as_cwd():
print("tmpdir: {0}".format(tmpdir))
print(f"tmpdir: {tmpdir}")
runner = CliRunner()

# If autoconfirm (-y) no need to prompt y
Expand Down Expand Up @@ -1030,7 +1030,7 @@ def test_ls_cli(monkeypatch, tmpdir):
stems = [os.path.splitext(f)[0] for f in filenames if f not in ignored_filenames]

for filename in filenames:
location = tmpdir.join(".tmuxp/{}".format(filename))
location = tmpdir.join(f".tmuxp/{filename}")
if filename.endswith("/"):
location.ensure_dir()
else:
Expand Down
12 changes: 6 additions & 6 deletions tests/test_workspacebuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def assertIsMissing(cmd, hist):
if assertCase(sent_cmd, history_cmd):
correct = True
break
assert correct, "Unknown sent command: [%s] in %s" % (sent_cmd, assertCase)
assert correct, f"Unknown sent command: [{sent_cmd}] in {assertCase}"


def test_session_options(session):
Expand Down Expand Up @@ -215,11 +215,11 @@ def test_global_options(session):

def test_global_session_env_options(session, monkeypatch):
visual_silence = "on"
monkeypatch.setenv(str("VISUAL_SILENCE"), str(visual_silence))
monkeypatch.setenv("VISUAL_SILENCE", str(visual_silence))
repeat_time = 738
monkeypatch.setenv(str("REPEAT_TIME"), str(repeat_time))
monkeypatch.setenv("REPEAT_TIME", str(repeat_time))
main_pane_height = 8
monkeypatch.setenv(str("MAIN_PANE_HEIGHT"), str(main_pane_height))
monkeypatch.setenv("MAIN_PANE_HEIGHT", str(main_pane_height))

yaml_config = loadfixture("workspacebuilder/env_var_options.yaml")
s = session
Expand Down Expand Up @@ -321,14 +321,14 @@ def test_window_shell(session):

for w, wconf in builder.iter_create_windows(s):
if "window_shell" in wconf:
assert wconf["window_shell"] == str("top")
assert wconf["window_shell"] == "top"

while retry():
session.server._update_windows()
if w["window_name"] != "top":
break

assert w.name != str("top")
assert w.name != "top"


def test_environment_variables(session):
Expand Down
1 change: 0 additions & 1 deletion tmuxp/_compat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf8 -*-
# flake8: NOQA
import sys

Expand Down
29 changes: 13 additions & 16 deletions tmuxp/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def _validate_choices(options):
def func(value):
if value not in options:
raise click.BadParameter(
"Possible choices are: {0}.".format(", ".join(options))
"Possible choices are: {}.".format(", ".join(options))
)
return value

Expand Down Expand Up @@ -188,7 +188,7 @@ def set_layout_hook(session, hook_name):
# unfortunately, select-layout won't work unless
# we've literally selected the window at least once
# with the client
hook_cmd.append("selectw -t {}".format(window.id))
hook_cmd.append(f"selectw -t {window.id}")
# edit: removed -t, or else it won't respect main-pane-w/h
hook_cmd.append("selectl")
hook_cmd.append("selectw -p")
Expand All @@ -199,7 +199,7 @@ def set_layout_hook(session, hook_name):
target_session=session.id, hook_name=hook_name
)
)
hook_cmd.append("selectw -t {}".format(attached_window.id))
hook_cmd.append(f"selectw -t {attached_window.id}")

# join the hook's commands with semicolons
hook_cmd = "{}".format("; ".join(hook_cmd))
Expand Down Expand Up @@ -236,7 +236,7 @@ def is_pure_name(path):

class ConfigPath(click.Path):
def __init__(self, config_dir=None, *args, **kwargs):
super(ConfigPath, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.config_dir = config_dir

def convert(self, value, param, ctx):
Expand All @@ -245,7 +245,7 @@ def convert(self, value, param, ctx):
config_dir = config_dir()

value = scan_config(value, config_dir=config_dir)
return super(ConfigPath, self).convert(value, param, ctx)
return super().convert(value, param, ctx)


def scan_config_argument(ctx, param, value, config_dir=None):
Expand All @@ -264,7 +264,7 @@ def scan_config_argument(ctx, param, value, config_dir=None):
value = scan_config(value, config_dir=config_dir)

elif isinstance(value, tuple):
value = tuple([scan_config(v, config_dir=config_dir) for v in value])
value = tuple(scan_config(v, config_dir=config_dir) for v in value)

return value

Expand Down Expand Up @@ -346,7 +346,7 @@ def scan_config(config, config_dir=None):
candidates = [
x
for x in [
"%s%s" % (join(config_dir, config), ext)
f"{join(config_dir, config)}{ext}"
for ext in VALID_CONFIG_DIR_FILE_EXTENSIONS
]
if exists(x)
Expand Down Expand Up @@ -421,8 +421,8 @@ def load_plugins(sconf):
except Exception as error:
click.echo(
click.style("[Plugin Error] ", fg="red")
+ "Couldn't load {0}\n".format(plugin)
+ click.style("{0}".format(error), fg="yellow")
+ f"Couldn't load {plugin}\n"
+ click.style(f"{error}", fg="yellow")
)
sys.exit(1)

Expand Down Expand Up @@ -985,7 +985,7 @@ def command_freeze(
save_to = os.path.abspath(
os.path.join(
get_config_dir(),
"%s.%s" % (sconf.get("session_name"), config_format or "yaml"),
"{}.{}".format(sconf.get("session_name"), config_format or "yaml"),
)
)
dest_prompt = click.prompt(
Expand Down Expand Up @@ -1135,7 +1135,6 @@ def command_load(
@cli.group(name="import")
def import_config_cmd():
"""Import a teamocil/tmuxinator config."""
pass


def import_config(configfile, importfunc):
Expand Down Expand Up @@ -1229,7 +1228,7 @@ def command_convert(confirmed, config):
to_filetype = "json"
else:
raise click.BadParameter(
"Unknown filetype: %s (valid: [.json, .yaml, .yml])" % (ext,)
f"Unknown filetype: {ext} (valid: [.json, .yaml, .yml])"
)

configparser = kaptan.Kaptan()
Expand All @@ -1240,7 +1239,7 @@ def command_convert(confirmed, config):
newconfig = configparser.export(to_filetype, indent=2, **export_kwargs)

if not confirmed:
if click.confirm("convert to <%s> to %s?" % (config, to_filetype)):
if click.confirm(f"convert to <{config}> to {to_filetype}?"):
if click.confirm("Save config to %s?" % newfile):
confirmed = True

Expand All @@ -1260,9 +1259,7 @@ def command_edit_config(config):
call([sys_editor, config])


@cli.command(
name="ls", short_help="List configured sessions in {}.".format(get_config_dir())
)
@cli.command(name="ls", short_help=f"List configured sessions in {get_config_dir()}.")
def command_ls():
tmuxp_dir = get_config_dir()
if os.path.exists(tmuxp_dir) and os.path.isdir(tmuxp_dir):
Expand Down
10 changes: 1 addition & 9 deletions tmuxp/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,25 @@ class TmuxpException(Exception):

"""Base Exception for Tmuxp Errors."""

pass


class ConfigError(TmuxpException):

"""Error parsing tmuxp configuration dict."""

pass


class EmptyConfigException(ConfigError):

"""Configuration is empty."""

pass


class TmuxpPluginException(TmuxpException):

"""Base Exception for Tmuxp Errors."""

pass


class BeforeLoadScriptNotExists(OSError):
def __init__(self, *args, **kwargs):
super(BeforeLoadScriptNotExists, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

self.strerror = "before_script file '%s' doesn't exist." % self.strerror

Expand Down
2 changes: 1 addition & 1 deletion tmuxp/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def format(self, record):
try:
record.message = record.getMessage()
except Exception as e:
record.message = "Bad message (%r): %r" % (e, record.__dict__)
record.message = f"Bad message ({e!r}): {record.__dict__!r}"

date_format = "%H:%m:%S"
record.asctime = time.strftime(date_format, self.converter(record.created))
Expand Down
5 changes: 0 additions & 5 deletions tmuxp/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ def before_workspace_builder(self, session):
session : :class:`libtmux.Session`
session to hook into
"""
pass

def on_window_create(self, window):
"""
Expand All @@ -169,7 +168,6 @@ def on_window_create(self, window):
window: :class:`libtmux.Window`
window to hook into
"""
pass

def after_window_finished(self, window):
"""
Expand All @@ -184,7 +182,6 @@ def after_window_finished(self, window):
window: :class:`libtmux.Window`
window to hook into
"""
pass

def before_script(self, session):
"""
Expand Down Expand Up @@ -213,7 +210,6 @@ def before_script(self, session):
session : :class:`libtmux.Session`
session to hook into
"""
pass

def reattach(self, session):
"""
Expand All @@ -224,4 +220,3 @@ def reattach(self, session):
session : :class:`libtmux.Session`
session to hook into
"""
pass
7 changes: 4 additions & 3 deletions tmuxp/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,10 @@ def get_code(use_pythonrc, imported_objects):
# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
# conventions and get $PYTHONSTARTUP first then .pythonrc.py.
if use_pythonrc:
for pythonrc in set(
[os.environ.get("PYTHONSTARTUP"), os.path.expanduser("~/.pythonrc.py")]
):
for pythonrc in {
os.environ.get("PYTHONSTARTUP"),
os.path.expanduser("~/.pythonrc.py"),
}:
if not pythonrc:
continue
if not os.path.isfile(pythonrc):
Expand Down
2 changes: 1 addition & 1 deletion tmuxp/workspacebuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
logger = logging.getLogger(__name__)


class WorkspaceBuilder(object):
class WorkspaceBuilder:

"""
Load workspace from session :py:obj:`dict`.
Expand Down