Exemplo n.º 1
0
def _get_config_file():
    # paths to config file, in the ordere they're checked
    paths = [
        os.environ.get(ENV_CONFIG),
        os.path.join(xdg_config_home(), "arkiv/arkiv.conf"),
        os.path.expanduser("~/.arkiv/arkiv.conf"),
        os.path.expanduser("~/.arkiv"),
    ]

    for p in paths:
        if p and os.path.isfile(p):
            return p  # use the first valid config file

    return os.path.join(xdg_config_home(), "arkiv/arkiv.conf")
Exemplo n.º 2
0
 def __init__(self):
     config_dir = xdg_config_home().joinpath('fledgling')
     config_file = config_dir.joinpath('config.ini')
     print('config_file', config_file)
     self.config = configparser.ConfigParser()
     self.config_dir = config_dir
     self.config_file = config_file
Exemplo n.º 3
0
def _get_config_dir() -> Path:
    if os.name == 'nt':
        path = Path(os.path.expandvars('%AppData%/jcotton42/ficdl'))
    else:
        path = xdg_config_home().joinpath('jcotton42/ficdl')
    path.mkdir(mode=0o770, parents=True, exist_ok=True)
    return path
Exemplo n.º 4
0
def _get_config_file():
    # paths to config file, in the ordere they're checked
    paths = [
        os.environ.get(ENV_CONFIG),
        os.path.join(xdg_config_home(), "jackup/jackup.conf"),
        os.path.expanduser("~/.jackup/jackup.conf"),
        os.path.expanduser("~/.jackup"),
    ]

    for p in paths:
        if p and os.path.isfile(p):
            log.debug(f"{p}")
            return p  # use the first valid config file

    # if no config file is found, default to XDG
    return os.path.join(xdg_config_home(), "jackup/jackup.conf")
Exemplo n.º 5
0
 def __init__(self):
     config_home = xdg_config_home() / "py3status-reddit"
     config_home.mkdir(parents=True, exist_ok=True)
     config_home.chmod(0o0700)
     filename = config_home / "refresh_token"
     filename.touch(0o0600, exist_ok=True)
     filename.chmod(0o0600)
     super().__init__(filename)
Exemplo n.º 6
0
class AppConfig(GoodConf):
    "Configuration for My App"
    # GitHub
    pat: str
    hooksecret: str

    # Runner
    config_home: pathlib.Path = xdg.xdg_config_home() / appname
    cache_home: pathlib.Path = xdg.xdg_cache_home() / appname
    dirs: typing.Any = None

    @validator('dirs', pre=True, always=True)
    def default_dirs(cls, v, *, values, **kwargs):
        return makepaths(values['config_home'], values['cache_home'])

    prefix: str
    remotes: typing.Dict[str, Remote]
    runnermap: typing.List[RunnerConf]

    web_host: IPvAnyAddress = ipaddress.IPv4Address('0.0.0.0')
    web_port: int = 5000
    web_tls: bool = True

    cleanup: bool = True

    # For testing
    activecfg: typing.FrozenSet[str] = frozenset()
    max_workers: int
    def_repo_args: dict = {}
    def_org_args: dict = {}

    class Config:
        default_files = def_configs
        file_env_var = "LXDRCFG"

    @root_validator
    def check_image_sources(cls, values):
        error = ""
        for rc in values.get('runnermap'):
            if ":" in rc.image:
                rem = rc.image.split(":")[0]
                if rem not in values.get("remotes"):
                    error += f"Remote '{rem}' is undefined\n"
        if error:
            raise ValueError(error)
        return values

    def key_pair_paths(self):
        return (self.config_home / "client.crt",
                self.config_home / "client.key")

    def app_paths(self):
        return [self.config_home, self.cache_home] + list(
            self.dirs.dict().values())

    def config_exists(self):
        return [cfgfile for cfgfile in def_configs if cfgfile.exists()]
Exemplo n.º 7
0
    def __init__(self, app_name, config_dict):
        self._config_dict = config_dict
        self._app_name = app_name
        self._file_name = self._app_name + ".conf"
        self._config_file = os.path.join(xdg.xdg_config_home(),
                                         self._file_name)

        if not os.path.isfile(self._config_file):
            self.write_config()
        self.read_file()
