Beispiel #1
0
def traverse_config(name):
    path = name.split(".")
    config = get_config()
    prop = config
    for i, p in enumerate(path[:-1]):
        prop = prop[p]
    return config, prop, path[-1]
Beispiel #2
0
 def me(self):
     if not self._me:
         config = get_config()
         default = config["threebot"]["default"]
         if default:
             self.__class__._me = self.get(name=default)
         else:
             for identity in self.list_all():
                 self.__class__._me = self.get(identity)
                 break
             else:
                 raise Value("No configured identity found")
     return self._me
Beispiel #3
0
def run(command):
    """Executes the passed command and initiates a jsng shell if no command is passed."""
    os.makedirs(BASE_CONFIG_DIR, exist_ok=True)
    pathlib.Path(HISTORY_FILENAME).touch()
    if command is None:
        config = get_config()
        if config["shell"] == "ipython":
            from IPython import embed

            sys.exit(embed(colors="neutral"))
        else:
            from jumpscale.shell import ptconfig
            from ptpython.repl import embed

            sys.exit(
                embed(globals(),
                      locals(),
                      configure=ptconfig,
                      history_filename=HISTORY_FILENAME))
    else:
        sys.exit(print(exec(command)))
Beispiel #4
0
class StoredFactory(events.Handler, Factory):
    STORE = STORES[config.get_config()["store"]]

    def __init__(self, type_, name_=None, parent_instance_=None, parent_factory_=None):
        super().__init__(type_, name_=name_, parent_instance_=parent_instance_, parent_factory_=parent_factory_)

        if not parent_instance_:
            self._load()

        events.add_listenter(self, AttributeUpdateEvent)

    @property
    def parent_location(self):
        if not self.parent_factory:
            raise ValueError("cannot get parent location if parent factory is not set")
        return self.parent_factory.location

    @property
    def location(self):
        """
        get a unique location for this factory

        Returns:
            Location: location object
        """
        name_list = []

        # first, get the location of parent factory if any
        if self.parent_factory:
            name_list += self.parent_location.name_list

        # if we have a parent instance, then this location should be unique
        # for this instance
        if self.parent_instance:
            name_list.append(self.parent_instance.instance_name)

        # if this factory have a name, append it too
        if self.name:
            name_list.append(self.name)

        # then we append the location of the type
        type_location = Location.from_type(self.type)
        name_list += type_location.name_list

        return Location(*name_list)

    @property
    def store(self):
        return self.STORE(self.location)

    def _validate_and_save_instance(self, name, instance):
        instance.validate()
        self.store.save(name, instance._get_data())

    def _try_save_instance(self, instance):
        # try to save instance if it's validated
        try:
            self._validate_and_save_instance(name, instance)
        except:
            pass

    def handle(self, ev):
        """
        handle when data is updated for an instance

        Args:
            ev (AttributeUpdateEvent): attribute update event
        """
        instance = ev.instance
        if instance.parent == self.parent_instance and isinstance(instance, self.type):
            self._try_save_instance(instance)

    def _load_sub_factories(self, name, instance):
        for factory in instance._get_factories().values():
            factory._set_parent_factory(self)
            factory._load()

    def new(self, name, *args, **kwargs):
        instance = super().new(name, *args, **kwargs)
        instance.save = partial(self._validate_and_save_instance, name, instance)

        self._load_sub_factories(name, instance)
        return instance

    def _load(self):
        for name in self.store.list_all():
            instance = self.new(name)
            instance._set_data(self.store.get(name))

    def delete(self, name):
        self.store.delete(name)
        super(StoredFactory, self).delete(name)

    def list_all(self):
        """
        get all instance names (stored or not)

        Returns:
            list of str: names
        """
        names = set(self.store.list_all())
        return names.union(super().list_all())

    def __iter__(self):
        for value in vars(self).values():
            if isinstance(value, self.type):
                yield value
Beispiel #5
0
    def exceptions(self):
        return self.__loaded_simplenamespace.jumpscale.core.exceptions

    def reload(self):
        self.__loaded = False
        self.__loaded_simplenamespace = None
        self._load()

    def _load(self):
        if not self.__loaded:
            self.__loaded_simplenamespace = namespaceify(loadjsmodules())

    def __getattr__(self, name):
        self._load()

        return getattr(self.__loaded_simplenamespace.jumpscale, name)


j = J()
j._load()

# register alerthandler as an error handler
alerts_config = get_config().get("alerts")
if alerts_config and alerts_config.get("enabled", True):
    j.tools.errorhandler.register_handler(
        handler=j.tools.alerthandler.alert_raise,
        level=alerts_config.get("level", 40))

# register global error hook
sys.excepthook = j.tools.errorhandler.excepthook
Beispiel #6
0
 def set_default(self, name):
     config = get_config()
     config["threebot"]["default"] = name
     update_config(config)
     self.__class__._me = None
Beispiel #7
0
logs_dir = os.path.expanduser(os.path.join("~/.config", "jumpscale", "logs"))

# TODO suitable logging format.
DEFAULT_LOGGING_CONFIG = {
    "handlers": [
        # {"sink": "sys.stdout", "format": "{time} - {message}", "colorize":True, "enqueue":True},
        {
            "sink": os.path.join(logs_dir, "file_jumpscale.log"),
            "serialize": True,
            "enqueue": True
        }
    ]
}

js_config = get_config()
if not "logging" in js_config or js_config["logging"]["handlers"] == [{}]:
    # FIXME: doesn't work as expected..
    js_config["logging"] = DEFAULT_LOGGING_CONFIG
    update_config(js_config)

js_config = get_config()
assert js_config["logging"] and js_config["logging"]["handlers"] != [{}]
# js_config = get_jumpscale_config()
# loguruconfig = js_config.get("logging")
logging_config = js_config["logging"]

# QUESTION: how to pass sink sys.stdout in json config?
logging_config["handlers"].append({
    "sink": sys.stdout,
    "format": "{time} - {message}",
Beispiel #8
0
def list_all():
    """list all configurations."""
    format_config(get_config())
Beispiel #9
0
def update(name, value):
    config = get_config()
    config[name] = value
    update_config(config)

    click.echo("Updated.")
Beispiel #10
0
def get(name):
    value = get_config()[name]
    click.echo(format_config_parameter(name, value))
Beispiel #11
0
def list_all():
    click.echo(format_config(get_config()))