Exemple #1
0
def make_wizard(default_file=None, confirm=False):
    """Makes a configuration wizard for xonsh config file.

    Parameters
    ----------
    default_file : str, optional
        Default filename to save and load to. User will still be prompted.
    confirm : bool, optional
        Confirm that the main part of the wizard should be run.
    """
    wiz = Wizard(children=[
        Message(message=WIZARD_HEAD),
        Load(default_file=default_file, check=True),
        Message(message=WIZARD_FS),
        make_fs(),
        Message(message=WIZARD_ENV),
        YesNo(question=WIZARD_ENV_QUESTION, yes=make_env(), no=Pass()),
        Message(message='\n' + HR + '\n'),
        Save(default_file=default_file, check=True),
        Message(message=WIZARD_TAIL),
    ])
    if confirm:
        q = 'Would you like to run the xonsh configuration wizard now, ' + YN
        wiz = YesNo(question=q, yes=wiz, no=Pass())
    return wiz
Exemple #2
0
def make_xontrib(xontrib, package):
    """Makes a message and StoreNonEmpty node for a xontrib."""
    name = xontrib.get('name', '<unknown-xontrib-name>')
    msg = '\n{BOLD_CYAN}' + name + '{NO_COLOR}\n'
    if 'url' in xontrib:
        msg += '{RED}url:{NO_COLOR} ' + xontrib['url'] + '\n'
    if 'package' in xontrib:
        msg += '{RED}package:{NO_COLOR} ' + xontrib['package'] + '\n'
    if 'url' in package:
        if 'url' in xontrib and package['url'] != xontrib['url']:
            msg += '{RED}package-url:{NO_COLOR} ' + package['url'] + '\n'
    if 'license' in package:
        msg += '{RED}license:{NO_COLOR} ' + package['license'] + '\n'
    msg += '{PURPLE}installed?{NO_COLOR} '
    msg += ('no' if find_xontrib(name) is None else 'yes') + '\n'
    desc = xontrib.get('description', '')
    if not isinstance(desc, str):
        desc = ''.join(desc)
    msg += _wrap_paragraphs(desc, width=69)
    if msg.endswith('\n'):
        msg = msg[:-1]
    mnode = Message(message=msg)
    convert = lambda x: name if tools.to_bool(x) else Unstorable
    pnode = StoreNonEmpty(XONTRIB_PROMPT, converter=convert,
                          path=_xontrib_path)
    return mnode, pnode
Exemple #3
0
def make_envvar(name):
    """Makes a StoreNonEmpty node for an environment variable."""
    env = builtins.__xonsh_env__
    vd = env.get_docs(name)
    if not vd.configurable:
        return
    default = vd.default
    if '\n' in default:
        default = '\n' + _wrap_paragraphs(default, width=69)
    curr = env.get(name)
    if tools.is_string(curr) and is_template_string(curr):
        curr = curr.replace('{', '{{').replace('}', '}}')
    curr = pformat(curr, width=69)
    if '\n' in curr:
        curr = '\n' + curr
    msg = ENVVAR_MESSAGE.format(name=name,
                                default=default,
                                current=curr,
                                docstr=_wrap_paragraphs(vd.docstr, width=69))
    mnode = Message(message=msg)
    ens = env.get_ensurer(name)
    path = '/env/' + name
    pnode = StoreNonEmpty(ENVVAR_PROMPT,
                          converter=ens.convert,
                          show_conversion=True,
                          path=path,
                          retry=True,
                          store_raw=vd.store_as_str)
    return mnode, pnode
Exemple #4
0
def make_wizard(default_file=None, confirm=False):
    """Makes a configuration wizard for xonsh config file.

    Parameters
    ----------
    default_file : str, optional
        Default filename to save and load to. User will still be prompted.
    confirm : bool, optional
        Confirm that the main part of the wizard should be run.
    """
    wiz = Wizard(children=[
            Message(message=WIZARD_HEAD),
            Load(default_file=default_file, check=True),
            Message(message=WIZARD_FS),
            make_fs(),
            Message(message=WIZARD_ENV),
            YesNo(question=WIZARD_ENV_QUESTION, yes=make_env(), no=Pass()),
            Message(message=WIZARD_XONTRIB),
            YesNo(question=WIZARD_XONTRIB_QUESTION, yes=make_xontribs(), no=Pass()),
            Message(message='\n' + HR + '\n'),
            Save(default_file=default_file, check=True),
            Message(message=WIZARD_TAIL),
            ])
    if confirm:
        q = ("Would you like to run the xonsh configuration wizard now?\n\n"
             "1. Yes\n2. No, but ask me later.\n3. No, and don't ask me again."
             "\n\n1, 2, or 3 [default: 2]? ")
        passer = Pass()
        saver = Save(check=False, ask_filename=False, default_file=default_file)
        wiz = Question(q, {1: wiz, 2: passer, 3: saver},
                       converter=lambda x: int(x) if x != '' else 2)
    return wiz