Exemplo n.º 8
0
def main():
    """the main function, to test the config manager"""
    app_name = "maximus"
    conf_stub = app_name + ".conf"
    conf_path = os.path.join(xdg.xdg_config_home(), conf_stub)
    conf_salt = uuid.uuid4().hex
    config_dict = {'path': conf_path, 'salt': conf_salt}
    the_config = ConfigController(app_name, config_dict)

    print("The app_name is: ", app_name)
    print("conf_path is: ", conf_path, "\n")
    print(the_config.get())
    sys.exit(0)
Exemplo n.º 9
0
def __get_confdir__():
    """
    Configuration directory is specified through:

    .env
    WAVY_CONFIG environment variable
    XDG configuration directory (wavy)
    """
    c = os.getenv('WAVY_CONFIG', None)
    if c is None:
        c = os.path.join(xdg.xdg_config_home(), 'wavy')

        if not os.path.exists(c):
            c = None

    logger.debug('config directory: %s' % c)
    return c
Exemplo n.º 10
0
def get_global_config_path() -> Path:
    """Get global config path."""
    return xdg.xdg_config_home() / "autoimport" / "config.toml"
Exemplo n.º 11
0
# Copyright 2021 Robert Schroll
# This file is part of rmcl and is distributed under the MIT license.

import json
from xdg import xdg_config_home

CONFIG_FILE = xdg_config_home() / 'rmcl' / 'config.json'


class Config(dict):
    def __init__(self):
        super().__init__()
        if CONFIG_FILE.exists():
            super().update(json.load(CONFIG_FILE.open('r')))
        else:
            CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)

    def _save(self):
        json.dump(self, CONFIG_FILE.open('w'), indent=2)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._save()

    def update(self, other):
        super().update(other)
        self._save()

    def __delitem__(self, key):
        super().__delitem__(key)
        self._save()
Exemplo n.º 12
0
def get_user_config_dir(user: str = None) -> Path:
    if _use_xdg(user):
        return xdg.xdg_config_home()
    return get_user_home(user) / ".config"
Exemplo n.º 13
0
import toml
import typer
from xdg import (
    xdg_config_home,
    xdg_data_dirs,
    xdg_data_home,
)

from infod.filesystem import InfoFs
from infod import logging
from infod.config import InfodConfig, CommandSpec

app = typer.Typer()

default_mount = xdg_data_home() / Path('infod/mnt')
default_config = xdg_config_home() / Path('infod/config.toml')


@app.command()
def serve(config: Path = default_config,
          mountpoint: typing.Optional[Path] = typer.Argument(None),
          debug: bool = False,
          debug_fuse: bool = False):
    config = toml.load(config)
    if not mountpoint:
        mountpoint = Path(config.get('mountpoint', default_mount))
    mountpoint.mkdir(parents=True, exist_ok=True)

    try:
        clean(mountpoint)
    except:
Exemplo n.º 14
0
class Config(ConfigTree):

    DEFAULT_PROFILE = "default"

    DEFAULT_CONFIG_FILE = "config.yaml"

    PACKAGE_HOME = os.path.join(xdg.xdg_config_home(), PACKAGE_NAME)

    DEFAULT_CONFIG_PATH = os.path.expanduser(
        os.path.join(PACKAGE_HOME, DEFAULT_CONFIG_FILE))

    def __init__(self, config_file=None, merge_default=False, *args, **kwargs):
        super(Config, self).__init__(*args, **kwargs)
        self.__exclude_keys__ |= {
            "_config_file", "_config_dir", "include_profile", "_profile_tree"
        }
        self._config_file = config_file or self.DEFAULT_CONFIG_PATH
        self._config_dir = os.path.dirname(self._config_file) or "."
        self.load()
        self._profile_tree = ProfileTree(**self.profiles,
                                         merge_default=merge_default)

    @property
    def config_file(self):
        return self._config_file

    @property
    def CONFIG_DIR(self):
        return self._config_dir

    @property
    def LOG_FILE(self):
        return os.path.join(self.CONFIG_DIR, f"{PACKAGE_NAME}.log")

    @property
    def profile(self):
        return self._profile_tree.profile

    @property
    def profiles(self):
        return self._profile_tree

    @property
    def profile_names(self):
        return self._profile_tree.profile_names

    def include_profile(self, profile):
        self._profile_tree.include_profile(profile)

    def exclude_profile(self, profile):
        self._profile_tree.exclude_profile(profile)

    def toggle_profile(self, profile):
        self._profile_tree.toggle_profile(profile)

    def load(self):
        if not os.path.exists(self.config_file):
            raise Exception(f"config file {self.config_file} not found")
        loader = yaml_loader(ConfigTree, self._config_dir)
        config = yaml.load(open(self.config_file), Loader=loader)
        self.update(config.items())

    def save(self):

        d = Tree([(k, v) for k, v in self.items()])
        d.update({"profiles": self._profile_tree})
        with open(self._config_file, 'w') as outfile:
            yaml.dump(d, outfile, default_flow_style=False, indent=4)
