diff --git a/docs/_ext/aafig.py b/docs/_ext/aafig.py index 38dd315d3e6..38e7e5f9286 100644 --- a/docs/_ext/aafig.py +++ b/docs/_ext/aafig.py @@ -32,7 +32,7 @@ logger = logging.getLogger(__name__) -DEFAULT_FORMATS = dict(html='svg', latex='pdf', text=None) +DEFAULT_FORMATS = dict(html="svg", latex="pdf", text=None) def merge_dict(dst, src): @@ -42,17 +42,17 @@ def merge_dict(dst, src): return dst -def get_basename(text, options, prefix='aafig'): +def get_basename(text, options, prefix="aafig"): options = options.copy() - if 'format' in options: - del options['format'] + if "format" in options: + del options["format"] hashkey = text + str(options) - id = sha(hashkey.encode('utf-8')).hexdigest() - return '%s-%s' % (prefix, id) + id = sha(hashkey.encode("utf-8")).hexdigest() + return "%s-%s" % (prefix, id) class AafigError(SphinxError): - category = 'aafig error' + category = "aafig error" class AafigDirective(images.Image): @@ -76,22 +76,22 @@ class AafigDirective(images.Image): def run(self): aafig_options = dict() - own_options_keys = [self.own_option_spec.keys()] + ['scale'] + own_options_keys = [self.own_option_spec.keys()] + ["scale"] for (k, v) in self.options.items(): if k in own_options_keys: # convert flags to booleans if v is None: v = True # convert percentage to float - if k == 'scale' or k == 'aspect': + if k == "scale" or k == "aspect": v = float(v) / 100.0 aafig_options[k] = v del self.options[k] - self.arguments = [''] + self.arguments = [""] (image_node,) = images.Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] - text = '\n'.join(self.content) + text = "\n".join(self.content) image_node.aafig = dict(options=aafig_options, text=text) return [image_node] @@ -101,45 +101,45 @@ def render_aafig_images(app, doctree): merge_dict(format_map, DEFAULT_FORMATS) if aafigure is None: logger.warn( - 'aafigure module not installed, ASCII art images ' - 'will be redered as literal text' + "aafigure module not installed, ASCII art images " + "will be redered as literal text" ) for img in doctree.traverse(nodes.image): - if not hasattr(img, 'aafig'): + if not hasattr(img, "aafig"): continue if aafigure is None: continue - options = img.aafig['options'] - text = img.aafig['text'] + options = img.aafig["options"] + text = img.aafig["text"] format = app.builder.format merge_dict(options, app.builder.config.aafig_default_options) if format in format_map: - options['format'] = format_map[format] + options["format"] = format_map[format] else: logger.warn( 'unsupported builder format "%s", please ' - 'add a custom entry in aafig_format config ' - 'option for this builder' % format + "add a custom entry in aafig_format config " + "option for this builder" % format ) img.replace_self(nodes.literal_block(text, text)) continue - if options['format'] is None: + if options["format"] is None: img.replace_self(nodes.literal_block(text, text)) continue try: fname, outfn, id, extra = render_aafigure(app, text, options) except AafigError as exc: - logger.warn('aafigure error: ' + str(exc)) + logger.warn("aafigure error: " + str(exc)) img.replace_self(nodes.literal_block(text, text)) continue - img['uri'] = fname + 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()] - if 'width' not in img: - img['width'] = width - if 'height' not in img: - img['height'] = height + if "width" not in img: + img["width"] = width + if "height" not in img: + img["height"] = height def render_aafigure(app, text, options): @@ -148,36 +148,36 @@ def render_aafigure(app, text, options): """ if aafigure is None: - raise AafigError('aafigure module not installed') + raise AafigError("aafigure module not installed") fname = get_basename(text, options) - fname = '%s.%s' % (get_basename(text, options), options['format']) - if app.builder.format == 'html': + fname = "%s.%s" % (get_basename(text, options), options["format"]) + if app.builder.format == "html": # HTML - imgpath = relative_uri(app.builder.env.docname, '_images') + imgpath = relative_uri(app.builder.env.docname, "_images") relfn = posixpath.join(imgpath, fname) - outfn = path.join(app.builder.outdir, '_images', fname) + outfn = path.join(app.builder.outdir, "_images", fname) else: # Non-HTML - if app.builder.format != 'latex': + if app.builder.format != "latex": logger.warn( - 'aafig: the builder format %s is not officially ' - 'supported, aafigure images could not work. ' - 'Please report problems and working builder to ' - 'avoid this warning inthe future' % app.builder.format + "aafig: the builder format %s is not officially " + "supported, aafigure images could not work. " + "Please report problems and working builder to " + "avoid this warning inthe future" % app.builder.format ) relfn = fname outfn = path.join(app.builder.outdir, fname) - metadata_fname = '%s.aafig' % outfn + metadata_fname = "%s.aafig" % outfn try: if path.isfile(outfn): extra = None - if options['format'].lower() == 'svg': + if options["format"].lower() == "svg": f = None try: try: - f = open(metadata_fname, 'r') + f = open(metadata_fname, "r") extra = f.read() except Exception: raise AafigError() @@ -197,9 +197,9 @@ def render_aafigure(app, text, options): raise AafigError(str(e)) extra = None - if options['format'].lower() == 'svg': + if options["format"].lower() == "svg": extra = visitor.get_size_attrs() - f = open(metadata_fname, 'w') + f = open(metadata_fname, "w") f.write(extra) f.close() @@ -207,10 +207,10 @@ def render_aafigure(app, text, options): def setup(app): - app.add_directive('aafig', AafigDirective) - app.connect('doctree-read', render_aafig_images) - app.add_config_value('aafig_format', DEFAULT_FORMATS, 'html') - app.add_config_value('aafig_default_options', dict(), 'html') + app.add_directive("aafig", AafigDirective) + app.connect("doctree-read", render_aafig_images) + app.add_config_value("aafig_format", DEFAULT_FORMATS, "html") + app.add_config_value("aafig_default_options", dict(), "html") # vim: set expandtab shiftwidth=4 softtabstop=4 : diff --git a/docs/conf.py b/docs/conf.py index ebd532c8d57..844c4358c25 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -21,114 +21,114 @@ extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx_autodoc_typehints', - 'sphinx.ext.todo', - 'sphinx.ext.napoleon', - 'sphinx.ext.linkcode', - 'aafig', - 'alagitpull', - 'sphinx_issues', - 'myst_parser', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx_autodoc_typehints", + "sphinx.ext.todo", + "sphinx.ext.napoleon", + "sphinx.ext.linkcode", + "aafig", + "alagitpull", + "sphinx_issues", + "myst_parser", ] myst_enable_extensions = ["colon_fence"] -issues_github_path = about['__github__'].replace('https://github.com/', '') +issues_github_path = about["__github__"].replace("https://github.com/", "") -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = {'.rst': 'restructuredtext', '.md': 'markdown'} +source_suffix = {".rst": "restructuredtext", ".md": "markdown"} -master_doc = 'index' +master_doc = "index" -project = about['__title__'] -copyright = about['__copyright__'] +project = about["__title__"] +copyright = about["__copyright__"] -version = '%s' % ('.'.join(about['__version__'].split('.'))[:2]) -release = '%s' % (about['__version__']) +version = "%s" % (".".join(about["__version__"].split("."))[:2]) +release = "%s" % (about["__version__"]) -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] -pygments_style = 'sphinx' +pygments_style = "sphinx" html_theme_path = [alagitpull.get_path()] -html_theme = 'alagitpull' -html_extra_path = ['manifest.json'] -html_static_path = ['_static'] +html_theme = "alagitpull" +html_extra_path = ["manifest.json"] +html_static_path = ["_static"] html_sidebars = { - '**': [ - 'about.html', - 'navigation.html', - 'relations.html', - 'more.html', - 'book.html', - 'searchbox.html', + "**": [ + "about.html", + "navigation.html", + "relations.html", + "more.html", + "book.html", + "searchbox.html", ] } html_theme_options = { - 'logo': 'img/tmuxp.svg', - 'github_user': 'tmux-python', - 'github_repo': 'tmuxp', - 'github_type': 'star', - 'github_banner': True, - 'projects': alagitpull.projects, - 'project_name': about['__title__'], - 'project_title': about['__title__'], - 'project_description': about['__description__'], - 'project_url': about['__docs__'], - 'show_meta_manifest_tag': True, - 'show_meta_og_tags': True, - 'show_meta_app_icon_tags': True, + "logo": "img/tmuxp.svg", + "github_user": "tmux-python", + "github_repo": "tmuxp", + "github_type": "star", + "github_banner": True, + "projects": alagitpull.projects, + "project_name": about["__title__"], + "project_title": about["__title__"], + "project_description": about["__description__"], + "project_url": about["__docs__"], + "show_meta_manifest_tag": True, + "show_meta_og_tags": True, + "show_meta_app_icon_tags": True, } -alagitpull_internal_hosts = ['tmuxp.git-pull.com', '0.0.0.0'] +alagitpull_internal_hosts = ["tmuxp.git-pull.com", "0.0.0.0"] alagitpull_external_hosts_new_window = True -htmlhelp_basename = '%sdoc' % about['__title__'] +htmlhelp_basename = "%sdoc" % about["__title__"] latex_documents = [ ( - 'index', - '{0}.tex'.format(about['__package_name__']), - '{0} Documentation'.format(about['__title__']), - about['__author__'], - 'manual', + "index", + "{0}.tex".format(about["__package_name__"]), + "{0} Documentation".format(about["__title__"]), + about["__author__"], + "manual", ) ] man_pages = [ ( - 'index', - about['__package_name__'], - '{0} Documentation'.format(about['__title__']), - about['__author__'], + "index", + about["__package_name__"], + "{0} Documentation".format(about["__title__"]), + about["__author__"], 1, ) ] texinfo_documents = [ ( - 'index', - '{0}'.format(about['__package_name__']), - '{0} Documentation'.format(about['__title__']), - about['__author__'], - about['__package_name__'], - about['__description__'], - 'Miscellaneous', + "index", + "{0}".format(about["__package_name__"]), + "{0} Documentation".format(about["__title__"]), + about["__author__"], + about["__package_name__"], + about["__description__"], + "Miscellaneous", ) ] intersphinx_mapping = { - 'python': ('https://docs.python.org/', None), - 'libtmux': ('https://libtmux.git-pull.com/', None), - 'click': ('http://click.pocoo.org/5', None), + "python": ("https://docs.python.org/", None), + "libtmux": ("https://libtmux.git-pull.com/", None), + "click": ("http://click.pocoo.org/5", None), } # aafig format, try to get working with pdf -aafig_format = dict(latex='pdf', html='gif') +aafig_format = dict(latex="pdf", html="gif") aafig_default_options = dict(scale=0.75, aspect=0.5, proportional=True) @@ -142,18 +142,18 @@ def linkcode_resolve(domain, info): # NOQA: C901 From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt """ - if domain != 'py': + if domain != "py": return None - modname = info['module'] - fullname = info['fullname'] + modname = info["module"] + fullname = info["fullname"] submod = sys.modules.get(modname) if submod is None: return None obj = submod - for part in fullname.split('.'): + for part in fullname.split("."): try: obj = getattr(obj, part) except Exception: @@ -187,18 +187,18 @@ def linkcode_resolve(domain, info): # NOQA: C901 fn = relpath(fn, start=dirname(tmuxp.__file__)) - if 'dev' in about['__version__']: + if "dev" in about["__version__"]: return "%s/blob/master/%s/%s%s" % ( - about['__github__'], - about['__package_name__'], + about["__github__"], + about["__package_name__"], fn, linespec, ) else: return "%s/blob/v%s/%s/%s%s" % ( - about['__github__'], - about['__version__'], - about['__package_name__'], + about["__github__"], + about["__version__"], + about["__package_name__"], fn, linespec, ) diff --git a/pyproject.toml b/pyproject.toml index c0b67c05e53..453a16065d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,3 @@ -[tool.black] -skip-string-normalization = true - [tool.poetry] name = "tmuxp" version = "1.9.4" diff --git a/tests/__init__.py b/tests/__init__.py index 8cee3f54f46..89d3f1684f0 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -7,5 +7,5 @@ import os current_dir = os.path.abspath(os.path.dirname(__file__)) -example_dir = os.path.abspath(os.path.join(current_dir, '..', 'examples')) -fixtures_dir = os.path.realpath(os.path.join(current_dir, 'fixtures')) +example_dir = os.path.abspath(os.path.join(current_dir, "..", "examples")) +fixtures_dir = os.path.realpath(os.path.join(current_dir, "fixtures")) diff --git a/tests/conftest.py b/tests/conftest.py index 410171cc8aa..7099fcb8954 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,7 +10,7 @@ logger = logging.getLogger(__name__) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def monkeypatch_plugin_test_packages(monkeypatch): paths = [ "tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bwb/", @@ -24,12 +24,12 @@ def monkeypatch_plugin_test_packages(monkeypatch): monkeypatch.syspath_prepend(os.path.abspath(os.path.relpath(path))) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def socket_name(request): - return 'tmuxp_test%s' % next(namer) + return "tmuxp_test%s" % next(namer) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def server(request, socket_name): t = Server() t.socket_name = socket_name @@ -42,27 +42,27 @@ def fin(): return t -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def session(server): - session_name = 'tmuxp' + session_name = "tmuxp" if not server.has_session(session_name): server.cmd( - '-f', - '/dev/null', # use a blank config to reduce side effects - 'new-session', - '-d', # detached - '-s', + "-f", + "/dev/null", # use a blank config to reduce side effects + "new-session", + "-d", # detached + "-s", session_name, - '/bin/sh', # use /bin/sh as a shell to reduce side effects + "/bin/sh", # use /bin/sh as a shell to reduce side effects # normally, it'd be -c, but new-session is special ) # find current sessions prefixed with tmuxp old_test_sessions = [ - s.get('session_name') + s.get("session_name") for s in server._sessions - if s.get('session_name').startswith(TEST_SESSION_PREFIX) + if s.get("session_name").startswith(TEST_SESSION_PREFIX) ] TEST_SESSION_NAME = get_test_session_name(server=server) @@ -77,22 +77,22 @@ def session(server): the newly created session for that testcase. """ try: - server.switch_client(session.get('session_id')) + server.switch_client(session.get("session_id")) pass except exc.LibTmuxException: # server.attach_session(session.get('session_id')) pass for old_test_session in old_test_sessions: - logger.debug('Old test test session %s found. Killing it.' % old_test_session) + logger.debug("Old test test session %s found. Killing it." % old_test_session) server.kill_session(old_test_session) - assert TEST_SESSION_NAME == session.get('session_name') - assert TEST_SESSION_NAME != 'tmuxp' + assert TEST_SESSION_NAME == session.get("session_name") + assert TEST_SESSION_NAME != "tmuxp" return session @pytest.fixture() def tmpdir(tmpdir_factory): - fn = tmpdir_factory.mktemp('tmuxp') + fn = tmpdir_factory.mktemp("tmuxp") return fn diff --git a/tests/fixtures/config/expand1.py b/tests/fixtures/config/expand1.py index e5d536403c4..d431741ef73 100644 --- a/tests/fixtures/config/expand1.py +++ b/tests/fixtures/config/expand1.py @@ -1,74 +1,74 @@ import os before_config = { - 'session_name': 'sampleconfig', - 'start_directory': '~', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "~", + "windows": [ { - 'window_name': 'editor', - 'panes': [ - {'shell_command': ['vim', 'top']}, - {'shell_command': ['vim']}, - {'shell_command': 'cowsay "hey"'}, + "window_name": "editor", + "panes": [ + {"shell_command": ["vim", "top"]}, + {"shell_command": ["vim"]}, + {"shell_command": 'cowsay "hey"'}, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}], + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}], }, { - 'start_directory': '/var/log', - 'options': {'automatic-rename': True}, - 'panes': [{'shell_command': 'htop'}, 'vim'], + "start_directory": "/var/log", + "options": {"automatic-rename": True}, + "panes": [{"shell_command": "htop"}, "vim"], }, - {'start_directory': './', 'panes': ['pwd']}, - {'start_directory': './asdf/', 'panes': ['pwd']}, - {'start_directory': '../', 'panes': ['pwd']}, - {'panes': ['top']}, + {"start_directory": "./", "panes": ["pwd"]}, + {"start_directory": "./asdf/", "panes": ["pwd"]}, + {"start_directory": "../", "panes": ["pwd"]}, + {"panes": ["top"]}, ], } after_config = { - 'session_name': 'sampleconfig', - 'start_directory': os.path.expanduser('~'), - 'windows': [ + "session_name": "sampleconfig", + "start_directory": os.path.expanduser("~"), + "windows": [ { - 'window_name': 'editor', - 'panes': [ - {'shell_command': ['vim', 'top']}, - {'shell_command': ['vim']}, - {'shell_command': ['cowsay "hey"']}, + "window_name": "editor", + "panes": [ + {"shell_command": ["vim", "top"]}, + {"shell_command": ["vim"]}, + {"shell_command": ['cowsay "hey"']}, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}], + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}], }, { - 'start_directory': '/var/log', - 'options': {'automatic-rename': True}, - 'panes': [{'shell_command': ['htop']}, {'shell_command': ['vim']}], + "start_directory": "/var/log", + "options": {"automatic-rename": True}, + "panes": [{"shell_command": ["htop"]}, {"shell_command": ["vim"]}], }, { - 'start_directory': os.path.normpath( - os.path.join(os.path.expanduser('~'), './') + "start_directory": os.path.normpath( + os.path.join(os.path.expanduser("~"), "./") ), - 'panes': [{'shell_command': ['pwd']}], + "panes": [{"shell_command": ["pwd"]}], }, { - 'start_directory': os.path.normpath( - os.path.join(os.path.expanduser('~'), './asdf') + "start_directory": os.path.normpath( + os.path.join(os.path.expanduser("~"), "./asdf") ), - 'panes': [{'shell_command': ['pwd']}], + "panes": [{"shell_command": ["pwd"]}], }, { - 'start_directory': os.path.normpath( - os.path.join(os.path.expanduser('~'), '../') + "start_directory": os.path.normpath( + os.path.join(os.path.expanduser("~"), "../") ), - 'panes': [{'shell_command': ['pwd']}], + "panes": [{"shell_command": ["pwd"]}], }, - {'panes': [{'shell_command': ['top']}]}, + {"panes": [{"shell_command": ["top"]}]}, ], } diff --git a/tests/fixtures/config/expand2.py b/tests/fixtures/config/expand2.py index 502ed04248b..2673685b616 100644 --- a/tests/fixtures/config/expand2.py +++ b/tests/fixtures/config/expand2.py @@ -2,7 +2,7 @@ from .._util import loadfixture -unexpanded_yaml = loadfixture('config/expand2-unexpanded.yaml') -expanded_yaml = loadfixture('config/expand2-expanded.yaml').format( - HOME=os.path.expanduser('~') +unexpanded_yaml = loadfixture("config/expand2-unexpanded.yaml") +expanded_yaml = loadfixture("config/expand2-expanded.yaml").format( + HOME=os.path.expanduser("~") ) diff --git a/tests/fixtures/config/expand_blank.py b/tests/fixtures/config/expand_blank.py index 13d96e92fd2..78343ca7110 100644 --- a/tests/fixtures/config/expand_blank.py +++ b/tests/fixtures/config/expand_blank.py @@ -1,35 +1,35 @@ expected = { - 'session_name': 'Blank pane test', - 'windows': [ + "session_name": "Blank pane test", + "windows": [ { - 'window_name': 'Blank pane test', - 'panes': [ - {'shell_command': []}, - {'shell_command': []}, - {'shell_command': []}, + "window_name": "Blank pane test", + "panes": [ + {"shell_command": []}, + {"shell_command": []}, + {"shell_command": []}, ], }, { - 'window_name': 'More blank panes', - 'panes': [ - {'shell_command': []}, - {'shell_command': []}, - {'shell_command': []}, + "window_name": "More blank panes", + "panes": [ + {"shell_command": []}, + {"shell_command": []}, + {"shell_command": []}, ], }, { - 'window_name': 'Empty string (return)', - 'panes': [ - {'shell_command': ['']}, - {'shell_command': ['']}, - {'shell_command': ['']}, + "window_name": "Empty string (return)", + "panes": [ + {"shell_command": [""]}, + {"shell_command": [""]}, + {"shell_command": [""]}, ], }, { - 'window_name': 'Blank with options', - 'panes': [ - {'shell_command': [], 'focus': True}, - {'shell_command': [], 'start_directory': '/tmp'}, + "window_name": "Blank with options", + "panes": [ + {"shell_command": [], "focus": True}, + {"shell_command": [], "start_directory": "/tmp"}, ], }, ], diff --git a/tests/fixtures/config/sampleconfig.py b/tests/fixtures/config/sampleconfig.py index 65aee3b87a9..46bc6f2d6fa 100644 --- a/tests/fixtures/config/sampleconfig.py +++ b/tests/fixtures/config/sampleconfig.py @@ -1,24 +1,24 @@ sampleconfigdict = { - 'session_name': 'sampleconfig', - 'start_directory': '~', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "~", + "windows": [ { - 'window_name': 'editor', - 'panes': [ - {'start_directory': '~', 'shell_command': ['vim']}, - {'shell_command': ['cowsay "hey"']}, + "window_name": "editor", + "panes": [ + {"start_directory": "~", "shell_command": ["vim"]}, + {"shell_command": ['cowsay "hey"']}, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [ + "window_name": "logging", + "panes": [ { - 'shell_command': ['tail -F /var/log/syslog'], - 'start_directory': '/var/log', + "shell_command": ["tail -F /var/log/syslog"], + "start_directory": "/var/log", } ], }, - {'options': {'automatic_rename': True}, 'panes': [{'shell_command': ['htop']}]}, + {"options": {"automatic_rename": True}, "panes": [{"shell_command": ["htop"]}]}, ], } diff --git a/tests/fixtures/config/shell_command_before.py b/tests/fixtures/config/shell_command_before.py index 7cc227dc052..2f0b1a69660 100644 --- a/tests/fixtures/config/shell_command_before.py +++ b/tests/fixtures/config/shell_command_before.py @@ -1,125 +1,125 @@ import os config_unexpanded = { # shell_command_before is string in some areas - 'session_name': 'sampleconfig', - 'start_directory': '/', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/", + "windows": [ { - 'window_name': 'editor', - 'start_directory': '~', - 'shell_command_before': 'source .venv/bin/activate', - 'panes': [ - {'shell_command': ['vim']}, + "window_name": "editor", + "start_directory": "~", + "shell_command_before": "source .venv/bin/activate", + "panes": [ + {"shell_command": ["vim"]}, { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': ['cowsay "hey"'], + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": ['cowsay "hey"'], }, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'shell_command_before': 'rbenv local 2.0.0-p0', - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}, {}], + "shell_command_before": "rbenv local 2.0.0-p0", + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}, {}], }, { - 'window_name': 'shufu', - 'panes': [ + "window_name": "shufu", + "panes": [ { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': ['htop'], + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": ["htop"], } ], }, - {'options': {'automatic-rename': True}, 'panes': [{'shell_command': ['htop']}]}, - {'panes': ['top']}, + {"options": {"automatic-rename": True}, "panes": [{"shell_command": ["htop"]}]}, + {"panes": ["top"]}, ], } config_expanded = { # shell_command_before is string in some areas - 'session_name': 'sampleconfig', - 'start_directory': '/', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/", + "windows": [ { - 'window_name': 'editor', - 'start_directory': os.path.expanduser('~'), - 'shell_command_before': ['source .venv/bin/activate'], - 'panes': [ - {'shell_command': ['vim']}, + "window_name": "editor", + "start_directory": os.path.expanduser("~"), + "shell_command_before": ["source .venv/bin/activate"], + "panes": [ + {"shell_command": ["vim"]}, { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': ['cowsay "hey"'], + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": ['cowsay "hey"'], }, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'window_name': 'logging', - 'panes': [ - {'shell_command': ['tail -F /var/log/syslog']}, - {'shell_command': []}, + "shell_command_before": ["rbenv local 2.0.0-p0"], + "window_name": "logging", + "panes": [ + {"shell_command": ["tail -F /var/log/syslog"]}, + {"shell_command": []}, ], }, { - 'window_name': 'shufu', - 'panes': [ + "window_name": "shufu", + "panes": [ { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': ['htop'], + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": ["htop"], } ], }, - {'options': {'automatic-rename': True}, 'panes': [{'shell_command': ['htop']}]}, - {'panes': [{'shell_command': ['top']}]}, + {"options": {"automatic-rename": True}, "panes": [{"shell_command": ["htop"]}]}, + {"panes": [{"shell_command": ["top"]}]}, ], } config_after = { # shell_command_before is string in some areas - 'session_name': 'sampleconfig', - 'start_directory': '/', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/", + "windows": [ { - 'window_name': 'editor', - 'start_directory': os.path.expanduser('~'), - 'shell_command_before': ['source .venv/bin/activate'], - 'panes': [ - {'shell_command': ['source .venv/bin/activate', 'vim']}, + "window_name": "editor", + "start_directory": os.path.expanduser("~"), + "shell_command_before": ["source .venv/bin/activate"], + "panes": [ + {"shell_command": ["source .venv/bin/activate", "vim"]}, { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': [ - 'source .venv/bin/activate', - 'rbenv local 2.0.0-p0', + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": [ + "source .venv/bin/activate", + "rbenv local 2.0.0-p0", 'cowsay "hey"', ], }, ], - 'layout': 'main-verticle', + "layout": "main-verticle", }, { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'start_directory': '/', - 'window_name': 'logging', - 'panes': [ - {'shell_command': ['rbenv local 2.0.0-p0', 'tail -F /var/log/syslog']}, - {'shell_command': ['rbenv local 2.0.0-p0']}, + "shell_command_before": ["rbenv local 2.0.0-p0"], + "start_directory": "/", + "window_name": "logging", + "panes": [ + {"shell_command": ["rbenv local 2.0.0-p0", "tail -F /var/log/syslog"]}, + {"shell_command": ["rbenv local 2.0.0-p0"]}, ], }, { - 'start_directory': '/', - 'window_name': 'shufu', - 'panes': [ + "start_directory": "/", + "window_name": "shufu", + "panes": [ { - 'shell_command_before': ['rbenv local 2.0.0-p0'], - 'shell_command': ['rbenv local 2.0.0-p0', 'htop'], + "shell_command_before": ["rbenv local 2.0.0-p0"], + "shell_command": ["rbenv local 2.0.0-p0", "htop"], } ], }, { - 'start_directory': '/', - 'options': {'automatic-rename': True}, - 'panes': [{'shell_command': ['htop']}], + "start_directory": "/", + "options": {"automatic-rename": True}, + "panes": [{"shell_command": ["htop"]}], }, - {'start_directory': '/', 'panes': [{'shell_command': ['top']}]}, + {"start_directory": "/", "panes": [{"shell_command": ["top"]}]}, ], } diff --git a/tests/fixtures/config/trickle.py b/tests/fixtures/config/trickle.py index 938d6416842..7792ba425a9 100644 --- a/tests/fixtures/config/trickle.py +++ b/tests/fixtures/config/trickle.py @@ -1,40 +1,40 @@ before = { # shell_command_before is string in some areas - 'session_name': 'sampleconfig', - 'start_directory': '/var', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/var", + "windows": [ { - 'window_name': 'editor', - 'start_directory': 'log', - 'panes': [{'shell_command': ['vim']}, {'shell_command': ['cowsay "hey"']}], - 'layout': 'main-verticle', + "window_name": "editor", + "start_directory": "log", + "panes": [{"shell_command": ["vim"]}, {"shell_command": ['cowsay "hey"']}], + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'start_directory': '~', - 'panes': [ - {'shell_command': ['tail -F /var/log/syslog']}, - {'shell_command': []}, + "window_name": "logging", + "start_directory": "~", + "panes": [ + {"shell_command": ["tail -F /var/log/syslog"]}, + {"shell_command": []}, ], }, ], } expected = { # shell_command_before is string in some areas - 'session_name': 'sampleconfig', - 'start_directory': '/var', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/var", + "windows": [ { - 'window_name': 'editor', - 'start_directory': '/var/log', - 'panes': [{'shell_command': ['vim']}, {'shell_command': ['cowsay "hey"']}], - 'layout': 'main-verticle', + "window_name": "editor", + "start_directory": "/var/log", + "panes": [{"shell_command": ["vim"]}, {"shell_command": ['cowsay "hey"']}], + "layout": "main-verticle", }, { - 'start_directory': '~', - 'window_name': 'logging', - 'panes': [ - {'shell_command': ['tail -F /var/log/syslog']}, - {'shell_command': []}, + "start_directory": "~", + "window_name": "logging", + "panes": [ + {"shell_command": ["tail -F /var/log/syslog"]}, + {"shell_command": []}, ], }, ], diff --git a/tests/fixtures/config_teamocil/layouts.py b/tests/fixtures/config_teamocil/layouts.py index 17803cf5321..686f8311c90 100644 --- a/tests/fixtures/config_teamocil/layouts.py +++ b/tests/fixtures/config_teamocil/layouts.py @@ -1,79 +1,79 @@ from .._util import loadfixture -teamocil_yaml = loadfixture('config_teamocil/layouts.yaml') +teamocil_yaml = loadfixture("config_teamocil/layouts.yaml") teamocil_dict = { - 'two-windows': { - 'windows': [ + "two-windows": { + "windows": [ { - 'name': 'foo', - 'clear': True, - 'root': '/foo', - 'layout': 'tiled', - 'panes': [{'cmd': "echo 'foo'"}, {'cmd': "echo 'foo again'"}], + "name": "foo", + "clear": True, + "root": "/foo", + "layout": "tiled", + "panes": [{"cmd": "echo 'foo'"}, {"cmd": "echo 'foo again'"}], }, { - 'name': 'bar', - 'root': '/bar', - 'splits': [ + "name": "bar", + "root": "/bar", + "splits": [ { - 'cmd': ["echo 'bar'", "echo 'bar in an array'"], - 'target': 'bottom-right', + "cmd": ["echo 'bar'", "echo 'bar in an array'"], + "target": "bottom-right", }, - {'cmd': "echo 'bar again'", 'focus': True, 'width': 50}, + {"cmd": "echo 'bar again'", "focus": True, "width": 50}, ], }, ] }, - 'two-windows-with-filters': { - 'windows': [ + "two-windows-with-filters": { + "windows": [ { - 'name': 'foo', - 'root': '/foo', - 'filters': { - 'before': ['echo first before filter', 'echo second before filter'], - 'after': ['echo first after filter', 'echo second after filter'], + "name": "foo", + "root": "/foo", + "filters": { + "before": ["echo first before filter", "echo second before filter"], + "after": ["echo first after filter", "echo second after filter"], }, - 'panes': [ - {'cmd': "echo 'foo'"}, - {'cmd': "echo 'foo again'", 'width': 50}, + "panes": [ + {"cmd": "echo 'foo'"}, + {"cmd": "echo 'foo again'", "width": 50}, ], } ] }, - 'two-windows-with-custom-command-options': { - 'windows': [ + "two-windows-with-custom-command-options": { + "windows": [ { - 'name': 'foo', - 'cmd_separator': '\n', - 'with_env_var': False, - 'clear': True, - 'root': '/foo', - 'layout': 'tiled', - 'panes': [{'cmd': "echo 'foo'"}, {'cmd': "echo 'foo again'"}], + "name": "foo", + "cmd_separator": "\n", + "with_env_var": False, + "clear": True, + "root": "/foo", + "layout": "tiled", + "panes": [{"cmd": "echo 'foo'"}, {"cmd": "echo 'foo again'"}], }, { - 'name': 'bar', - 'cmd_separator': ' && ', - 'with_env_var': True, - 'root': '/bar', - 'splits': [ + "name": "bar", + "cmd_separator": " && ", + "with_env_var": True, + "root": "/bar", + "splits": [ { - 'cmd': ["echo 'bar'", "echo 'bar in an array'"], - 'target': 'bottom-right', + "cmd": ["echo 'bar'", "echo 'bar in an array'"], + "target": "bottom-right", }, - {'cmd': "echo 'bar again'", 'focus': True, 'width': 50}, + {"cmd": "echo 'bar again'", "focus": True, "width": 50}, ], }, ] }, - 'three-windows-within-a-session': { - 'session': { - 'name': 'my awesome session', - 'windows': [ - {'name': 'first window', 'panes': [{'cmd': "echo 'foo'"}]}, - {'name': 'second window', 'panes': [{'cmd': "echo 'foo'"}]}, - {'name': 'third window', 'panes': [{'cmd': "echo 'foo'"}]}, + "three-windows-within-a-session": { + "session": { + "name": "my awesome session", + "windows": [ + {"name": "first window", "panes": [{"cmd": "echo 'foo'"}]}, + {"name": "second window", "panes": [{"cmd": "echo 'foo'"}]}, + {"name": "third window", "panes": [{"cmd": "echo 'foo'"}]}, ], } }, @@ -81,86 +81,86 @@ two_windows = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'foo', - 'start_directory': '/foo', - 'clear': True, - 'layout': 'tiled', - 'panes': [ - {'shell_command': "echo 'foo'"}, - {'shell_command': "echo 'foo again'"}, + "window_name": "foo", + "start_directory": "/foo", + "clear": True, + "layout": "tiled", + "panes": [ + {"shell_command": "echo 'foo'"}, + {"shell_command": "echo 'foo again'"}, ], }, { - 'window_name': 'bar', - 'start_directory': '/bar', - 'panes': [ + "window_name": "bar", + "start_directory": "/bar", + "panes": [ { - 'shell_command': ["echo 'bar'", "echo 'bar in an array'"], - 'target': 'bottom-right', + "shell_command": ["echo 'bar'", "echo 'bar in an array'"], + "target": "bottom-right", }, - {'shell_command': "echo 'bar again'", 'focus': True}, + {"shell_command": "echo 'bar again'", "focus": True}, ], }, ], } two_windows_with_filters = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'foo', - 'start_directory': '/foo', - 'shell_command_before': [ - 'echo first before filter', - 'echo second before filter', + "window_name": "foo", + "start_directory": "/foo", + "shell_command_before": [ + "echo first before filter", + "echo second before filter", ], - 'shell_command_after': [ - 'echo first after filter', - 'echo second after filter', + "shell_command_after": [ + "echo first after filter", + "echo second after filter", ], - 'panes': [ - {'shell_command': "echo 'foo'"}, - {'shell_command': "echo 'foo again'"}, + "panes": [ + {"shell_command": "echo 'foo'"}, + {"shell_command": "echo 'foo again'"}, ], } ], } two_windows_with_custom_command_options = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'foo', - 'start_directory': '/foo', - 'clear': True, - 'layout': 'tiled', - 'panes': [ - {'shell_command': "echo 'foo'"}, - {'shell_command': "echo 'foo again'"}, + "window_name": "foo", + "start_directory": "/foo", + "clear": True, + "layout": "tiled", + "panes": [ + {"shell_command": "echo 'foo'"}, + {"shell_command": "echo 'foo again'"}, ], }, { - 'window_name': 'bar', - 'start_directory': '/bar', - 'panes': [ + "window_name": "bar", + "start_directory": "/bar", + "panes": [ { - 'shell_command': ["echo 'bar'", "echo 'bar in an array'"], - 'target': 'bottom-right', + "shell_command": ["echo 'bar'", "echo 'bar in an array'"], + "target": "bottom-right", }, - {'shell_command': "echo 'bar again'", 'focus': True}, + {"shell_command": "echo 'bar again'", "focus": True}, ], }, ], } three_windows_within_a_session = { - 'session_name': 'my awesome session', - 'windows': [ - {'window_name': 'first window', 'panes': [{'shell_command': "echo 'foo'"}]}, - {'window_name': 'second window', 'panes': [{'shell_command': "echo 'foo'"}]}, - {'window_name': 'third window', 'panes': [{'shell_command': "echo 'foo'"}]}, + "session_name": "my awesome session", + "windows": [ + {"window_name": "first window", "panes": [{"shell_command": "echo 'foo'"}]}, + {"window_name": "second window", "panes": [{"shell_command": "echo 'foo'"}]}, + {"window_name": "third window", "panes": [{"shell_command": "echo 'foo'"}]}, ], } diff --git a/tests/fixtures/config_teamocil/test1.py b/tests/fixtures/config_teamocil/test1.py index 0ea0dfa73f0..9633095710b 100644 --- a/tests/fixtures/config_teamocil/test1.py +++ b/tests/fixtures/config_teamocil/test1.py @@ -1,27 +1,27 @@ from .._util import loadfixture -teamocil_yaml = loadfixture('config_teamocil/test1.yaml') +teamocil_yaml = loadfixture("config_teamocil/test1.yaml") teamocil_conf = { - 'windows': [ + "windows": [ { - 'name': 'sample-two-panes', - 'root': '~/Code/sample/www', - 'layout': 'even-horizontal', - 'panes': [{'cmd': ['pwd', 'ls -la']}, {'cmd': 'rails server --port 3000'}], + "name": "sample-two-panes", + "root": "~/Code/sample/www", + "layout": "even-horizontal", + "panes": [{"cmd": ["pwd", "ls -la"]}, {"cmd": "rails server --port 3000"}], } ] } expected = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'sample-two-panes', - 'layout': 'even-horizontal', - 'start_directory': '~/Code/sample/www', - 'panes': [ - {'shell_command': ['pwd', 'ls -la']}, - {'shell_command': 'rails server --port 3000'}, + "window_name": "sample-two-panes", + "layout": "even-horizontal", + "start_directory": "~/Code/sample/www", + "panes": [ + {"shell_command": ["pwd", "ls -la"]}, + {"shell_command": "rails server --port 3000"}, ], } ], diff --git a/tests/fixtures/config_teamocil/test2.py b/tests/fixtures/config_teamocil/test2.py index 85ea65a82f8..e9a0f69b6c1 100644 --- a/tests/fixtures/config_teamocil/test2.py +++ b/tests/fixtures/config_teamocil/test2.py @@ -1,29 +1,29 @@ from .._util import loadfixture -teamocil_yaml = loadfixture('config_teamocil/test2.yaml') +teamocil_yaml = loadfixture("config_teamocil/test2.yaml") teamocil_dict = { - 'windows': [ + "windows": [ { - 'name': 'sample-four-panes', - 'root': '~/Code/sample/www', - 'layout': 'tiled', - 'panes': [{'cmd': 'pwd'}, {'cmd': 'pwd'}, {'cmd': 'pwd'}, {'cmd': 'pwd'}], + "name": "sample-four-panes", + "root": "~/Code/sample/www", + "layout": "tiled", + "panes": [{"cmd": "pwd"}, {"cmd": "pwd"}, {"cmd": "pwd"}, {"cmd": "pwd"}], } ] } expected = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'sample-four-panes', - 'layout': 'tiled', - 'start_directory': '~/Code/sample/www', - 'panes': [ - {'shell_command': 'pwd'}, - {'shell_command': 'pwd'}, - {'shell_command': 'pwd'}, - {'shell_command': 'pwd'}, + "window_name": "sample-four-panes", + "layout": "tiled", + "start_directory": "~/Code/sample/www", + "panes": [ + {"shell_command": "pwd"}, + {"shell_command": "pwd"}, + {"shell_command": "pwd"}, + {"shell_command": "pwd"}, ], } ], diff --git a/tests/fixtures/config_teamocil/test3.py b/tests/fixtures/config_teamocil/test3.py index 2406f2b0f5d..0bc92980f24 100644 --- a/tests/fixtures/config_teamocil/test3.py +++ b/tests/fixtures/config_teamocil/test3.py @@ -1,42 +1,42 @@ from .._util import loadfixture -teamocil_yaml = loadfixture('config_teamocil/test3.yaml') +teamocil_yaml = loadfixture("config_teamocil/test3.yaml") teamocil_dict = { - 'windows': [ + "windows": [ { - 'name': 'my-first-window', - 'root': '~/Projects/foo-www', - 'layout': 'even-vertical', - 'filters': { - 'before': 'rbenv local 2.0.0-p0', - 'after': 'echo \'I am done initializing this pane.\'', + "name": "my-first-window", + "root": "~/Projects/foo-www", + "layout": "even-vertical", + "filters": { + "before": "rbenv local 2.0.0-p0", + "after": "echo 'I am done initializing this pane.'", }, - 'panes': [ - {'cmd': 'git status'}, - {'cmd': 'bundle exec rails server --port 40', 'focus': True}, - {'cmd': ['sudo service memcached start', 'sudo service mongodb start']}, + "panes": [ + {"cmd": "git status"}, + {"cmd": "bundle exec rails server --port 40", "focus": True}, + {"cmd": ["sudo service memcached start", "sudo service mongodb start"]}, ], } ] } expected = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'my-first-window', - 'layout': 'even-vertical', - 'start_directory': "~/Projects/foo-www", - 'shell_command_before': 'rbenv local 2.0.0-p0', - 'shell_command_after': ('echo ' '\'I am done initializing this pane.\''), - 'panes': [ - {'shell_command': 'git status'}, - {'shell_command': 'bundle exec rails server --port 40', 'focus': True}, + "window_name": "my-first-window", + "layout": "even-vertical", + "start_directory": "~/Projects/foo-www", + "shell_command_before": "rbenv local 2.0.0-p0", + "shell_command_after": ("echo " "'I am done initializing this pane.'"), + "panes": [ + {"shell_command": "git status"}, + {"shell_command": "bundle exec rails server --port 40", "focus": True}, { - 'shell_command': [ - 'sudo service memcached start', - 'sudo service mongodb start', + "shell_command": [ + "sudo service memcached start", + "sudo service mongodb start", ] }, ], diff --git a/tests/fixtures/config_teamocil/test4.py b/tests/fixtures/config_teamocil/test4.py index b9b5f97a354..5827bfcabdf 100644 --- a/tests/fixtures/config_teamocil/test4.py +++ b/tests/fixtures/config_teamocil/test4.py @@ -1,24 +1,24 @@ from .._util import loadfixture -teamocil_yaml = loadfixture('config_teamocil/test4.yaml') +teamocil_yaml = loadfixture("config_teamocil/test4.yaml") teamocil_dict = { - 'windows': [ + "windows": [ { - 'name': 'erb-example', - 'root': "<%= ENV['MY_PROJECT_ROOT'] %>", - 'panes': [{'cmd': 'pwd'}], + "name": "erb-example", + "root": "<%= ENV['MY_PROJECT_ROOT'] %>", + "panes": [{"cmd": "pwd"}], } ] } expected = { - 'session_name': None, - 'windows': [ + "session_name": None, + "windows": [ { - 'window_name': 'erb-example', - 'start_directory': "<%= ENV['MY_PROJECT_ROOT'] %>", - 'panes': [{'shell_command': 'pwd'}], + "window_name": "erb-example", + "start_directory": "<%= ENV['MY_PROJECT_ROOT'] %>", + "panes": [{"shell_command": "pwd"}], } ], } diff --git a/tests/fixtures/config_tmuxinator/test1.py b/tests/fixtures/config_tmuxinator/test1.py index 2fe873812d8..138671942ef 100644 --- a/tests/fixtures/config_tmuxinator/test1.py +++ b/tests/fixtures/config_tmuxinator/test1.py @@ -1,19 +1,19 @@ from .._util import loadfixture -tmuxinator_yaml = loadfixture('config_tmuxinator/test1.yaml') +tmuxinator_yaml = loadfixture("config_tmuxinator/test1.yaml") tmuxinator_dict = { - 'windows': [ - {'editor': {'layout': 'main-vertical', 'panes': ['vim', 'guard']}}, - {'server': 'bundle exec rails s'}, - {'logs': 'tail -f logs/development.log'}, + "windows": [ + {"editor": {"layout": "main-vertical", "panes": ["vim", "guard"]}}, + {"server": "bundle exec rails s"}, + {"logs": "tail -f logs/development.log"}, ] } expected = { - 'session_name': None, - 'windows': [ - {'window_name': 'editor', 'layout': 'main-vertical', 'panes': ['vim', 'guard']}, - {'window_name': 'server', 'panes': ['bundle exec rails s']}, - {'window_name': 'logs', 'panes': ['tail -f logs/development.log']}, + "session_name": None, + "windows": [ + {"window_name": "editor", "layout": "main-vertical", "panes": ["vim", "guard"]}, + {"window_name": "server", "panes": ["bundle exec rails s"]}, + {"window_name": "logs", "panes": ["tail -f logs/development.log"]}, ], } diff --git a/tests/fixtures/config_tmuxinator/test2.py b/tests/fixtures/config_tmuxinator/test2.py index fe32160f042..23273bf7ddf 100644 --- a/tests/fixtures/config_tmuxinator/test2.py +++ b/tests/fixtures/config_tmuxinator/test2.py @@ -1,76 +1,76 @@ from .._util import loadfixture -tmuxinator_yaml = loadfixture('config_tmuxinator/test2.yaml') +tmuxinator_yaml = loadfixture("config_tmuxinator/test2.yaml") tmuxinator_dict = { - 'project_name': 'sample', - 'project_root': '~/test', - 'socket_name': 'foo', - 'pre': 'sudo /etc/rc.d/mysqld start', - 'rbenv': '2.0.0-p247', - 'cli_args': '-f ~/.tmux.mac.conf', - 'tabs': [ + "project_name": "sample", + "project_root": "~/test", + "socket_name": "foo", + "pre": "sudo /etc/rc.d/mysqld start", + "rbenv": "2.0.0-p247", + "cli_args": "-f ~/.tmux.mac.conf", + "tabs": [ { - 'editor': { - 'pre': [ + "editor": { + "pre": [ 'echo "I get run in each pane, ' 'before each pane command!"', None, ], - 'layout': 'main-vertical', - 'panes': ['vim', None, 'top'], + "layout": "main-vertical", + "panes": ["vim", None, "top"], } }, - {'shell': 'git pull'}, + {"shell": "git pull"}, { - 'guard': { - 'layout': 'tiled', - 'pre': [ + "guard": { + "layout": "tiled", + "pre": [ 'echo "I get run in each pane."', 'echo "Before each pane command!"', ], - 'panes': [None, None, None], + "panes": [None, None, None], } }, - {'database': 'bundle exec rails db'}, - {'server': 'bundle exec rails s'}, - {'logs': 'tail -f log/development.log'}, - {'console': 'bundle exec rails c'}, - {'capistrano': None}, - {'server': 'ssh user@example.com'}, + {"database": "bundle exec rails db"}, + {"server": "bundle exec rails s"}, + {"logs": "tail -f log/development.log"}, + {"console": "bundle exec rails c"}, + {"capistrano": None}, + {"server": "ssh user@example.com"}, ], } expected = { - 'session_name': 'sample', - 'socket_name': 'foo', - 'config': '~/.tmux.mac.conf', - 'start_directory': '~/test', - 'shell_command_before': ['sudo /etc/rc.d/mysqld start', 'rbenv shell 2.0.0-p247'], - 'windows': [ + "session_name": "sample", + "socket_name": "foo", + "config": "~/.tmux.mac.conf", + "start_directory": "~/test", + "shell_command_before": ["sudo /etc/rc.d/mysqld start", "rbenv shell 2.0.0-p247"], + "windows": [ { - 'window_name': 'editor', - 'shell_command_before': [ + "window_name": "editor", + "shell_command_before": [ 'echo "I get run in each pane, before each pane command!"', None, ], - 'layout': 'main-vertical', - 'panes': ['vim', None, 'top'], + "layout": "main-vertical", + "panes": ["vim", None, "top"], }, - {'window_name': 'shell', 'panes': ['git pull']}, + {"window_name": "shell", "panes": ["git pull"]}, { - 'window_name': 'guard', - 'layout': 'tiled', - 'shell_command_before': [ + "window_name": "guard", + "layout": "tiled", + "shell_command_before": [ 'echo "I get run in each pane."', 'echo "Before each pane command!"', ], - 'panes': [None, None, None], + "panes": [None, None, None], }, - {'window_name': 'database', 'panes': ['bundle exec rails db']}, - {'window_name': 'server', 'panes': ['bundle exec rails s']}, - {'window_name': 'logs', 'panes': ['tail -f log/development.log']}, - {'window_name': 'console', 'panes': ['bundle exec rails c']}, - {'window_name': 'capistrano', 'panes': [None]}, - {'window_name': 'server', 'panes': ['ssh user@example.com']}, + {"window_name": "database", "panes": ["bundle exec rails db"]}, + {"window_name": "server", "panes": ["bundle exec rails s"]}, + {"window_name": "logs", "panes": ["tail -f log/development.log"]}, + {"window_name": "console", "panes": ["bundle exec rails c"]}, + {"window_name": "capistrano", "panes": [None]}, + {"window_name": "server", "panes": ["ssh user@example.com"]}, ], } diff --git a/tests/fixtures/config_tmuxinator/test3.py b/tests/fixtures/config_tmuxinator/test3.py index 9e5698083de..df2353f5c01 100644 --- a/tests/fixtures/config_tmuxinator/test3.py +++ b/tests/fixtures/config_tmuxinator/test3.py @@ -1,79 +1,79 @@ from .._util import loadfixture -tmuxinator_yaml = loadfixture('config_tmuxinator/test3.yaml') +tmuxinator_yaml = loadfixture("config_tmuxinator/test3.yaml") tmuxinator_dict = { - 'name': 'sample', - 'root': '~/test', - 'socket_name': 'foo', - 'tmux_options': '-f ~/.tmux.mac.conf', - 'pre': 'sudo /etc/rc.d/mysqld start', - 'pre_window': 'rbenv shell 2.0.0-p247', - 'windows': [ + "name": "sample", + "root": "~/test", + "socket_name": "foo", + "tmux_options": "-f ~/.tmux.mac.conf", + "pre": "sudo /etc/rc.d/mysqld start", + "pre_window": "rbenv shell 2.0.0-p247", + "windows": [ { - 'editor': { - 'pre': [ + "editor": { + "pre": [ 'echo "I get run in each pane, ' 'before each pane command!"', None, ], - 'layout': 'main-vertical', - 'root': '~/test/editor', - 'panes': ['vim', None, 'top'], + "layout": "main-vertical", + "root": "~/test/editor", + "panes": ["vim", None, "top"], } }, - {'shell': ['git pull', 'git merge']}, + {"shell": ["git pull", "git merge"]}, { - 'guard': { - 'layout': 'tiled', - 'pre': [ + "guard": { + "layout": "tiled", + "pre": [ 'echo "I get run in each pane."', 'echo "Before each pane command!"', ], - 'panes': [None, None, None], + "panes": [None, None, None], } }, - {'database': 'bundle exec rails db'}, - {'server': 'bundle exec rails s'}, - {'logs': 'tail -f log/development.log'}, - {'console': 'bundle exec rails c'}, - {'capistrano': None}, - {'server': 'ssh user@example.com'}, + {"database": "bundle exec rails db"}, + {"server": "bundle exec rails s"}, + {"logs": "tail -f log/development.log"}, + {"console": "bundle exec rails c"}, + {"capistrano": None}, + {"server": "ssh user@example.com"}, ], } expected = { - 'session_name': 'sample', - 'socket_name': 'foo', - 'start_directory': '~/test', - 'config': '~/.tmux.mac.conf', - 'shell_command': 'sudo /etc/rc.d/mysqld start', - 'shell_command_before': ['rbenv shell 2.0.0-p247'], - 'windows': [ + "session_name": "sample", + "socket_name": "foo", + "start_directory": "~/test", + "config": "~/.tmux.mac.conf", + "shell_command": "sudo /etc/rc.d/mysqld start", + "shell_command_before": ["rbenv shell 2.0.0-p247"], + "windows": [ { - 'window_name': 'editor', - 'shell_command_before': [ + "window_name": "editor", + "shell_command_before": [ 'echo "I get run in each pane, before each pane command!"', None, ], - 'layout': 'main-vertical', - 'start_directory': '~/test/editor', - 'panes': ['vim', None, 'top'], + "layout": "main-vertical", + "start_directory": "~/test/editor", + "panes": ["vim", None, "top"], }, - {'window_name': 'shell', 'panes': ['git pull', 'git merge']}, + {"window_name": "shell", "panes": ["git pull", "git merge"]}, { - 'window_name': 'guard', - 'layout': 'tiled', - 'shell_command_before': [ + "window_name": "guard", + "layout": "tiled", + "shell_command_before": [ 'echo "I get run in each pane."', 'echo "Before each pane command!"', ], - 'panes': [None, None, None], + "panes": [None, None, None], }, - {'window_name': 'database', 'panes': ['bundle exec rails db']}, - {'window_name': 'server', 'panes': ['bundle exec rails s']}, - {'window_name': 'logs', 'panes': ['tail -f log/development.log']}, - {'window_name': 'console', 'panes': ['bundle exec rails c']}, - {'window_name': 'capistrano', 'panes': [None]}, - {'window_name': 'server', 'panes': ['ssh user@example.com']}, + {"window_name": "database", "panes": ["bundle exec rails db"]}, + {"window_name": "server", "panes": ["bundle exec rails s"]}, + {"window_name": "logs", "panes": ["tail -f log/development.log"]}, + {"window_name": "console", "panes": ["bundle exec rails c"]}, + {"window_name": "capistrano", "panes": [None]}, + {"window_name": "server", "panes": ["ssh user@example.com"]}, ], } diff --git a/tests/fixtures/pluginsystem/partials/all_pass.py b/tests/fixtures/pluginsystem/partials/all_pass.py index 19da4b6e63e..72c4116a427 100644 --- a/tests/fixtures/pluginsystem/partials/all_pass.py +++ b/tests/fixtures/pluginsystem/partials/all_pass.py @@ -4,17 +4,17 @@ class AllVersionPassPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmuxp-plugin-my-tmuxp-plugin', - 'tmux_min_version': '1.8', - 'tmux_max_version': '100.0', - 'tmux_version_incompatible': ['2.3'], - 'libtmux_min_version': '0.8.3', - 'libtmux_max_version': '100.0', - 'libtmux_version_incompatible': ['0.7.1'], - 'tmuxp_min_version': '1.7.0', - 'tmuxp_max_version': '100.0.0', - 'tmuxp_version_incompatible': ['1.5.6'], - 'tmux_version': '3.0', - 'tmuxp_version': '1.7.0', + "plugin_name": "tmuxp-plugin-my-tmuxp-plugin", + "tmux_min_version": "1.8", + "tmux_max_version": "100.0", + "tmux_version_incompatible": ["2.3"], + "libtmux_min_version": "0.8.3", + "libtmux_max_version": "100.0", + "libtmux_version_incompatible": ["0.7.1"], + "tmuxp_min_version": "1.7.0", + "tmuxp_max_version": "100.0.0", + "tmuxp_version_incompatible": ["1.5.6"], + "tmux_version": "3.0", + "tmuxp_version": "1.7.0", } MyTestTmuxpPlugin.__init__(self, config) diff --git a/tests/fixtures/pluginsystem/partials/libtmux_version_fail.py b/tests/fixtures/pluginsystem/partials/libtmux_version_fail.py index 8e7535cab1d..80d992f415b 100644 --- a/tests/fixtures/pluginsystem/partials/libtmux_version_fail.py +++ b/tests/fixtures/pluginsystem/partials/libtmux_version_fail.py @@ -4,9 +4,9 @@ class LibtmuxVersionFailMinPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'libtmux-min-version-fail', - 'libtmux_min_version': '0.8.3', - 'libtmux_version': '0.7.0', + "plugin_name": "libtmux-min-version-fail", + "libtmux_min_version": "0.8.3", + "libtmux_version": "0.7.0", } MyTestTmuxpPlugin.__init__(self, config) @@ -14,9 +14,9 @@ def __init__(self): class LibtmuxVersionFailMaxPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'libtmux-max-version-fail', - 'libtmux_max_version': '3.0', - 'libtmux_version': '3.5', + "plugin_name": "libtmux-max-version-fail", + "libtmux_max_version": "3.0", + "libtmux_version": "3.5", } MyTestTmuxpPlugin.__init__(self, config) @@ -24,8 +24,8 @@ def __init__(self): class LibtmuxVersionFailIncompatiblePlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'libtmux-incompatible-version-fail', - 'libtmux_version_incompatible': ['0.7.1'], - 'libtmux_version': '0.7.1', + "plugin_name": "libtmux-incompatible-version-fail", + "libtmux_version_incompatible": ["0.7.1"], + "libtmux_version": "0.7.1", } MyTestTmuxpPlugin.__init__(self, config) diff --git a/tests/fixtures/pluginsystem/partials/test_plugin_helpers.py b/tests/fixtures/pluginsystem/partials/test_plugin_helpers.py index d58eca8dd85..1ca4ec5fa7e 100644 --- a/tests/fixtures/pluginsystem/partials/test_plugin_helpers.py +++ b/tests/fixtures/pluginsystem/partials/test_plugin_helpers.py @@ -3,18 +3,18 @@ class MyTestTmuxpPlugin(TmuxpPlugin): def __init__(self, config): - tmux_version = config.pop('tmux_version', None) - libtmux_version = config.pop('libtmux_version', None) - tmuxp_version = config.pop('tmuxp_version', None) + tmux_version = config.pop("tmux_version", None) + libtmux_version = config.pop("libtmux_version", None) + tmuxp_version = config.pop("tmuxp_version", None) TmuxpPlugin.__init__(self, **config) # WARNING! This should not be done in anything but a test if tmux_version: - self.version_constraints['tmux']['version'] = tmux_version + self.version_constraints["tmux"]["version"] = tmux_version if libtmux_version: - self.version_constraints['libtmux']['version'] = libtmux_version + self.version_constraints["libtmux"]["version"] = libtmux_version if tmuxp_version: - self.version_constraints['tmuxp']['version'] = tmuxp_version + self.version_constraints["tmuxp"]["version"] = tmuxp_version self._version_check() diff --git a/tests/fixtures/pluginsystem/partials/tmux_version_fail.py b/tests/fixtures/pluginsystem/partials/tmux_version_fail.py index 19ffbb1e086..48b2f95f883 100644 --- a/tests/fixtures/pluginsystem/partials/tmux_version_fail.py +++ b/tests/fixtures/pluginsystem/partials/tmux_version_fail.py @@ -4,9 +4,9 @@ class TmuxVersionFailMinPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmux-min-version-fail', - 'tmux_min_version': '1.8', - 'tmux_version': '1.7', + "plugin_name": "tmux-min-version-fail", + "tmux_min_version": "1.8", + "tmux_version": "1.7", } MyTestTmuxpPlugin.__init__(self, config) @@ -14,9 +14,9 @@ def __init__(self): class TmuxVersionFailMaxPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmux-max-version-fail', - 'tmux_max_version': '3.0', - 'tmux_version': '3.5', + "plugin_name": "tmux-max-version-fail", + "tmux_max_version": "3.0", + "tmux_version": "3.5", } MyTestTmuxpPlugin.__init__(self, config) @@ -24,9 +24,9 @@ def __init__(self): class TmuxVersionFailIncompatiblePlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmux-incompatible-version-fail', - 'tmux_version_incompatible': ['2.3'], - 'tmux_version': '2.3', + "plugin_name": "tmux-incompatible-version-fail", + "tmux_version_incompatible": ["2.3"], + "tmux_version": "2.3", } MyTestTmuxpPlugin.__init__(self, config) diff --git a/tests/fixtures/pluginsystem/partials/tmuxp_version_fail.py b/tests/fixtures/pluginsystem/partials/tmuxp_version_fail.py index 47c4a8e82c3..861f1cfcb82 100644 --- a/tests/fixtures/pluginsystem/partials/tmuxp_version_fail.py +++ b/tests/fixtures/pluginsystem/partials/tmuxp_version_fail.py @@ -4,9 +4,9 @@ class TmuxpVersionFailMinPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmuxp-min-version-fail', - 'tmuxp_min_version': '1.7.0', - 'tmuxp_version': '1.6.3', + "plugin_name": "tmuxp-min-version-fail", + "tmuxp_min_version": "1.7.0", + "tmuxp_version": "1.6.3", } MyTestTmuxpPlugin.__init__(self, config) @@ -14,9 +14,9 @@ def __init__(self): class TmuxpVersionFailMaxPlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmuxp-max-version-fail', - 'tmuxp_max_version': '2.0.0', - 'tmuxp_version': '2.5', + "plugin_name": "tmuxp-max-version-fail", + "tmuxp_max_version": "2.0.0", + "tmuxp_version": "2.5", } MyTestTmuxpPlugin.__init__(self, config) @@ -24,8 +24,8 @@ def __init__(self): class TmuxpVersionFailIncompatiblePlugin(MyTestTmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmuxp-incompatible-version-fail', - 'tmuxp_version_incompatible': ['1.5.0'], - 'tmuxp_version': '1.5.0', + "plugin_name": "tmuxp-incompatible-version-fail", + "tmuxp_version_incompatible": ["1.5.0"], + "tmuxp_version": "1.5.0", } MyTestTmuxpPlugin.__init__(self, config) diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_awf/tmuxp_test_plugin_awf/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_awf/tmuxp_test_plugin_awf/plugin.py index 442f86e2677..fb3ddc35727 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_awf/tmuxp_test_plugin_awf/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_awf/tmuxp_test_plugin_awf/plugin.py @@ -3,16 +3,16 @@ class PluginAfterWindowFinished(TmuxpPlugin): def __init__(self): - self.message = '[+] This is the Tmuxp Test Plugin' + self.message = "[+] This is the Tmuxp Test Plugin" def after_window_finished(self, window): - if window.name == 'editor': - window.rename_window('plugin_test_awf') - elif window.name == 'awf_mw_test': - window.rename_window('plugin_test_awf_mw') - elif window.name == 'awf_mw_test_2': - window.rename_window('plugin_test_awf_mw_2') - elif window.name == 'mp_test_owc': - window.rename_window('mp_test_awf') + if window.name == "editor": + window.rename_window("plugin_test_awf") + elif window.name == "awf_mw_test": + window.rename_window("plugin_test_awf_mw") + elif window.name == "awf_mw_test_2": + window.rename_window("plugin_test_awf_mw_2") + elif window.name == "mp_test_owc": + window.rename_window("mp_test_awf") else: pass diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bs/tmuxp_test_plugin_bs/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bs/tmuxp_test_plugin_bs/plugin.py index 98692ac9f30..faacc0cd862 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bs/tmuxp_test_plugin_bs/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bs/tmuxp_test_plugin_bs/plugin.py @@ -3,7 +3,7 @@ class PluginBeforeScript(TmuxpPlugin): def __init__(self): - self.message = '[+] This is the Tmuxp Test Plugin' + self.message = "[+] This is the Tmuxp Test Plugin" def before_script(self, session): - session.rename_session('plugin_test_bs') + session.rename_session("plugin_test_bs") diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bwb/tmuxp_test_plugin_bwb/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bwb/tmuxp_test_plugin_bwb/plugin.py index 78fd68f28b0..aa9cb1419e6 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bwb/tmuxp_test_plugin_bwb/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_bwb/tmuxp_test_plugin_bwb/plugin.py @@ -3,7 +3,7 @@ class PluginBeforeWorkspaceBuilder(TmuxpPlugin): def __init__(self): - self.message = '[+] This is the Tmuxp Test Plugin' + self.message = "[+] This is the Tmuxp Test Plugin" def before_workspace_builder(self, session): - session.rename_session('plugin_test_bwb') + session.rename_session("plugin_test_bwb") diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_fail/tmuxp_test_plugin_fail/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_fail/tmuxp_test_plugin_fail/plugin.py index abe56e46c75..4de06ee2e72 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_fail/tmuxp_test_plugin_fail/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_fail/tmuxp_test_plugin_fail/plugin.py @@ -4,7 +4,7 @@ class PluginFailVersion(TmuxpPlugin): def __init__(self): config = { - 'plugin_name': 'tmuxp-plugin-fail-version', - 'tmuxp_max_version': '0.0.0', + "plugin_name": "tmuxp-plugin-fail-version", + "tmuxp_max_version": "0.0.0", } TmuxpPlugin.__init__(self, **config) diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_owc/tmuxp_test_plugin_owc/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_owc/tmuxp_test_plugin_owc/plugin.py index 2ba059cd4d8..0c6af1dc698 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_owc/tmuxp_test_plugin_owc/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_owc/tmuxp_test_plugin_owc/plugin.py @@ -3,16 +3,16 @@ class PluginOnWindowCreate(TmuxpPlugin): def __init__(self): - self.message = '[+] This is the Tmuxp Test Plugin' + self.message = "[+] This is the Tmuxp Test Plugin" def on_window_create(self, window): - if window.name == 'editor': - window.rename_window('plugin_test_owc') - elif window.name == 'owc_mw_test': - window.rename_window('plugin_test_owc_mw') - elif window.name == 'owc_mw_test_2': - window.rename_window('plugin_test_owc_mw_2') - elif window.name == 'mp_test': - window.rename_window('mp_test_owc') + if window.name == "editor": + window.rename_window("plugin_test_owc") + elif window.name == "owc_mw_test": + window.rename_window("plugin_test_owc_mw") + elif window.name == "owc_mw_test_2": + window.rename_window("plugin_test_owc_mw_2") + elif window.name == "mp_test": + window.rename_window("mp_test_owc") else: pass diff --git a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_r/tmuxp_test_plugin_r/plugin.py b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_r/tmuxp_test_plugin_r/plugin.py index ccf251142a0..1cc6ccb8f03 100644 --- a/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_r/tmuxp_test_plugin_r/plugin.py +++ b/tests/fixtures/pluginsystem/plugins/tmuxp_test_plugin_r/tmuxp_test_plugin_r/plugin.py @@ -3,7 +3,7 @@ class PluginReattach(TmuxpPlugin): def __init__(self): - self.message = '[+] This is the Tmuxp Test Plugin' + self.message = "[+] This is the Tmuxp Test Plugin" def reattach(self, session): - session.rename_session('plugin_test_r') + session.rename_session("plugin_test_r") diff --git a/tests/test_cli.py b/tests/test_cli.py index 8802535f6c8..64cfce75932 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -68,28 +68,28 @@ def test_get_configs_cwd(tmpdir): confdir = tmpdir.mkdir("tmuxpconf2") with confdir.as_cwd(): - config1 = open('.tmuxp.json', 'w+b') + config1 = open(".tmuxp.json", "w+b") config1.close() configs_found = config.in_cwd() assert len(configs_found) == 1 - assert '.tmuxp.json' in configs_found + assert ".tmuxp.json" in configs_found @pytest.mark.parametrize( - 'path,expect', + "path,expect", [ - ('.', False), - ('./', False), - ('', False), - ('.tmuxp.yaml', False), - ('../.tmuxp.yaml', False), - ('../', False), - ('/hello/world', False), - ('~/.tmuxp/hey', False), - ('~/work/c/tmux/', False), - ('~/work/c/tmux/.tmuxp.yaml', False), - ('myproject', True), + (".", False), + ("./", False), + ("", False), + (".tmuxp.yaml", False), + ("../.tmuxp.yaml", False), + ("../", False), + ("/hello/world", False), + ("~/.tmuxp/hey", False), + ("~/work/c/tmux/", False), + ("~/work/c/tmux/.tmuxp.yaml", False), + ("myproject", True), ], ) def test_is_pure_name(path, expect): @@ -117,172 +117,172 @@ def test_is_pure_name(path, expect): @pytest.fixture def homedir(tmpdir): - return tmpdir.join('home').mkdir() + return tmpdir.join("home").mkdir() @pytest.fixture def configdir(homedir): - return homedir.join('.tmuxp').mkdir() + return homedir.join(".tmuxp").mkdir() @pytest.fixture def projectdir(homedir): - return homedir.join('work').join('project') + return homedir.join("work").join("project") def test_tmuxp_configdir_env_var(tmpdir, monkeypatch): - monkeypatch.setenv('TMUXP_CONFIGDIR', str(tmpdir)) + monkeypatch.setenv("TMUXP_CONFIGDIR", str(tmpdir)) assert get_config_dir() == tmpdir def test_tmuxp_configdir_xdg_config_dir(tmpdir, monkeypatch): - monkeypatch.setenv('XDG_CONFIG_HOME', str(tmpdir)) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmpdir)) tmux_dir = tmpdir.mkdir("tmuxp") assert get_config_dir() == str(tmux_dir) def test_resolve_dot(tmpdir, homedir, configdir, projectdir, monkeypatch): - monkeypatch.setenv('HOME', str(homedir)) - monkeypatch.setenv("XDG_CONFIG_HOME", str(homedir.join('.config'))) + monkeypatch.setenv("HOME", str(homedir)) + monkeypatch.setenv("XDG_CONFIG_HOME", str(homedir.join(".config"))) - projectdir.join('.tmuxp.yaml').ensure() - user_config_name = 'myconfig' - user_config = configdir.join('%s.yaml' % user_config_name).ensure() + projectdir.join(".tmuxp.yaml").ensure() + user_config_name = "myconfig" + user_config = configdir.join("%s.yaml" % user_config_name).ensure() - project_config = str(projectdir.join('.tmuxp.yaml')) + project_config = str(projectdir.join(".tmuxp.yaml")) with projectdir.as_cwd(): expect = project_config - assert scan_config('.') == expect - assert scan_config('./') == expect - assert scan_config('') == expect - assert scan_config('../project') == expect - assert scan_config('../project/') == expect - assert scan_config('.tmuxp.yaml') == expect - assert scan_config('../../.tmuxp/%s.yaml' % user_config_name) == str( + assert scan_config(".") == expect + assert scan_config("./") == expect + assert scan_config("") == expect + assert scan_config("../project") == expect + assert scan_config("../project/") == expect + assert scan_config(".tmuxp.yaml") == expect + assert scan_config("../../.tmuxp/%s.yaml" % user_config_name) == str( user_config ) - assert scan_config('myconfig') == str(user_config) - assert scan_config('~/.tmuxp/myconfig.yaml') == str(user_config) + assert scan_config("myconfig") == str(user_config) + assert scan_config("~/.tmuxp/myconfig.yaml") == str(user_config) with pytest.raises(Exception): - scan_config('.tmuxp.json') + scan_config(".tmuxp.json") with pytest.raises(Exception): - scan_config('.tmuxp.ini') + scan_config(".tmuxp.ini") with pytest.raises(Exception): - scan_config('../') + scan_config("../") with pytest.raises(Exception): - scan_config('mooooooo') + scan_config("mooooooo") with homedir.as_cwd(): expect = project_config - assert scan_config('work/project') == expect - assert scan_config('work/project/') == expect - assert scan_config('./work/project') == expect - assert scan_config('./work/project/') == expect - assert scan_config('.tmuxp/%s.yaml' % user_config_name) == str(user_config) - assert scan_config('./.tmuxp/%s.yaml' % user_config_name) == str(user_config) - assert scan_config('myconfig') == str(user_config) - assert scan_config('~/.tmuxp/myconfig.yaml') == str(user_config) + assert scan_config("work/project") == expect + assert scan_config("work/project/") == expect + assert scan_config("./work/project") == expect + assert scan_config("./work/project/") == expect + assert scan_config(".tmuxp/%s.yaml" % user_config_name) == str(user_config) + assert scan_config("./.tmuxp/%s.yaml" % user_config_name) == str(user_config) + assert scan_config("myconfig") == str(user_config) + assert scan_config("~/.tmuxp/myconfig.yaml") == str(user_config) with pytest.raises(Exception): - scan_config('') + scan_config("") with pytest.raises(Exception): - scan_config('.') + scan_config(".") with pytest.raises(Exception): - scan_config('.tmuxp.yaml') + scan_config(".tmuxp.yaml") with pytest.raises(Exception): - scan_config('../') + scan_config("../") with pytest.raises(Exception): - scan_config('mooooooo') + scan_config("mooooooo") with configdir.as_cwd(): expect = project_config - assert scan_config('../work/project') == expect - assert scan_config('../../home/work/project') == expect - assert scan_config('../work/project/') == expect - assert scan_config('%s.yaml' % user_config_name) == str(user_config) - assert scan_config('./%s.yaml' % user_config_name) == str(user_config) - assert scan_config('myconfig') == str(user_config) - assert scan_config('~/.tmuxp/myconfig.yaml') == str(user_config) + assert scan_config("../work/project") == expect + assert scan_config("../../home/work/project") == expect + assert scan_config("../work/project/") == expect + assert scan_config("%s.yaml" % user_config_name) == str(user_config) + assert scan_config("./%s.yaml" % user_config_name) == str(user_config) + assert scan_config("myconfig") == str(user_config) + assert scan_config("~/.tmuxp/myconfig.yaml") == str(user_config) with pytest.raises(Exception): - scan_config('') + scan_config("") with pytest.raises(Exception): - scan_config('.') + scan_config(".") with pytest.raises(Exception): - scan_config('.tmuxp.yaml') + scan_config(".tmuxp.yaml") with pytest.raises(Exception): - scan_config('../') + scan_config("../") with pytest.raises(Exception): - scan_config('mooooooo') + scan_config("mooooooo") with tmpdir.as_cwd(): expect = project_config - assert scan_config('home/work/project') == expect - assert scan_config('./home/work/project/') == expect - assert scan_config('home/.tmuxp/%s.yaml' % user_config_name) == str(user_config) - assert scan_config('./home/.tmuxp/%s.yaml' % user_config_name) == str( + assert scan_config("home/work/project") == expect + assert scan_config("./home/work/project/") == expect + assert scan_config("home/.tmuxp/%s.yaml" % user_config_name) == str(user_config) + assert scan_config("./home/.tmuxp/%s.yaml" % user_config_name) == str( user_config ) - assert scan_config('myconfig') == str(user_config) - assert scan_config('~/.tmuxp/myconfig.yaml') == str(user_config) + assert scan_config("myconfig") == str(user_config) + assert scan_config("~/.tmuxp/myconfig.yaml") == str(user_config) with pytest.raises(Exception): - scan_config('') + scan_config("") with pytest.raises(Exception): - scan_config('.') + scan_config(".") with pytest.raises(Exception): - scan_config('.tmuxp.yaml') + scan_config(".tmuxp.yaml") with pytest.raises(Exception): - scan_config('../') + scan_config("../") with pytest.raises(Exception): - scan_config('mooooooo') + scan_config("mooooooo") def test_scan_config_arg(homedir, configdir, projectdir, monkeypatch): runner = CliRunner() @click.command() - @click.argument('config', type=cli.ConfigPath(exists=True), nargs=-1) + @click.argument("config", type=cli.ConfigPath(exists=True), nargs=-1) def config_cmd(config): click.echo(config) - monkeypatch.setenv('HOME', str(homedir)) - projectdir.join('.tmuxp.yaml').ensure() - user_config_name = 'myconfig' - user_config = configdir.join('%s.yaml' % user_config_name).ensure() + monkeypatch.setenv("HOME", str(homedir)) + projectdir.join(".tmuxp.yaml").ensure() + user_config_name = "myconfig" + user_config = configdir.join("%s.yaml" % user_config_name).ensure() - project_config = str(projectdir.join('.tmuxp.yaml')) + project_config = str(projectdir.join(".tmuxp.yaml")) def check_cmd(config_arg): return runner.invoke(config_cmd, [config_arg]).output with projectdir.as_cwd(): expect = project_config - assert expect in check_cmd('.') - assert expect in check_cmd('./') - assert expect in check_cmd('') - assert expect in check_cmd('../project') - assert expect in check_cmd('../project/') - assert expect in check_cmd('.tmuxp.yaml') - assert str(user_config) in check_cmd('../../.tmuxp/%s.yaml' % user_config_name) - assert user_config.purebasename in check_cmd('myconfig') - assert str(user_config) in check_cmd('~/.tmuxp/myconfig.yaml') - - assert 'file not found' in check_cmd('.tmuxp.json') - assert 'file not found' in check_cmd('.tmuxp.ini') - assert 'No tmuxp files found' in check_cmd('../') - assert 'config not found in config dir' in check_cmd('moo') + assert expect in check_cmd(".") + assert expect in check_cmd("./") + assert expect in check_cmd("") + assert expect in check_cmd("../project") + assert expect in check_cmd("../project/") + assert expect in check_cmd(".tmuxp.yaml") + assert str(user_config) in check_cmd("../../.tmuxp/%s.yaml" % user_config_name) + assert user_config.purebasename in check_cmd("myconfig") + assert str(user_config) in check_cmd("~/.tmuxp/myconfig.yaml") + + assert "file not found" in check_cmd(".tmuxp.json") + assert "file not found" in check_cmd(".tmuxp.ini") + assert "No tmuxp files found" in check_cmd("../") + assert "config not found in config dir" in check_cmd("moo") def test_load_workspace(server, monkeypatch): # this is an implementation test. Since this testsuite may be ran within # a tmux session by the developer himself, delete the TMUX variable # temporarily. - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) session_file = curjoin("workspacebuilder/two_pane.yaml") # open it detached @@ -291,33 +291,33 @@ def test_load_workspace(server, monkeypatch): ) assert isinstance(session, libtmux.Session) - assert session.name == 'sampleconfig' + assert session.name == "sampleconfig" def test_load_workspace_named_session(server, monkeypatch): # this is an implementation test. Since this testsuite may be ran within # a tmux session by the developer himself, delete the TMUX variable # temporarily. - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) session_file = curjoin("workspacebuilder/two_pane.yaml") # open it detached session = load_workspace( session_file, socket_name=server.socket_name, - new_session_name='tmuxp-new', + new_session_name="tmuxp-new", detached=True, ) assert isinstance(session, libtmux.Session) - assert session.name == 'tmuxp-new' + assert session.name == "tmuxp-new" @pytest.mark.skipif( - has_lt_version('2.1'), reason='exact session name matches only tmux >= 2.1' + has_lt_version("2.1"), reason="exact session name matches only tmux >= 2.1" ) def test_load_workspace_name_match_regression_252(tmpdir, server, monkeypatch): - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) session_file = curjoin("workspacebuilder/two_pane.yaml") # open it detached @@ -326,9 +326,9 @@ def test_load_workspace_name_match_regression_252(tmpdir, server, monkeypatch): ) assert isinstance(session, libtmux.Session) - assert session.name == 'sampleconfig' + assert session.name == "sampleconfig" - projfile = tmpdir.join('simple.yaml') + projfile = tmpdir.join("simple.yaml") projfile.write( """ @@ -343,19 +343,19 @@ def test_load_workspace_name_match_regression_252(tmpdir, server, monkeypatch): session = load_workspace( projfile.strpath, socket_name=server.socket_name, detached=True ) - assert session.name == 'sampleconfi' + assert session.name == "sampleconfi" def test_load_symlinked_workspace(server, tmpdir, monkeypatch): # this is an implementation test. Since this testsuite may be ran within # a tmux session by the developer himself, delete the TMUX variable # temporarily. - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) - realtemp = tmpdir.mkdir('myrealtemp') - linktemp = tmpdir.join('symlinktemp') + realtemp = tmpdir.mkdir("myrealtemp") + linktemp = tmpdir.join("symlinktemp") linktemp.mksymlinkto(realtemp) - projfile = linktemp.join('simple.yaml') + projfile = linktemp.join("simple.yaml") projfile.write( """ @@ -373,7 +373,7 @@ def test_load_symlinked_workspace(server, tmpdir, monkeypatch): pane = session.attached_window.attached_pane assert isinstance(session, libtmux.Session) - assert session.name == 'samplesimple' + assert session.name == "samplesimple" assert pane.current_path == realtemp.strpath @@ -383,134 +383,134 @@ def test_regression_00132_session_name_with_dots(tmpdir, server, session): inputs = [] runner = CliRunner() result = runner.invoke( - cli.command_load, cli_args, input=''.join(inputs), standalone_mode=False + cli.command_load, cli_args, input="".join(inputs), standalone_mode=False ) assert result.exception assert isinstance(result.exception, libtmux.exc.BadSessionName) -@pytest.mark.parametrize("cli_args", [(['load', '.']), (['load', '.tmuxp.yaml'])]) +@pytest.mark.parametrize("cli_args", [(["load", "."]), (["load", ".tmuxp.yaml"])]) def test_load_zsh_autotitle_warning(cli_args, tmpdir, monkeypatch): # create dummy tmuxp yaml so we don't get yelled at - tmpdir.join('.tmuxp.yaml').ensure() - tmpdir.join('.oh-my-zsh').ensure(dir=True) - monkeypatch.setenv('HOME', str(tmpdir)) + tmpdir.join(".tmuxp.yaml").ensure() + tmpdir.join(".oh-my-zsh").ensure(dir=True) + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): runner = CliRunner() - monkeypatch.delenv('DISABLE_AUTO_TITLE', raising=False) - monkeypatch.setenv('SHELL', 'zsh') + monkeypatch.delenv("DISABLE_AUTO_TITLE", raising=False) + monkeypatch.setenv("SHELL", "zsh") result = runner.invoke(cli.cli, cli_args) - assert 'Please set' in result.output + assert "Please set" in result.output - monkeypatch.setenv('DISABLE_AUTO_TITLE', 'false') + monkeypatch.setenv("DISABLE_AUTO_TITLE", "false") result = runner.invoke(cli.cli, cli_args) - assert 'Please set' in result.output + assert "Please set" in result.output - monkeypatch.setenv('DISABLE_AUTO_TITLE', 'true') + monkeypatch.setenv("DISABLE_AUTO_TITLE", "true") result = runner.invoke(cli.cli, cli_args) - assert 'Please set' not in result.output + assert "Please set" not in result.output - monkeypatch.delenv('DISABLE_AUTO_TITLE', raising=False) - monkeypatch.setenv('SHELL', 'sh') + monkeypatch.delenv("DISABLE_AUTO_TITLE", raising=False) + monkeypatch.setenv("SHELL", "sh") result = runner.invoke(cli.cli, cli_args) - assert 'Please set' not in result.output + assert "Please set" not in result.output @pytest.mark.parametrize( "cli_args", [ - (['load', '.', '--log-file', 'log.txt']), + (["load", ".", "--log-file", "log.txt"]), ], ) def test_load_log_file(cli_args, tmpdir, monkeypatch): # create dummy tmuxp yaml that breaks to prevent actually loading tmux - tmpdir.join('.tmuxp.yaml').write( + tmpdir.join(".tmuxp.yaml").write( """ session_name: hello """ ) - tmpdir.join('.oh-my-zsh').ensure(dir=True) - monkeypatch.setenv('HOME', str(tmpdir)) + tmpdir.join(".oh-my-zsh").ensure(dir=True) + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): - print('tmpdir: {0}'.format(tmpdir)) + print("tmpdir: {0}".format(tmpdir)) runner = CliRunner() # If autoconfirm (-y) no need to prompt y - input_args = 'y\ny\n' if '-y' not in cli_args else '' + input_args = "y\ny\n" if "-y" not in cli_args else "" runner.invoke(cli.cli, cli_args, input=input_args) - assert 'Loading' in tmpdir.join('log.txt').open().read() + assert "Loading" in tmpdir.join("log.txt").open().read() -@pytest.mark.parametrize("cli_cmd", ['shell', ('shell', '--pdb')]) +@pytest.mark.parametrize("cli_cmd", ["shell", ("shell", "--pdb")]) @pytest.mark.parametrize( "cli_args,inputs,env,expected_output", [ ( - ['-L{SOCKET_NAME}', '-c', 'print(str(server.socket_name))'], + ["-L{SOCKET_NAME}", "-c", "print(str(server.socket_name))"], [], {}, - '{SERVER_SOCKET_NAME}', + "{SERVER_SOCKET_NAME}", ), ( [ - '-L{SOCKET_NAME}', - '{SESSION_NAME}', - '-c', - 'print(session.name)', + "-L{SOCKET_NAME}", + "{SESSION_NAME}", + "-c", + "print(session.name)", ], [], {}, - '{SESSION_NAME}', + "{SESSION_NAME}", ), ( [ - '-L{SOCKET_NAME}', - '{SESSION_NAME}', - '{WINDOW_NAME}', - '-c', - 'print(server.has_session(session.name))', + "-L{SOCKET_NAME}", + "{SESSION_NAME}", + "{WINDOW_NAME}", + "-c", + "print(server.has_session(session.name))", ], [], {}, - 'True', + "True", ), ( [ - '-L{SOCKET_NAME}', - '{SESSION_NAME}', - '{WINDOW_NAME}', - '-c', - 'print(window.name)', + "-L{SOCKET_NAME}", + "{SESSION_NAME}", + "{WINDOW_NAME}", + "-c", + "print(window.name)", ], [], {}, - '{WINDOW_NAME}', + "{WINDOW_NAME}", ), ( [ - '-L{SOCKET_NAME}', - '{SESSION_NAME}', - '{WINDOW_NAME}', - '-c', - 'print(pane.id)', + "-L{SOCKET_NAME}", + "{SESSION_NAME}", + "{WINDOW_NAME}", + "-c", + "print(pane.id)", ], [], {}, - '{PANE_ID}', + "{PANE_ID}", ), ( [ - '-L{SOCKET_NAME}', - '-c', - 'print(pane.id)', + "-L{SOCKET_NAME}", + "-c", + "print(pane.id)", ], [], - {'TMUX_PANE': '{PANE_ID}'}, - '{PANE_ID}', + {"TMUX_PANE": "{PANE_ID}"}, + "{PANE_ID}", ), ], ) @@ -525,8 +525,8 @@ def test_shell( server, session, ): - monkeypatch.setenv('HOME', str(tmpdir)) - window_name = 'my_window' + monkeypatch.setenv("HOME", str(tmpdir)) + window_name = "my_window" window = session.new_window(window_name=window_name) window.split_window() @@ -549,7 +549,7 @@ def test_shell( runner = CliRunner() result = runner.invoke( - cli.cli, cli_args, input=''.join(inputs), catch_exceptions=False + cli.cli, cli_args, input="".join(inputs), catch_exceptions=False ) assert expected_output.format(**template_ctx) in result.output @@ -557,47 +557,47 @@ def test_shell( @pytest.mark.parametrize( "cli_cmd", [ - 'shell', - ('shell', '--pdb'), + "shell", + ("shell", "--pdb"), ], ) @pytest.mark.parametrize( "cli_args,inputs,env,template_ctx,exception,message", [ ( - ['-LDoesNotExist', '-c', 'print(str(server.socket_name))'], + ["-LDoesNotExist", "-c", "print(str(server.socket_name))"], [], {}, {}, LibTmuxException, - r'.*DoesNotExist.*', + r".*DoesNotExist.*", ), ( [ - '-L{SOCKET_NAME}', - 'nonexistant_session', - '-c', - 'print(str(server.socket_name))', + "-L{SOCKET_NAME}", + "nonexistant_session", + "-c", + "print(str(server.socket_name))", ], [], {}, - {'session_name': 'nonexistant_session'}, + {"session_name": "nonexistant_session"}, exc.TmuxpException, - 'Session not found: nonexistant_session', + "Session not found: nonexistant_session", ), ( [ - '-L{SOCKET_NAME}', - '{SESSION_NAME}', - 'nonexistant_window', - '-c', - 'print(str(server.socket_name))', + "-L{SOCKET_NAME}", + "{SESSION_NAME}", + "nonexistant_window", + "-c", + "print(str(server.socket_name))", ], [], {}, - {'window_name': 'nonexistant_window'}, + {"window_name": "nonexistant_window"}, exc.TmuxpException, - 'Window not found: {WINDOW_NAME}', + "Window not found: {WINDOW_NAME}", ), ], ) @@ -615,8 +615,8 @@ def test_shell_target_missing( server, session, ): - monkeypatch.setenv('HOME', str(tmpdir)) - window_name = 'my_window' + monkeypatch.setenv("HOME", str(tmpdir)) + window_name = "my_window" window = session.new_window(window_name=window_name) window.split_window() @@ -624,8 +624,8 @@ def test_shell_target_missing( SOCKET_NAME=server.socket_name, SOCKET_PATH=server.socket_path, SESSION_NAME=session.name, - WINDOW_NAME=template_ctx.get('window_name', window_name), - PANE_ID=template_ctx.get('pane_id'), + WINDOW_NAME=template_ctx.get("window_name", window_name), + PANE_ID=template_ctx.get("pane_id"), SERVER_SOCKET_NAME=server.socket_name, ) cli_cmd = list(cli_cmd) if isinstance(cli_cmd, (list, tuple)) else [cli_cmd] @@ -640,11 +640,11 @@ def test_shell_target_missing( if exception is not None: with pytest.raises(exception, match=message.format(**template_ctx)): result = runner.invoke( - cli.cli, cli_args, input=''.join(inputs), catch_exceptions=False + cli.cli, cli_args, input="".join(inputs), catch_exceptions=False ) else: result = runner.invoke( - cli.cli, cli_args, input=''.join(inputs), catch_exceptions=False + cli.cli, cli_args, input="".join(inputs), catch_exceptions=False ) assert message.format(**template_ctx) in result.output @@ -654,7 +654,7 @@ def test_shell_target_missing( [ # 'shell', # ('shell', '--pdb'), - ('shell', '--code'), + ("shell", "--code"), # ('shell', '--bpython'), # ('shell', '--ptipython'), # ('shell', '--ptpython'), @@ -666,19 +666,19 @@ def test_shell_target_missing( [ ( [ - '-L{SOCKET_NAME}', + "-L{SOCKET_NAME}", ], [], {}, - '(InteractiveConsole)', + "(InteractiveConsole)", ), ( [ - '-L{SOCKET_NAME}', + "-L{SOCKET_NAME}", ], [], - {'PANE_ID': '{PANE_ID}'}, - '(InteractiveConsole)', + {"PANE_ID": "{PANE_ID}"}, + "(InteractiveConsole)", ), ], ) @@ -693,8 +693,8 @@ def test_shell_plus( server, session, ): - monkeypatch.setenv('HOME', str(tmpdir)) - window_name = 'my_window' + monkeypatch.setenv("HOME", str(tmpdir)) + window_name = "my_window" window = session.new_window(window_name=window_name) window.split_window() @@ -717,7 +717,7 @@ def test_shell_plus( runner = CliRunner() result = runner.invoke( - cli.cli, cli_args, input=''.join(inputs), catch_exceptions=True + cli.cli, cli_args, input="".join(inputs), catch_exceptions=True ) assert message.format(**template_ctx) in result.output @@ -725,167 +725,167 @@ def test_shell_plus( @pytest.mark.parametrize( "cli_args", [ - (['convert', '.']), - (['convert', '.tmuxp.yaml']), - (['convert', '.tmuxp.yaml', '-y']), - (['convert', '.tmuxp.yml']), - (['convert', '.tmuxp.yml', '-y']), + (["convert", "."]), + (["convert", ".tmuxp.yaml"]), + (["convert", ".tmuxp.yaml", "-y"]), + (["convert", ".tmuxp.yml"]), + (["convert", ".tmuxp.yml", "-y"]), ], ) def test_convert(cli_args, tmpdir, monkeypatch): # create dummy tmuxp yaml so we don't get yelled at filename = cli_args[1] - if filename == '.': - filename = '.tmuxp.yaml' - file_ext = filename.rsplit('.', 1)[-1] - assert file_ext in ['yaml', 'yml'], file_ext - tmpdir.join(filename).write('\nsession_name: hello\n') - tmpdir.join('.oh-my-zsh').ensure(dir=True) - monkeypatch.setenv('HOME', str(tmpdir)) + if filename == ".": + filename = ".tmuxp.yaml" + file_ext = filename.rsplit(".", 1)[-1] + assert file_ext in ["yaml", "yml"], file_ext + tmpdir.join(filename).write("\nsession_name: hello\n") + tmpdir.join(".oh-my-zsh").ensure(dir=True) + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): runner = CliRunner() # If autoconfirm (-y) no need to prompt y - input_args = 'y\ny\n' if '-y' not in cli_args else '' + input_args = "y\ny\n" if "-y" not in cli_args else "" runner.invoke(cli.cli, cli_args, input=input_args) - assert tmpdir.join('.tmuxp.json').check() - assert tmpdir.join('.tmuxp.json').open().read() == json.dumps( - {'session_name': 'hello'}, indent=2 + assert tmpdir.join(".tmuxp.json").check() + assert tmpdir.join(".tmuxp.json").open().read() == json.dumps( + {"session_name": "hello"}, indent=2 ) @pytest.mark.parametrize( "cli_args", [ - (['convert', '.']), - (['convert', '.tmuxp.json']), - (['convert', '.tmuxp.json', '-y']), + (["convert", "."]), + (["convert", ".tmuxp.json"]), + (["convert", ".tmuxp.json", "-y"]), ], ) def test_convert_json(cli_args, tmpdir, monkeypatch): # create dummy tmuxp yaml so we don't get yelled at - tmpdir.join('.tmuxp.json').write('{"session_name": "hello"}') - tmpdir.join('.oh-my-zsh').ensure(dir=True) - monkeypatch.setenv('HOME', str(tmpdir)) + tmpdir.join(".tmuxp.json").write('{"session_name": "hello"}') + tmpdir.join(".oh-my-zsh").ensure(dir=True) + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): runner = CliRunner() # If autoconfirm (-y) no need to prompt y - input_args = 'y\ny\n' if '-y' not in cli_args else '' + input_args = "y\ny\n" if "-y" not in cli_args else "" runner.invoke(cli.cli, cli_args, input=input_args) - assert tmpdir.join('.tmuxp.yaml').check() - assert tmpdir.join('.tmuxp.yaml').open().read() == 'session_name: hello\n' + assert tmpdir.join(".tmuxp.yaml").check() + assert tmpdir.join(".tmuxp.yaml").open().read() == "session_name: hello\n" -@pytest.mark.parametrize("cli_args", [(['import'])]) +@pytest.mark.parametrize("cli_args", [(["import"])]) def test_import(cli_args, monkeypatch): runner = CliRunner() result = runner.invoke(cli.cli, cli_args) - assert 'tmuxinator' in result.output - assert 'teamocil' in result.output + assert "tmuxinator" in result.output + assert "teamocil" in result.output @pytest.mark.parametrize( "cli_args", [ - (['--help']), - (['-h']), + (["--help"]), + (["-h"]), ], ) def test_help(cli_args, monkeypatch): runner = CliRunner() result = runner.invoke(cli.cli, cli_args) - assert 'Usage: cli [OPTIONS] COMMAND [ARGS]...' in result.output + assert "Usage: cli [OPTIONS] COMMAND [ARGS]..." in result.output @pytest.mark.parametrize( "cli_args,inputs", [ ( - ['import', 'teamocil', './.teamocil/config.yaml'], - ['\n', 'y\n', './la.yaml\n', 'y\n'], + ["import", "teamocil", "./.teamocil/config.yaml"], + ["\n", "y\n", "./la.yaml\n", "y\n"], ), ( - ['import', 'teamocil', './.teamocil/config.yaml'], - ['\n', 'y\n', './exists.yaml\n', './la.yaml\n', 'y\n'], + ["import", "teamocil", "./.teamocil/config.yaml"], + ["\n", "y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"], ), ( - ['import', 'teamocil', 'config'], - ['\n', 'y\n', './exists.yaml\n', './la.yaml\n', 'y\n'], + ["import", "teamocil", "config"], + ["\n", "y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"], ), ], ) def test_import_teamocil(cli_args, inputs, tmpdir, monkeypatch): - teamocil_config = loadfixture('config_teamocil/test4.yaml') - teamocil_dir = tmpdir.join('.teamocil').mkdir() - teamocil_dir.join('config.yaml').write(teamocil_config) - tmpdir.join('exists.yaml').ensure() - monkeypatch.setenv('HOME', str(tmpdir)) + teamocil_config = loadfixture("config_teamocil/test4.yaml") + teamocil_dir = tmpdir.join(".teamocil").mkdir() + teamocil_dir.join("config.yaml").write(teamocil_config) + tmpdir.join("exists.yaml").ensure() + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): runner = CliRunner() - runner.invoke(cli.cli, cli_args, input=''.join(inputs)) - assert tmpdir.join('la.yaml').check() + runner.invoke(cli.cli, cli_args, input="".join(inputs)) + assert tmpdir.join("la.yaml").check() @pytest.mark.parametrize( "cli_args,inputs", [ ( - ['import', 'tmuxinator', './.tmuxinator/config.yaml'], - ['\n', 'y\n', './la.yaml\n', 'y\n'], + ["import", "tmuxinator", "./.tmuxinator/config.yaml"], + ["\n", "y\n", "./la.yaml\n", "y\n"], ), ( - ['import', 'tmuxinator', './.tmuxinator/config.yaml'], - ['\n', 'y\n', './exists.yaml\n', './la.yaml\n', 'y\n'], + ["import", "tmuxinator", "./.tmuxinator/config.yaml"], + ["\n", "y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"], ), ( - ['import', 'tmuxinator', 'config'], - ['\n', 'y\n', './exists.yaml\n', './la.yaml\n', 'y\n'], + ["import", "tmuxinator", "config"], + ["\n", "y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"], ), ], ) def test_import_tmuxinator(cli_args, inputs, tmpdir, monkeypatch): - tmuxinator_config = loadfixture('config_tmuxinator/test3.yaml') - tmuxinator_dir = tmpdir.join('.tmuxinator').mkdir() - tmuxinator_dir.join('config.yaml').write(tmuxinator_config) - tmpdir.join('exists.yaml').ensure() - monkeypatch.setenv('HOME', str(tmpdir)) + tmuxinator_config = loadfixture("config_tmuxinator/test3.yaml") + tmuxinator_dir = tmpdir.join(".tmuxinator").mkdir() + tmuxinator_dir.join("config.yaml").write(tmuxinator_config) + tmpdir.join("exists.yaml").ensure() + monkeypatch.setenv("HOME", str(tmpdir)) with tmpdir.as_cwd(): runner = CliRunner() - out = runner.invoke(cli.cli, cli_args, input=''.join(inputs)) + out = runner.invoke(cli.cli, cli_args, input="".join(inputs)) print(out.output) - assert tmpdir.join('la.yaml').check() + assert tmpdir.join("la.yaml").check() @pytest.mark.parametrize( "cli_args,inputs", [ - (['freeze', 'myfrozensession'], ['y\n', './la.yaml\n', 'y\n']), + (["freeze", "myfrozensession"], ["y\n", "./la.yaml\n", "y\n"]), ( # Exists - ['freeze', 'myfrozensession'], - ['y\n', './exists.yaml\n', './la.yaml\n', 'y\n'], + ["freeze", "myfrozensession"], + ["y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"], ), ( # Imply current session if not entered - ['freeze'], - ['y\n', './la.yaml\n', 'y\n'], + ["freeze"], + ["y\n", "./la.yaml\n", "y\n"], ), - (['freeze'], ['y\n', './exists.yaml\n', './la.yaml\n', 'y\n']), # Exists + (["freeze"], ["y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"]), # Exists ], ) def test_freeze(server, cli_args, inputs, tmpdir, monkeypatch): - monkeypatch.setenv('HOME', str(tmpdir)) - tmpdir.join('exists.yaml').ensure() + monkeypatch.setenv("HOME", str(tmpdir)) + tmpdir.join("exists.yaml").ensure() - server.new_session(session_name='myfirstsession') - server.new_session(session_name='myfrozensession') + server.new_session(session_name="myfirstsession") + server.new_session(session_name="myfrozensession") # Assign an active pane to the session second_session = server.list_sessions()[1] @@ -897,60 +897,60 @@ def test_freeze(server, cli_args, inputs, tmpdir, monkeypatch): with tmpdir.as_cwd(): runner = CliRunner() # Use tmux server (socket name) used in the test - cli_args = cli_args + ['-L', server.socket_name] - out = runner.invoke(cli.cli, cli_args, input=''.join(inputs)) + cli_args = cli_args + ["-L", server.socket_name] + out = runner.invoke(cli.cli, cli_args, input="".join(inputs)) print(out.output) - assert tmpdir.join('la.yaml').check() + assert tmpdir.join("la.yaml").check() - yaml_config = tmpdir.join('la.yaml').open().read() - frozen_config = kaptan.Kaptan(handler='yaml').import_config(yaml_config).get() + yaml_config = tmpdir.join("la.yaml").open().read() + frozen_config = kaptan.Kaptan(handler="yaml").import_config(yaml_config).get() - assert frozen_config['session_name'] == 'myfrozensession' + assert frozen_config["session_name"] == "myfrozensession" @pytest.mark.parametrize( "cli_args,inputs", [ ( # Overwrite - ['freeze', 'mysession', '--force'], - ['\n', 'y\n', './exists.yaml\n', 'y\n'], + ["freeze", "mysession", "--force"], + ["\n", "y\n", "./exists.yaml\n", "y\n"], ), ( # Imply current session if not entered - ['freeze', '--force'], - ['\n', 'y\n', './exists.yaml\n', 'y\n'], + ["freeze", "--force"], + ["\n", "y\n", "./exists.yaml\n", "y\n"], ), ], ) def test_freeze_overwrite(server, cli_args, inputs, tmpdir, monkeypatch): - monkeypatch.setenv('HOME', str(tmpdir)) - tmpdir.join('exists.yaml').ensure() + monkeypatch.setenv("HOME", str(tmpdir)) + tmpdir.join("exists.yaml").ensure() - server.new_session(session_name='mysession') + server.new_session(session_name="mysession") with tmpdir.as_cwd(): runner = CliRunner() # Use tmux server (socket name) used in the test - cli_args = cli_args + ['-L', server.socket_name] - out = runner.invoke(cli.cli, cli_args, input=''.join(inputs)) + cli_args = cli_args + ["-L", server.socket_name] + out = runner.invoke(cli.cli, cli_args, input="".join(inputs)) print(out.output) - assert tmpdir.join('exists.yaml').check() + assert tmpdir.join("exists.yaml").check() def test_get_abs_path(tmpdir): expect = str(tmpdir) with tmpdir.as_cwd(): - cli.get_abs_path('../') == os.path.dirname(expect) - cli.get_abs_path('.') == expect - cli.get_abs_path('./') == expect + cli.get_abs_path("../") == os.path.dirname(expect) + cli.get_abs_path(".") == expect + cli.get_abs_path("./") == expect cli.get_abs_path(expect) == expect def test_get_tmuxinator_dir(monkeypatch): - assert cli.get_tmuxinator_dir() == os.path.expanduser('~/.tmuxinator/') + assert cli.get_tmuxinator_dir() == os.path.expanduser("~/.tmuxinator/") - monkeypatch.setenv('HOME', '/moo') - assert cli.get_tmuxinator_dir() == '/moo/.tmuxinator/' - assert cli.get_tmuxinator_dir() == os.path.expanduser('~/.tmuxinator/') + monkeypatch.setenv("HOME", "/moo") + assert cli.get_tmuxinator_dir() == "/moo/.tmuxinator/" + assert cli.get_tmuxinator_dir() == os.path.expanduser("~/.tmuxinator/") def test_get_cwd(tmpdir): @@ -962,36 +962,36 @@ def test_get_cwd(tmpdir): def test_get_teamocil_dir(monkeypatch): - assert cli.get_teamocil_dir() == os.path.expanduser('~/.teamocil/') + assert cli.get_teamocil_dir() == os.path.expanduser("~/.teamocil/") - monkeypatch.setenv('HOME', '/moo') - assert cli.get_teamocil_dir() == '/moo/.teamocil/' - assert cli.get_teamocil_dir() == os.path.expanduser('~/.teamocil/') + monkeypatch.setenv("HOME", "/moo") + assert cli.get_teamocil_dir() == "/moo/.teamocil/" + assert cli.get_teamocil_dir() == os.path.expanduser("~/.teamocil/") def test_validate_choices(): - validate = cli._validate_choices(['choice1', 'choice2']) + validate = cli._validate_choices(["choice1", "choice2"]) - assert validate('choice1') - assert validate('choice2') + assert validate("choice1") + assert validate("choice2") with pytest.raises(click.BadParameter): - assert validate('choice3') + assert validate("choice3") def test_pass_config_dir_ClickPath(tmpdir): - configdir = tmpdir.join('myconfigdir') + configdir = tmpdir.join("myconfigdir") configdir.mkdir() - user_config_name = 'myconfig' - user_config = configdir.join('%s.yaml' % user_config_name).ensure() + user_config_name = "myconfig" + user_config = configdir.join("%s.yaml" % user_config_name).ensure() - expect = str(configdir.join('myconfig.yaml')) + expect = str(configdir.join("myconfig.yaml")) runner = CliRunner() @click.command() @click.argument( - 'config', + "config", type=cli.ConfigPath(exists=True, config_dir=(str(configdir))), nargs=-1, ) @@ -1002,43 +1002,43 @@ def check_cmd(config_arg): return runner.invoke(config_cmd, [config_arg]).output with configdir.as_cwd(): - assert expect in check_cmd('myconfig') - assert expect in check_cmd('myconfig.yaml') - assert expect in check_cmd('./myconfig.yaml') - assert str(user_config) in check_cmd(str(configdir.join('myconfig.yaml'))) + assert expect in check_cmd("myconfig") + assert expect in check_cmd("myconfig.yaml") + assert expect in check_cmd("./myconfig.yaml") + assert str(user_config) in check_cmd(str(configdir.join("myconfig.yaml"))) - assert 'file not found' in check_cmd('.tmuxp.json') + assert "file not found" in check_cmd(".tmuxp.json") def test_ls_cli(monkeypatch, tmpdir): monkeypatch.setenv("HOME", str(tmpdir)) - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmpdir.join('.config'))) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmpdir.join(".config"))) filenames = [ - '.git/', - '.gitignore/', - 'session_1.yaml', - 'session_2.yaml', - 'session_3.json', - 'session_4.txt', + ".git/", + ".gitignore/", + "session_1.yaml", + "session_2.yaml", + "session_3.json", + "session_4.txt", ] # should ignore: # - directories should be ignored # - extensions not covered in VALID_CONFIG_DIR_FILE_EXTENSIONS - ignored_filenames = ['.git/', '.gitignore/', 'session_4.txt'] + ignored_filenames = [".git/", ".gitignore/", "session_4.txt"] 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)) - if filename.endswith('/'): + location = tmpdir.join(".tmuxp/{}".format(filename)) + if filename.endswith("/"): location.ensure_dir() else: location.ensure() runner = CliRunner() cli_output = runner.invoke(command_ls).output - assert cli_output == '\n'.join(stems) + '\n' + assert cli_output == "\n".join(stems) + "\n" def test_load_plugins(monkeypatch_plugin_test_packages): @@ -1046,7 +1046,7 @@ def test_load_plugins(monkeypatch_plugin_test_packages): plugins_config = loadfixture("workspacebuilder/plugin_bwb.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(plugins_config).get() sconfig = config.expand(sconfig) @@ -1061,13 +1061,13 @@ def test_load_plugins(monkeypatch_plugin_test_packages): assert plugin.__class__ in test_plugin_class_types -@pytest.mark.skip('Not sure how to clean up the tmux session this makes') +@pytest.mark.skip("Not sure how to clean up the tmux session this makes") @pytest.mark.parametrize( "cli_args,inputs", [ ( - ['load', 'tests/fixtures/workspacebuilder/plugin_versions_fail.yaml'], - ['y\n'], + ["load", "tests/fixtures/workspacebuilder/plugin_versions_fail.yaml"], + ["y\n"], ) ], ) @@ -1076,16 +1076,16 @@ def test_load_plugins_version_fail_skip( ): runner = CliRunner() - results = runner.invoke(cli.cli, cli_args, input=''.join(inputs)) - assert '[Loading]' in results.output + results = runner.invoke(cli.cli, cli_args, input="".join(inputs)) + assert "[Loading]" in results.output @pytest.mark.parametrize( "cli_args,inputs", [ ( - ['load', 'tests/fixtures/workspacebuilder/plugin_versions_fail.yaml'], - ['n\n'], + ["load", "tests/fixtures/workspacebuilder/plugin_versions_fail.yaml"], + ["n\n"], ) ], ) @@ -1094,18 +1094,18 @@ def test_load_plugins_version_fail_no_skip( ): runner = CliRunner() - results = runner.invoke(cli.cli, cli_args, input=''.join(inputs)) - assert '[Not Skipping]' in results.output + results = runner.invoke(cli.cli, cli_args, input="".join(inputs)) + assert "[Not Skipping]" in results.output @pytest.mark.parametrize( - "cli_args", [(['load', 'tests/fixtures/workspacebuilder/plugin_missing_fail.yaml'])] + "cli_args", [(["load", "tests/fixtures/workspacebuilder/plugin_missing_fail.yaml"])] ) def test_load_plugins_plugin_missing(monkeypatch_plugin_test_packages, cli_args): runner = CliRunner() results = runner.invoke(cli.cli, cli_args) - assert '[Plugin Error]' in results.output + assert "[Plugin Error]" in results.output def test_plugin_system_before_script( @@ -1114,7 +1114,7 @@ def test_plugin_system_before_script( # this is an implementation test. Since this testsuite may be ran within # a tmux session by the developer himself, delete the TMUX variable # temporarily. - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) session_file = curjoin("workspacebuilder/plugin_bs.yaml") # open it detached @@ -1123,13 +1123,13 @@ def test_plugin_system_before_script( ) assert isinstance(session, libtmux.Session) - assert session.name == 'plugin_test_bs' + assert session.name == "plugin_test_bs" def test_reattach_plugins(monkeypatch_plugin_test_packages, server): config_plugins = loadfixture("workspacebuilder/plugin_r.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -1144,14 +1144,14 @@ def test_reattach_plugins(monkeypatch_plugin_test_packages, server): except libtmux.exc.LibTmuxException: pass - proc = builder.session.cmd('display-message', '-p', "'#S'") + proc = builder.session.cmd("display-message", "-p", "'#S'") assert proc.stdout[0] == "'plugin_test_r'" def test_load_attached(server, monkeypatch): # Load a session and attach from outside tmux - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) attach_session_mock = MagicMock() attach_session_mock.return_value.stderr = None @@ -1159,7 +1159,7 @@ def test_load_attached(server, monkeypatch): monkeypatch.setattr("libtmux.session.Session.attach_session", attach_session_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -1171,7 +1171,7 @@ def test_load_attached(server, monkeypatch): def test_load_attached_detached(server, monkeypatch): # Load a session but don't attach - monkeypatch.delenv('TMUX', raising=False) + monkeypatch.delenv("TMUX", raising=False) attach_session_mock = MagicMock() attach_session_mock.return_value.stderr = None @@ -1179,7 +1179,7 @@ def test_load_attached_detached(server, monkeypatch): monkeypatch.setattr("libtmux.session.Session.attach_session", attach_session_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -1191,7 +1191,7 @@ def test_load_attached_detached(server, monkeypatch): def test_load_attached_within_tmux(server, monkeypatch): # Load a session and attach from within tmux - monkeypatch.setenv('TMUX', "/tmp/tmux-1234/default,123,0") + monkeypatch.setenv("TMUX", "/tmp/tmux-1234/default,123,0") switch_client_mock = MagicMock() switch_client_mock.return_value.stderr = None @@ -1199,7 +1199,7 @@ def test_load_attached_within_tmux(server, monkeypatch): monkeypatch.setattr("libtmux.session.Session.switch_client", switch_client_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -1211,7 +1211,7 @@ def test_load_attached_within_tmux(server, monkeypatch): def test_load_attached_within_tmux_detached(server, monkeypatch): # Load a session and attach from within tmux - monkeypatch.setenv('TMUX', "/tmp/tmux-1234/default,123,0") + monkeypatch.setenv("TMUX", "/tmp/tmux-1234/default,123,0") switch_client_mock = MagicMock() switch_client_mock.return_value.stderr = None @@ -1219,7 +1219,7 @@ def test_load_attached_within_tmux_detached(server, monkeypatch): monkeypatch.setattr("libtmux.session.Session.switch_client", switch_client_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -1231,7 +1231,7 @@ def test_load_attached_within_tmux_detached(server, monkeypatch): def test_load_append_windows_to_current_session(server, monkeypatch): yaml_config = loadfixture("workspacebuilder/two_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -1251,21 +1251,21 @@ def test_load_append_windows_to_current_session(server, monkeypatch): def test_debug_info_cli(monkeypatch, tmpdir): - monkeypatch.setenv('SHELL', '/bin/bash') + monkeypatch.setenv("SHELL", "/bin/bash") runner = CliRunner() cli_output = runner.invoke(command_debug_info).output - assert 'environment' in cli_output - assert 'python version' in cli_output - assert 'system PATH' in cli_output - assert 'tmux version' in cli_output - assert 'libtmux version' in cli_output - assert 'tmuxp version' in cli_output - assert 'tmux path' in cli_output - assert 'tmuxp path' in cli_output - assert 'shell' in cli_output - assert 'tmux session' in cli_output - assert 'tmux windows' in cli_output - assert 'tmux panes' in cli_output - assert 'tmux global options' in cli_output - assert 'tmux window options' in cli_output + assert "environment" in cli_output + assert "python version" in cli_output + assert "system PATH" in cli_output + assert "tmux version" in cli_output + assert "libtmux version" in cli_output + assert "tmuxp version" in cli_output + assert "tmux path" in cli_output + assert "tmuxp path" in cli_output + assert "shell" in cli_output + assert "tmux session" in cli_output + assert "tmux windows" in cli_output + assert "tmux panes" in cli_output + assert "tmux global options" in cli_output + assert "tmux window options" in cli_output diff --git a/tests/test_config.py b/tests/test_config.py index 74e58ea8294..181751684bf 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -10,11 +10,11 @@ from . import example_dir from .fixtures import config as fixtures -TMUXP_DIR = os.path.join(os.path.dirname(__file__), '.tmuxp') +TMUXP_DIR = os.path.join(os.path.dirname(__file__), ".tmuxp") def load_yaml(yaml): - return kaptan.Kaptan(handler='yaml').import_config(yaml).get() + return kaptan.Kaptan(handler="yaml").import_config(yaml).get() def load_config(_file): @@ -22,12 +22,12 @@ def load_config(_file): def test_export_json(tmpdir): - json_config_file = tmpdir.join('config.json') + json_config_file = tmpdir.join("config.json") configparser = kaptan.Kaptan() configparser.import_config(fixtures.sampleconfig.sampleconfigdict) - json_config_data = configparser.export('json', indent=2) + json_config_data = configparser.export("json", indent=2) json_config_file.write(json_config_data) @@ -37,13 +37,13 @@ def test_export_json(tmpdir): def test_export_yaml(tmpdir): - yaml_config_file = tmpdir.join('config.yaml') + yaml_config_file = tmpdir.join("config.yaml") configparser = kaptan.Kaptan() sampleconfig = config.inline(fixtures.sampleconfig.sampleconfigdict) configparser.import_config(sampleconfig) - yaml_config_data = configparser.export('yaml', indent=2, default_flow_style=False) + yaml_config_data = configparser.export("yaml", indent=2, default_flow_style=False) yaml_config_file.write(yaml_config_data) @@ -54,25 +54,25 @@ def test_export_yaml(tmpdir): def test_scan_config(tmpdir): configs = [] - garbage_file = tmpdir.join('config.psd') - garbage_file.write('wat') + garbage_file = tmpdir.join("config.psd") + garbage_file.write("wat") for r, d, f in os.walk(str(tmpdir)): - for filela in (x for x in f if x.endswith(('.json', '.ini', 'yaml'))): + for filela in (x for x in f if x.endswith((".json", ".ini", "yaml"))): configs.append(str(tmpdir.join(filela))) files = 0 - if tmpdir.join('config.json').check(): + if tmpdir.join("config.json").check(): files += 1 - assert str(tmpdir.join('config.json')) in configs + assert str(tmpdir.join("config.json")) in configs - if tmpdir.join('config.yaml').check(): + if tmpdir.join("config.yaml").check(): files += 1 - assert str(tmpdir.join('config.yaml')) in configs + assert str(tmpdir.join("config.yaml")) in configs - if tmpdir.join('config.ini').check(): + if tmpdir.join("config.ini").check(): files += 1 - assert str(tmpdir.join('config.ini')) in configs + assert str(tmpdir.join("config.ini")) in configs assert len(configs) == files @@ -96,35 +96,35 @@ def test_config_expand2(): """Tests for :meth:`config.inline()`.""" ibefore_config = { # inline config - 'session_name': 'sampleconfig', - 'start_directory': '~', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "~", + "windows": [ { - 'shell_command': ['top'], - 'window_name': 'editor', - 'panes': [{'shell_command': ['vim']}, {'shell_command': ['cowsay "hey"']}], - 'layout': 'main-verticle', + "shell_command": ["top"], + "window_name": "editor", + "panes": [{"shell_command": ["vim"]}, {"shell_command": ['cowsay "hey"']}], + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}], + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}], }, - {'options': {'automatic-rename': True}, 'panes': [{'shell_command': ['htop']}]}, + {"options": {"automatic-rename": True}, "panes": [{"shell_command": ["htop"]}]}, ], } iafter_config = { - 'session_name': 'sampleconfig', - 'start_directory': '~', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "~", + "windows": [ { - 'shell_command': 'top', - 'window_name': 'editor', - 'panes': ['vim', 'cowsay "hey"'], - 'layout': 'main-verticle', + "shell_command": "top", + "window_name": "editor", + "panes": ["vim", 'cowsay "hey"'], + "layout": "main-verticle", }, - {'window_name': 'logging', 'panes': ['tail -F /var/log/syslog']}, - {'options': {'automatic-rename': True}, 'panes': ['htop']}, + {"window_name": "logging", "panes": ["tail -F /var/log/syslog"]}, + {"options": {"automatic-rename": True}, "panes": ["htop"]}, ], } @@ -139,40 +139,40 @@ def test_inline_config(): """Test config inheritance for the nested 'start_command'.""" inheritance_config_before = { - 'session_name': 'sampleconfig', - 'start_directory': '/', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/", + "windows": [ { - 'window_name': 'editor', - 'start_directory': '~', - 'panes': [{'shell_command': ['vim']}, {'shell_command': ['cowsay "hey"']}], - 'layout': 'main-verticle', + "window_name": "editor", + "start_directory": "~", + "panes": [{"shell_command": ["vim"]}, {"shell_command": ['cowsay "hey"']}], + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}], + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}], }, - {'window_name': 'shufu', 'panes': [{'shell_command': ['htop']}]}, - {'options': {'automatic-rename': True}, 'panes': [{'shell_command': ['htop']}]}, + {"window_name": "shufu", "panes": [{"shell_command": ["htop"]}]}, + {"options": {"automatic-rename": True}, "panes": [{"shell_command": ["htop"]}]}, ], } inheritance_config_after = { - 'session_name': 'sampleconfig', - 'start_directory': '/', - 'windows': [ + "session_name": "sampleconfig", + "start_directory": "/", + "windows": [ { - 'window_name': 'editor', - 'start_directory': '~', - 'panes': [{'shell_command': ['vim']}, {'shell_command': ['cowsay "hey"']}], - 'layout': 'main-verticle', + "window_name": "editor", + "start_directory": "~", + "panes": [{"shell_command": ["vim"]}, {"shell_command": ['cowsay "hey"']}], + "layout": "main-verticle", }, { - 'window_name': 'logging', - 'panes': [{'shell_command': ['tail -F /var/log/syslog']}], + "window_name": "logging", + "panes": [{"shell_command": ["tail -F /var/log/syslog"]}], }, - {'window_name': 'shufu', 'panes': [{'shell_command': ['htop']}]}, - {'options': {'automatic-rename': True}, 'panes': [{'shell_command': ['htop']}]}, + {"window_name": "shufu", "panes": [{"shell_command": ["htop"]}]}, + {"options": {"automatic-rename": True}, "panes": [{"shell_command": ["htop"]}]}, ], } @@ -245,8 +245,8 @@ def test_trickle_window_with_no_pane_config(): sconfig = load_yaml(test_yaml) config.validate_schema(sconfig) - assert config.expand(config.trickle(sconfig))['windows'][1]['panes'][0] == { - 'shell_command': [] + assert config.expand(config.trickle(sconfig))["windows"][1]["panes"][0] == { + "shell_command": [] } @@ -278,7 +278,7 @@ def test_expands_blank_panes(): """ - yaml_config_file = os.path.join(example_dir, 'blank-panes.yaml') + yaml_config_file = os.path.join(example_dir, "blank-panes.yaml") test_config = load_config(yaml_config_file) assert config.expand(test_config) == fixtures.expand_blank.expected @@ -297,7 +297,7 @@ def test_no_session_name(): - htop """ - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() with pytest.raises(exc.ConfigError) as excinfo: @@ -310,7 +310,7 @@ def test_no_windows(): session_name: test session """ - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() with pytest.raises(exc.ConfigError) as excinfo: @@ -333,7 +333,7 @@ def test_no_window_name(): - htop """ - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() with pytest.raises(exc.ConfigError) as excinfo: @@ -372,13 +372,13 @@ def test_replaces_env_variables(monkeypatch): monkeypatch.setenv(str(env_key), str(env_val)) sconfig = config.expand(sconfig) - assert "%s/test" % env_val == sconfig['start_directory'] - assert "%s/test2" % env_val in sconfig['shell_command_before'] - assert "%s/test3" % env_val == sconfig['before_script'] - assert "hi - %s" % env_val == sconfig['session_name'] - assert "%s/moo" % env_val == sconfig['global_options']['default-shell'] - assert "%s/lol" % env_val == sconfig['options']['default-command'] - assert "logging @ %s" % env_val == sconfig['windows'][1]['window_name'] + assert "%s/test" % env_val == sconfig["start_directory"] + assert "%s/test2" % env_val in sconfig["shell_command_before"] + assert "%s/test3" % env_val == sconfig["before_script"] + assert "hi - %s" % env_val == sconfig["session_name"] + assert "%s/moo" % env_val == sconfig["global_options"]["default-shell"] + assert "%s/lol" % env_val == sconfig["options"]["default-command"] + assert "logging @ %s" % env_val == sconfig["windows"][1]["window_name"] def test_plugins(): @@ -393,9 +393,9 @@ def test_plugins(): start_directory: /var/log """ - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() with pytest.raises(exc.ConfigError) as excinfo: config.validate_schema(sconfig) - assert excinfo.matches('only supports list type') + assert excinfo.matches("only supports list type") diff --git a/tests/test_config_teamocil.py b/tests/test_config_teamocil.py index dda802fbd85..721e3878abf 100644 --- a/tests/test_config_teamocil.py +++ b/tests/test_config_teamocil.py @@ -9,7 +9,7 @@ from .fixtures import config_teamocil as fixtures -TMUXP_DIR = os.path.join(os.path.dirname(__file__), '.tmuxp') +TMUXP_DIR = os.path.join(os.path.dirname(__file__), ".tmuxp") @pytest.mark.parametrize( @@ -38,7 +38,7 @@ ], ) def test_config_to_dict(teamocil_yaml, teamocil_dict, tmuxp_dict): - configparser = kaptan.Kaptan(handler='yaml') + configparser = kaptan.Kaptan(handler="yaml") test_config = configparser.import_config(teamocil_yaml) yaml_to_dict = test_config.get() assert yaml_to_dict == teamocil_dict @@ -48,14 +48,14 @@ def test_config_to_dict(teamocil_yaml, teamocil_dict, tmuxp_dict): config.validate_schema(config.import_teamocil(teamocil_dict)) -@pytest.fixture(scope='module') +@pytest.fixture(scope="module") def multisession_config(): """Return loaded multisession teamocil config as a dictionary. Also prevents re-running assertion the loads the yaml, since ordering of deep list items like panes will be inconsistent.""" teamocil_yaml = fixtures.layouts.teamocil_yaml - configparser = kaptan.Kaptan(handler='yaml') + configparser = kaptan.Kaptan(handler="yaml") test_config = configparser.import_config(teamocil_yaml) teamocil_dict = fixtures.layouts.teamocil_dict @@ -66,14 +66,14 @@ def multisession_config(): @pytest.mark.parametrize( "session_name,expected", [ - ('two-windows', fixtures.layouts.two_windows), - ('two-windows-with-filters', fixtures.layouts.two_windows_with_filters), + ("two-windows", fixtures.layouts.two_windows), + ("two-windows-with-filters", fixtures.layouts.two_windows_with_filters), ( - 'two-windows-with-custom-command-options', + "two-windows-with-custom-command-options", fixtures.layouts.two_windows_with_custom_command_options, ), ( - 'three-windows-within-a-session', + "three-windows-within-a-session", fixtures.layouts.three_windows_within_a_session, ), ], diff --git a/tests/test_config_tmuxinator.py b/tests/test_config_tmuxinator.py index 3f2341ca308..88241c22a93 100644 --- a/tests/test_config_tmuxinator.py +++ b/tests/test_config_tmuxinator.py @@ -9,7 +9,7 @@ from .fixtures import config_tmuxinator as fixtures -TMUXP_DIR = os.path.join(os.path.dirname(__file__), '.tmuxp') +TMUXP_DIR = os.path.join(os.path.dirname(__file__), ".tmuxp") @pytest.mark.parametrize( @@ -33,7 +33,7 @@ ], ) def test_config_to_dict(tmuxinator_yaml, tmuxinator_dict, tmuxp_dict): - configparser = kaptan.Kaptan(handler='yaml') + configparser = kaptan.Kaptan(handler="yaml") test_config = configparser.import_config(tmuxinator_yaml) yaml_to_dict = test_config.get() assert yaml_to_dict == tmuxinator_dict diff --git a/tests/test_plugin.py b/tests/test_plugin.py index d894c989378..adb47044cfc 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -31,54 +31,54 @@ def test_all_pass(): def test_tmux_version_fail_min(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxVersionFailMinPlugin() - assert 'tmux-min-version-fail' in str(exc_info.value) + assert "tmux-min-version-fail" in str(exc_info.value) def test_tmux_version_fail_max(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxVersionFailMaxPlugin() - assert 'tmux-max-version-fail' in str(exc_info.value) + assert "tmux-max-version-fail" in str(exc_info.value) def test_tmux_version_fail_incompatible(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxVersionFailIncompatiblePlugin() - assert 'tmux-incompatible-version-fail' in str(exc_info.value) + assert "tmux-incompatible-version-fail" in str(exc_info.value) def test_tmuxp_version_fail_min(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxpVersionFailMinPlugin() - assert 'tmuxp-min-version-fail' in str(exc_info.value) + assert "tmuxp-min-version-fail" in str(exc_info.value) def test_tmuxp_version_fail_max(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxpVersionFailMaxPlugin() - assert 'tmuxp-max-version-fail' in str(exc_info.value) + assert "tmuxp-max-version-fail" in str(exc_info.value) def test_tmuxp_version_fail_incompatible(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: TmuxpVersionFailIncompatiblePlugin() - assert 'tmuxp-incompatible-version-fail' in str(exc_info.value) + assert "tmuxp-incompatible-version-fail" in str(exc_info.value) def test_libtmux_version_fail_min(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: LibtmuxVersionFailMinPlugin() - assert 'libtmux-min-version-fail' in str(exc_info.value) + assert "libtmux-min-version-fail" in str(exc_info.value) def test_libtmux_version_fail_max(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: LibtmuxVersionFailMaxPlugin() - assert 'libtmux-max-version-fail' in str(exc_info.value) + assert "libtmux-max-version-fail" in str(exc_info.value) def test_libtmux_version_fail_incompatible(): - with pytest.raises(TmuxpPluginException, match=r'Incompatible.*') as exc_info: + with pytest.raises(TmuxpPluginException, match=r"Incompatible.*") as exc_info: LibtmuxVersionFailIncompatiblePlugin() - assert 'libtmux-incompatible-version-fail' in str(exc_info.value) + assert "libtmux-incompatible-version-fail" in str(exc_info.value) diff --git a/tests/test_util.py b/tests/test_util.py index 420e1abfd1f..e87c3bf0f96 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -11,7 +11,7 @@ def test_raise_BeforeLoadScriptNotExists_if_not_exists(): - script_file = os.path.join(fixtures_dir, 'script_noexists.sh') + script_file = os.path.join(fixtures_dir, "script_noexists.sh") with pytest.raises(BeforeLoadScriptNotExists): run_before_script(script_file) @@ -21,51 +21,51 @@ def test_raise_BeforeLoadScriptNotExists_if_not_exists(): def test_raise_BeforeLoadScriptError_if_retcode(): - script_file = os.path.join(fixtures_dir, 'script_failed.sh') + script_file = os.path.join(fixtures_dir, "script_failed.sh") with pytest.raises(BeforeLoadScriptError): run_before_script(script_file) def test_return_stdout_if_ok(capsys): - script_file = os.path.join(fixtures_dir, 'script_complete.sh') + script_file = os.path.join(fixtures_dir, "script_complete.sh") run_before_script(script_file) out, err = capsys.readouterr() - assert 'hello' in out + assert "hello" in out def test_beforeload_returncode(): - script_file = os.path.join(fixtures_dir, 'script_failed.sh') + script_file = os.path.join(fixtures_dir, "script_failed.sh") with pytest.raises(exc.BeforeLoadScriptError) as excinfo: run_before_script(script_file) - assert excinfo.match(r'113') + assert excinfo.match(r"113") def test_beforeload_returns_stderr_messages(): - script_file = os.path.join(fixtures_dir, 'script_failed.sh') + script_file = os.path.join(fixtures_dir, "script_failed.sh") with pytest.raises(exc.BeforeLoadScriptError) as excinfo: run_before_script(script_file) - assert excinfo.match(r'failed with returncode') + assert excinfo.match(r"failed with returncode") def test_get_session_should_default_to_local_attached_session(server, monkeypatch): - server.new_session(session_name='myfirstsession') - second_session = server.new_session(session_name='mysecondsession') + server.new_session(session_name="myfirstsession") + second_session = server.new_session(session_name="mysecondsession") # Assign an active pane to the session first_pane_on_second_session_id = second_session.list_windows()[0].list_panes()[0][ - 'pane_id' + "pane_id" ] - monkeypatch.setenv('TMUX_PANE', first_pane_on_second_session_id) + monkeypatch.setenv("TMUX_PANE", first_pane_on_second_session_id) assert get_session(server) == second_session def test_get_session_should_return_first_session_if_no_active_session(server): - first_session = server.new_session(session_name='myfirstsession') - server.new_session(session_name='mysecondsession') + first_session = server.new_session(session_name="myfirstsession") + server.new_session(session_name="mysecondsession") assert get_session(server) == first_session diff --git a/tests/test_workspacebuilder.py b/tests/test_workspacebuilder.py index e85b4091779..03e800ce9d6 100644 --- a/tests/test_workspacebuilder.py +++ b/tests/test_workspacebuilder.py @@ -19,7 +19,7 @@ def test_split_windows(session): yaml_config = loadfixture("workspacebuilder/two_pane.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) @@ -28,7 +28,7 @@ def test_split_windows(session): assert len(s._windows) == window_count for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): - w.select_layout('tiled') # fix glitch with pane size + w.select_layout("tiled") # fix glitch with pane size p = p assert len(s._windows) == window_count assert isinstance(w, Window) @@ -41,7 +41,7 @@ def test_split_windows_three_pane(session): yaml_config = loadfixture("workspacebuilder/three_pane.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) @@ -50,21 +50,21 @@ def test_split_windows_three_pane(session): assert len(s._windows) == window_count for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): - w.select_layout('tiled') # fix glitch with pane size + w.select_layout("tiled") # fix glitch with pane size p = p assert len(s._windows) == window_count assert isinstance(w, Window) assert len(s._windows) == window_count window_count += 1 - w.set_window_option('main-pane-height', 50) - w.select_layout(wconf['layout']) + w.set_window_option("main-pane-height", 50) + w.select_layout(wconf["layout"]) def test_focus_pane_index(session): - yaml_config = loadfixture('workspacebuilder/focus_and_pane.yaml') + yaml_config = loadfixture("workspacebuilder/focus_and_pane.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) @@ -73,10 +73,10 @@ def test_focus_pane_index(session): builder.build(session=session) - assert session.attached_window.name == 'focused window' + assert session.attached_window.name == "focused window" pane_base_index = int( - session.attached_window.show_window_option('pane-base-index', g=True) + session.attached_window.show_window_option("pane-base-index", g=True) ) if not pane_base_index: @@ -94,9 +94,9 @@ def test_focus_pane_index(session): w = session.attached_window - assert w.name != 'man' + assert w.name != "man" - pane_path = '/usr' + pane_path = "/usr" while retry(): p = w.attached_pane @@ -106,15 +106,15 @@ def test_focus_pane_index(session): assert p.current_path == pane_path - proc = session.cmd('show-option', '-gv', 'base-index') + proc = session.cmd("show-option", "-gv", "base-index") base_index = int(proc.stdout[0]) session.server._update_windows() - window3 = session.find_where({'window_index': str(base_index + 2)}) + window3 = session.find_where({"window_index": str(base_index + 2)}) assert isinstance(window3, Window) p = None - pane_path = '/' + pane_path = "/" while retry(): p = window3.attached_pane @@ -126,14 +126,14 @@ def test_focus_pane_index(session): @pytest.mark.skip( - reason=''' + reason=""" Test needs to be rewritten, assertion not reliable across platforms and CI. See https://github.com/tmux-python/tmuxp/issues/310. - '''.strip() + """.strip() ) def test_suppress_history(session): yaml_config = loadfixture("workspacebuilder/suppress_history.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) @@ -141,18 +141,18 @@ def test_suppress_history(session): builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) - inHistoryWindow = session.find_where({'window_name': 'inHistory'}) - isMissingWindow = session.find_where({'window_name': 'isMissing'}) + inHistoryWindow = session.find_where({"window_name": "inHistory"}) + isMissingWindow = session.find_where({"window_name": "isMissing"}) def assertHistory(cmd, hist): - return 'inHistory' in cmd and cmd.endswith(hist) + return "inHistory" in cmd and cmd.endswith(hist) def assertIsMissing(cmd, hist): - return 'isMissing' in cmd and not cmd.endswith(hist) + return "isMissing" in cmd and not cmd.endswith(hist) for w, window_name, assertCase in [ - (inHistoryWindow, 'inHistory', assertHistory), - (isMissingWindow, 'isMissing', assertIsMissing), + (inHistoryWindow, "inHistory", assertHistory), + (isMissingWindow, "isMissing", assertIsMissing), ]: assert w.name == window_name correct = False @@ -161,19 +161,19 @@ def assertIsMissing(cmd, hist): p.select_pane() # Print the last-in-history command in the pane - p.cmd('send-keys', ' fc -ln -1') - p.cmd('send-keys', 'Enter') + p.cmd("send-keys", " fc -ln -1") + p.cmd("send-keys", "Enter") - buffer_name = 'test' + buffer_name = "test" while retry(): # from v0.7.4 libtmux session.cmd adds target -t self.id by default # show-buffer doesn't accept -t, use global cmd. # Get the contents of the pane - p.cmd('capture-pane', '-b', buffer_name) + p.cmd("capture-pane", "-b", buffer_name) - captured_pane = session.server.cmd('show-buffer', '-b', buffer_name) - session.server.cmd('delete-buffer', '-b', buffer_name) + captured_pane = session.server.cmd("show-buffer", "-b", buffer_name) + session.server.cmd("delete-buffer", "-b", buffer_name) # Parse the sent and last-in-history commands sent_cmd = captured_pane.stdout[0].strip() @@ -188,62 +188,62 @@ def assertIsMissing(cmd, hist): def test_session_options(session): yaml_config = loadfixture("workspacebuilder/session_options.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) - assert "/bin/sh" in s.show_option('default-shell') - assert "/bin/sh" in s.show_option('default-command') + assert "/bin/sh" in s.show_option("default-shell") + assert "/bin/sh" in s.show_option("default-command") def test_global_options(session): yaml_config = loadfixture("workspacebuilder/global_options.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) - assert "top" in s.show_option('status-position', _global=True) - assert 493 == s.show_option('repeat-time', _global=True) + assert "top" in s.show_option("status-position", _global=True) + assert 493 == s.show_option("repeat-time", _global=True) def test_global_session_env_options(session, monkeypatch): - visual_silence = 'on' - monkeypatch.setenv(str('VISUAL_SILENCE'), str(visual_silence)) + visual_silence = "on" + monkeypatch.setenv(str("VISUAL_SILENCE"), str(visual_silence)) repeat_time = 738 - monkeypatch.setenv(str('REPEAT_TIME'), str(repeat_time)) + monkeypatch.setenv(str("REPEAT_TIME"), str(repeat_time)) main_pane_height = 8 - monkeypatch.setenv(str('MAIN_PANE_HEIGHT'), str(main_pane_height)) + monkeypatch.setenv(str("MAIN_PANE_HEIGHT"), str(main_pane_height)) yaml_config = loadfixture("workspacebuilder/env_var_options.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) - assert visual_silence in s.show_option('visual-silence', _global=True) - assert repeat_time == s.show_option('repeat-time') - assert main_pane_height == s.attached_window.show_window_option('main-pane-height') + assert visual_silence in s.show_option("visual-silence", _global=True) + assert repeat_time == s.show_option("repeat-time") + assert main_pane_height == s.attached_window.show_window_option("main-pane-height") def test_window_options(session): yaml_config = loadfixture("workspacebuilder/window_options.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) - if has_gte_version('2.3'): - sconfig['windows'][0]['options']['pane-border-format'] = ' #P ' + if has_gte_version("2.3"): + sconfig["windows"][0]["options"]["pane-border-format"] = " #P " builder = WorkspaceBuilder(sconf=sconfig) @@ -251,23 +251,23 @@ def test_window_options(session): assert len(s._windows) == window_count for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): - w.select_layout('tiled') # fix glitch with pane size + w.select_layout("tiled") # fix glitch with pane size p = p assert len(s._windows) == window_count assert isinstance(w, Window) - assert w.show_window_option('main-pane-height') == 5 - if has_gte_version('2.3'): - assert w.show_window_option('pane-border-format') == ' #P ' + assert w.show_window_option("main-pane-height") == 5 + if has_gte_version("2.3"): + assert w.show_window_option("pane-border-format") == " #P " assert len(s._windows) == window_count window_count += 1 - w.select_layout(wconf['layout']) + w.select_layout(wconf["layout"]) @pytest.mark.flaky(reruns=5) def test_window_options_after(session): yaml_config = loadfixture("workspacebuilder/window_options_after.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) @@ -278,7 +278,7 @@ def assert_last_line(p, s): correct = False while retry(): - pane_out = p.cmd('capture-pane', '-p', '-J').stdout + pane_out = p.cmd("capture-pane", "-p", "-J").stdout while not pane_out[-1].strip(): # delete trailing lines tmux 1.8 pane_out.pop() if len(pane_out) > 1 and pane_out[-2].strip() == s: @@ -287,7 +287,7 @@ def assert_last_line(p, s): # Print output for easier debugging if assertion fails if not correct: - print('\n'.join(pane_out)) + print("\n".join(pane_out)) return correct @@ -295,60 +295,60 @@ def assert_last_line(p, s): assert assert_last_line( pane, str(i) ), "Initial command did not execute properly/" + str(i) - pane.cmd('send-keys', 'Up') # Will repeat echo + pane.cmd("send-keys", "Up") # Will repeat echo pane.enter() # in each iteration assert assert_last_line( pane, str(i) ), "Repeated command did not execute properly/" + str(i) - session.cmd('send-keys', ' echo moo') - session.cmd('send-keys', 'Enter') + session.cmd("send-keys", " echo moo") + session.cmd("send-keys", "Enter") for pane in session.attached_window.panes: assert assert_last_line( - pane, 'moo' + pane, "moo" ), "Synchronized command did not execute properly" def test_window_shell(session): yaml_config = loadfixture("workspacebuilder/window_shell.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig) for w, wconf in builder.iter_create_windows(s): - if 'window_shell' in wconf: - assert wconf['window_shell'] == str('top') + if "window_shell" in wconf: + assert wconf["window_shell"] == str("top") while retry(): session.server._update_windows() - if w['window_name'] != 'top': + if w["window_name"] != "top": break - assert w.name != str('top') + assert w.name != str("top") def test_environment_variables(session): yaml_config = loadfixture("workspacebuilder/environment_vars.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session) - assert session.show_environment('FOO') == 'BAR' - assert session.show_environment('PATH') == '/tmp' + assert session.show_environment("FOO") == "BAR" + assert session.show_environment("PATH") == "/tmp" def test_automatic_rename_option(session): """With option automatic-rename: on.""" yaml_config = loadfixture("workspacebuilder/window_automatic_rename.yaml") s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) @@ -358,50 +358,50 @@ def test_automatic_rename_option(session): for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): - w.select_layout('tiled') # fix glitch with pane size + w.select_layout("tiled") # fix glitch with pane size p = p assert len(s._windows), window_count assert isinstance(w, Window) - assert w.show_window_option('automatic-rename') == 'on' + assert w.show_window_option("automatic-rename") == "on" assert len(s._windows) == window_count window_count += 1 - w.select_layout(wconf['layout']) + w.select_layout(wconf["layout"]) - assert s.name != 'tmuxp' + assert s.name != "tmuxp" w = s.windows[0] while retry(): session.server._update_windows() - if w.name != 'sh': + if w.name != "sh": break - assert w.name != 'sh' + assert w.name != "sh" - pane_base_index = w.show_window_option('pane-base-index', g=True) + pane_base_index = w.show_window_option("pane-base-index", g=True) w.select_pane(pane_base_index) while retry(): session.server._update_windows() - if w.name == 'sh': + if w.name == "sh": break - assert w.name == 'sh' + assert w.name == "sh" - w.select_pane('-D') + w.select_pane("-D") while retry(): session.server._update_windows() - if w['window_name'] != 'sh': + if w["window_name"] != "sh": break - assert w.name != 'sh' + assert w.name != "sh" def test_blank_pane_count(session): """:todo: Verify blank panes of various types build into workspaces.""" - yaml_config_file = os.path.join(example_dir, 'blank-panes.yaml') + yaml_config_file = os.path.join(example_dir, "blank-panes.yaml") test_config = kaptan.Kaptan().import_config(yaml_config_file).get() test_config = config.expand(test_config) builder = WorkspaceBuilder(sconf=test_config) @@ -409,25 +409,25 @@ def test_blank_pane_count(session): assert session == builder.session - window1 = session.find_where({'window_name': 'Blank pane test'}) + window1 = session.find_where({"window_name": "Blank pane test"}) assert len(window1._panes) == 3 - window2 = session.find_where({'window_name': 'More blank panes'}) + window2 = session.find_where({"window_name": "More blank panes"}) assert len(window2._panes) == 3 - window3 = session.find_where({'window_name': 'Empty string (return)'}) + window3 = session.find_where({"window_name": "Empty string (return)"}) assert len(window3._panes) == 3 - window4 = session.find_where({'window_name': 'Blank with options'}) + window4 = session.find_where({"window_name": "Blank with options"}) assert len(window4._panes) == 2 def test_start_directory(session, tmpdir): yaml_config = loadfixture("workspacebuilder/start_directory.yaml") - test_dir = str(tmpdir.mkdir('foo bar')) + test_dir = str(tmpdir.mkdir("foo bar")) test_config = yaml_config.format(TMP_DIR=str(tmpdir), TEST_DIR=test_dir) - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(test_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) @@ -436,7 +436,7 @@ def test_start_directory(session, tmpdir): builder.build(session=session) assert session == builder.session - dirs = ['/usr/bin', '/dev', test_dir, '/usr', '/usr'] + dirs = ["/usr/bin", "/dev", test_dir, "/usr", "/usr"] for path, window in zip(dirs, session.windows): for p in window.panes: @@ -467,11 +467,11 @@ def test_start_directory_relative(session, tmpdir): """ yaml_config = loadfixture("workspacebuilder/start_directory_relative.yaml") - test_dir = str(tmpdir.mkdir('foo bar')) - config_dir = str(tmpdir.mkdir('testRelConfigDir')) + test_dir = str(tmpdir.mkdir("foo bar")) + config_dir = str(tmpdir.mkdir("testRelConfigDir")) test_config = yaml_config.format(TEST_DIR=test_dir) - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(test_config).get() # the second argument of os.getcwd() mimics the behavior # the CLI loader will do, but it passes in the config file's location. @@ -486,7 +486,7 @@ def test_start_directory_relative(session, tmpdir): assert session == builder.session - dirs = ['/usr/bin', '/dev', test_dir, config_dir, config_dir] + dirs = ["/usr/bin", "/dev", test_dir, config_dir, config_dir] for path, window in zip(dirs, session.windows): for p in window.panes: @@ -511,19 +511,19 @@ def test_pane_order(session): """ yaml_config = loadfixture("workspacebuilder/pane_ordering.yaml").format( - HOME=os.path.realpath(os.path.expanduser('~')) + HOME=os.path.realpath(os.path.expanduser("~")) ) # test order of `panes` (and pane_index) above aganist pane_dirs pane_paths = [ - '/usr/bin', - '/usr', - '/usr/sbin', - os.path.realpath(os.path.expanduser('~')), + "/usr/bin", + "/usr", + "/usr/sbin", + os.path.realpath(os.path.expanduser("~")), ] s = session - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) @@ -534,7 +534,7 @@ def test_pane_order(session): assert len(s._windows) == window_count for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): - w.select_layout('tiled') # fix glitch with pane size + w.select_layout("tiled") # fix glitch with pane size p = p assert len(s._windows) == window_count @@ -544,7 +544,7 @@ def test_pane_order(session): window_count += 1 for w in session.windows: - pane_base_index = w.show_window_option('pane-base-index', g=True) + pane_base_index = w.show_window_option("pane-base-index", g=True) for p_index, p in enumerate(w.list_panes(), start=pane_base_index): assert int(p_index) == int(p.index) @@ -562,11 +562,11 @@ def test_pane_order(session): def test_window_index(session): yaml_config = loadfixture("workspacebuilder/window_index.yaml") - proc = session.cmd('show-option', '-gv', 'base-index') + proc = session.cmd("show-option", "-gv", "base-index") base_index = int(proc.stdout[0]) - name_index_map = {'zero': 0 + base_index, 'one': 1 + base_index, 'five': 5} + name_index_map = {"zero": 0 + base_index, "one": 1 + base_index, "five": 5} - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) @@ -574,16 +574,16 @@ def test_window_index(session): builder = WorkspaceBuilder(sconf=sconfig) for window, _ in builder.iter_create_windows(session): - expected_index = name_index_map[window['window_name']] - assert int(window['window_index']) == expected_index + expected_index = name_index_map[window["window_name"]] + assert int(window["window_index"]) == expected_index def test_before_load_throw_error_if_retcode_error(server): config_script_fails = loadfixture("workspacebuilder/config_script_fails.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") yaml = config_script_fails.format( fixtures_dir=fixtures_dir, - script_failed=os.path.join(fixtures_dir, 'script_failed.sh'), + script_failed=os.path.join(fixtures_dir, "script_failed.sh"), ) sconfig = sconfig.import_config(yaml).get() @@ -606,10 +606,10 @@ def test_before_load_throw_error_if_file_not_exists(server): config_script_not_exists = loadfixture( "workspacebuilder/config_script_not_exists.yaml" ) - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") yaml = config_script_not_exists.format( fixtures_dir=fixtures_dir, - script_not_exists=os.path.join(fixtures_dir, 'script_not_exists.sh'), + script_not_exists=os.path.join(fixtures_dir, "script_not_exists.sh"), ) sconfig = sconfig.import_config(yaml).get() sconfig = config.expand(sconfig) @@ -623,7 +623,7 @@ def test_before_load_throw_error_if_file_not_exists(server): assert temp_session_exists with pytest.raises((exc.BeforeLoadScriptNotExists, OSError)) as excinfo: builder.build(session=sess) - excinfo.match(r'No such file or directory') + excinfo.match(r"No such file or directory") result = server.has_session(session_name) assert not result, "Kills session if before_script doesn't exist" @@ -632,11 +632,11 @@ def test_before_load_true_if_test_passes(server): config_script_completes = loadfixture( "workspacebuilder/config_script_completes.yaml" ) - assert os.path.exists(os.path.join(fixtures_dir, 'script_complete.sh')) - sconfig = kaptan.Kaptan(handler='yaml') + assert os.path.exists(os.path.join(fixtures_dir, "script_complete.sh")) + sconfig = kaptan.Kaptan(handler="yaml") yaml = config_script_completes.format( fixtures_dir=fixtures_dir, - script_complete=os.path.join(fixtures_dir, 'script_complete.sh'), + script_complete=os.path.join(fixtures_dir, "script_complete.sh"), ) sconfig = sconfig.import_config(yaml).get() @@ -654,11 +654,11 @@ def test_before_load_true_if_test_passes_with_args(server): "workspacebuilder/config_script_completes.yaml" ) - assert os.path.exists(os.path.join(fixtures_dir, 'script_complete.sh')) - sconfig = kaptan.Kaptan(handler='yaml') + assert os.path.exists(os.path.join(fixtures_dir, "script_complete.sh")) + sconfig = kaptan.Kaptan(handler="yaml") yaml = config_script_completes.format( fixtures_dir=fixtures_dir, - script_complete=os.path.join(fixtures_dir, 'script_complete.sh') + ' -v', + script_complete=os.path.join(fixtures_dir, "script_complete.sh") + " -v", ) sconfig = sconfig.import_config(yaml).get() @@ -676,7 +676,7 @@ def test_plugin_system_before_workspace_builder( ): config_plugins = loadfixture("workspacebuilder/plugin_bwb.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -685,14 +685,14 @@ def test_plugin_system_before_workspace_builder( builder.build(session=session) - proc = session.cmd('display-message', '-p', "'#S'") + proc = session.cmd("display-message", "-p", "'#S'") assert proc.stdout[0] == "'plugin_test_bwb'" def test_plugin_system_on_window_create(monkeypatch_plugin_test_packages, session): config_plugins = loadfixture("workspacebuilder/plugin_owc.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -701,14 +701,14 @@ def test_plugin_system_on_window_create(monkeypatch_plugin_test_packages, sessio builder.build(session=session) - proc = session.cmd('display-message', '-p', "'#W'") + proc = session.cmd("display-message", "-p", "'#W'") assert proc.stdout[0] == "'plugin_test_owc'" def test_plugin_system_after_window_finished(monkeypatch_plugin_test_packages, session): config_plugins = loadfixture("workspacebuilder/plugin_awf.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -717,14 +717,14 @@ def test_plugin_system_after_window_finished(monkeypatch_plugin_test_packages, s builder.build(session=session) - proc = session.cmd('display-message', '-p', "'#W'") + proc = session.cmd("display-message", "-p", "'#W'") assert proc.stdout[0] == "'plugin_test_awf'" def test_plugin_system_on_window_create_multiple_windows(session): config_plugins = loadfixture("workspacebuilder/plugin_owc_multiple_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -733,7 +733,7 @@ def test_plugin_system_on_window_create_multiple_windows(session): builder.build(session=session) - proc = session.cmd('list-windows', '-F', "'#W'") + proc = session.cmd("list-windows", "-F", "'#W'") assert "'plugin_test_owc_mw'" in proc.stdout assert "'plugin_test_owc_mw_2'" in proc.stdout @@ -743,7 +743,7 @@ def test_plugin_system_after_window_finished_multiple_windows( ): config_plugins = loadfixture("workspacebuilder/plugin_awf_multiple_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -752,7 +752,7 @@ def test_plugin_system_after_window_finished_multiple_windows( builder.build(session=session) - proc = session.cmd('list-windows', '-F', "'#W'") + proc = session.cmd("list-windows", "-F", "'#W'") assert "'plugin_test_awf_mw'" in proc.stdout assert "'plugin_test_awf_mw_2'" in proc.stdout @@ -760,7 +760,7 @@ def test_plugin_system_after_window_finished_multiple_windows( def test_plugin_system_multiple_plugins(monkeypatch_plugin_test_packages, session): config_plugins = loadfixture("workspacebuilder/plugin_multiple_plugins.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) @@ -770,19 +770,19 @@ def test_plugin_system_multiple_plugins(monkeypatch_plugin_test_packages, sessio builder.build(session=session) # Drop through to the before_script plugin hook - proc = session.cmd('display-message', '-p', "'#S'") + proc = session.cmd("display-message", "-p", "'#S'") assert proc.stdout[0] == "'plugin_test_bwb'" # Drop through to the after_window_finished. This won't succeed # unless on_window_create succeeds because of how the test plugin # override methods are currently written - proc = session.cmd('display-message', '-p', "'#W'") + proc = session.cmd("display-message", "-p", "'#W'") assert proc.stdout[0] == "'mp_test_awf'" def test_load_configs_same_session(server): yaml_config = loadfixture("workspacebuilder/three_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -793,7 +793,7 @@ def test_load_configs_same_session(server): yaml_config = loadfixture("workspacebuilder/two_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -803,7 +803,7 @@ def test_load_configs_same_session(server): yaml_config = loadfixture("workspacebuilder/two_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -815,7 +815,7 @@ def test_load_configs_same_session(server): def test_load_configs_separate_sessions(server): yaml_config = loadfixture("workspacebuilder/three_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -826,7 +826,7 @@ def test_load_configs_separate_sessions(server): yaml_config = loadfixture("workspacebuilder/two_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -839,7 +839,7 @@ def test_load_configs_separate_sessions(server): def test_find_current_active_pane(server, monkeypatch): yaml_config = loadfixture("workspacebuilder/three_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) @@ -847,7 +847,7 @@ def test_find_current_active_pane(server, monkeypatch): yaml_config = loadfixture("workspacebuilder/two_windows.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) diff --git a/tests/test_workspacefreezer.py b/tests/test_workspacefreezer.py index 62acb5bdaf7..f85dc5dd24d 100644 --- a/tests/test_workspacefreezer.py +++ b/tests/test_workspacefreezer.py @@ -11,7 +11,7 @@ def test_freeze_config(session): yaml_config = loadfixture("workspacefreezer/sampleconfig.yaml") - sconfig = kaptan.Kaptan(handler='yaml') + sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) @@ -29,5 +29,5 @@ def test_freeze_config(session): kaptanconf = kaptan.Kaptan() kaptanconf = kaptanconf.import_config(sconf) - kaptanconf.export('json', indent=2) - kaptanconf.export('yaml', indent=2, default_flow_style=False, safe=True) + kaptanconf.export("json", indent=2) + kaptanconf.export("yaml", indent=2, default_flow_style=False, safe=True) diff --git a/tmuxp/__about__.py b/tmuxp/__about__.py index 284692e9b39..915b7928ccb 100644 --- a/tmuxp/__about__.py +++ b/tmuxp/__about__.py @@ -1,13 +1,13 @@ -__title__ = 'tmuxp' -__package_name__ = 'tmuxp' -__version__ = '1.9.4' -__description__ = 'tmux session manager' -__email__ = 'tony@git-pull.com' -__author__ = 'Tony Narlock' -__github__ = 'https://github.com/tmux-python/tmuxp' -__docs__ = 'https://tmuxp.git-pull.com' -__tracker__ = 'https://github.com/tmux-python/tmuxp/issues' -__changes__ = 'https://github.com/tmux-python/tmuxp/blob/master/CHANGES' -__pypi__ = 'https://pypi.org/project/tmuxp/' -__license__ = 'MIT' -__copyright__ = 'Copyright 2013- Tony Narlock' +__title__ = "tmuxp" +__package_name__ = "tmuxp" +__version__ = "1.9.4" +__description__ = "tmux session manager" +__email__ = "tony@git-pull.com" +__author__ = "Tony Narlock" +__github__ = "https://github.com/tmux-python/tmuxp" +__docs__ = "https://tmuxp.git-pull.com" +__tracker__ = "https://github.com/tmux-python/tmuxp/issues" +__changes__ = "https://github.com/tmux-python/tmuxp/blob/master/CHANGES" +__pypi__ = "https://pypi.org/project/tmuxp/" +__license__ = "MIT" +__copyright__ = "Copyright 2013- Tony Narlock" diff --git a/tmuxp/_compat.py b/tmuxp/_compat.py index 45690772914..77ed92d7400 100644 --- a/tmuxp/_compat.py +++ b/tmuxp/_compat.py @@ -26,4 +26,4 @@ def console_to_str(s): try: return s.decode(console_encoding) except UnicodeDecodeError: - return s.decode('utf_8') + return s.decode("utf_8") diff --git a/tmuxp/cli.py b/tmuxp/cli.py index a0ff5773e40..c457a6fd839 100644 --- a/tmuxp/cli.py +++ b/tmuxp/cli.py @@ -33,14 +33,14 @@ logger = logging.getLogger(__name__) -VALID_CONFIG_DIR_FILE_EXTENSIONS = ['.yaml', '.yml', '.json'] +VALID_CONFIG_DIR_FILE_EXTENSIONS = [".yaml", ".yml", ".json"] def get_cwd(): return os.getcwd() -def tmuxp_echo(message=None, log_level='INFO', style_log=False, **click_kwargs): +def tmuxp_echo(message=None, log_level="INFO", style_log=False, **click_kwargs): """ Combines logging.log and click.echo """ @@ -68,13 +68,13 @@ def get_config_dir(): """ paths = [] - if 'TMUXP_CONFIGDIR' in os.environ: - paths.append(os.environ['TMUXP_CONFIGDIR']) - if 'XDG_CONFIG_HOME' in os.environ: - paths.append(os.path.join(os.environ['XDG_CONFIG_HOME'], 'tmuxp')) + if "TMUXP_CONFIGDIR" in os.environ: + paths.append(os.environ["TMUXP_CONFIGDIR"]) + if "XDG_CONFIG_HOME" in os.environ: + paths.append(os.path.join(os.environ["XDG_CONFIG_HOME"], "tmuxp")) else: - paths.append('~/.config/tmuxp/') - paths.append('~/.tmuxp') + paths.append("~/.config/tmuxp/") + paths.append("~/.tmuxp") for path in paths: path = os.path.expanduser(path) @@ -99,10 +99,10 @@ def get_tmuxinator_dir(): -------- :meth:`tmuxp.config.import_tmuxinator` """ - if 'TMUXINATOR_CONFIG' in os.environ: - return os.path.expanduser(os.environ['TMUXINATOR_CONFIG']) + if "TMUXINATOR_CONFIG" in os.environ: + return os.path.expanduser(os.environ["TMUXINATOR_CONFIG"]) - return os.path.expanduser('~/.tmuxinator/') + return os.path.expanduser("~/.tmuxinator/") def get_teamocil_dir(): @@ -118,7 +118,7 @@ def get_teamocil_dir(): -------- :meth:`tmuxp.config.import_teamocil` """ - return os.path.expanduser('~/.teamocil/') + return os.path.expanduser("~/.teamocil/") def _validate_choices(options): @@ -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: {0}.".format(", ".join(options)) ) return value @@ -181,28 +181,28 @@ def set_layout_hook(session, hook_name): hook_name : str hook name to bind to, e.g. 'client-attached' """ - cmd = ['set-hook', '-t', session.id, hook_name] + cmd = ["set-hook", "-t", session.id, hook_name] hook_cmd = [] attached_window = session.attached_window for window in session.windows: # 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("selectw -t {}".format(window.id)) # edit: removed -t, or else it won't respect main-pane-w/h - hook_cmd.append('selectl') - hook_cmd.append('selectw -p') + hook_cmd.append("selectl") + hook_cmd.append("selectw -p") # unset the hook immediately after executing hook_cmd.append( - 'set-hook -u -t {target_session} {hook_name}'.format( + "set-hook -u -t {target_session} {hook_name}".format( target_session=session.id, hook_name=hook_name ) ) - hook_cmd.append('selectw -t {}'.format(attached_window.id)) + hook_cmd.append("selectw -t {}".format(attached_window.id)) # join the hook's commands with semicolons - hook_cmd = '{}'.format('; '.join(hook_cmd)) + hook_cmd = "{}".format("; ".join(hook_cmd)) # append the hook command cmd.append(hook_cmd) @@ -229,8 +229,8 @@ def is_pure_name(path): not os.path.isabs(path) and len(os.path.dirname(path)) == 0 and not os.path.splitext(path)[1] - and path != '.' - and path != '' + and path != "." + and path != "" ) @@ -285,7 +285,7 @@ def get_abs_path(config): def _resolve_path_no_overwrite(config): path = get_abs_path(config) if os.path.exists(path): - raise click.exceptions.UsageError('%s exists. Pick a new filename.' % path) + raise click.exceptions.UsageError("%s exists. Pick a new filename." % path) return path @@ -334,7 +334,7 @@ def scan_config(config, config_dir=None): elif ( not isabs(config) or len(dirname(config)) > 1 - or config == '.' + or config == "." or config == "" or config == "./" ): # if relative, fill in full path @@ -346,22 +346,22 @@ def scan_config(config, config_dir=None): candidates = [ x for x in [ - '%s%s' % (join(config_dir, config), ext) + "%s%s" % (join(config_dir, config), ext) for ext in VALID_CONFIG_DIR_FILE_EXTENSIONS ] if exists(x) ] if not len(candidates): file_error = ( - 'config not found in config dir (yaml/yml/json) %s ' - 'for name' % (config_dir) + "config not found in config dir (yaml/yml/json) %s " + "for name" % (config_dir) ) else: candidates = [ x for x in [ join(config, ext) - for ext in ['.tmuxp.yaml', '.tmuxp.yml', '.tmuxp.json'] + for ext in [".tmuxp.yaml", ".tmuxp.yml", ".tmuxp.json"] ] if exists(x) ] @@ -369,24 +369,24 @@ def scan_config(config, config_dir=None): if len(candidates) > 1: tmuxp_echo( click.style( - 'Multiple .tmuxp.{yml,yaml,json} configs in %s' + "Multiple .tmuxp.{yml,yaml,json} configs in %s" % dirname(config), fg="red", ) ) tmuxp_echo( click.wrap_text( - 'This is undefined behavior, use only one. ' - 'Use file names e.g. myproject.json, coolproject.yaml. ' - 'You can load them by filename.' + "This is undefined behavior, use only one. " + "Use file names e.g. myproject.json, coolproject.yaml. " + "You can load them by filename." ) ) elif not len(candidates): - file_error = 'No tmuxp files found in directory' + file_error = "No tmuxp files found in directory" if len(candidates): config = candidates[0] elif not exists(config): - file_error = 'file not found' + file_error = "file not found" if file_error: raise FileError(file_error, config) @@ -399,30 +399,30 @@ def load_plugins(sconf): Load and return plugins in config """ plugins = [] - if 'plugins' in sconf: - for plugin in sconf['plugins']: + if "plugins" in sconf: + for plugin in sconf["plugins"]: try: - module_name = plugin.split('.') - module_name = '.'.join(module_name[:-1]) - plugin_name = plugin.split('.')[-1] + module_name = plugin.split(".") + module_name = ".".join(module_name[:-1]) + plugin_name = plugin.split(".")[-1] plugin = getattr(importlib.import_module(module_name), plugin_name) plugins.append(plugin()) except exc.TmuxpPluginException as error: if not click.confirm( - '%sSkip loading %s?' - % (click.style(str(error), fg='yellow'), plugin_name), + "%sSkip loading %s?" + % (click.style(str(error), fg="yellow"), plugin_name), default=True, ): click.echo( - click.style('[Not Skipping] ', fg='yellow') - + 'Plugin versions constraint not met. Exiting...' + click.style("[Not Skipping] ", fg="yellow") + + "Plugin versions constraint not met. Exiting..." ) sys.exit(1) 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') + click.style("[Plugin Error] ", fg="red") + + "Couldn't load {0}\n".format(plugin) + + click.style("{0}".format(error), fg="yellow") ) sys.exit(1) @@ -447,11 +447,11 @@ def _reattach(builder): """ for plugin in builder.plugins: plugin.reattach(builder.session) - proc = builder.session.cmd('display-message', '-p', "'#S'") + proc = builder.session.cmd("display-message", "-p", "'#S'") for line in proc.stdout: print(line) - if 'TMUX' in os.environ: + if "TMUX" in os.environ: builder.session.switch_client() else: @@ -469,23 +469,23 @@ def _load_attached(builder, detached): """ builder.build() - if 'TMUX' in os.environ: # tmuxp ran from inside tmux + if "TMUX" in os.environ: # tmuxp ran from inside tmux # unset TMUX, save it, e.g. '/tmp/tmux-1000/default,30668,0' - tmux_env = os.environ.pop('TMUX') + tmux_env = os.environ.pop("TMUX") - if has_gte_version('2.6'): - set_layout_hook(builder.session, 'client-session-changed') + if has_gte_version("2.6"): + set_layout_hook(builder.session, "client-session-changed") builder.session.switch_client() # switch client to new session - os.environ['TMUX'] = tmux_env # set TMUX back again + os.environ["TMUX"] = tmux_env # set TMUX back again else: - if has_gte_version('2.6'): + if has_gte_version("2.6"): # if attaching for first time - set_layout_hook(builder.session, 'client-attached') + set_layout_hook(builder.session, "client-attached") # for cases where user switches client for first time - set_layout_hook(builder.session, 'client-session-changed') + set_layout_hook(builder.session, "client-session-changed") if not detached: builder.session.attach_session() @@ -501,11 +501,11 @@ def _load_detached(builder): """ builder.build() - if has_gte_version('2.6'): # prepare for both cases - set_layout_hook(builder.session, 'client-attached') - set_layout_hook(builder.session, 'client-session-changed') + if has_gte_version("2.6"): # prepare for both cases + set_layout_hook(builder.session, "client-attached") + set_layout_hook(builder.session, "client-session-changed") - print('Session created in detached state.') + print("Session created in detached state.") def _load_append_windows_to_current_session(builder): @@ -518,9 +518,9 @@ def _load_append_windows_to_current_session(builder): """ current_attached_session = builder.find_current_attached_session() builder.build(current_attached_session, append=True) - if has_gte_version('2.6'): # prepare for both cases - set_layout_hook(builder.session, 'client-attached') - set_layout_hook(builder.session, 'client-session-changed') + if has_gte_version("2.6"): # prepare for both cases + set_layout_hook(builder.session, "client-attached") + set_layout_hook(builder.session, "client-session-changed") def _setup_plugins(builder): @@ -645,8 +645,8 @@ def load_workspace( config_file = os.path.realpath(config_file) tmuxp_echo( - click.style('[Loading] ', fg='green') - + click.style(config_file, fg='blue', bold=True) + click.style("[Loading] ", fg="green") + + click.style(config_file, fg="blue", bold=True) ) # kaptan allows us to open a yaml or json file as a dict @@ -656,7 +656,7 @@ def load_workspace( sconfig = config.expand(sconfig, os.path.dirname(config_file)) # Overwrite session name if new_session_name: - sconfig['session_name'] = new_session_name + sconfig["session_name"] = new_session_name # propagate config inheritance (e.g. session -> window, window -> pane) sconfig = config.trickle(sconfig) @@ -667,25 +667,25 @@ def load_workspace( colors=colors, ) - which('tmux') # raise exception if tmux not found + which("tmux") # raise exception if tmux not found try: # load WorkspaceBuilder object for tmuxp config / tmux server builder = WorkspaceBuilder( sconf=sconfig, plugins=load_plugins(sconfig), server=t ) except exc.EmptyConfigException: - tmuxp_echo('%s is empty or parsed no config data' % config_file, err=True) + tmuxp_echo("%s is empty or parsed no config data" % config_file, err=True) return - session_name = sconfig['session_name'] + session_name = sconfig["session_name"] # if the session already exists, prompt the user to attach if builder.session_exists(session_name) and not append: if not detached and ( answer_yes or click.confirm( - '%s is already running. Attach?' - % click.style(session_name, fg='green'), + "%s is already running. Attach?" + % click.style(session_name, fg="green"), default=True, ) ): @@ -698,7 +698,7 @@ def load_workspace( return _setup_plugins(builder) if append: - if 'TMUX' in os.environ: # tmuxp ran from inside tmux + if "TMUX" in os.environ: # tmuxp ran from inside tmux _load_append_windows_to_current_session(builder) else: _load_attached(builder, detached) @@ -710,17 +710,17 @@ def load_workspace( _load_attached(builder, detached) return _setup_plugins(builder) - if 'TMUX' in os.environ: # tmuxp ran from inside tmux + if "TMUX" in os.environ: # tmuxp ran from inside tmux msg = ( "Already inside TMUX, switch to session? yes/no\n" "Or (a)ppend windows in the current active session?\n[y/n/a]" ) - options = ['y', 'n', 'a'] + options = ["y", "n", "a"] choice = click.prompt(msg, value_proc=_validate_choices(options)) - if choice == 'y': + if choice == "y": _load_attached(builder, detached) - elif choice == 'a': + elif choice == "a": _load_append_windows_to_current_session(builder) else: _load_detached(builder) @@ -734,15 +734,15 @@ def load_workspace( tmuxp_echo(e, err=True) choice = click.prompt( - 'Error loading workspace. (k)ill, (a)ttach, (d)etach?', - value_proc=_validate_choices(['k', 'a', 'd']), - default='k', + "Error loading workspace. (k)ill, (a)ttach, (d)etach?", + value_proc=_validate_choices(["k", "a", "d"]), + default="k", ) - if choice == 'k': + if choice == "k": builder.session.kill_session() - tmuxp_echo('Session killed.') - elif choice == 'a': + tmuxp_echo("Session killed.") + elif choice == "a": _reattach(builder) else: sys.exit() @@ -750,12 +750,12 @@ def load_workspace( return _setup_plugins(builder) -@click.group(context_settings={'obj': {}, 'help_option_names': ['-h', '--help']}) -@click.version_option(__version__, '-V', '--version', message='%(prog)s %(version)s') +@click.group(context_settings={"obj": {}, "help_option_names": ["-h", "--help"]}) +@click.version_option(__version__, "-V", "--version", message="%(prog)s %(version)s") @click.option( - '--log-level', - default='INFO', - help='Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)', + "--log-level", + default="INFO", + help="Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)", ) def cli(log_level): """Manage tmux sessions. @@ -766,7 +766,7 @@ def cli(log_level): try: has_minimum_version() except TmuxCommandNotFound: - tmuxp_echo('tmux not found. tmuxp requires you install tmux first.') + tmuxp_echo("tmux not found. tmuxp requires you install tmux first.") sys.exit() except exc.TmuxpException as e: tmuxp_echo(e, err=True) @@ -774,7 +774,7 @@ def cli(log_level): setup_logger(logger=logger, level=log_level.upper()) -def setup_logger(logger=None, level='INFO'): +def setup_logger(logger=None, level="INFO"): """ Setup logging for CLI use. @@ -811,43 +811,41 @@ def startup(config_dir): os.makedirs(config_dir) -@cli.command(name='shell') -@click.argument('session_name', nargs=1, required=False) -@click.argument('window_name', nargs=1, required=False) -@click.option('-S', 'socket_path', help='pass-through for tmux -S') -@click.option('-L', 'socket_name', help='pass-through for tmux -L') +@cli.command(name="shell") +@click.argument("session_name", nargs=1, required=False) +@click.argument("window_name", nargs=1, required=False) +@click.option("-S", "socket_path", help="pass-through for tmux -S") +@click.option("-L", "socket_name", help="pass-through for tmux -L") @click.option( - '-c', - 'command', - help='Instead of opening shell, execute python code in libtmux and exit', + "-c", + "command", + help="Instead of opening shell, execute python code in libtmux and exit", ) @click.option( - '--best', - 'shell', - flag_value='best', - help='Use best shell available in site packages', + "--best", + "shell", + flag_value="best", + help="Use best shell available in site packages", default=True, ) -@click.option('--pdb', 'shell', flag_value='pdb', help='Use plain pdb') +@click.option("--pdb", "shell", flag_value="pdb", help="Use plain pdb") +@click.option("--code", "shell", flag_value="code", help="Use stdlib's code.interact()") @click.option( - '--code', 'shell', flag_value='code', help='Use stdlib\'s code.interact()' + "--ptipython", "shell", flag_value="ptipython", help="Use ptpython + ipython" ) +@click.option("--ptpython", "shell", flag_value="ptpython", help="Use ptpython") +@click.option("--ipython", "shell", flag_value="ipython", help="Use ipython") +@click.option("--bpython", "shell", flag_value="bpython", help="Use bpython") @click.option( - '--ptipython', 'shell', flag_value='ptipython', help='Use ptpython + ipython' -) -@click.option('--ptpython', 'shell', flag_value='ptpython', help='Use ptpython') -@click.option('--ipython', 'shell', flag_value='ipython', help='Use ipython') -@click.option('--bpython', 'shell', flag_value='bpython', help='Use bpython') -@click.option( - '--use-pythonrc/--no-startup', - 'use_pythonrc', - help='Load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code', + "--use-pythonrc/--no-startup", + "use_pythonrc", + help="Load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code", default=False, ) @click.option( - '--use-vi-mode/--no-vi-mode', - 'use_vi_mode', - help='Use vi-mode in ptpython/ptipython', + "--use-vi-mode/--no-vi-mode", + "use_vi_mode", + help="Use vi-mode in ptpython/ptipython", default=False, ) def command_shell( @@ -887,7 +885,7 @@ def command_shell( if command is not None: exec(command) else: - if shell == 'pdb' or (os.getenv('PYTHONBREAKPOINT') and PY3 and PYMINOR >= 7): + if shell == "pdb" or (os.getenv("PYTHONBREAKPOINT") and PY3 and PYMINOR >= 7): from ._compat import breakpoint as tmuxp_breakpoint tmuxp_breakpoint() @@ -907,34 +905,34 @@ def command_shell( ) -@cli.command(name='freeze') -@click.argument('session_name', nargs=1, required=False) -@click.option('-S', 'socket_path', help='pass-through for tmux -S') -@click.option('-L', 'socket_name', help='pass-through for tmux -L') +@cli.command(name="freeze") +@click.argument("session_name", nargs=1, required=False) +@click.option("-S", "socket_path", help="pass-through for tmux -S") +@click.option("-L", "socket_name", help="pass-through for tmux -L") @click.option( - '-f', - '--config-format', - type=click.Choice(['yaml', 'json']), - help='format to save in', + "-f", + "--config-format", + type=click.Choice(["yaml", "json"]), + help="format to save in", ) -@click.option('-o', '--save-to', type=click.Path(exists=False), help='file to save to') +@click.option("-o", "--save-to", type=click.Path(exists=False), help="file to save to") @click.option( - '-y', - '--yes', + "-y", + "--yes", type=bool, is_flag=True, default=False, help="Don't prompt for confirmation", ) @click.option( - '-q', - '--quiet', + "-q", + "--quiet", type=bool, is_flag=True, default=False, help="Don't prompt for confirmation", ) -@click.option('--force', 'force', help='overwrite the config file', is_flag=True) +@click.option("--force", "force", help="overwrite the config file", is_flag=True) def command_freeze( session_name, socket_name, config_format, save_to, socket_path, yes, quiet, force ): @@ -947,12 +945,12 @@ def command_freeze( try: if session_name: - session = t.find_where({'session_name': session_name}) + session = t.find_where({"session_name": session_name}) else: session = util.get_session(t) if not session: - raise exc.TmuxpException('Session not found.') + raise exc.TmuxpException("Session not found.") except exc.TmuxpException as e: print(e) return @@ -964,21 +962,21 @@ def command_freeze( if not quiet: print( - '---------------------------------------------------------------' - '\n' - 'Freeze does its best to snapshot live tmux sessions.\n' + "---------------------------------------------------------------" + "\n" + "Freeze does its best to snapshot live tmux sessions.\n" ) if not ( yes or click.confirm( - 'The new config *WILL* require adjusting afterwards. Save config?' + "The new config *WILL* require adjusting afterwards. Save config?" ) ): if not quiet: print( - 'tmuxp has examples in JSON and YAML format at ' - '\n' - 'View tmuxp docs at .' + "tmuxp has examples in JSON and YAML format at " + "\n" + "View tmuxp docs at ." ) sys.exit() @@ -987,81 +985,81 @@ def command_freeze( save_to = os.path.abspath( os.path.join( get_config_dir(), - '%s.%s' % (sconf.get('session_name'), config_format or 'yaml'), + "%s.%s" % (sconf.get("session_name"), config_format or "yaml"), ) ) dest_prompt = click.prompt( - 'Save to: %s' % save_to, value_proc=get_abs_path, default=save_to + "Save to: %s" % save_to, value_proc=get_abs_path, default=save_to ) if not force and os.path.exists(dest_prompt): - print('%s exists. Pick a new filename.' % dest_prompt) + print("%s exists. Pick a new filename." % dest_prompt) continue dest = dest_prompt dest = os.path.abspath(os.path.relpath(os.path.expanduser(dest))) if config_format is None: - valid_config_formats = ['json', 'yaml'] + valid_config_formats = ["json", "yaml"] _, config_format = os.path.splitext(dest) config_format = config_format[1:].lower() if config_format not in valid_config_formats: config_format = click.prompt( "Couldn't ascertain one of [%s] from file name. Convert to" % ", ".join(valid_config_formats), - value_proc=_validate_choices(['yaml', 'json']), - default='yaml', + value_proc=_validate_choices(["yaml", "json"]), + default="yaml", ) - if config_format == 'yaml': + if config_format == "yaml": newconfig = configparser.export( - 'yaml', indent=2, default_flow_style=False, safe=True + "yaml", indent=2, default_flow_style=False, safe=True ) - elif config_format == 'json': - newconfig = configparser.export('json', indent=2) + elif config_format == "json": + newconfig = configparser.export("json", indent=2) - if yes or click.confirm('Save to %s?' % dest): + if yes or click.confirm("Save to %s?" % dest): destdir = os.path.dirname(dest) if not os.path.isdir(destdir): os.makedirs(destdir) - buf = open(dest, 'w') + buf = open(dest, "w") buf.write(newconfig) buf.close() if not quiet: - print('Saved to %s.' % dest) + print("Saved to %s." % dest) -@cli.command(name='load', short_help='Load tmuxp workspaces.') +@cli.command(name="load", short_help="Load tmuxp workspaces.") @click.pass_context -@click.argument('config', type=ConfigPath(exists=True), nargs=-1) -@click.option('-S', 'socket_path', help='pass-through for tmux -S') -@click.option('-L', 'socket_name', help='pass-through for tmux -L') -@click.option('-f', 'tmux_config_file', help='pass-through for tmux -f') -@click.option('-s', 'new_session_name', help='start new session with new session name') -@click.option('--yes', '-y', 'answer_yes', help='yes', is_flag=True) +@click.argument("config", type=ConfigPath(exists=True), nargs=-1) +@click.option("-S", "socket_path", help="pass-through for tmux -S") +@click.option("-L", "socket_name", help="pass-through for tmux -L") +@click.option("-f", "tmux_config_file", help="pass-through for tmux -f") +@click.option("-s", "new_session_name", help="start new session with new session name") +@click.option("--yes", "-y", "answer_yes", help="yes", is_flag=True) @click.option( - '-d', 'detached', help='Load the session without attaching it', is_flag=True + "-d", "detached", help="Load the session without attaching it", is_flag=True ) @click.option( - '-a', - 'append', - help='Load configuration, appending windows to the current session', + "-a", + "append", + help="Load configuration, appending windows to the current session", is_flag=True, ) @click.option( - 'colors', - '-2', + "colors", + "-2", flag_value=256, default=True, - help='Force tmux to assume the terminal supports 256 colours.', + help="Force tmux to assume the terminal supports 256 colours.", ) @click.option( - 'colors', - '-8', + "colors", + "-8", flag_value=88, - help='Like -2, but indicates that the terminal supports 88 colours.', + help="Like -2, but indicates that the terminal supports 88 colours.", ) -@click.option('--log-file', help='File to log errors/output to') +@click.option("--log-file", help="File to log errors/output to") def command_load( ctx, config, @@ -1104,14 +1102,14 @@ def command_load( logger.addHandler(logfile_handler) tmux_options = { - 'socket_name': socket_name, - 'socket_path': socket_path, - 'tmux_config_file': tmux_config_file, - 'new_session_name': new_session_name, - 'answer_yes': answer_yes, - 'colors': colors, - 'detached': detached, - 'append': append, + "socket_name": socket_name, + "socket_path": socket_path, + "tmux_config_file": tmux_config_file, + "new_session_name": new_session_name, + "answer_yes": answer_yes, + "colors": colors, + "detached": detached, + "append": append, } if not config: @@ -1127,74 +1125,74 @@ def command_load( # Load each configuration but the last to the background for cfg in config[:-1]: opt = tmux_options.copy() - opt.update({'detached': True, 'new_session_name': None}) + opt.update({"detached": True, "new_session_name": None}) load_workspace(cfg, **opt) # todo: obey the -d in the cli args only if user specifies load_workspace(config[-1], **tmux_options) -@cli.group(name='import') +@cli.group(name="import") def import_config_cmd(): """Import a teamocil/tmuxinator config.""" pass def import_config(configfile, importfunc): - configparser = kaptan.Kaptan(handler='yaml') + configparser = kaptan.Kaptan(handler="yaml") configparser.import_config(configfile) newconfig = importfunc(configparser.get()) configparser.import_config(newconfig) config_format = click.prompt( - 'Convert to', value_proc=_validate_choices(['yaml', 'json']), default='yaml' + "Convert to", value_proc=_validate_choices(["yaml", "json"]), default="yaml" ) - if config_format == 'yaml': - newconfig = configparser.export('yaml', indent=2, default_flow_style=False) - elif config_format == 'json': - newconfig = configparser.export('json', indent=2) + if config_format == "yaml": + newconfig = configparser.export("yaml", indent=2, default_flow_style=False) + elif config_format == "json": + newconfig = configparser.export("json", indent=2) else: - sys.exit('Unknown config format.') + sys.exit("Unknown config format.") tmuxp_echo( - newconfig + '---------------------------------------------------------------' - '\n' - 'Configuration import does its best to convert files.\n' + newconfig + "---------------------------------------------------------------" + "\n" + "Configuration import does its best to convert files.\n" ) if click.confirm( - 'The new config *WILL* require adjusting afterwards. Save config?' + "The new config *WILL* require adjusting afterwards. Save config?" ): dest = None while not dest: dest_path = click.prompt( - 'Save to [%s]' % os.getcwd(), value_proc=_resolve_path_no_overwrite + "Save to [%s]" % os.getcwd(), value_proc=_resolve_path_no_overwrite ) # dest = dest_prompt - if click.confirm('Save to %s?' % dest_path): + if click.confirm("Save to %s?" % dest_path): dest = dest_path - buf = open(dest, 'w') + buf = open(dest, "w") buf.write(newconfig) buf.close() - tmuxp_echo('Saved to %s.' % dest) + tmuxp_echo("Saved to %s." % dest) else: tmuxp_echo( - 'tmuxp has examples in JSON and YAML format at ' - '\n' - 'View tmuxp docs at ' + "tmuxp has examples in JSON and YAML format at " + "\n" + "View tmuxp docs at " ) sys.exit() @import_config_cmd.command( - name='teamocil', short_help='Convert and import a teamocil config.' + name="teamocil", short_help="Convert and import a teamocil config." ) @click.argument( - 'configfile', type=ConfigPath(exists=True, config_dir=get_teamocil_dir), nargs=1 + "configfile", type=ConfigPath(exists=True, config_dir=get_teamocil_dir), nargs=1 ) def command_import_teamocil(configfile): """Convert a teamocil config from CONFIGFILE to tmuxp format and import @@ -1204,10 +1202,10 @@ def command_import_teamocil(configfile): @import_config_cmd.command( - name='tmuxinator', short_help='Convert and import a tmuxinator config.' + name="tmuxinator", short_help="Convert and import a tmuxinator config." ) @click.argument( - 'configfile', type=ConfigPath(exists=True, config_dir=get_tmuxinator_dir), nargs=1 + "configfile", type=ConfigPath(exists=True, config_dir=get_tmuxinator_dir), nargs=1 ) def command_import_tmuxinator(configfile): """Convert a tmuxinator config from CONFIGFILE to tmuxp format and import @@ -1215,55 +1213,55 @@ def command_import_tmuxinator(configfile): import_config(configfile, config.import_tmuxinator) -@cli.command(name='convert') +@cli.command(name="convert") @click.option( - '--yes', '-y', 'confirmed', help='Auto confirms with "yes".', is_flag=True + "--yes", "-y", "confirmed", help='Auto confirms with "yes".', is_flag=True ) -@click.argument('config', type=ConfigPath(exists=True), nargs=1) +@click.argument("config", type=ConfigPath(exists=True), nargs=1) def command_convert(confirmed, config): """Convert a tmuxp config between JSON and YAML.""" _, ext = os.path.splitext(config) ext = ext.lower() - if ext == '.json': - to_filetype = 'yaml' - elif ext in ['.yaml', '.yml']: - to_filetype = 'json' + if ext == ".json": + to_filetype = "yaml" + elif ext in [".yaml", ".yml"]: + to_filetype = "json" else: raise click.BadParameter( - 'Unknown filetype: %s (valid: [.json, .yaml, .yml])' % (ext,) + "Unknown filetype: %s (valid: [.json, .yaml, .yml])" % (ext,) ) configparser = kaptan.Kaptan() configparser.import_config(config) - newfile = config.replace(ext, '.%s' % to_filetype) + newfile = config.replace(ext, ".%s" % to_filetype) - export_kwargs = {'default_flow_style': False} if to_filetype == 'yaml' else {} + export_kwargs = {"default_flow_style": False} if to_filetype == "yaml" else {} 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('Save config to %s?' % newfile): + if click.confirm("convert to <%s> to %s?" % (config, to_filetype)): + if click.confirm("Save config to %s?" % newfile): confirmed = True if confirmed: - buf = open(newfile, 'w') + buf = open(newfile, "w") buf.write(newconfig) buf.close() - print('New config saved to <%s>.' % newfile) + print("New config saved to <%s>." % newfile) -@cli.command(name='edit', short_help='Run $EDITOR on config.') -@click.argument('config', type=ConfigPath(exists=True), nargs=1) +@cli.command(name="edit", short_help="Run $EDITOR on config.") +@click.argument("config", type=ConfigPath(exists=True), nargs=1) def command_edit_config(config): config = scan_config(config) - sys_editor = os.environ.get('EDITOR', 'vim') + sys_editor = os.environ.get("EDITOR", "vim") call([sys_editor, config]) @cli.command( - name='ls', short_help='List configured sessions in {}.'.format(get_config_dir()) + name="ls", short_help="List configured sessions in {}.".format(get_config_dir()) ) def command_ls(): tmuxp_dir = get_config_dir() @@ -1275,7 +1273,7 @@ def command_ls(): print(stem) -@cli.command(name='debug-info', short_help='Print out all diagnostic info') +@cli.command(name="debug-info", short_help="Print out all diagnostic info") def command_debug_info(): """ Print debug info to submit with Issues. @@ -1285,54 +1283,54 @@ def prepend_tab(strings): """ Prepend tab to strings in list. """ - return list(map(lambda x: '\t%s' % x, strings)) + return list(map(lambda x: "\t%s" % x, strings)) def output_break(): """ Generate output break. """ - return '-' * 25 + return "-" * 25 def format_tmux_resp(std_resp): """ Format tmux command response for tmuxp stdout. """ - return '\n'.join( + return "\n".join( [ - '\n'.join(prepend_tab(std_resp.stdout)), - click.style('\n'.join(prepend_tab(std_resp.stderr)), fg='red'), + "\n".join(prepend_tab(std_resp.stdout)), + click.style("\n".join(prepend_tab(std_resp.stderr)), fg="red"), ] ) output = [ output_break(), - 'environment:\n%s' - % '\n'.join( + "environment:\n%s" + % "\n".join( prepend_tab( [ - 'dist: %s' % platform.platform(), - 'arch: %s' % platform.machine(), - 'uname: %s' % '; '.join(platform.uname()[:3]), - 'version: %s' % platform.version(), + "dist: %s" % platform.platform(), + "arch: %s" % platform.machine(), + "uname: %s" % "; ".join(platform.uname()[:3]), + "version: %s" % platform.version(), ] ) ), output_break(), - 'python version: %s' % ' '.join(sys.version.split('\n')), - 'system PATH: %s' % os.environ['PATH'], - 'tmux version: %s' % get_version(), - 'libtmux version: %s' % libtmux_version, - 'tmuxp version: %s' % __version__, - 'tmux path: %s' % which('tmux'), - 'tmuxp path: %s' % tmuxp_path, - 'shell: %s' % os.environ['SHELL'], + "python version: %s" % " ".join(sys.version.split("\n")), + "system PATH: %s" % os.environ["PATH"], + "tmux version: %s" % get_version(), + "libtmux version: %s" % libtmux_version, + "tmuxp version: %s" % __version__, + "tmux path: %s" % which("tmux"), + "tmuxp path: %s" % tmuxp_path, + "shell: %s" % os.environ["SHELL"], output_break(), - 'tmux sessions:\n%s' % format_tmux_resp(tmux_cmd('list-sessions')), - 'tmux windows:\n%s' % format_tmux_resp(tmux_cmd('list-windows')), - 'tmux panes:\n%s' % format_tmux_resp(tmux_cmd('list-panes')), - 'tmux global options:\n%s' % format_tmux_resp(tmux_cmd('show-options', '-g')), - 'tmux window options:\n%s' - % format_tmux_resp(tmux_cmd('show-window-options', '-g')), + "tmux sessions:\n%s" % format_tmux_resp(tmux_cmd("list-sessions")), + "tmux windows:\n%s" % format_tmux_resp(tmux_cmd("list-windows")), + "tmux panes:\n%s" % format_tmux_resp(tmux_cmd("list-panes")), + "tmux global options:\n%s" % format_tmux_resp(tmux_cmd("show-options", "-g")), + "tmux window options:\n%s" + % format_tmux_resp(tmux_cmd("show-window-options", "-g")), ] - tmuxp_echo('\n'.join(output)) + tmuxp_echo("\n".join(output)) diff --git a/tmuxp/config.py b/tmuxp/config.py index d7b8047ebe0..243d644fbb7 100644 --- a/tmuxp/config.py +++ b/tmuxp/config.py @@ -28,24 +28,24 @@ def validate_schema(sconf): """ # verify session_name - if 'session_name' not in sconf: + if "session_name" not in sconf: raise exc.ConfigError('config requires "session_name"') - if 'windows' not in sconf: + if "windows" not in sconf: raise exc.ConfigError('config requires list of "windows"') - for window in sconf['windows']: - if 'window_name' not in window: + for window in sconf["windows"]: + if "window_name" not in window: raise exc.ConfigError('config window is missing "window_name"') - if 'plugins' in sconf: - if not isinstance(sconf['plugins'], list): + if "plugins" in sconf: + if not isinstance(sconf["plugins"], list): raise exc.ConfigError('"plugins" only supports list type') return True -def is_config_file(filename, extensions=['.yml', '.yaml', '.json']): +def is_config_file(filename, extensions=[".yml", ".yaml", ".json"]): """ Return True if file has a valid config file type. @@ -65,7 +65,7 @@ def is_config_file(filename, extensions=['.yml', '.yaml', '.json']): def in_dir( - config_dir=os.path.expanduser('~/.tmuxp'), extensions=['.yml', '.yaml', '.json'] + config_dir=os.path.expanduser("~/.tmuxp"), extensions=[".yml", ".yaml", ".json"] ): """ Return a list of configs in ``config_dir``. @@ -84,7 +84,7 @@ def in_dir( configs = [] for filename in os.listdir(config_dir): - if is_config_file(filename, extensions) and not filename.startswith('.'): + if is_config_file(filename, extensions) and not filename.startswith("."): configs.append(filename) return configs @@ -104,7 +104,7 @@ def in_cwd(): configs = [] for filename in os.listdir(os.getcwd()): - if filename.startswith('.tmuxp') and is_config_file(filename): + if filename.startswith(".tmuxp") and is_config_file(filename): configs.append(filename) return configs @@ -144,26 +144,26 @@ def inline(sconf): """ if ( - 'shell_command' in sconf - and isinstance(sconf['shell_command'], list) - and len(sconf['shell_command']) == 1 + "shell_command" in sconf + and isinstance(sconf["shell_command"], list) + and len(sconf["shell_command"]) == 1 ): - sconf['shell_command'] = sconf['shell_command'][0] + sconf["shell_command"] = sconf["shell_command"][0] if len(sconf.keys()) == int(1): - sconf = sconf['shell_command'] + sconf = sconf["shell_command"] if ( - 'shell_command_before' in sconf - and isinstance(sconf['shell_command_before'], list) - and len(sconf['shell_command_before']) == 1 + "shell_command_before" in sconf + and isinstance(sconf["shell_command_before"], list) + and len(sconf["shell_command_before"]) == 1 ): - sconf['shell_command_before'] = sconf['shell_command_before'][0] + sconf["shell_command_before"] = sconf["shell_command_before"][0] # recurse into window and pane config items - if 'windows' in sconf: - sconf['windows'] = [inline(window) for window in sconf['windows']] - if 'panes' in sconf: - sconf['panes'] = [inline(pane) for pane in sconf['panes']] + if "windows" in sconf: + sconf["windows"] = [inline(window) for window in sconf["windows"]] + if "panes" in sconf: + sconf["panes"] = [inline(pane) for pane in sconf["panes"]] return sconf @@ -206,40 +206,40 @@ def expand(sconf, cwd=None, parent=None): if not cwd: cwd = os.getcwd() - if 'session_name' in sconf: - sconf['session_name'] = expandshell(sconf['session_name']) - if 'window_name' in sconf: - sconf['window_name'] = expandshell(sconf['window_name']) - if 'environment' in sconf: - for key in sconf['environment']: - val = sconf['environment'][key] + if "session_name" in sconf: + sconf["session_name"] = expandshell(sconf["session_name"]) + if "window_name" in sconf: + sconf["window_name"] = expandshell(sconf["window_name"]) + if "environment" in sconf: + for key in sconf["environment"]: + val = sconf["environment"][key] val = expandshell(val) - if any(val.startswith(a) for a in ['.', './']): + if any(val.startswith(a) for a in [".", "./"]): val = os.path.normpath(os.path.join(cwd, val)) - sconf['environment'][key] = val - if 'global_options' in sconf: - for key in sconf['global_options']: - val = sconf['global_options'][key] + sconf["environment"][key] = val + if "global_options" in sconf: + for key in sconf["global_options"]: + val = sconf["global_options"][key] if isinstance(val, str): val = expandshell(val) - if any(val.startswith(a) for a in ['.', './']): + if any(val.startswith(a) for a in [".", "./"]): val = os.path.normpath(os.path.join(cwd, val)) - sconf['global_options'][key] = val - if 'options' in sconf: - for key in sconf['options']: - val = sconf['options'][key] + sconf["global_options"][key] = val + if "options" in sconf: + for key in sconf["options"]: + val = sconf["options"][key] if isinstance(val, str): val = expandshell(val) - if any(val.startswith(a) for a in ['.', './']): + if any(val.startswith(a) for a in [".", "./"]): val = os.path.normpath(os.path.join(cwd, val)) - sconf['options'][key] = val + sconf["options"][key] = val # Any config section, session, window, pane that can contain the # 'shell_command' value - if 'start_directory' in sconf: - sconf['start_directory'] = expandshell(sconf['start_directory']) - start_path = sconf['start_directory'] - if any(start_path.startswith(a) for a in ['.', './']): + if "start_directory" in sconf: + sconf["start_directory"] = expandshell(sconf["start_directory"]) + start_path = sconf["start_directory"] + if any(start_path.startswith(a) for a in [".", "./"]): # if window has a session, or pane has a window with a # start_directory of . or ./, make sure the start_directory can be # relative to the parent. @@ -247,67 +247,67 @@ def expand(sconf, cwd=None, parent=None): # This is for the case where you may be loading a config from # outside your shell current directory. if parent: - cwd = parent['start_directory'] + cwd = parent["start_directory"] start_path = os.path.normpath(os.path.join(cwd, start_path)) - sconf['start_directory'] = start_path + sconf["start_directory"] = start_path - if 'before_script' in sconf: - sconf['before_script'] = expandshell(sconf['before_script']) - if any(sconf['before_script'].startswith(a) for a in ['.', './']): - sconf['before_script'] = os.path.normpath( - os.path.join(cwd, sconf['before_script']) + if "before_script" in sconf: + sconf["before_script"] = expandshell(sconf["before_script"]) + if any(sconf["before_script"].startswith(a) for a in [".", "./"]): + sconf["before_script"] = os.path.normpath( + os.path.join(cwd, sconf["before_script"]) ) - if 'shell_command' in sconf and isinstance(sconf['shell_command'], str): - sconf['shell_command'] = [sconf['shell_command']] + if "shell_command" in sconf and isinstance(sconf["shell_command"], str): + sconf["shell_command"] = [sconf["shell_command"]] - if 'shell_command_before' in sconf and isinstance( - sconf['shell_command_before'], str + if "shell_command_before" in sconf and isinstance( + sconf["shell_command_before"], str ): - sconf['shell_command_before'] = [sconf['shell_command_before']] + sconf["shell_command_before"] = [sconf["shell_command_before"]] - if 'shell_command_before' in sconf and isinstance( - sconf['shell_command_before'], list + if "shell_command_before" in sconf and isinstance( + sconf["shell_command_before"], list ): - sconf['shell_command_before'] = [ - expandshell(scmd) for scmd in sconf['shell_command_before'] + sconf["shell_command_before"] = [ + expandshell(scmd) for scmd in sconf["shell_command_before"] ] # recurse into window and pane config items - if 'windows' in sconf: - sconf['windows'] = [expand(window, parent=sconf) for window in sconf['windows']] - elif 'panes' in sconf: + if "windows" in sconf: + sconf["windows"] = [expand(window, parent=sconf) for window in sconf["windows"]] + elif "panes" in sconf: - for pconf in sconf['panes']: - p_index = sconf['panes'].index(pconf) + for pconf in sconf["panes"]: + p_index = sconf["panes"].index(pconf) p = copy.deepcopy(pconf) - pconf = sconf['panes'][p_index] = {} + pconf = sconf["panes"][p_index] = {} if isinstance(p, str): - p = {'shell_command': [p]} + p = {"shell_command": [p]} elif not p: - p = {'shell_command': []} + p = {"shell_command": []} assert isinstance(p, dict) - if 'shell_command' in p: - cmd = p['shell_command'] + if "shell_command" in p: + cmd = p["shell_command"] - if isinstance(p['shell_command'], str): + if isinstance(p["shell_command"], str): cmd = [cmd] - if not cmd or any(a == cmd for a in [None, 'blank', 'pane']): + if not cmd or any(a == cmd for a in [None, "blank", "pane"]): cmd = [] if isinstance(cmd, list) and len(cmd) == int(1): - if any(a in cmd for a in [None, 'blank', 'pane']): + if any(a in cmd for a in [None, "blank", "pane"]): cmd = [] - p['shell_command'] = cmd + p["shell_command"] = cmd else: - p['shell_command'] = [] + p["shell_command"] = [] pconf.update(p) - sconf['panes'] = [expand(pane, parent=sconf) for pane in sconf['panes']] + sconf["panes"] = [expand(pane, parent=sconf) for pane in sconf["panes"]] return sconf @@ -335,57 +335,57 @@ def trickle(sconf): # prepends a pane's ``shell_command`` list with the window and sessions' # ``shell_command_before``. - if 'start_directory' in sconf: - session_start_directory = sconf['start_directory'] + if "start_directory" in sconf: + session_start_directory = sconf["start_directory"] else: session_start_directory = None - if 'suppress_history' in sconf: - suppress_history = sconf['suppress_history'] + if "suppress_history" in sconf: + suppress_history = sconf["suppress_history"] else: suppress_history = None - for windowconfig in sconf['windows']: + for windowconfig in sconf["windows"]: # Prepend start_directory to relative window commands if session_start_directory: - if 'start_directory' not in windowconfig: - windowconfig['start_directory'] = session_start_directory + if "start_directory" not in windowconfig: + windowconfig["start_directory"] = session_start_directory else: if not any( - windowconfig['start_directory'].startswith(a) for a in ['~', '/'] + windowconfig["start_directory"].startswith(a) for a in ["~", "/"] ): window_start_path = os.path.join( - session_start_directory, windowconfig['start_directory'] + session_start_directory, windowconfig["start_directory"] ) - windowconfig['start_directory'] = window_start_path + windowconfig["start_directory"] = window_start_path # We only need to trickle to the window, workspace builder checks wconf if suppress_history is not None: - if 'suppress_history' not in windowconfig: - windowconfig['suppress_history'] = suppress_history + if "suppress_history" not in windowconfig: + windowconfig["suppress_history"] = suppress_history # If panes were NOT specified for a window, assume that a single pane # with no shell commands is desired - if 'panes' not in windowconfig: - windowconfig['panes'] = [{'shell_command': []}] + if "panes" not in windowconfig: + windowconfig["panes"] = [{"shell_command": []}] - for paneconfig in windowconfig['panes']: + for paneconfig in windowconfig["panes"]: commands_before = [] # Prepend shell_command_before to commands - if 'shell_command_before' in sconf: - commands_before.extend(sconf['shell_command_before']) - if 'shell_command_before' in windowconfig: - commands_before.extend(windowconfig['shell_command_before']) - if 'shell_command_before' in paneconfig: - commands_before.extend(paneconfig['shell_command_before']) - - if 'shell_command' in paneconfig: - commands_before.extend(paneconfig['shell_command']) - - p_index = windowconfig['panes'].index(paneconfig) - windowconfig['panes'][p_index]['shell_command'] = commands_before + if "shell_command_before" in sconf: + commands_before.extend(sconf["shell_command_before"]) + if "shell_command_before" in windowconfig: + commands_before.extend(windowconfig["shell_command_before"]) + if "shell_command_before" in paneconfig: + commands_before.extend(paneconfig["shell_command_before"]) + + if "shell_command" in paneconfig: + commands_before.extend(paneconfig["shell_command"]) + + p_index = windowconfig["panes"].index(paneconfig) + windowconfig["panes"][p_index]["shell_command"] = commands_before # paneconfig['shell_command'] = commands_before return sconf @@ -408,79 +408,79 @@ def import_tmuxinator(sconf): tmuxp_config = {} - if 'project_name' in sconf: - tmuxp_config['session_name'] = sconf.pop('project_name') - elif 'name' in sconf: - tmuxp_config['session_name'] = sconf.pop('name') + if "project_name" in sconf: + tmuxp_config["session_name"] = sconf.pop("project_name") + elif "name" in sconf: + tmuxp_config["session_name"] = sconf.pop("name") else: - tmuxp_config['session_name'] = None + tmuxp_config["session_name"] = None - if 'project_root' in sconf: - tmuxp_config['start_directory'] = sconf.pop('project_root') - elif 'root' in sconf: - tmuxp_config['start_directory'] = sconf.pop('root') + if "project_root" in sconf: + tmuxp_config["start_directory"] = sconf.pop("project_root") + elif "root" in sconf: + tmuxp_config["start_directory"] = sconf.pop("root") - if 'cli_args' in sconf: - tmuxp_config['config'] = sconf['cli_args'] + if "cli_args" in sconf: + tmuxp_config["config"] = sconf["cli_args"] - if '-f' in tmuxp_config['config']: - tmuxp_config['config'] = tmuxp_config['config'].replace('-f', '').strip() - elif 'tmux_options' in sconf: - tmuxp_config['config'] = sconf['tmux_options'] + if "-f" in tmuxp_config["config"]: + tmuxp_config["config"] = tmuxp_config["config"].replace("-f", "").strip() + elif "tmux_options" in sconf: + tmuxp_config["config"] = sconf["tmux_options"] - if '-f' in tmuxp_config['config']: - tmuxp_config['config'] = tmuxp_config['config'].replace('-f', '').strip() + if "-f" in tmuxp_config["config"]: + tmuxp_config["config"] = tmuxp_config["config"].replace("-f", "").strip() - if 'socket_name' in sconf: - tmuxp_config['socket_name'] = sconf['socket_name'] + if "socket_name" in sconf: + tmuxp_config["socket_name"] = sconf["socket_name"] - tmuxp_config['windows'] = [] + tmuxp_config["windows"] = [] - if 'tabs' in sconf: - sconf['windows'] = sconf.pop('tabs') + if "tabs" in sconf: + sconf["windows"] = sconf.pop("tabs") - if 'pre' in sconf and 'pre_window' in sconf: - tmuxp_config['shell_command'] = sconf['pre'] + if "pre" in sconf and "pre_window" in sconf: + tmuxp_config["shell_command"] = sconf["pre"] - if isinstance(sconf['pre'], str): - tmuxp_config['shell_command_before'] = [sconf['pre_window']] + if isinstance(sconf["pre"], str): + tmuxp_config["shell_command_before"] = [sconf["pre_window"]] else: - tmuxp_config['shell_command_before'] = sconf['pre_window'] - elif 'pre' in sconf: - if isinstance(sconf['pre'], str): - tmuxp_config['shell_command_before'] = [sconf['pre']] + tmuxp_config["shell_command_before"] = sconf["pre_window"] + elif "pre" in sconf: + if isinstance(sconf["pre"], str): + tmuxp_config["shell_command_before"] = [sconf["pre"]] else: - tmuxp_config['shell_command_before'] = sconf['pre'] + tmuxp_config["shell_command_before"] = sconf["pre"] - if 'rbenv' in sconf: - if 'shell_command_before' not in tmuxp_config: - tmuxp_config['shell_command_before'] = [] - tmuxp_config['shell_command_before'].append('rbenv shell %s' % sconf['rbenv']) + if "rbenv" in sconf: + if "shell_command_before" not in tmuxp_config: + tmuxp_config["shell_command_before"] = [] + tmuxp_config["shell_command_before"].append("rbenv shell %s" % sconf["rbenv"]) - for w in sconf['windows']: + for w in sconf["windows"]: for k, v in w.items(): - windowdict = {'window_name': k} + windowdict = {"window_name": k} if isinstance(v, str) or v is None: - windowdict['panes'] = [v] - tmuxp_config['windows'].append(windowdict) + windowdict["panes"] = [v] + tmuxp_config["windows"].append(windowdict) continue elif isinstance(v, list): - windowdict['panes'] = v - tmuxp_config['windows'].append(windowdict) + windowdict["panes"] = v + tmuxp_config["windows"].append(windowdict) continue - if 'pre' in v: - windowdict['shell_command_before'] = v['pre'] - if 'panes' in v: - windowdict['panes'] = v['panes'] - if 'root' in v: - windowdict['start_directory'] = v['root'] + if "pre" in v: + windowdict["shell_command_before"] = v["pre"] + if "panes" in v: + windowdict["panes"] = v["panes"] + if "root" in v: + windowdict["start_directory"] = v["root"] - if 'layout' in v: - windowdict['layout'] = v['layout'] - tmuxp_config['windows'].append(windowdict) + if "layout" in v: + windowdict["layout"] = v["layout"] + tmuxp_config["windows"].append(windowdict) return tmuxp_config @@ -508,51 +508,51 @@ def import_teamocil(sconf): tmuxp_config = {} - if 'session' in sconf: - sconf = sconf['session'] + if "session" in sconf: + sconf = sconf["session"] - if 'name' in sconf: - tmuxp_config['session_name'] = sconf['name'] + if "name" in sconf: + tmuxp_config["session_name"] = sconf["name"] else: - tmuxp_config['session_name'] = None + tmuxp_config["session_name"] = None - if 'root' in sconf: - tmuxp_config['start_directory'] = sconf.pop('root') + if "root" in sconf: + tmuxp_config["start_directory"] = sconf.pop("root") - tmuxp_config['windows'] = [] + tmuxp_config["windows"] = [] - for w in sconf['windows']: + for w in sconf["windows"]: - windowdict = {'window_name': w['name']} + windowdict = {"window_name": w["name"]} - if 'clear' in w: - windowdict['clear'] = w['clear'] + if "clear" in w: + windowdict["clear"] = w["clear"] - if 'filters' in w: - if 'before' in w['filters']: - for b in w['filters']['before']: - windowdict['shell_command_before'] = w['filters']['before'] - if 'after' in w['filters']: - for b in w['filters']['after']: - windowdict['shell_command_after'] = w['filters']['after'] + if "filters" in w: + if "before" in w["filters"]: + for b in w["filters"]["before"]: + windowdict["shell_command_before"] = w["filters"]["before"] + if "after" in w["filters"]: + for b in w["filters"]["after"]: + windowdict["shell_command_after"] = w["filters"]["after"] - if 'root' in w: - windowdict['start_directory'] = w.pop('root') + if "root" in w: + windowdict["start_directory"] = w.pop("root") - if 'splits' in w: - w['panes'] = w.pop('splits') + if "splits" in w: + w["panes"] = w.pop("splits") - if 'panes' in w: - for p in w['panes']: - if 'cmd' in p: - p['shell_command'] = p.pop('cmd') - if 'width' in p: + if "panes" in w: + for p in w["panes"]: + if "cmd" in p: + p["shell_command"] = p.pop("cmd") + if "width" in p: # todo support for height/width - p.pop('width') - windowdict['panes'] = w['panes'] + p.pop("width") + windowdict["panes"] = w["panes"] - if 'layout' in w: - windowdict['layout'] = w['layout'] - tmuxp_config['windows'].append(windowdict) + if "layout" in w: + windowdict["layout"] = w["layout"] + tmuxp_config["windows"].append(windowdict) return tmuxp_config diff --git a/tmuxp/exc.py b/tmuxp/exc.py index 7ddcb24a097..7f5e38adde9 100644 --- a/tmuxp/exc.py +++ b/tmuxp/exc.py @@ -54,10 +54,10 @@ def __init__(self, returncode, cmd, output=None): self.cmd = cmd self.output = output self.message = ( - 'before_script failed with returncode {returncode}.\n' - 'command: {cmd}\n' - 'Error output:\n' - '{output}' + "before_script failed with returncode {returncode}.\n" + "command: {cmd}\n" + "Error output:\n" + "{output}" ).format(returncode=self.returncode, cmd=self.cmd, output=self.output) def __str__(self): diff --git a/tmuxp/log.py b/tmuxp/log.py index 15f3b8b6699..98db7ec6331 100644 --- a/tmuxp/log.py +++ b/tmuxp/log.py @@ -11,25 +11,25 @@ from colorama import Fore, Style LEVEL_COLORS = { - 'DEBUG': Fore.BLUE, # Blue - 'INFO': Fore.GREEN, # Green - 'WARNING': Fore.YELLOW, - 'ERROR': Fore.RED, - 'CRITICAL': Fore.RED, + "DEBUG": Fore.BLUE, # Blue + "INFO": Fore.GREEN, # Green + "WARNING": Fore.YELLOW, + "ERROR": Fore.RED, + "CRITICAL": Fore.RED, } LOG_LEVELS = { - 'CRITICAL': 50, - 'ERROR': 40, - 'WARNING': 30, - 'INFO': 20, - 'DEBUG': 10, - 'NOTSET': 0, + "CRITICAL": 50, + "ERROR": 40, + "WARNING": 30, + "INFO": 20, + "DEBUG": 10, + "NOTSET": 0, } def set_style( - message, stylized, style_before=None, style_after=None, prefix='', suffix='' + message, stylized, style_before=None, style_after=None, prefix="", suffix="" ): if stylized: return prefix + style_before + message + style_after + suffix @@ -55,27 +55,27 @@ def default_log_template(self, record, stylized=False): reset = Style.RESET_ALL levelname = set_style( - '(%(levelname)s)', + "(%(levelname)s)", stylized, style_before=(LEVEL_COLORS.get(record.levelname) + Style.BRIGHT), style_after=Style.RESET_ALL, - suffix=' ', + suffix=" ", ) asctime = set_style( - '%(asctime)s', + "%(asctime)s", stylized, style_before=(Fore.BLACK + Style.DIM + Style.BRIGHT), style_after=(Fore.RESET + Style.RESET_ALL), - prefix='[', - suffix=']', + prefix="[", + suffix="]", ) name = set_style( - '%(name)s', + "%(name)s", stylized, style_before=(Fore.WHITE + Style.DIM + Style.BRIGHT), style_after=(Fore.RESET + Style.RESET_ALL), - prefix=' ', - suffix=' ', + prefix=" ", + suffix=" ", ) if stylized: @@ -96,7 +96,7 @@ def format(self, record): except Exception as e: record.message = "Bad message (%r): %r" % (e, record.__dict__) - date_format = '%H:%m:%S' + date_format = "%H:%m:%S" record.asctime = time.strftime(date_format, self.converter(record.created)) prefix = self.template(record) % record.__dict__ @@ -126,39 +126,39 @@ def debug_log_template(self, record): levelname = ( LEVEL_COLORS.get(record.levelname) + Style.BRIGHT - + '(%(levelname)1.1s)' + + "(%(levelname)1.1s)" + Style.RESET_ALL - + ' ' + + " " ) asctime = ( - '[' + "[" + Fore.BLACK + Style.DIM + Style.BRIGHT - + '%(asctime)s' + + "%(asctime)s" + Fore.RESET + Style.RESET_ALL - + ']' + + "]" ) name = ( - ' ' + " " + Fore.WHITE + Style.DIM + Style.BRIGHT - + '%(name)s' + + "%(name)s" + Fore.RESET + Style.RESET_ALL - + ' ' + + " " ) - module_funcName = Fore.GREEN + Style.BRIGHT + '%(module)s.%(funcName)s()' + module_funcName = Fore.GREEN + Style.BRIGHT + "%(module)s.%(funcName)s()" lineno = ( Fore.BLACK + Style.DIM + Style.BRIGHT - + ':' + + ":" + Style.RESET_ALL + Fore.CYAN - + '%(lineno)d' + + "%(lineno)d" ) tpl = reset + levelname + asctime + name + module_funcName + lineno + reset diff --git a/tmuxp/plugin.py b/tmuxp/plugin.py index 759e0bb4714..58cb500d72f 100644 --- a/tmuxp/plugin.py +++ b/tmuxp/plugin.py @@ -7,19 +7,19 @@ from .exc import TmuxpPluginException #: Minimum version of tmux required to run libtmux -TMUX_MIN_VERSION = '1.8' +TMUX_MIN_VERSION = "1.8" #: Most recent version of tmux supported TMUX_MAX_VERSION = None #: Minimum version of libtmux required to run libtmux -LIBTMUX_MIN_VERSION = '0.8.3' +LIBTMUX_MIN_VERSION = "0.8.3" #: Most recent version of libtmux supported LIBTMUX_MAX_VERSION = None #: Minimum version of tmuxp required to use plugins -TMUXP_MIN_VERSION = '1.6.0' +TMUXP_MIN_VERSION = "1.6.0" #: Most recent version of tmuxp TMUXP_MAX_VERSION = None @@ -28,7 +28,7 @@ class TmuxpPlugin: def __init__( self, - plugin_name='tmuxp-plugin', + plugin_name="tmuxp-plugin", tmux_min_version=TMUX_MIN_VERSION, tmux_max_version=TMUX_MAX_VERSION, tmux_version_incompatible=None, @@ -87,27 +87,27 @@ def __init__( self.tmuxp_version = LooseVersion(__version__) self.version_constraints = { - 'tmux': { - 'version': self.tmux_version, - 'vmin': tmux_min_version, - 'vmax': tmux_max_version, - 'incompatible': tmux_version_incompatible + "tmux": { + "version": self.tmux_version, + "vmin": tmux_min_version, + "vmax": tmux_max_version, + "incompatible": tmux_version_incompatible if tmux_version_incompatible else [], }, - 'libtmux': { - 'version': self.libtmux_version, - 'vmin': libtmux_min_version, - 'vmax': libtmux_max_version, - 'incompatible': libtmux_version_incompatible + "libtmux": { + "version": self.libtmux_version, + "vmin": libtmux_min_version, + "vmax": libtmux_max_version, + "incompatible": libtmux_version_incompatible if libtmux_version_incompatible else [], }, - 'tmuxp': { - 'version': self.tmuxp_version, - 'vmin': tmuxp_min_version, - 'vmax': tmuxp_max_version, - 'incompatible': tmuxp_version_incompatible + "tmuxp": { + "version": self.tmuxp_version, + "vmin": tmuxp_min_version, + "vmax": tmuxp_max_version, + "incompatible": tmuxp_version_incompatible if tmuxp_version_incompatible else [], }, @@ -124,9 +124,9 @@ def _version_check(self): assert self._pass_version_check(**constraints) except AssertionError: raise TmuxpPluginException( - 'Incompatible {dep} version: {version}\n{plugin_name} ' - 'requirements:\nmin: {vmin} | max: {vmax} | ' - 'incompatible: {incompatible}\n'.format( + "Incompatible {dep} version: {version}\n{plugin_name} " + "requirements:\nmin: {vmin} | max: {vmax} | " + "incompatible: {incompatible}\n".format( dep=dep, plugin_name=self.plugin_name, **constraints ) ) diff --git a/tmuxp/shell.py b/tmuxp/shell.py index 3607b752906..33936d28f14 100644 --- a/tmuxp/shell.py +++ b/tmuxp/shell.py @@ -58,14 +58,14 @@ def has_bpython(): def detect_best_shell(): if has_ptipython(): - return 'ptipython' + return "ptipython" elif has_ptpython(): - return 'ptpython' + return "ptpython" elif has_ipython(): - return 'ipython' + return "ipython" elif has_bpython(): - return 'bpython' - return 'code' + return "bpython" + return "code" def get_bpython(options, extra_args=None): @@ -78,15 +78,15 @@ def launch_bpython(): imported_objects = get_launch_args(**options) kwargs = {} if extra_args: - kwargs['args'] = extra_args + kwargs["args"] = extra_args embed(imported_objects, **kwargs) return launch_bpython def get_ipython_arguments(): - ipython_args = 'IPYTHON_ARGUMENTS' - return os.environ.get(ipython_args, '').split() + ipython_args = "IPYTHON_ARGUMENTS" + return os.environ.get(ipython_args, "").split() def get_ipython(options, **extra_args): @@ -122,7 +122,7 @@ def get_ptpython(options, vi_mode=False): def launch_ptpython(): imported_objects = get_launch_args(**options) - history_filename = os.path.expanduser('~/.ptpython_history') + history_filename = os.path.expanduser("~/.ptpython_history") embed( globals=imported_objects, history_filename=history_filename, @@ -148,7 +148,7 @@ def get_ptipython(options, vi_mode=False): def launch_ptipython(): imported_objects = get_launch_args(**options) - history_filename = os.path.expanduser('~/.ptpython_history') + history_filename = os.path.expanduser("~/.ptpython_history") embed( user_ns=imported_objects, history_filename=history_filename, @@ -163,15 +163,15 @@ def get_launch_args(**kwargs): import libtmux return { - 'libtmux': libtmux, - 'Server': libtmux.Server, - 'Session': libtmux.Session, - 'Window': libtmux.Window, - 'Pane': libtmux.Pane, - 'server': kwargs.get('server'), - 'session': kwargs.get('session'), - 'window': kwargs.get('window'), - 'pane': kwargs.get('pane'), + "libtmux": libtmux, + "Server": libtmux.Server, + "Session": libtmux.Session, + "Window": libtmux.Window, + "Pane": libtmux.Pane, + "server": kwargs.get("server"), + "session": kwargs.get("session"), + "window": kwargs.get("window"), + "pane": kwargs.get("pane"), } @@ -191,8 +191,8 @@ def get_code(use_pythonrc, imported_objects): readline.set_completer(rlcompleter.Completer(imported_objects).complete) # Enable tab completion on systems using libedit (e.g. macOS). # These lines are copied from Lib/site.py on Python 3.4. - readline_doc = getattr(readline, '__doc__', '') - if readline_doc is not None and 'libedit' in readline_doc: + readline_doc = getattr(readline, "__doc__", "") + if readline_doc is not None and "libedit" in readline_doc: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab:complete") @@ -201,7 +201,7 @@ def get_code(use_pythonrc, imported_objects): # conventions and get $PYTHONSTARTUP first then .pythonrc.py. if use_pythonrc: for pythonrc in set( - [os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')] + [os.environ.get("PYTHONSTARTUP"), os.path.expanduser("~/.pythonrc.py")] ): if not pythonrc: continue @@ -211,7 +211,7 @@ def get_code(use_pythonrc, imported_objects): pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. - exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects) + exec(compile(pythonrc_code, pythonrc, "exec"), imported_objects) def launch_code(): code.interact(local=imported_objects) @@ -219,20 +219,20 @@ def launch_code(): return launch_code -def launch(shell='best', use_pythonrc=False, use_vi_mode=False, **kwargs): +def launch(shell="best", use_pythonrc=False, use_vi_mode=False, **kwargs): # Also allowing passing shell='code' to force using code.interact imported_objects = get_launch_args(**kwargs) - if shell == 'best': + if shell == "best": shell = detect_best_shell() - if shell == 'ptipython': + if shell == "ptipython": launch = get_ptipython(options=kwargs, vi_mode=use_vi_mode) - elif shell == 'ptpython': + elif shell == "ptpython": launch = get_ptpython(options=kwargs, vi_mode=use_vi_mode) - elif shell == 'ipython': + elif shell == "ipython": launch = get_ipython(options=kwargs) - elif shell == 'bpython': + elif shell == "bpython": launch = get_bpython(options=kwargs) else: launch = get_code(use_pythonrc=use_pythonrc, imported_objects=imported_objects) diff --git a/tmuxp/util.py b/tmuxp/util.py index 725dcde8bdc..118345a6110 100644 --- a/tmuxp/util.py +++ b/tmuxp/util.py @@ -29,15 +29,15 @@ def run_before_script(script_file, cwd=None): stdout=subprocess.PIPE, cwd=cwd, ) - for line in iter(proc.stdout.readline, b''): + for line in iter(proc.stdout.readline, b""): sys.stdout.write(console_to_str(line)) proc.wait() if proc.returncode: stderr = proc.stderr.read() proc.stderr.close() - stderr = console_to_str(stderr).split('\n') - stderr = '\n'.join(list(filter(None, stderr))) # filter empty + stderr = console_to_str(stderr).split("\n") + stderr = "\n".join(list(filter(None, stderr))) # filter empty raise exc.BeforeLoadScriptError( proc.returncode, os.path.abspath(script_file), stderr @@ -58,20 +58,20 @@ def oh_my_zsh_auto_title(): """ - if 'SHELL' in os.environ and 'zsh' in os.environ.get('SHELL'): - if os.path.exists(os.path.expanduser('~/.oh-my-zsh')): + if "SHELL" in os.environ and "zsh" in os.environ.get("SHELL"): + if os.path.exists(os.path.expanduser("~/.oh-my-zsh")): # oh-my-zsh exists if ( - 'DISABLE_AUTO_TITLE' not in os.environ - or os.environ.get('DISABLE_AUTO_TITLE') == "false" + "DISABLE_AUTO_TITLE" not in os.environ + or os.environ.get("DISABLE_AUTO_TITLE") == "false" ): print( - 'Please set:\n\n' - '\texport DISABLE_AUTO_TITLE=\'true\'\n\n' - 'in ~/.zshrc or where your zsh profile is stored.\n' + "Please set:\n\n" + "\texport DISABLE_AUTO_TITLE='true'\n\n" + "in ~/.zshrc or where your zsh profile is stored.\n" 'Remember the "export" at the beginning!\n\n' - 'Then create a new shell or type:\n\n' - '\t$ source ~/.zshrc' + "Then create a new shell or type:\n\n" + "\t$ source ~/.zshrc" ) @@ -82,11 +82,11 @@ def raise_if_tmux_not_running(server): except LibTmuxException as e: if any( needle in str(e) - for needle in ['No such file or directory', 'no server running on'] + for needle in ["No such file or directory", "no server running on"] ): raise LibTmuxException( - 'no tmux session found. Start a tmux session and try again. \n' - 'Original error: ' + str(e) + "no tmux session found. Start a tmux session and try again. \n" + "Original error: " + str(e) ) else: raise e @@ -94,12 +94,12 @@ def raise_if_tmux_not_running(server): def get_current_pane(server): """Return Pane if one found in env""" - if os.getenv('TMUX_PANE') is not None: + if os.getenv("TMUX_PANE") is not None: try: return [ p for p in server._list_panes() - if p.get('pane_id') == os.getenv('TMUX_PANE') + if p.get("pane_id") == os.getenv("TMUX_PANE") ][0] except IndexError: pass @@ -107,32 +107,32 @@ def get_current_pane(server): def get_session(server, session_name=None, current_pane=None): if session_name: - session = server.find_where({'session_name': session_name}) + session = server.find_where({"session_name": session_name}) elif current_pane is not None: - session = server.find_where({'session_id': current_pane['session_id']}) + session = server.find_where({"session_id": current_pane["session_id"]}) else: current_pane = get_current_pane(server) if current_pane: - session = server.find_where({'session_id': current_pane['session_id']}) + session = server.find_where({"session_id": current_pane["session_id"]}) else: session = server.list_sessions()[0] if not session: if session_name: - raise exc.TmuxpException('Session not found: %s' % session_name) + raise exc.TmuxpException("Session not found: %s" % session_name) else: - raise exc.TmuxpException('Session not found') + raise exc.TmuxpException("Session not found") return session def get_window(session, window_name=None, current_pane=None): if window_name: - window = session.find_where({'window_name': window_name}) + window = session.find_where({"window_name": window_name}) if not window: - raise exc.TmuxpException('Window not found: %s' % window_name) + raise exc.TmuxpException("Window not found: %s" % window_name) elif current_pane is not None: - window = session.find_where({'window_id': current_pane['window_id']}) + window = session.find_where({"window_id": current_pane["window_id"]}) else: window = session.list_windows()[0] @@ -142,7 +142,7 @@ def get_window(session, window_name=None, current_pane=None): def get_pane(window, current_pane=None): try: if current_pane is not None: - pane = window.find_where({'pane_id': current_pane['pane_id']}) # NOQA: F841 + pane = window.find_where({"pane_id": current_pane["pane_id"]}) # NOQA: F841 else: pane = window.attached_pane # NOQA: F841 except exc.TmuxpException as e: diff --git a/tmuxp/workspacebuilder.py b/tmuxp/workspacebuilder.py index c38b1c5b01b..9f604717056 100644 --- a/tmuxp/workspacebuilder.py +++ b/tmuxp/workspacebuilder.py @@ -86,7 +86,7 @@ def __init__(self, sconf, plugins=[], server=None): """ if not sconf: - raise exc.EmptyConfigException('session configuration is empty.') + raise exc.EmptyConfigException("session configuration is empty.") # config.validate_schema(sconf) @@ -104,7 +104,7 @@ def session_exists(self, session_name=None): if not exists: return exists - self.session = self.server.find_where({'session_name': session_name}) + self.session = self.server.find_where({"session_name": session_name}) return True def build(self, session=None, append=False): @@ -128,30 +128,30 @@ def build(self, session=None, append=False): if not session: if not self.server: raise exc.TmuxpException( - 'WorkspaceBuilder.build requires server to be passed ' - + 'on initialization, or pass in session object to here.' + "WorkspaceBuilder.build requires server to be passed " + + "on initialization, or pass in session object to here." ) - if self.server.has_session(self.sconf['session_name']): + if self.server.has_session(self.sconf["session_name"]): self.session = self.server.find_where( - {'session_name': self.sconf['session_name']} + {"session_name": self.sconf["session_name"]} ) raise TmuxSessionExists( - 'Session name %s is already running.' % self.sconf['session_name'] + "Session name %s is already running." % self.sconf["session_name"] ) else: - if 'start_directory' in self.sconf: + if "start_directory" in self.sconf: session = self.server.new_session( - session_name=self.sconf['session_name'], - start_directory=self.sconf['start_directory'], + session_name=self.sconf["session_name"], + start_directory=self.sconf["start_directory"], ) else: session = self.server.new_session( - session_name=self.sconf['session_name'] + session_name=self.sconf["session_name"] ) - assert self.sconf['session_name'] == session.name - assert len(self.sconf['session_name']) > 0 + assert self.sconf["session_name"] == session.name + assert len(self.sconf["session_name"]) > 0 self.session = session self.server = session.server @@ -167,26 +167,26 @@ def build(self, session=None, append=False): focus = None - if 'before_script' in self.sconf: + if "before_script" in self.sconf: try: cwd = None # we want to run the before_script file cwd'd from the # session start directory, if it exists. - if 'start_directory' in self.sconf: - cwd = self.sconf['start_directory'] - run_before_script(self.sconf['before_script'], cwd=cwd) + if "start_directory" in self.sconf: + cwd = self.sconf["start_directory"] + run_before_script(self.sconf["before_script"], cwd=cwd) except Exception as e: self.session.kill_session() raise e - if 'options' in self.sconf: - for option, value in self.sconf['options'].items(): + if "options" in self.sconf: + for option, value in self.sconf["options"].items(): self.session.set_option(option, value) - if 'global_options' in self.sconf: - for option, value in self.sconf['global_options'].items(): + if "global_options" in self.sconf: + for option, value in self.sconf["global_options"].items(): self.session.set_option(option, value, _global=True) - if 'environment' in self.sconf: - for option, value in self.sconf['environment'].items(): + if "environment" in self.sconf: + for option, value in self.sconf["environment"].items(): self.session.set_environment(option, value) for w, wconf in self.iter_create_windows(session, append): @@ -200,13 +200,13 @@ def build(self, session=None, append=False): assert isinstance(p, Pane) p = p - if 'layout' in wconf: - w.select_layout(wconf['layout']) + if "layout" in wconf: + w.select_layout(wconf["layout"]) - if 'focus' in pconf and pconf['focus']: + if "focus" in pconf and pconf["focus"]: focus_pane = p - if 'focus' in wconf and wconf['focus']: + if "focus" in wconf and wconf["focus"]: focus = w self.config_after_window(w, wconf) @@ -242,11 +242,11 @@ def iter_create_windows(self, session, append=False): Newly created window, and the section from the tmuxp configuration that was used to create the window. """ - for i, wconf in enumerate(self.sconf['windows'], start=1): - if 'window_name' not in wconf: + for i, wconf in enumerate(self.sconf["windows"], start=1): + if "window_name" not in wconf: window_name = None else: - window_name = wconf['window_name'] + window_name = wconf["window_name"] is_first_window_pass = self.first_window_pass(i, session, append) @@ -255,20 +255,20 @@ def iter_create_windows(self, session, append=False): w1 = session.attached_window w1.move_window(99) - if 'start_directory' in wconf: - sd = wconf['start_directory'] + if "start_directory" in wconf: + sd = wconf["start_directory"] else: sd = None - if 'window_shell' in wconf: - ws = wconf['window_shell'] + if "window_shell" in wconf: + ws = wconf["window_shell"] else: ws = None # If the first pane specifies a shell, use that instead. try: - if wconf['panes'][0]['shell'] != '': - ws = wconf['panes'][0]['shell'] + if wconf["panes"][0]["shell"] != "": + ws = wconf["panes"][0]["shell"] except (KeyError, IndexError): pass @@ -276,7 +276,7 @@ def iter_create_windows(self, session, append=False): window_name=window_name, start_directory=sd, attach=False, # do not move to the new window - window_index=wconf.get('window_index', ''), + window_index=wconf.get("window_index", ""), window_shell=ws, ) @@ -285,11 +285,11 @@ def iter_create_windows(self, session, append=False): assert isinstance(w, Window) session.server._update_windows() - if 'options' in wconf and isinstance(wconf['options'], dict): - for key, val in wconf['options'].items(): + if "options" in wconf and isinstance(wconf["options"], dict): + for key, val in wconf["options"].items(): w.set_window_option(key, val) - if 'focus' in wconf and wconf['focus']: + if "focus" in wconf and wconf["focus"]: w.select_window() session.server._update_windows() @@ -317,30 +317,30 @@ def iter_create_panes(self, w, wconf): """ assert isinstance(w, Window) - pane_base_index = int(w.show_window_option('pane-base-index', g=True)) + pane_base_index = int(w.show_window_option("pane-base-index", g=True)) p = None - for pindex, pconf in enumerate(wconf['panes'], start=pane_base_index): + for pindex, pconf in enumerate(wconf["panes"], start=pane_base_index): if pindex == int(pane_base_index): p = w.attached_pane else: def get_pane_start_directory(): - if 'start_directory' in pconf: - return pconf['start_directory'] - elif 'start_directory' in wconf: - return wconf['start_directory'] + if "start_directory" in pconf: + return pconf["start_directory"] + elif "start_directory" in wconf: + return wconf["start_directory"] else: return None def get_pane_shell(): - if 'shell' in pconf: - return pconf['shell'] - elif 'window_shell' in wconf: - return wconf['window_shell'] + if "shell" in pconf: + return pconf["shell"] + elif "window_shell" in wconf: + return wconf["window_shell"] else: return None @@ -352,21 +352,21 @@ def get_pane_shell(): ) assert isinstance(p, Pane) - if 'layout' in wconf: - w.select_layout(wconf['layout']) + if "layout" in wconf: + w.select_layout(wconf["layout"]) - if 'suppress_history' in pconf: - suppress = pconf['suppress_history'] - elif 'suppress_history' in wconf: - suppress = wconf['suppress_history'] + if "suppress_history" in pconf: + suppress = pconf["suppress_history"] + elif "suppress_history" in wconf: + suppress = wconf["suppress_history"] else: suppress = True - for cmd in pconf['shell_command']: + for cmd in pconf["shell_command"]: p.send_keys(cmd, suppress_history=suppress) - if 'focus' in pconf and pconf['focus']: - w.select_pane(p['pane_id']) + if "focus" in pconf and pconf["focus"]: + w.select_pane(p["pane_id"]) w.server._update_panes() @@ -386,8 +386,8 @@ def config_after_window(self, w, wconf): wconf : dict config section for window """ - if 'options_after' in wconf and isinstance(wconf['options_after'], dict): - for key, val in wconf['options_after'].items(): + if "options_after" in wconf and isinstance(wconf["options_after"], dict): + for key, val in wconf["options_after"].items(): w.set_window_option(key, val) def find_current_attached_session(self): @@ -423,17 +423,17 @@ def freeze(session): dict tmuxp compatible workspace config """ - sconf = {'session_name': session['session_name'], 'windows': []} + sconf = {"session_name": session["session_name"], "windows": []} for w in session.windows: wconf = { - 'options': w.show_window_options(), - 'window_name': w.name, - 'layout': w.layout, - 'panes': [], + "options": w.show_window_options(), + "window_name": w.name, + "layout": w.layout, + "panes": [], } - if w.get('window_active', '0') == '1': - wconf['focus'] = 'true' + if w.get("window_active", "0") == "1": + wconf["focus"] = "true" # If all panes have same path, set 'start_directory' instead # of using 'cd' shell commands. @@ -441,35 +441,35 @@ def pane_has_same_path(p): return w.panes[0].current_path == p.current_path if all(pane_has_same_path(p) for p in w.panes): - wconf['start_directory'] = w.panes[0].current_path + wconf["start_directory"] = w.panes[0].current_path for p in w.panes: - pconf = {'shell_command': []} + pconf = {"shell_command": []} - if 'start_directory' not in wconf: - pconf['shell_command'].append('cd ' + p.current_path) + if "start_directory" not in wconf: + pconf["shell_command"].append("cd " + p.current_path) - if p.get('pane_active', '0') == '1': - pconf['focus'] = 'true' + if p.get("pane_active", "0") == "1": + pconf["focus"] = "true" current_cmd = p.current_command def filter_interpretters_and_shells(): - return current_cmd.startswith('-') or any( - current_cmd.endswith(cmd) for cmd in ['python', 'ruby', 'node'] + return current_cmd.startswith("-") or any( + current_cmd.endswith(cmd) for cmd in ["python", "ruby", "node"] ) if filter_interpretters_and_shells(): current_cmd = None if current_cmd: - pconf['shell_command'].append(current_cmd) + pconf["shell_command"].append(current_cmd) else: - if not len(pconf['shell_command']): - pconf = 'pane' + if not len(pconf["shell_command"]): + pconf = "pane" - wconf['panes'].append(pconf) + wconf["panes"].append(pconf) - sconf['windows'].append(wconf) + sconf["windows"].append(wconf) return sconf