def import_config(configfile, importfunc): 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' ) 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.') click.echo( newconfig + '---------------------------------------------------------------' '\n' 'Configuration import does its best to convert files.\n' ) if click.confirm( '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 ) # dest = dest_prompt if click.confirm('Save to %s?' % dest_path): dest = dest_path buf = open(dest, 'w') buf.write(newconfig) buf.close() click.echo('Saved to %s.' % dest) else: click.echo( 'tmuxp has examples in JSON and YAML format at ' '<http://tmuxp.readthedocs.io/en/latest/examples.html>\n' 'View tmuxp docs at <http://tmuxp.readthedocs.io/>' ) sys.exit()
def import_config(configfile, importfunc): 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" ) 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.") tmuxp_echo( newconfig + "---------------------------------------------------------------" "\n" "Configuration import does its best to convert files.\n" ) if click.confirm( "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 ) # dest = dest_prompt if click.confirm("Save to %s?" % dest_path): dest = dest_path buf = open(dest, "w") buf.write(newconfig) buf.close() tmuxp_echo("Saved to %s." % dest) else: tmuxp_echo( "tmuxp has examples in JSON and YAML format at " "<http://tmuxp.git-pull.com/examples.html>\n" "View tmuxp docs at <http://tmuxp.git-pull.com/>" ) sys.exit()
def test_start_directory_relative(session, tmpdir): """Same as above test, but with relative start directory, mimicing loading it from a location of project file. Like:: $ tmuxp load ~/workspace/myproject/.tmuxp.yaml instead of:: $ cd ~/workspace/myproject/.tmuxp.yaml $ tmuxp load . """ yaml_config = loadfixture("workspacebuilder/start_directory_relative.yaml") 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 = 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. sconfig = config.expand(sconfig, config_dir) sconfig = config.trickle(sconfig) assert os.path.exists(config_dir) assert os.path.exists(test_dir) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) assert session == builder.session dirs = ['/usr/bin', '/dev', test_dir, config_dir, config_dir] for path, window in zip(dirs, session.windows): for p in window.panes: while retry(): p.server._update_panes() # Handle case where directories resolve to /private/ in OSX pane_path = p.current_path if pane_path is None: pass elif path in pane_path or pane_path == path: result = path == pane_path or path in pane_path break assert result
def test_suppress_history(session): yaml_config = loadfixture("workspacebuilder/suppress_history.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=session) inHistoryPane = session.find_where( {'window_name': 'inHistory'}).attached_pane isMissingPane = session.find_where( {'window_name': 'isMissing'}).attached_pane def assertHistory(cmd, hist): return 'inHistory' in cmd and cmd == hist def assertIsMissing(cmd, hist): return 'isMissing' in cmd and cmd != hist for p, assertCase in [ (inHistoryPane, assertHistory,), (isMissingPane, assertIsMissing,) ]: correct = False p.window.select_window() p.select_pane() # Print the last-in-history command in the pane session.cmd('send-keys', ' fc -ln -1') session.cmd('send-keys', 'Enter') for _ in range(10): time.sleep(0.1) # Get the contents of the pane session.cmd('capture-pane') captured_pane = session.cmd('show-buffer') session.cmd('delete-buffer') # Parse the sent and last-in-history commands sent_cmd = captured_pane.stdout[0].strip() history_cmd = captured_pane.stdout[-2].strip() if assertCase(sent_cmd, history_cmd): correct = True break assert correct, "Unknown sent command: [%s]" % sent_cmd
def test_plugin_system_before_workspace_builder( monkeypatch_plugin_test_packages, session ): config_plugins = loadfixture("workspacebuilder/plugin_bwb.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig, plugins=load_plugins(sconfig)) assert len(builder.plugins) > 0 builder.build(session=session) proc = session.cmd('display-message', '-p', "'#S'") assert proc.stdout[0] == "'plugin_test_bwb'"
def test_blank_pane_count(self): test_config = kaptan.Kaptan().import_config( self.yaml_config_file).get() test_config = config.expand(test_config) builder = WorkspaceBuilder(sconf=test_config) builder.build(session=self.session) window1 = self.session.findWhere({'window_name': 'Blank pane test'}) self.assertEqual(len(window1._panes), 6) window1 = self.session.findWhere( {'window_name': 'Empty string (return)'}) self.assertEqual(len(window1._panes), 3) self.assertEqual(self.session, builder.session)
def test_py_file_away_handler(testconfig): with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as fobj: fobj.write("""DATABASE = 'mysql://*****:*****@localhost/girlz' DEBUG = False PAGINATION = { 'per_page': 10, 'limit': 20, } """) try: config = kaptan.Kaptan() config.import_config(fobj.name) assert config.get("PAGINATION.limit") == 20 finally: os.unlink(fobj.name)
def test_yml_file_handler(self): with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False) as fobj: fobj.write(""" development: DATABASE_URI: mysql://root:123456@localhost/posts production: DATABASE_URI: mysql://poor_user:poor_password@localhost/poor_posts """) config = kaptan.Kaptan() config.import_config(fobj.name) self.assertEqual( config.get('production.DATABASE_URI'), 'mysql://*****:*****@localhost/poor_posts' )
def test_plugin_system_after_window_finished(monkeypatch_plugin_test_packages, session): config_plugins = test_utils.read_config_file( "workspacebuilder/plugin_awf.yaml") sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig, plugins=load_plugins(sconfig)) assert len(builder.plugins) > 0 builder.build(session=session) proc = session.cmd("display-message", "-p", "'#W'") assert proc.stdout[0] == "'plugin_test_awf'"
def test_before_load_true_if_test_passes_with_args(server): config_script_completes = test_utils.read_config_file( "workspacebuilder/config_script_completes.yaml") script_complete_sh = FIXTURE_PATH / "script_complete.sh" assert script_complete_sh.exists() sconfig = kaptan.Kaptan(handler="yaml") yaml = config_script_completes.format(script_complete=script_complete_sh) sconfig = sconfig.import_config(yaml).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) builder = WorkspaceBuilder(sconf=sconfig) with temp_session(server) as session: builder.build(session=session)
def test_load_plugins(): plugins_config = loadfixture("workspacebuilder/plugin_bwb.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(plugins_config).get() sconfig = config.expand(sconfig) plugins = load_plugins(sconfig) assert len(plugins) == 1 test_plugin_class_types = [ PluginBeforeWorkspaceBuilder().__class__, ] for plugin in plugins: assert plugin.__class__ in test_plugin_class_types
def test_json_file_handler(): with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as fobj: fobj.write("""{"development": { "DATABASE_URI": "mysql://*****:*****@localhost/posts" }, "production": { "DATABASE_URI": "mysql://*****:*****@localhost/poor_posts" } } """) config = kaptan.Kaptan(handler='json') config.import_config(fobj.name) assert config.get( 'production.DATABASE_URI' ) == 'mysql://*****:*****@localhost/poor_posts'
def test_true_if_test_passes_with_args(self): assert(os.path.exists(os.path.join(fixtures_dir, 'script_complete.sh'))) sconfig = kaptan.Kaptan(handler='yaml') yaml = self.config_script_completes.format( fixtures_dir=fixtures_dir, script_complete=os.path.join(fixtures_dir, 'script_complete.sh') + ' -v' ) sconfig = sconfig.import_config(yaml).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) builder = WorkspaceBuilder(sconf=sconfig) with self.temp_session() as session: builder.build(session=self.session)
def test_plugin_system_after_window_finished_multiple_windows(session): config_plugins = loadfixture( "workspacebuilder/plugin_awf_multiple_windows.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig, plugins=load_plugins(sconfig)) assert len(builder.plugins) > 0 builder.build(session=session) proc = session.cmd('list-windows', '-F', "'#W'") assert "'plugin_test_awf_mw'" in proc.stdout assert "'plugin_test_awf_mw_2'" in proc.stdout
def test_plugin_system_on_window_create_multiple_windows(session): config_plugins = test_utils.read_config_file( "workspacebuilder/plugin_owc_multiple_windows.yaml") sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(config_plugins).get() sconfig = config.expand(sconfig) builder = WorkspaceBuilder(sconf=sconfig, plugins=load_plugins(sconfig)) assert len(builder.plugins) > 0 builder.build(session=session) proc = session.cmd("list-windows", "-F", "'#W'") assert "'plugin_test_owc_mw'" in proc.stdout assert "'plugin_test_owc_mw_2'" in proc.stdout
def test_window_index(session): yaml_config = loadfixture("workspacebuilder/window_index.yaml") 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} sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) 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
def test_pane_order(self): # test order of `panes` (and pane_index) above aganist pane_dirs pane_paths = [ '/usr/bin', '/usr', '/usr/sbin', os.path.realpath(os.path.expanduser('~')) ] s = self.session sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(self.yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) builder = WorkspaceBuilder(sconf=sconfig) window_count = len(self.session._windows) # current window count self.assertEqual(len(s._windows), window_count) for w, wconf in builder.iter_create_windows(s): window_pane_count = len(w._panes) for p in builder.iter_create_panes(w, wconf): p = p self.assertEqual(len(s._windows), window_count) self.assertIsInstance(w, Window) self.assertEqual(len(s._windows), window_count) window_count += 1 for w in self.session.windows: 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): self.assertEqual(int(p_index), int(p.get('pane_index'))) # pane-base-index start at base-index, pane_paths always start # at 0 since python list. pane_path = pane_paths[p_index - pane_base_index] for i in range(60): p.server._update_panes() if p.get('pane_current_path') == pane_path: break time.sleep(.2) self.assertEqual(p.get('pane_current_path'), pane_path)
def test_file_handler(self): with tempfile.NamedTemporaryFile(mode='w', suffix='.py', dir='.', delete=False) as fobj: fobj.write("""DATABASE = 'mysql://*****:*****@localhost/girlz' DEBUG = False PAGINATION = { 'per_page': 10, 'limit': 20, } """) try: normalize_name = os.path.basename(fobj.name).rpartition('.')[0] config = kaptan.Kaptan(handler='file') config.import_config(normalize_name) self.assertEqual(config.get("PAGINATION.limit"), 20) finally: os.unlink(fobj.name)
def test_window_index(session): yaml_config = test_utils.read_config_file( "workspacebuilder/window_index.yaml") 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} sconfig = kaptan.Kaptan(handler="yaml") sconfig = sconfig.import_config(yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) 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
def test_start_directory(self): sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(self.yaml_config).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) logger.error(sconfig) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=self.session) assert (self.session == builder.session) for path in ['/var/log', '/dev/', '/var/', os.getcwd()]: for window in self.session.windows: for p in window.panes: self.assertTrue(p.get('pane_start_path', path))
def test_split_windows(self): s = self.session sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(self.yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) window_count = len(self.session._windows) # current window count self.assertEqual(len(s._windows), window_count) for w, wconf in builder.iter_create_windows(s): window_pane_count = len(w._panes) for p in builder.iter_create_panes(w, wconf): p = p self.assertEqual(len(s._windows), window_count) self.assertIsInstance(w, Window) self.assertEqual(len(s._windows), window_count) window_count += 1
def load_config(config, version): if not os.path.exists(config): local_path = os.path.join(os.path.expanduser('~'), config) if not os.path.exists(local_path): raise Exception('Unable to find configuration file: %s' % config) else: config = local_path file_extension = os.path.splitext(config)[1][1:] conf = kaptan.Kaptan(handler=kaptan.HANDLER_EXT.get(file_extension)) conf.import_config(config) repos = conf.export('dict') or {} res = {} for repo in repos.get('repositories'): if repo.get('version') == version: res = repo.get('remotes') return res
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") switch_client_mock = MagicMock() switch_client_mock.return_value.stderr = None monkeypatch.setattr("libtmux.session.Session.switch_client", switch_client_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) _load_attached(builder, True) assert builder.session.switch_client.call_count == 1
def test_load_attached_detached(server, monkeypatch): # Load a session but don't attach monkeypatch.delenv('TMUX', raising=False) attach_session_mock = MagicMock() attach_session_mock.return_value.stderr = None monkeypatch.setattr("libtmux.session.Session.attach_session", attach_session_mock) yaml_config = loadfixture("workspacebuilder/two_pane.yaml") sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig, server=server) _load_attached(builder, True) assert builder.session.attach_session.call_count == 0
def test_plugins(): yaml_config = """ session_name: test session plugins: tmuxp-plugin-one.plugin.TestPluginOne windows: - window_name: editor panes: shell_command: - tail -F /var/log/syslog start_directory: /var/log """ 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')
def test_split_windows(session): yaml_config = loadfixture("workspacebuilder/two_pane.yaml") s = session sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) window_count = len(session._windows) # current window count assert len(s._windows) == window_count for w, wconf in builder.iter_create_windows(s): for p in builder.iter_create_panes(w, wconf): p = p assert len(s._windows) == window_count assert isinstance(w, Window) assert len(s._windows) == window_count window_count += 1
def test_makes_recursive(tmpdir, git_dummy_repo_dir): """Ensure that directories in pull are made recursively.""" YAML_CONFIG = """ {tmpdir}/study/myrepo: my_url: git+file://{repo_dir} """ YAML_CONFIG = YAML_CONFIG.format(tmpdir=str(tmpdir), repo_dir=git_dummy_repo_dir) conf = kaptan.Kaptan(handler='yaml') conf.import_config(YAML_CONFIG) conf = conf.export('dict') repos = extract_repos(conf) for r in filter_repos(repos): repo = create_repo_from_pip_url(**r) repo.obtain()
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') yaml = config_script_completes.format( fixtures_dir=fixtures_dir, script_complete=os.path.join(fixtures_dir, 'script_complete.sh'), ) sconfig = sconfig.import_config(yaml).get() sconfig = config.expand(sconfig) sconfig = config.trickle(sconfig) builder = WorkspaceBuilder(sconf=sconfig) with temp_session(server) as session: builder.build(session=session)
def test_split_windows(self): s = self.session sconfig = kaptan.Kaptan(handler='yaml') sconfig = sconfig.import_config(self.yaml_config).get() builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=self.session) self.assertEqual( self.session.attached_window().get('window_name'), 'focused window' ) pane_base_index = int(self.session.attached_window().show_window_option( 'pane-base-index', g=True )) if not pane_base_index: pane_base_index = 0 else: pane_base_index = int(pane_base_index) # get the pane index for each pane pane_base_indexes = [] for pane in self.session.attached_window().panes: pane_base_indexes.append(int(pane.get('pane_index'))) pane_indexes_should_be = [pane_base_index + x for x in range(0, 3)] self.assertListEqual(pane_indexes_should_be, pane_base_indexes) w = self.session.attached_window() self.assertNotEqual(w.get('window_name'), 'man') pane_path = '/usr' for i in range(60): p = w.attached_pane() p.server._update_panes() if p.get('pane_current_path') == pane_path: break time.sleep(.2) self.assertEqual(p.get('pane_current_path'), pane_path)
def test_start_directory(self): test_config = self.yaml_config.format(TEST_DIR=self.test_dir, ) start_directory = os.getcwd() 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. sconfig = config.expand(sconfig, self.config_dir) sconfig = config.trickle(sconfig) assert (os.path.exists(self.config_dir)) assert (os.path.exists(self.test_dir)) builder = WorkspaceBuilder(sconf=sconfig) builder.build(session=self.session) assert (self.session == builder.session) dirs = [ '/usr/bin', '/dev', self.test_dir, self.config_dir, self.config_dir, ] for path, window in zip(dirs, self.session.windows): for p in window.panes: for i in range(60): p.server._update_panes() # Handle case where directories resolve to /private/ in OSX pane_path = p.get('pane_current_path') if pane_path is None: pass elif (path in pane_path or pane_path == path): result = (path == pane_path or path in pane_path) break time.sleep(.2) self.assertTrue(result)