Exemplo n.º 15
0
import time
import pathlib
import typing

import pendulum
import click
import xdg

from .api import RepublikApi, TokenType, RepublikCDN

API_URL_REPUBLIK = "https://api.republik.ch/graphql"
POLL_FREQUENCY = pendulum.duration(seconds=3)
TOKENS_DIR = xdg.xdg_config_home() / "repyblik" / "tokens"


@click.group()
@click.option(
    "--email",
    "-m",
    prompt="Your email address",
    help="The email address you registered with the REPUBLIK",
    required=True,
    type=str,
)
@click.pass_context
def cli(ctx, email):
    click.echo(f"Using '{email}' for this session...")

    ctx.ensure_object(dict)
    ctx.obj["EMAIL"] = email
    ctx.obj["TOKEN_FILE"] = TOKENS_DIR / email
Exemplo n.º 16
0
import sqlite3
import os
import pathlib
import sys
from query import Query, QueryColumn

from xdg import xdg_config_home
from typing import Iterator
from user_types import MetaDict, MetaValue

path = pathlib.Path(os.path.abspath(os.path.dirname(sys.argv[0])))
sql_path = path.joinpath("sql")
db_dir = pathlib.Path(xdg_config_home()).joinpath("daifukusan", "bpm_playlist")
db_path = db_dir.joinpath("database.db")
db_dir.mkdir(parents=True, exist_ok=True)


class __Database:
    __db_columns = [
        "path",
        "title",
        "albumartist",
        "artist",
        "composer",
        "genre",
        "artistsort",
        "album",
        "bpm",
        "length",
        "year",
    ]
Exemplo n.º 17
0
def cmd_main(
    ctx: click.Context,
    user_configs: typing.Iterator[typing.TextIO],
    root_stream_log_level: int,
    logfiles: typing.Iterable[typing.Tuple[int, pathlib.Path]],
):
    """A CLI toolkit to generate and manupilate the ABC Treebank.
    \f

    :param ctx: The context argument that is used by Click.
    :param user_configs:
        List of streams of configuration files. 
        Each file is opened beforehand 
        and will be closed properly by Click.
    :param root_stream_log_level:
        The log level for the root logger. Specified in integer.
    :param logfiles:
        List of additional log handlers.
        Each item consists of a tuple of a log level and an output path.
    """
    ctx.ensure_object(dict)

    # ====================
    # Configure logging
    # ====================
    # Adjust the root stream handler
    logger_root = logging.getLogger()
    logger_root.setLevel(root_stream_log_level)
    logging.info(
        f"The log level of the root logger is set to {logger_root.level}")

    # Add file handlers to the root
    for level, hpath in logfiles:
        hd = logging.FileHandler(hpath)
        hd.setLevel(level)
        logger_root.addHandler(hd)
    # === END FOR level, hpath ===

    logger_root.info(
        f"The handler(s) of the root logger is/are: {logging.root.handlers}")

    # ====================
    # Build config
    # ====================
    from dictknife import deepmerge
    import ruamel.yaml
    yaml = ruamel.yaml.YAML()
    import xdg
    import os

    CONFIG: typing.Dict[str, typing.Any] = CONF.CONF_DEFAULT
    path_config_user: pathlib.Path = xdg.xdg_config_home() / "ABCTreebank.yaml"
    if os.path.exists(path_config_user):
        with open(path_config_user, "r") as cu:
            CONFIG = deepmerge(CONFIG, cu, method="merge")
        # === END WITH cu ===
    # === END IF ===

    for h_cf in user_configs:
        CONFIG = deepmerge(CONFIG, yaml.load(h_cf), method="merge")
    # === END IF ===

    ctx.obj["CONFIG"] = CONFIG
