def save_access_tokens(self): """ Saves a user's access token to their `sybl.json` file, specified by the `XDG_DATA_HOME` directory. If the directory or file do not exist, they will be created prior to writing. """ directory = xdg_data_home() path = directory / "sybl.json" # Ensure the path exists if not Path(directory).is_dir(): log.info( f"Creating the following as it does not exist: {directory}") Path(directory).mkdir(parents=True) # Ensure the file itself exists, even if it's empty if not Path(path).is_file(): log.info(f"Creating the following file: '{path}'") Path(path).touch() key_name = f"{self.email}.{self.model_name}" new_model = { "model_id": self.model_id, "access_token": self.access_token } with path.open("r") as sybl_json: contents = sybl_json.read() json_contents = json.loads(contents if contents else "{}") json_contents[key_name] = new_model with path.open("w") as sybl_json: sybl_json.write(json.dumps(json_contents))
def load_access_token(email, model_name) -> Tuple[str, str]: """ Loads the access token from XDG_DATA_HOME using email and model name Parameters: email (str): The email the model is registered with model_name (str): The name of the model to be loaded Returns: Tuple[str, str]: Tuple of access token and model id Raise: ValueError: raised if the model name and email pair is not found in XDG_DATA_HOME FileNotFoundError: raised if XDG_DATA_HOME/sybl.json is not found meaning no access token has been stored """ model_key: str = f"{email}.{model_name}" path = xdg_data_home() / "sybl.json" with path.open("r") as f: # pylint: disable=invalid-name file_contents: str = f.read() models_dict: Dict = json.loads(file_contents) try: model_data = models_dict[model_key] return model_data["access_token"], model_data["model_id"] except KeyError as e: # pylint: disable=invalid-name log.error("Model not registered") raise ValueError( f"Model {model_name} not registered to {email}") from e
def __init__(self, app_name, the_salt): self._current_cache = set() self._cache_file = app_name + ".cache" self._cache_path = os.path.join(xdg.xdg_data_home() , self._cache_file) self._hash_salt = the_salt loaded_cache = self.load_cache() print(len(loaded_cache)) if len(loaded_cache) == 0: self.create_cache() self.load_cache() print(self._current_cache)
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 main(): parser = argparse.ArgumentParser(description=f'{__splash__}\n{__about__}', formatter_class=CustomFormatter) parser.add_argument( '--secret-token', help='The secret token for the bot, '\ 'from the discord developer portal. '\ 'If you have set $ZARDOZ_TOKEN, this '\ 'option will override that.' ) parser.add_argument( '--database', type=lambda p: Path(p).absolute(), default=xdg_data_home().joinpath('zardoz-bot', 'db.json'), help='Path to the bot database. Default follows the '\ 'XDG specifiction.' ) parser.add_argument( '--log', type=lambda p: Path(p).absolute(), default=xdg_data_home().joinpath('zardoz-bot', 'bot.log'), help='Path to the log file. Default follows the '\ 'XDG specifiction.' ) args = parser.parse_args() log = setup_logger(log_file=args.log) TOKEN = args.secret_token if not TOKEN: try: TOKEN = os.environ['ZARDOZ_TOKEN'] except KeyError: log.error('Must set ZARDOZ_TOKEN or use --secret-token') sys.exit(1) else: log.info('Got secret token from $ZARDOZ_TOKEN.') # get a handle for the history database args.database.parent.mkdir(exist_ok=True) DB = Database(args.database) bot = commands.Bot(command_prefix='/') @bot.event async def on_ready(): log.info(f'Ready: member of {bot.guilds}') log.info(f'Users: {bot.users}') DB.add_guilds(bot.guilds) @bot.command(name='zabout', help='Project info.') async def zabout(ctx): msg = f'version: {__version__}\n'\ f'source: https://github.com/camillescott/zardoz\n'\ f'active installs: {len(bot.guilds)}' await ctx.message.reply(msg) bot.add_cog(RollCommands(bot, DB)) bot.add_cog(CritCommands(bot, DB)) bot.add_cog(VarCommands(bot, DB)) bot.add_cog(ModeCommands(bot, DB)) bot.add_cog(HistoryCommands(bot, DB)) bot.run(TOKEN)
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)
def default_log_file(debug=False): if not debug: return xdg_data_home().joinpath('zardoz-bot', 'bot.log') else: return xdg_data_home().joinpath('zardoz-bot', 'debug', 'bot.log')
#!/home/david/Projects/pmenu/.venv/bin/python import os, sys import pathlib import subprocess import tldextract from xdg import xdg_data_home PASSWORD_STORE_DIR = '/home/david/.password-store' LAST_URL_PATH = pathlib.Path(os.environ.get('TABFS_MOUNT_DIR') or xdg_data_home() / 'TabFS/mnt') / 'tabs/last-focused/url.txt' def fake_pass_base(url: str) -> str: ext = tldextract.extract(url) general_name = pathlib.Path(PASSWORD_STORE_DIR, f'{ext.domain}.{ext.suffix}') sub_name = pathlib.Path(PASSWORD_STORE_DIR, f'{ext.subdomain}.{ext.domain}.{ext.suffix}') if ext.subdomain and sub_name.is_dir(): return str(sub_name) elif ext.subdomain and sub_name.is_file(): return str(sub_name.parent) elif general_name.is_dir(): return str(general_name) elif general_name.is_file(): return str(general_name.parent) return PASSWORD_STORE_DIR try: with open(LAST_URL_PATH, 'r') as f: url = f.read() except Exception as e:
import sys PY_VER = sys.version_info if PY_VER >= (3, 7): import importlib.resources as imp_res # type: ignore else: import importlib_resources as imp_res # type: ignore # === END IF === import xdg with imp_res.path("abctk", "runtime") as runtime_path: DIR_RUNTIME = runtime_path DIR_SHARE = xdg.xdg_data_home() / "ABCT-toolkit" DIR_CACHE = xdg.xdg_cache_home() / "ABCT-toolkit" _TOKEN_EMBEDDING_DIM = 200 _CHAR_EMBEDDING_DIM = 50 _CHAR_EMBEDDED_DIM = 100 _TOKEN_INDEXERS = { "tokens": { "type": "single_id", "lowercase_tokens": False, }, "token_characters": { "type": "characters", "min_padding_length": 5, "character_tokenizer": {
cli = click.Group() cli.add_command(change_plan) cli.add_command(create_config) cli.add_command(create_plan) cli.add_command(create_task) cli.add_command(delete_plan) cli.add_command(delete_task) cli.add_command(event_loop) cli.add_command(list_plan) cli.add_command(list_task) log_dir = xdg_data_home().joinpath('fledgling') if not log_dir.is_dir(): log_dir.mkdir(parents=True) log_file = log_dir.joinpath('fledgling.log') logging.basicConfig( filename=str(log_file), format='%(levelname)s:%(asctime)s:%(message)s', # TODO: 应当支持通过配置文件修改level。 level=logging.DEBUG, ) if __name__ == '__main__': cli()
def test_xdg_data_home_unset(monkeypatch: MonkeyPatch) -> None: """Test xdg_data_home when XDG_DATA_HOME is unset.""" monkeypatch.delenv("XDG_DATA_HOME", raising=False) monkeypatch.setenv("HOME", os.fspath(HOME_DIR)) assert xdg.xdg_data_home() == HOME_DIR / ".local" / "share"
def test_xdg_data_home_set(monkeypatch: MonkeyPatch) -> None: """Test xdg_data_home when XDG_DATA_HOME is set.""" monkeypatch.setenv("XDG_DATA_HOME", "/xdg_data_home") assert xdg.xdg_data_home() == Path("/xdg_data_home")
def test_xdg_data_home_empty(monkeypatch: MonkeyPatch) -> None: """Test xdg_data_home when XDG_DATA_HOME is empty.""" monkeypatch.setenv("HOME", os.fspath(HOME_DIR)) monkeypatch.setenv("XDG_DATA_HOME", "") assert xdg.xdg_data_home() == HOME_DIR / ".local" / "share"
def __init__(self, data_dir: typing.Union[Path, None] = None): if data_dir is None: data_dir = xdg.xdg_data_home() self.path = data_dir / "lumipallo" self.path.mkdir(parents=True, exist_ok=True)
from xdg import xdg_config_home, xdg_data_home from . import __file__ as module_path from .data.placard import PlacardExperienceData 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"
def default_database_dir(debug=False): if not debug: return xdg_data_home().joinpath('zardoz-bot', 'databases') else: return xdg_data_home().joinpath('zardoz-bot', 'debug', 'databases')
''' Supports both `dataset` ("ez") access and sqlite3 access to the database file. ''' import dataset import sqlite3 import xdg def sql_connection(): ''' Returns: as sqlite3 connection object to the database (an also be used to create the DB file) ''' return sqlite3.connect(_db_file) def ez_connection(): ''' Return a dataset (easy-to-use) connection to the NCEI data database ''' return dataset.connect('sqlite:///' + _db_file) def ensure_db(): ''' Make sure the database exists ''' c = sql_connection() c.close() return True _db_file = str(xdg.xdg_data_home()) + '/findacity.db'
from pathlib import Path import pkg_resources from xdg import xdg_data_home # From rcu.py, with comment # Todo: this should be based on the specific RM model DISPLAY = { 'screenwidth': 1404, 'screenheight': 1872, 'realwidth': 1408, 'dpi': 226 } # Qt docs say 1 pt is always 1/72 inch # Multiply ptperpx by pixels to convert to PDF coords PTPERPX = 72 / DISPLAY['dpi'] PDFHEIGHT = DISPLAY['screenheight'] * PTPERPX PDFWIDTH = DISPLAY['screenwidth'] * PTPERPX SPOOL_MAX = 10 * 1024 * 1024 # TODO: parameterize TEMPLATE_PATH = xdg_data_home() / 'rmrl' / 'templates' VERSION = pkg_resources.get_distribution('rmrl').version