Esempio n. 1
0
def command_freeze(session_name, socket_name, socket_path):
    """Import teamocil config to tmuxp format."""

    t = Server(
        socket_name=socket_name,
        socket_path=socket_path,
    )

    try:
        session = t.find_where({
            'session_name': session_name
        })

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    configparser.import_config(newconfig)
    config_format = "yaml"
    newconfig = configparser.export(
            'yaml', indent=2, default_flow_style=False, safe=True
    )

    save_to = os.path.abspath(
        os.path.join(
            get_config_dir(),
            '%s.%s' % (sconf.get('session_name'), config_format)
        )
    )
    dest_prompt = save_to
    dest = dest_prompt
    dest = os.path.abspath(os.path.relpath(os.path.expanduser(dest)))
    destdir = os.path.dirname(dest)
    if not os.path.isdir(destdir):
        os.makedirs(destdir)
    buf = open(dest, 'w')
    buf.write(newconfig)
    buf.close()

    print('Saved to %s.' % dest)
Esempio n. 2
0
File: cli.py Progetto: aurieh/tmuxp
def command_freeze(session_name, socket_name, socket_path):
    """Snapshot a session into a config.

    If SESSION_NAME is provided, snapshot that session. Otherwise, use the
    current session."""

    t = Server(socket_name=socket_name, socket_path=socket_path)

    try:
        if session_name:
            session = t.find_where({'session_name': session_name})
        else:
            session = t.list_sessions()[0]

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    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, safe=True
        )
    elif config_format == 'json':
        newconfig = configparser.export('json', indent=2)
    else:
        sys.exit('Unknown config format.')

    print(newconfig)
    print(
        '---------------------------------------------------------------'
        '\n'
        'Freeze does it best to snapshot live tmux sessions.\n'
    )
    if click.confirm(
        'The new config *WILL* require adjusting afterwards. Save config?'
    ):
        dest = None
        while not dest:
            save_to = os.path.abspath(
                os.path.join(
                    get_config_dir(),
                    '%s.%s' % (sconf.get('session_name'), config_format),
                )
            )
            dest_prompt = click.prompt(
                'Save to: %s' % save_to, value_proc=get_abs_path, default=save_to
            )
            if os.path.exists(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 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.write(newconfig)
            buf.close()

            print('Saved to %s.' % dest)
    else:
        print(
            '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()
Esempio n. 3
0
def command_freeze(session_name, socket_name, socket_path):
    """Snapshot a session into a config.

    If SESSION_NAME is provided, snapshot that session. Otherwise, use the
    current session."""

    t = Server(socket_name=socket_name, socket_path=socket_path)

    try:
        if session_name:
            session = t.find_where({'session_name': session_name})
        else:
            session = t.list_sessions()[0]

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    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, safe=True
        )
    elif config_format == 'json':
        newconfig = configparser.export('json', indent=2)
    else:
        sys.exit('Unknown config format.')

    print(newconfig)
    print(
        '---------------------------------------------------------------'
        '\n'
        'Freeze does it best to snapshot live tmux sessions.\n'
    )
    if click.confirm(
        'The new config *WILL* require adjusting afterwards. Save config?'
    ):
        dest = None
        while not dest:
            save_to = os.path.abspath(
                os.path.join(
                    get_config_dir(),
                    '%s.%s' % (sconf.get('session_name'), config_format),
                )
            )
            dest_prompt = click.prompt(
                'Save to: %s' % save_to,
                value_proc=get_abs_path,
                default=save_to,
                confirmation_prompt=True,
            )
            if os.path.exists(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 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.write(newconfig)
            buf.close()

            print('Saved to %s.' % dest)
    else:
        print(
            '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()
Esempio n. 4
0
def command_freeze(args):
    """Import teamocil config to tmuxp format."""

    ctext = ' '.join(args.session_name)

    t = Server(
        socket_name=args.socket_name,
        socket_path=args.socket_path,
        colors=args.colors
    )

    try:
        session = t.find_where({
            'session_name': ctext
        })

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    configparser.import_config(newconfig)
    config_format = prompt_choices('Convert to', choices=[
        'yaml', 'json'], default='yaml')

    if config_format == 'yaml':
        newconfig = configparser.export(
            'yaml', indent=2, default_flow_style=False, safe=True
        )
    elif config_format == 'json':
        newconfig = configparser.export('json', indent=2)
    else:
        sys.exit('Unknown config format.')

    print(newconfig)
    print(
        '---------------------------------------------------------------')
    print(
        'Configuration import does its best to convert teamocil files.\n')
    if args.answer_yes or prompt_yes_no(
        'The new config *WILL* require adjusting afterwards. Save config?'
    ):
        dest = None
        while not dest:
            save_to = os.path.abspath(
                os.path.join(
                    config_dir,
                    '%s.%s' % (sconf.get('session_name'), config_format)
                )
            )
            dest_prompt = prompt('Save to: ', save_to)
            if os.path.exists(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 args.answer_yes or prompt_yes_no('Save to %s?' % dest):
            destdir = os.path.dirname(dest)
            if not os.path.isdir(destdir):
                os.makedirs(destdir)
            buf = open(dest, 'w')
            buf.write(newconfig)
            buf.close()

            print('Saved to %s.' % dest)
    else:
        print(
            '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()
Esempio n. 5
0
def command_shell(session_name, window_name, socket_name, socket_path, command):
    """Launch python shell for tmux server, session, window and pane.

    Priority given to loaded session/wndow/pane objects:
    - session_name and window_name arguments
    - current shell: environmental variable of TMUX_PANE (which gives us window and
      session)
    - ``server.attached_session``, ``session.attached_window``, ``window.attached_pane``
    """
    server = Server(socket_name=socket_name, socket_path=socket_path)

    try:
        server.sessions
    except LibTmuxException as e:
        if 'No such file or directory' in str(e):
            raise LibTmuxException(
                'no tmux session found. Start a tmux session and try again. \n'
                'Original error: ' + str(e)
            )
        else:
            raise e

    current_pane = None
    if os.getenv('TMUX_PANE') is not None:
        try:
            current_pane = [
                p
                for p in server._list_panes()
                if p.get('pane_id') == os.getenv('TMUX_PANE')
            ][0]
        except IndexError:
            pass

    try:
        if 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']})
        else:
            session = server.list_sessions()[0]

        if not session:
            raise exc.TmuxpException('Session not found: %s' % session_name)
    except exc.TmuxpException as e:
        print(e)
        return

    try:
        if window_name:
            window = session.find_where({'window_name': window_name})
            if not window:
                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']})
        else:
            window = session.list_windows()[0]

    except exc.TmuxpException as e:
        print(e)
        return

    try:
        if current_pane is not None:
            pane = window.find_where({'pane_id': current_pane['pane_id']})  # NOQA: F841
        else:
            pane = window.attached_pane  # NOQA: F841
    except exc.TmuxpException as e:
        print(e)
        return

    if command is not None:
        exec(command)
    else:
        from ._compat import breakpoint as tmuxp_breakpoint

        tmuxp_breakpoint()
Esempio n. 6
0
def command_freeze(
    session_name, socket_name, config_format, save_to, socket_path, yes, quiet, force
):
    """Snapshot a session into a config.

    If SESSION_NAME is provided, snapshot that session. Otherwise, use the
    current session."""

    t = Server(socket_name=socket_name, socket_path=socket_path)

    try:
        if 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.")
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    configparser.import_config(newconfig)

    if not quiet:
        print(
            "---------------------------------------------------------------"
            "\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?"
        )
    ):
        if not quiet:
            print(
                "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()

    dest = save_to
    while not dest:
        save_to = os.path.abspath(
            os.path.join(
                get_config_dir(),
                "{}.{}".format(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
        )
        if not force and os.path.exists(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"]
        _, 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",
            )

    if config_format == "yaml":
        newconfig = configparser.export(
            "yaml", indent=2, default_flow_style=False, safe=True
        )
    elif config_format == "json":
        newconfig = configparser.export("json", indent=2)

    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.write(newconfig)
        buf.close()

        if not quiet:
            print("Saved to %s." % dest)
Esempio n. 7
0
def command_freeze(args):
    """Import teamocil config to tmuxp format."""

    ctext = ' '.join(args.session_name)

    t = Server(socket_name=args.socket_name,
               socket_path=args.socket_path,
               colors=args.colors)

    try:
        session = t.find_where({'session_name': ctext})

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    configparser.import_config(newconfig)
    config_format = prompt_choices('Convert to',
                                   choices=['yaml', 'json'],
                                   default='yaml')

    if config_format == 'yaml':
        newconfig = configparser.export('yaml',
                                        indent=2,
                                        default_flow_style=False,
                                        safe=True)
    elif config_format == 'json':
        newconfig = configparser.export('json', indent=2)
    else:
        sys.exit('Unknown config format.')

    print(newconfig)
    print('---------------------------------------------------------------')
    print('Configuration import does its best to convert teamocil files.\n')
    if args.answer_yes or prompt_yes_no(
            'The new config *WILL* require adjusting afterwards. Save config?'
    ):
        dest = None
        while not dest:
            save_to = os.path.abspath(
                os.path.join(
                    config_dir,
                    '%s.%s' % (sconf.get('session_name'), config_format)))
            dest_prompt = prompt('Save to: ', save_to)
            if os.path.exists(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 args.answer_yes or prompt_yes_no('Save to %s?' % dest):
            destdir = os.path.dirname(dest)
            if not os.path.isdir(destdir):
                os.makedirs(destdir)
            buf = open(dest, 'w')
            buf.write(newconfig)
            buf.close()

            print('Saved to %s.' % dest)
    else:
        print('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()