Exemplo n.º 18
0
# Great setup for local developers, just need to enable DEBUG in local.env
env = environ.Env(
    DEBUG=(bool, False),
    SECRET_KEY=(str, "lih*)#c#npi*(tgw8xs-@4a-%k*1tnd4uqo)zy!rzzx5sc#-+d"),
    ADMIN=(tuple, []),  # Tuple of ONE admin (name, email)
    ALLOWED_HOSTS=(list, []),
    STATIC_URL=(
        str, "/static/"),  # URL path that server will server static files from
    STATIC_ROOT=(str, None),  # Collect static files here
    DATABASE=(str, "sqlite:///" + repo_root("db.sqlite3")),
    OMDB_API_KEY=(str, ""),  # REQUIRED if omdb is used
    SENTRY_DSN=(str, ""),  # REQUIRED if sentry is used
    SENTRY_TRACE_RATE=(float, 0.01),
)

if (xdg_config_home() / "vote4film/local.env").exists():
    config_file = str(
        environ.Path(xdg_config_home() / "vote4film/local.env", required=True))
else:
    config_file = repo_root("local.env", required=True)

# Read environment configuration (it must exist even for local developers)
try:
    environ.Env.read_env(config_file)
except ImproperlyConfigured:
    print("-" * 80)
    print("Are you a developer running this locally?")
    print(
        'You must create local.env in repository root with "DEBUG=on" inside.')
    print("-" * 80)
    sys.exit(1)
Exemplo n.º 19
0
def test_xdg_config_home_unset(monkeypatch: MonkeyPatch) -> None:
    """Test xdg_config_home when XDG_CONFIG_HOME is unset."""
    monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
    monkeypatch.setenv("HOME", os.fspath(HOME_DIR))
    assert xdg.xdg_config_home() == HOME_DIR / ".config"
Exemplo n.º 20
0
def main():
    cache = f'{xdg.xdg_cache_home()}/raccoon-entries'

    excludes = ['exo-open', 'steam://', '/usr/bin/wine', '/opt/google/chrome/google-chrome']

    def refresh_cache():
        dirs = xdg.xdg_data_dirs() + [xdg.xdg_data_home()]
        dirs = [dir/'applications' for dir in dirs]

        def walk(path):
            try:
                return next(os.walk(path))[2]
            except StopIteration:
                return []

        files = [ [ f'{path}/{f}'
                    for f
                    in walk(path)
                    if f.endswith('.desktop')
                  ]
                  for path
                  in dirs
                ]

        files = [f for dir in files for f in dir]

        entries = {}
        for f in files:
            parser = ConfigParser(strict=False, interpolation=None)
            parser.read(f)
            try:
                entry = parser['Desktop Entry']
            except KeyError:
                continue
            if entry.get('Type') == 'Application' and entry.get('Name') and entry.get('Exec'):
                cmd = entry['Exec']
                while True:
                    n = cmd.find('%')
                    if n == -1:
                        break
                    cmd = cmd[:n] + cmd[n+2:]
                cmd = ' '.join(cmd.split())
                if all(exclude not in cmd for exclude in excludes):
                    entries[f'{entry["Name"]} ({cmd})'] = cmd

        with open(cache, 'w') as f:
            json.dump(entries, f)

    def entries():
        while True:
            try:
                with open(cache) as f:
                    return json.load(f)
            except FileNotFoundError:
                refresh_cache()

    preferred_entries = {}
    try:
        with open(xdg.xdg_config_home()/'raccoon-dmenu-desktop/preferred.list') as f:
            for line in f.readlines():
                l = line.split('=')
                try:
                    preferred_entries[l[0]] = l[1].rstrip()
                except IndexError:
                    print(f'bad preferred.list entry: {line}')
    except FileNotFoundError:
        print('no preferred.list')

    def preferred(k):
        for j in preferred_entries.keys():
            if k.startswith(j):
                k = preferred_entries[j]+' '+k
                print(k)
        return k.lower()

    dmenu = sys.argv
    dmenu[0] = 'dmenu'

    entries = entries()

    out = run(dmenu, input='\n'.join(sorted(entries.keys(), key=preferred)), capture_output=True, text=True).stdout

    try:
        cmd = entries[out.rstrip()]
    except KeyError:
        sys.exit(1)

    Popen(cmd, shell=True)
Exemplo n.º 21
0
def test_xdg_config_home_set(monkeypatch: MonkeyPatch) -> None:
    """Test xdg_config_home when XDG_CONFIG_HOME is set."""
    monkeypatch.setenv("XDG_CONFIG_HOME", "/xdg_config_home")
    assert xdg.xdg_config_home() == Path("/xdg_config_home")
Exemplo n.º 22
0
def test_xdg_config_home_empty(monkeypatch: MonkeyPatch) -> None:
    """Test xdg_config_home when XDG_CONFIG_HOME is empty."""
    monkeypatch.setenv("HOME", os.fspath(HOME_DIR))
    monkeypatch.setenv("XDG_CONFIG_HOME", "")
    assert xdg.xdg_config_home() == HOME_DIR / ".config"