Exemple #5
0
def make_fs():
    """Makes the foreign shell part of the wizard."""
    cond = create_truefalse_cond(prompt='Add a foreign shell, ' + YN)
    fs = While(
        cond=cond,
        body=[
            Input('shell name (e.g. bash): ',
                  path='/foreign_shells/{idx}/shell'),
            StoreNonEmpty('interactive shell [bool, default=True]: ',
                          converter=tools.to_bool,
                          show_conversion=True,
                          path='/foreign_shells/{idx}/interactive'),
            StoreNonEmpty('login shell [bool, default=False]: ',
                          converter=tools.to_bool,
                          show_conversion=True,
                          path='/foreign_shells/{idx}/login'),
            StoreNonEmpty("env command [str, default='env']: ",
                          path='/foreign_shells/{idx}/envcmd'),
            StoreNonEmpty("alias command [str, default='alias']: ",
                          path='/foreign_shells/{idx}/aliascmd'),
            StoreNonEmpty(("extra command line arguments [list of str, "
                           "default=[]]: "),
                          converter=ast.literal_eval,
                          show_conversion=True,
                          path='/foreign_shells/{idx}/extra_args'),
            StoreNonEmpty('current environment [dict, default=None]: ',
                          converter=ast.literal_eval,
                          show_conversion=True,
                          path='/foreign_shells/{idx}/currenv'),
            StoreNonEmpty('safely handle exceptions [bool, default=True]: ',
                          converter=tools.to_bool,
                          show_conversion=True,
                          path='/foreign_shells/{idx}/safe'),
            StoreNonEmpty("pre-command [str, default='']: ",
                          path='/foreign_shells/{idx}/prevcmd'),
            StoreNonEmpty("post-command [str, default='']: ",
                          path='/foreign_shells/{idx}/postcmd'),
            StoreNonEmpty("foreign function command [str, default=None]: ",
                          path='/foreign_shells/{idx}/funcscmd'),
            StoreNonEmpty("source command [str, default=None]: ",
                          path='/foreign_shells/{idx}/sourcer'),
            Message(message='')  # inserts a newline
        ])
    return fs
Exemple #6
0
# -*- coding: utf-8 -*-
"""Tests the xonsh lexer."""
from __future__ import unicode_literals, print_function
import os

import nose
from nose.tools import assert_equal, assert_true, assert_false

from xonsh.wizard import (Node, Wizard, Pass, PrettyFormatter, Message,
                          Question, StateVisitor)

TREE0 = Wizard(children=[Pass(), Message(message='yo')])
TREE1 = Question('wakka?', {'jawaka': Pass()})


def test_pretty_format_tree0():
    exp = ('Wizard(children=[\n' ' Pass(),\n' " Message('yo')\n" '])')
    obs = PrettyFormatter(TREE0).visit()
    yield assert_equal, exp, obs
    yield assert_equal, exp, str(TREE0)
    yield assert_equal, exp.replace('\n', ''), repr(TREE0)


def test_pretty_format_tree1():
    exp = ('Question(\n'
           " question='wakka?',\n"
           ' responses={\n'
           "  'jawaka': Pass()\n"
           ' }\n'
           ')')
    obs = PrettyFormatter(TREE1).visit()
Exemple #7
0
"""Tests the xonsh lexer."""
import os

import pytest  # noqa F401

from xonsh.wizard import (
    FileInserter,
    Message,
    Pass,
    PrettyFormatter,
    Question,
    StateVisitor,
    Wizard,
)

TREE0 = Wizard(children=[Pass(), Message(message="yo")])
TREE1 = Question("wakka?", {"jawaka": Pass()})


def test_pretty_format_tree0():
    exp = "Wizard(children=[\n" " Pass(),\n" " Message('yo')\n" "])"
    obs = PrettyFormatter(TREE0).visit()
    assert exp == obs
    assert exp == str(TREE0)
    assert exp.replace("\n", "") == repr(TREE0)


def test_pretty_format_tree1():
    exp = ("Question(\n"
           " question='wakka?',\n"
           " responses={\n"