Exemplo n.º 23
0
from urllib import request, parse
import os.path
import json
import spotipy
from Xlib.display import Display
from spotipy.oauth2 import SpotifyClientCredentials
from xdg import xdg_cache_home, xdg_config_home
from pathlib import Path
import tempfile

player = Playerctl.Player()
playing = False
previousAlbumArt = None #Used to not reblur if you're listening to an album

cachedir = xdg_cache_home().joinpath("background-media")
configdir = xdg_config_home().joinpath("background-media")
tempdir = Path(os.path.join(tempfile.gettempdir(),"background-media"))

#setup dirs
cachedir.mkdir(parents=True, exist_ok=True)
configdir.mkdir(parents=True, exist_ok=True)
tempdir.mkdir(parents=True, exist_ok=True)

def getResolution():
    screen = Display(':0').screen()
    return "{}x{}".format(screen.width_in_pixels,screen.height_in_pixels)
def squareResolution():
    screen = Display(':0').screen()
    x = screen.width_in_pixels
    y = screen.height_in_pixels
    if x >= y:
Exemplo n.º 24
0
class Config:

    DEFAULT_CONFIG = {
        'broker': {
            'url': 'amqp://localhost:5672/%2F'
        },
        'api': {
            'enabled': True,
            'port': 8089
        },
        'components': [],
        # 'workdir': '/var/villas/controller/simulators/'
        'workdir': os.getcwd(),
        'uuid': str(uuid.uuid4())
    }

    DEFAULT_PATHS = xdg_config_dirs() + [
        xdg_config_home(),
        getcwd(),
        os.path.join(getcwd(), 'etc'), '/etc/villas/controller/'
    ]

    def __init__(self, fp=None):
        if fp is None:
            fn = self.find_default_path()
            if fn:
                with open(fn) as fp:
                    self.load(fp)
            else:
                self.config = {}  # Start without config
        else:
            self.load(fp)

    def load(self, fp):
        config = yaml.load(fp, Loader=yaml.FullLoader)
        merged = merge(self.DEFAULT_CONFIG, config)

        self.config = dotmap.DotMap(merged)

    def find_default_path(self,
                          filename='config',
                          suffixes=['json', 'yaml', 'yml']):
        for path in Config.DEFAULT_PATHS:
            for suffix in suffixes:
                fn = os.path.join(path, f'{filename}.{suffix}')
            if os.access(fn, os.R_OK):
                return fn

    @property
    def components(self) -> List[Component]:
        return [Component.from_dict(c) for c in self.config.components]

    def __getattr__(self, attr):
        return self.config.get(attr)

    def check(self):
        uuids = [c.uuid for c in self.components]

        dups_uuids = set([u for u in uuids if uuids.count(u) > 1])

        if len(dups_uuids) > 0:
            raise RuntimeError('Duplicate UUIDs: ' + dups_uuids)
Exemplo n.º 25
0
import typing
import urllib.parse

import xdg
from goodconf import GoodConf
from pydantic import (BaseModel, IPvAnyAddress, constr, root_validator,
                      validator)

with importlib.resources.path('lxdrunner.scripts', 'setuprunner.sh') as path:
    def_script = path

appname = "lxdrunner"

def_configs = [
    pathlib.Path("config.yml"),
    xdg.xdg_config_home() / f"{appname}/config.yml"
]


class RunnerConf(BaseModel):
    name: str
    labels: frozenset
    image: str
    profiles: typing.List[str] = ['default']
    runner_os: typing.Literal['linux', 'win', 'osx']
    runner_arch: typing.Literal['x64', 'arm', 'arm64']
    type: typing.Literal['container', 'virtual-machine']
    setup_script: pathlib.Path = def_script
    max_workers: int = 10
    worksem: threading.BoundedSemaphore = None
from sds011 import SDS011  # py-sds011
import aqi  # python-aqi
from xdg import xdg_config_home, xdg_config_dirs, xdg_state_home

NOTION_BASE_URL = "https://api.getnotion.com/api"

# The temperature that the purpleair sensor gathers is higher than the ambient
# temperature due to the heat generated by the sensor
# https://www.facebook.com/groups/purpleair/permalink/722201454903597/?comment_id=722420321548377
# https://www.reddit.com/r/PurpleAir/comments/imvepg/just_got_my_purpleair_to_measure_aqi_i_didnt/g45uonx
# pa.js widget has a "temperatureOffset" variable with a value I don't know yet
OBSERVED_ADDITIONAL_PURPLE_AIR_TEMP_OFFSET = 1
PURPLE_AIR_TEMP_OFFSET = -9.43 + OBSERVED_ADDITIONAL_PURPLE_AIR_TEMP_OFFSET

filename = 'monitor_air_quality_config.yaml'
dirs = [xdg_config_home()]
dirs.extend((xdg_config_dirs()))
config_files = [
    PosixPath(x, filename) for x in dirs if PosixPath(x, filename).exists()
]
if not config_files:
    config = dict()
else:
    with config_files[0].open() as f:
        config = yaml.safe_load(f)


def celsius_to_fahrenheit(degrees_c):
    return 32.0 + (float(degrees_c) * 1.8)

Exemplo n.º 27
0
            color = "#ffff00"
        else:
            color = "#ff0000"
        delayStr = "({:+.0f})".format(delay)
    else:
        delayStr = ""
    if isinstance(predicted_arrival_timestamp, int):
        predicted_arrival_time = datetime.fromtimestamp(
            predicted_arrival_timestamp)
    else:
        # We assume it's datetime already.
        predicted_arrival_time = predicted_arrival_timestamp
    return f'{stop_name} at <span fgcolor="{color}">{predicted_arrival_time:%H:%M}{delayStr}</span>'


api_key_path = Path(xdg.xdg_config_home(), "travelynx.conf")
if api_key_path.exists():
    with api_key_path.open("r") as f:
        api_key = f.read().strip()
else:
    print(
        f"Could not find Travelynx API key at {api_key_path}.",
        file=sys.stderr,
    )
    sys.exit(1)

api_base = f"https://travelynx.de/api/v1/status/{api_key}"
try:
    res = requests.get(api_base)
except requests.exceptions.ConnectionError:
    print(
Exemplo n.º 28
0
# Copyright 2021 Robert Schroll
# This file is part of RMfuse and is distributed under the MIT license.

import ast
from configparser import ConfigParser
import enum
import inspect
import logging
import sys

from xdg import xdg_config_home

from rmrl import render

log = logging.getLogger(__name__)
CONFIG_FILE = xdg_config_home() / 'rmfuse' / 'config.ini'


class FSMode(enum.Enum):
    meta = 'meta'
    raw = 'raw'
    orig = 'orig'
    annot = 'annot'

    def __str__(self):
        return self.name


def _get_render_defaults():
    defaults = inspect.getfullargspec(render).kwonlydefaults
    del defaults['progress_cb']
Exemplo n.º 29
0
TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATICFILES_DIRS = [os.path.join(BASE_DIR, "assets")]
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"

AUTH_USER_MODEL = "st_web.User"

# ----- Syncthing settings -----

st_config_path = os.path.join(xdg_config_home(), "syncthing/config.xml")
parsed_xml = ElementTree.parse(st_config_path)
folders = parsed_xml.findall("folder")
ST_CONFIG = []
for folder in folders:
    ST_CONFIG.append({
        "id": folder.get("id"),
        "label": folder.get("label"),
        "path": folder.get("path"),
    })
Exemplo n.º 30
0
PACKAGE_PATH = Path(module_path).parent

PACKAGE_STATIC_PATH = PACKAGE_PATH / "static"

PACKAGE_SCRIPTS_PATH = PACKAGE_PATH / "scripts"

BASE_DATA_PATH = (
    Path(os.environ["FT_DATA_PATH"])
    if "FT_DATA_PATH" in os.environ
    else Path(xdg_data_home(), "footron")
)

BASE_CONFIG_PATH = (
    Path(os.environ["FT_CONFIG_PATH"])
    if "FT_CONFIG_PATH" in os.environ
    else Path(xdg_config_home(), "footron")
)

BASE_MESSAGING_URL = (
    os.environ["FT_MSG_URL"]
    if "FT_MSG_URL" in os.environ
    else "ws://localhost:8088/messaging/out/"
)

BASE_BIN_PATH = BASE_DATA_PATH / "bin"

ROLLBAR_TOKEN = os.environ["FT_ROLLBAR"] if "FT_ROLLBAR" in os.environ else None

STABILITY_CHECK = (
    bool(int(os.environ["FT_CHECK_STABILITY"]))
    if "FT_CHECK_STABILITY" in os.environ