def _cache_database(): global globs, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load filename patterns (globs) globs = GlobDB() for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs2')): globs.merge_file(path) globs.finalise() # Load magic sniffing data magic = MagicDB() for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.merge_file(path) magic.finalise() # Load subclasses for path in BaseDirectory.load_data_paths( os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def __init__(self, release): self.release = release self.name = 'apt-venv' self.config = _loadJSON(open('/etc/apt-venv.conf')) self.distro = None for distro in self.config['distributions']: if self.release in self.config['distributions'][distro]['releases']: self.distro = distro if not self.distro: base = "Release \"{}\" not valid. ".format(self.release) if not self.release: base = "No release declared. " all_releases = [] for distro in sorted(self.config['distributions'].keys()): releases = self.config['distributions'][distro]['releases'] all_releases.append(" [%s] %s" % (distro, ' - '.join(releases))) raise ValueError(base + "Please specify one of:\n%s" % '\n'.join(all_releases)) self.config_path = _BaseDirectory.save_config_path(self.name) self.cache_path = _BaseDirectory.save_cache_path(self.name) self.data_path = _BaseDirectory.save_data_path(self.name) self.config_path = _os.path.join(self.config_path, self.release) self.cache_path = _os.path.join(self.cache_path, self.release) self.data_path = _os.path.join(self.data_path, self.release) self.bashrc = _os.path.join(self.config_path, "bash.rc") self.sourceslist = _os.path.join(self.config_path, "sources.list") self.aptconf = _os.path.join(self.config_path, "apt.conf")
def load_config(): resource_name = 'yt-bulk-py' if not bd.load_first_config(resource_name): sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name)) conf_dir = bd.load_first_config(resource_name) conf_file = os.path.join(conf_dir, 'config') conf_skel = """# Configuration file for yt-bulk-py # Account information for the user doing the uploading. [user] email = [email protected] password = secret """ if not os.path.isfile(conf_file): with open(conf_file, 'w+b') as f: f.write(conf_skel) config = ConfigParser.ConfigParser() config.read(conf_file) if not 'user' in config.sections(): sys.stderr.write('Error: No [user] section in config file.') exit(1) if not 'email' in config.options('user') and 'password' in config.options( 'user'): sys.stderr.write( 'Error: Missing "email" or "password" options in config file.') exit(1) return (config.get('user', 'email'), config.get('user', 'password'))
def __init__(self, release): self.release = release self.name = 'apt-venv' self.config = self._load_config_from_files() self.distro = None for distro in self.config['distributions']: if self.release in self.config['distributions'][distro]['releases']: self.distro = distro if not self.distro: base = "Release \"{}\" not valid. ".format(self.release) if not self.release: base = "No release declared. " all_releases = [] for distro in sorted(self.config['distributions'].keys()): releases = self.config['distributions'][distro]['releases'] all_releases.append(" [%s] %s" % (distro, ' - '.join(releases))) raise ValueError(base + "Please specify one of:\n%s" % '\n'.join(all_releases)) self.config_path = _BaseDirectory.save_config_path(self.name) self.cache_path = _BaseDirectory.save_cache_path(self.name) self.data_path = _BaseDirectory.save_data_path(self.name) self.config_path = _os.path.join(self.config_path, self.release) self.cache_path = _os.path.join(self.cache_path, self.release) self.data_path = _os.path.join(self.data_path, self.release) self.bashrc = _os.path.join(self.config_path, "bash.rc") self.sourceslist = _os.path.join(self.config_path, "sources.list") self.aptconf = _os.path.join(self.config_path, "apt.conf")
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list( base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(widget.get_active())).lower() self.output_debug("Setting autostart to", activestr) dfile.set(AUTOSTART_KEY, activestr) ## remove the format specifiers executable = dfile.getExec().replace("%F", "") dfile.set("Exec", executable) dfile.write(filename=autostart_file)
def __init__(self, sender=None, addresses=[], *args, **kwargs): super().__init__(*args, **kwargs) if not isinstance(addresses, list): addresses = [addresses] elif not addresses: import xdg.BaseDirectory as xdgb p = xdgb.load_first_config('notifier', 'addresses') if p is not None: with open(p, 'r') as f: addresses = f.read().split() if not addresses: raise ValueError('No email addresses (defaults are read from {}/addresses, one address per line)' .format(xdgb.save_config_path('notifier'))) for addr in addresses: if not isinstance(addr, str) or not '@' in addr: raise TypeError('`addresses` must be an email address or a list of email addresses') self._addresses = addresses if sender is None: sender = 'Notifier' self._sender = sender self._addr = 'notifier@{}'.format(platform.node())
def __init__(self): # Init databases and fifo name = 'roficlip' self.ring_db = '{0}/{1}'.format(BaseDirectory.save_data_path(name), 'ring.db') self.persist_db = '{0}/{1}'.format(BaseDirectory.save_data_path(name), 'persistent.db') self.fifo_path = '{0}/{1}.fifo'.format( BaseDirectory.get_runtime_dir(strict=False), name) self.config_path = '{0}/settings'.format( BaseDirectory.save_config_path(name)) if not os.path.isfile(self.ring_db): open(self.ring_db, "a+").close() if not os.path.isfile(self.persist_db): open(self.persist_db, "a+").close() if (not os.path.exists(self.fifo_path) or not stat.S_ISFIFO(os.stat(self.fifo_path).st_mode)): os.mkfifo(self.fifo_path) self.fifo = os.open(self.fifo_path, os.O_RDONLY | os.O_NONBLOCK) # Init clipboard and read databases self.cb = gtk.Clipboard() self.ring = self.read(self.ring_db) self.persist = self.read(self.persist_db) # Load settings self.load_config() # Init notifications if self.cfg['notify']: pynotify.init(name)
def load_config(): resource_name = 'yt-bulk-py' if not bd.load_first_config(resource_name): sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name)) conf_dir = bd.load_first_config(resource_name) conf_file = os.path.join(conf_dir, 'config') conf_skel = """# Configuration file for yt-bulk-py # Account information for the user doing the uploading. [user] email = [email protected] password = secret """ if not os.path.isfile(conf_file): with open(conf_file, 'w+b') as f: f.write(conf_skel) config = ConfigParser.ConfigParser() config.read(conf_file) if not 'user' in config.sections(): sys.stderr.write('Error: No [user] section in config file.') exit(1) if not 'email' in config.options('user') and 'password' in config.options('user'): sys.stderr.write('Error: Missing "email" or "password" options in config file.') exit(1) return (config.get('user', 'email'), config.get('user', 'password'))
def on_checkautostart_toggled(self, widget): KUPFER_DESKTOP = "kupfer.desktop" AUTOSTART_KEY = "X-GNOME-Autostart-enabled" autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP) if not os.path.exists(autostart_file): desktop_files = list(base.load_data_paths("applications", KUPFER_DESKTOP)) if not desktop_files: self.output_error("Installed kupfer desktop file not found!") return desktop_file_path = desktop_files[0] # Read installed file and modify it dfile = desktop.DesktopEntry(desktop_file_path) executable = dfile.getExec() ## append no-splash if "--no-splash" not in executable: executable += " --no-splash" dfile.set("Exec", executable) else: dfile = desktop.DesktopEntry(autostart_file) activestr = str(bool(widget.get_active())).lower() self.output_debug("Setting autostart to", activestr) dfile.set(AUTOSTART_KEY, activestr) ## remove the format specifiers executable = dfile.getExec().replace("%F", "") dfile.set("Exec", executable) dfile.write(filename=autostart_file)
def __init__(self): config_dir = xdg.save_config_path('hobo') data_dir = xdg.save_data_path('hobo') self.images_dir = os.path.join(data_dir, 'images') if not os.path.isdir(self.images_dir): os.mkdir(self.images_dir) self.template_file = os.path.join(self.images_dir, 'hobo.templates') touch(self.template_file) self.db = Db(os.path.join(data_dir, 'hobo.db')) config_file = os.path.join(config_dir, 'hobo.ini') self._cfg = ConfigParser() self._cfg.read(config_file) self.bridge_device = self.get('config', 'bridge_device') or 'hob0' self.base_mem = self.get('config', 'base_mem') or '1024' self.base_cpu = self.get('config', 'base_cpu') or '1' # compression analysis: # -1 256M # -9 213M # --best 223M # might as well use -1 # libvirt docs recommend: # --best --block-size=16777216 # but it's sloooow self.compress_flags = self.get('config', 'compress_flags') or '-1 -T0 --block-size=16777216'
def getconfpath(resource): '''get conf path or create as required''' confpath = xdgbasedir.load_first_config(resource) if confpath is None: confpath = xdgbasedir.save_config_path(resource) # put filename on return confpath
def _cache_database(): global globs, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. # Load aliases for path in BaseDirectory.load_data_paths(os.path.join("mime", "aliases")): with open(path, "r") as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load filename patterns (globs) globs = GlobDB() for path in BaseDirectory.load_data_paths(os.path.join("mime", "globs2")): globs.merge_file(path) globs.finalise() # Load magic sniffing data magic = MagicDB() for path in BaseDirectory.load_data_paths(os.path.join("mime", "magic")): magic.merge_file(path) magic.finalise() # Load subclasses for path in BaseDirectory.load_data_paths(os.path.join("mime", "subclasses")): with open(path, "r") as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def main(steam_path=None, mountpoint=None): # Setup XDG directories config_dir = BaseDirectory.save_config_path('steamfuse') data_dir = BaseDirectory.save_data_path('steamfuse') cache_dir = BaseDirectory.save_cache_path('steamfuse') # Check/Set path to steam installation if steam_path is None: steam_path = os.path.expanduser('~/.local/share/Steam') if not os.path.exists(steam_path): steam_path = os.path.expanduser('~/.var/app/com.valvesoftware.Steam/data/Steam/') if not os.path.exists(steam_path): print('Could not find Steam install dir. Specify as argument.') return -1 # Find libraries and installed games main_library = os.path.join(steam_path, 'steamapps') libraryfolders_vdf = vdf.load(open(os.path.join(main_library, 'libraryfolders.vdf'), 'r')) more_libraries = [ os.path.join(folder['path'], 'steamapps') for key, folder in libraryfolders_vdf['libraryfolders'].items() if key.isdigit() and int(key) > 0 ] # Setup mergerfs mount mergerfs_path = os.path.join(data_dir, 'mergerfs') if not os.path.exists(mergerfs_path): os.mkdir(mergerfs_path) proc = subprocess.Popen( ['mergerfs', f'{main_library}:{":".join(more_libraries)}', f'{mergerfs_path}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, text=True) out, err = proc.communicate() if err: print(err) return -1 # Download applist from Steam applist = os.path.join(cache_dir, 'applist.json') if not os.path.exists(applist): url = 'https://api.steampowered.com/ISteamApps/GetAppList/v2/' res = requests.get(url, allow_redirects=True) open(applist, 'wb').write(res.content) if mountpoint is None: mountpoint = os.path.join(data_dir, 'SteamFuse') if not os.path.exists(mountpoint): os.mkdir(mountpoint) try: FUSE(SteamFuseTree(mergerfs_path, applist), mountpoint=mountpoint, nothreads=True, foreground=True) except RuntimeError: pass proc = subprocess.Popen( ['fusermount', '-u', f'{mergerfs_path}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, text=True) out, err = proc.communicate() if err: print(err) return -1
def load_credentials(): p = xdgb.load_first_config('prisma', 'credentials') if p is None: exit('Please save your card number and password (each on its own line) in {}/credentials' .format(xdgb.save_config_path('prisma'))) with open(p, 'r') as f: t = f.read().split() return (t[0], t[1])
def __init__(self): self.CACHE_HOME = os.path.join(BaseDirectory.xdg_cache_home, "puding") # creating cache home if it doesn't exist if not os.path.isdir(self.CACHE_HOME): os.makedirs(self.CACHE_HOME) self.CONFIG_HOME = BaseDirectory.save_config_path("puding") self.CONFIG_FILE = os.path.join(self.CONFIG_HOME, "settings.json") self.DATA_HOME = BaseDirectory.save_data_path("puding") self.DATA_PATH = map(self.append_app_name, BaseDirectory.xdg_data_dirs) self.DEV_HOME = os.path.abspath(os.path.dirname(__file__))
def init(self, args): # copy config file and theme file `$HOME/.config/mirage_linemode` BaseDirectory.save_config_path(self._plugin_name_full) dst = get_config_path() if args.overwrite or os.access(dst, os.F_OK) is False: shutil.copy2(self._config_path, dst) dst = get_theme_path() if args.overwrite or os.access(dst, os.F_OK) is False: shutil.copy2(self._theme_path, dst)
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list(reversed(list(_xdg_basedirectory.load_config_paths("")))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path("")) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join("~", ".config"))] return [_os_path.join(path, "mutt-ldap.cfg") for path in paths]
def _cache_database(): global exts, globs, literals, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True exts = {} # Maps extensions to types globs = [] # List of (glob, type) pairs literals = {} # Maps literal names to types aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. magic = MagicDB() def _import_glob_file(path): """Loads name matching information from a MIME directory.""" with open(path) as f: for line in f: if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = lookup(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): if rest not in exts: exts[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: globs.append((pattern, mtype)) else: literals[pattern] = mtype for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs')): _import_glob_file(path) for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.mergeFile(path) # Sort globs by length globs.sort(key=lambda x: len(x[0])) # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load subclasses for path in BaseDirectory.load_data_paths( os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def __init__(self, debug=False): homedir = os.path.expanduser('~') self._conf_dir_name = BaseDirectory.save_config_path('actracker') self._log_dir_name = BaseDirectory.save_data_path('actracker') self._conf_fname = os.path.join(self._conf_dir_name, 'conf.json') self._load_conf() self._load_log() self._last_application = ('', '') self.activity_counter = {} self._current_day = datetime.now().day self.debug = debug
def _cache_database(): global exts, globs, literals, magic, aliases, inheritance, _cache_uptodate _cache_uptodate = True exts = {} # Maps extensions to types globs = [] # List of (glob, type) pairs literals = {} # Maps literal names to types aliases = {} # Maps alias Mime types to canonical names inheritance = defaultdict(set) # Maps to sets of parent mime types. magic = MagicDB() def _import_glob_file(path): """Loads name matching information from a MIME directory.""" with open(path) as f: for line in f: if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = lookup(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): if rest not in exts: exts[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: globs.append((pattern, mtype)) else: literals[pattern] = mtype for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs')): _import_glob_file(path) for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')): magic.mergeFile(path) # Sort globs by length globs.sort(key=lambda x: len(x[0]) ) # Load aliases for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')): with open(path, 'r') as f: for line in f: alias, canonical = line.strip().split(None, 1) aliases[alias] = canonical # Load subclasses for path in BaseDirectory.load_data_paths(os.path.join('mime', 'subclasses')): with open(path, 'r') as f: for line in f: sub, parent = line.strip().split(None, 1) inheritance[sub].add(parent)
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list( reversed(list(_xdg_basedirectory.load_config_paths('')))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path('')) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join('~', '.config'))] return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths]
def parse_opts(): ''' This method parses the commandline options to next, if any, and it parses the configuration file ''' t = TUI() parser = OptionParser(usage=constants.USAGE) parser.add_option(u'-c', u'--conf', nargs=1, dest=u'new_path', help=u'NEW_PATH specifies a different configuration file') parser.add_option(u'-r', u'--random', action="store_const", dest="func", const=t.do_random, help=u'Start an ep for a random show') parser.add_option(u'-l', u'--list', action="store_const", dest="func", const=t.do_list, help=u'List all your shows') parser.add_option(u'-n', u'--new', action="store_const", dest="func", const=t.do_new, help=u'List shows for which there are new eps on your system') parser.add_option(u'-u', u'--update', action="store_const", dest="func", const=t.do_update, help=u'Connect to the TVRage database and update your show information') parser.add_option(u'-a', u'--add', action="store_const", dest="func", const=t.do_add_show, help=u'Add a show to the database') parser.add_option(u'--add_location', action="store_const", dest="func", const=t.do_add_show_location, help=u'Add a location for a show to the database') parser.add_option(u'--change', action="store_const", dest="func", const=t.do_change_show, help=u'Change the current season and ep for a show') parser.add_option(u'--scan', action="store_const", dest="func", const=t.do_scan, help=u'Scan your series path for shows') (options, args) = parser.parse_args() # Load a default config config = ConfigParser.SafeConfigParser() config.add_section(u'general') config.set(u'general', constants.ConfKeys.PLAYER_CMD, u'mplayer') config.set(u'general', constants.ConfKeys.SHOW_PATH, u'~/downloads/series') db_path = BaseDirectory.save_data_path('next') config.set(u'general', constants.ConfKeys.DB_PATH, db_path) # Load the config override if options.new_path: path = options.new_path if not (os.path.exists(path) and os.access(path, os.F_OK) and os.access(path, os.W_OK)): print u'No configfile found in "{0}", generating default configfile. Please modify, then start next again!'.format(path) gen_example(path) sys.exit(-1) else: path = BaseDirectory.load_first_config('next', 'next.conf') if path: config.read(path) result = dict(config.items(u'general')) for (k, v) in result.items(): # make sure bools are parsed correct if 'false' == v.lower() or 'no' == v.lower() or '0' == v: result[k] = False if 'true' == v.lower() or 'yes' == v.lower() or '1' == v: result[k] = True t.conf = result return options, result, args
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list(reversed(list( _xdg_basedirectory.load_config_paths('')))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path('')) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join('~', '.mutt'))] # return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths] return '/home/derek/.mutt/mutt-ldap.cfg'
def test_runtime_dir_notset(self): environ.pop('XDG_RUNTIME_DIR', None) self.assertRaises(KeyError, BaseDirectory.get_runtime_dir, strict=True) fallback = BaseDirectory.get_runtime_dir(strict=False) assert fallback.startswith('/tmp/'), fallback assert os.path.isdir(fallback), fallback mode = stat.S_IMODE(os.stat(fallback).st_mode) self.assertEqual(mode, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Calling it again should return the same directory. fallback2 = BaseDirectory.get_runtime_dir(strict=False) self.assertEqual(fallback, fallback2) mode = stat.S_IMODE(os.stat(fallback2).st_mode) self.assertEqual(mode, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def test_runtime_dir_notset(self): environ.pop('XDG_RUNTIME_DIR', None) self.assertRaises(KeyError, BaseDirectory.get_runtime_dir, strict=True) fallback = BaseDirectory.get_runtime_dir(strict=False) assert fallback.startswith('/tmp/'), fallback assert os.path.isdir(fallback), fallback mode = stat.S_IMODE(os.stat(fallback).st_mode) self.assertEqual(mode, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) # Calling it again should return the same directory. fallback2 = BaseDirectory.get_runtime_dir(strict=False) self.assertEqual(fallback, fallback2) mode = stat.S_IMODE(os.stat(fallback2).st_mode) self.assertEqual(mode, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
def write(self, filename=None): """ Writes a configuration file. Write a configuration file at <pre>filename</pre>. If no filename is supplied, the default path is <pre>~/.config/pydof/pydof.rc</pre> or the <pre>pydof/pydof.rc</pre> file in your configured XDG configuration directory. """ if filename is None: basedir.save_config_path("pydof") self.write(Config.DEFAULTPATH) else: with open(filename, "w") as configfile: self.__parser.write(configfile)
def write(self, filename=None): """ Writes a configuration file. Write a configuration file at <pre>filename</pre>. If no filename is supplied, the default path is <pre>~/.config/pydof/pydof.rc</pre> or the <pre>pydof/pydof.rc</pre> file in your configured XDG configuration directory. """ if filename is None: basedir.save_config_path("pydof") self.write(Config.DEFAULTPATH) else: with open(filename, 'w') as configfile: self.__parser.write(configfile)
def main(): cache_directory = BaseDirectory.save_cache_path('ob_xdg_apps') xml_file = os.path.join(cache_directory, 'menu.xml') appdirs = (os.path.join(datadir, 'applications') for datadir in BaseDirectory.xdg_data_dirs) if os.path.isfile(xml_file): updated = False for appdir in appdirs: if os.path.isdir(appdir): if os.stat(appdir).st_ctime > os.stat(xml_file).st_ctime: updated = True break if not updated: with open(xml_file) as f: print f.read() return icon_theme = gtk.icon_theme_get_default() menu = etree.Element('openbox_pipe_menu') menu_accumulator = MenuAccumulator() for desktop_entry in get_desktop_entries(): menu_accumulator.add_entry(desktop_entry) menu_accumulator.finalize() categories = sorted(menu_accumulator.structure.keys()) for category in categories: submenu_id = '{}-submenu'.format(category) submenu = etree.SubElement(menu, 'menu', {'id': submenu_id, 'label': category}) for desktop_entry in menu_accumulator.structure[category]: name = desktop_entry.getName() item_attributes = {'label': name.decode('utf-8')} entry_icon = desktop_entry.getIcon() if os.path.isfile(entry_icon): item_attributes['icon'] = entry_icon else: icon_name = os.path.splitext(entry_icon)[0] icon_info = icon_theme.lookup_icon(icon_name, 48, 0) if icon_info is not None: item_attributes['icon'] = icon_info.get_filename() item = etree.SubElement(submenu, 'item', item_attributes) action = etree.SubElement(item, 'action', {'name': 'Execute'}) command = etree.SubElement(action, 'command') command.text = desktop_entry.getExec() if desktop_entry.getStartupNotify(): startup_notify = etree.SubElement(action, 'startupnotify') enabled = etree.SubElement(startup_notify, 'enabled') enabled.text = 'yes' xml = etree.tostring(menu, pretty_print=True) with open(xml_file, 'w') as f: f.write(xml) print xml
def _get_status_filename(): """ Get the status filename. Filename generated from xdg module, in $XDG_RUNTIME_DIR or in /tmp (in this order). """ logger = logging.getLogger("_get_status_filename") status_basename = "chrandr.state" runtime_dir = None try: from xdg import BaseDirectory runtime_dir = BaseDirectory.get_runtime_dir() except ImportError: logger.info("xdg module not found") runtime_dir = os.getenv("XDG_RUNTIME_DIR") except KeyError: pass if runtime_dir is None: logger.debug("No environment variable XDG_RUNTIME_DIR") # no runtime dir, use /tmp import tempfile runtime_dir = tempfile.gettempdir() status_basename = "chrandr." + str(os.getuid()) + ".state" filename = os.path.join(runtime_dir, status_basename) logger.debug("Status filename: %s", filename) return filename
def _load_config(self): config = ConfigParser.SafeConfigParser() self.VERBOSE = False self._read_configs_into(config) DEFAULT_WORDPRESS_URL = 'http://wordpress.example.com/wordpress/xmlrpc.php' if not config.has_section('account'): config.add_section('account') # Fill in some default values config.set('account', 'url', DEFAULT_WORDPRESS_URL) config.set('account', 'username', 'joe_user') config.set('account', 'password', 'trustNo1') config.add_section('config') config.set('config', 'data_storage', 'file') config.set('config', 'publish_default', 'no') config.set('config', 'save_uploads', 'no') config.set('config', 'scale_images', 'no') path = os.path.join(BaseDirectory.save_config_path('rst2wp'), 'wordpressrc') print 'Need configuration! Edit %s' % (path, ) with file(path, 'wb') as fp: config.write(fp) sys.exit() if config.get('account', 'url') == DEFAULT_WORDPRESS_URL: # Don't wipe out what they might have configured print 'Still needs configuration! Edit %s' % (path, ) sys.exit() self._config = config return config
def load(self, *, config_fd: TextIO = None) -> None: config = '' if config_fd: config = config_fd.read() else: # Local configurations (per project) are supposed to be static. # That's why it's only checked for 'loading' and never written to. # Essentially, all authentication-related changes, like # login/logout or macaroon-refresh, will not be persisted for the # next runs. file_path = '' if os.path.exists(LOCAL_CONFIG_FILENAME): file_path = LOCAL_CONFIG_FILENAME # FIXME: We don't know this for sure when loading the config. # Need a better separation of concerns. logger.warn( 'Using local configuration ({!r}), changes will not be ' 'persisted.'.format(file_path)) else: file_path = BaseDirectory.load_first_config( 'snapcraft', 'snapcraft.cfg') if file_path and os.path.exists(file_path): with open(file_path, 'r') as f: config = f.read() if config: _load_potentially_base64_config(self.parser, config)
def read_convert_config(): config_path = "%s/%s" % (xdg.load_first_config('trip'), CONVERTER_CONFIG_FILE) config_dict = read_config(config_path) return config_dict
def _load_config(self): config = ConfigParser.SafeConfigParser() self.VERBOSE = False self._read_configs_into(config) DEFAULT_WORDPRESS_URL = 'http://wordpress.example.com/wordpress/xmlrpc.php' if not config.has_section('account'): config.add_section('account') # Fill in some default values config.set('account', 'url', DEFAULT_WORDPRESS_URL) config.set('account', 'username', 'joe_user') config.set('account', 'password', 'trustNo1') config.add_section('config') config.set('config', 'data_storage', 'file') config.set('config', 'publish_default', 'no') config.set('config', 'save_uploads', 'no') config.set('config', 'scale_images', 'no') path = os.path.join(BaseDirectory.save_config_path('rst2wp'), 'wordpressrc') print 'Need configuration! Edit %s'%(path,) with file(path, 'wb') as fp: config.write(fp) sys.exit() if config.get('account', 'url') == DEFAULT_WORDPRESS_URL: # Don't wipe out what they might have configured print 'Still needs configuration! Edit %s'%(path,) sys.exit() self._config = config return config
def get_config(): config_path = BaseDirectory.load_first_config("pyfortunes.cfg") if not config_path: sys.exit("pyfortunes.cfg not found") config = configparser.ConfigParser() config.read(config_path) return config
def get_load_path(cls, xdg_subdir=None, config_file=None): """Return the path to where a configuration file may be loaded from. Search each of the ``$XDG_CONFIG_DIRS`` for a file named ``$xdg_subdir/$config_file``. :param xdg_subdir: A string. The directory to append to each of the ``$XDG_CONFIG_DIRS``. Defaults to ``'pulp_smash'``. :param config_file: A string. The name of the settings file. Typically defaults to ``'settings.json'``. :returns: A string. The path to a configuration file, if one is found. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If no configuration file is found. """ if xdg_subdir is None: xdg_subdir = cls._get_xdg_subdir() if config_file is None: config_file = cls._get_config_file() for dir_ in BaseDirectory.load_config_paths(xdg_subdir): path = os.path.join(dir_, config_file) if os.path.exists(path): return path raise exceptions.ConfigFileNotFoundError( "Pulp Smash is unable to find a configuration file. The " "following (XDG compliant) paths have been searched: " ", ".join((os.path.join(xdg_config_dir, xdg_subdir, config_file) for xdg_config_dir in BaseDirectory.xdg_config_dirs)))
def get_config_files(filename): """ Iterator to @filename in all config paths, with most important (takes precendence) files first """ return base.load_config_paths(PACKAGE_NAME, filename) or ()
def write_ripper_config(): album_art_dict = { 'album_art_dir': "~/Pictures/album_art", 'embeded_art': True, 'folder_art': False } encoders_dict = {} encoders_dict[0] = { 'codec': 'flac', 'output_dir': 'FLAC' } encoders_dict[1] = { 'codec': 'mp3', 'bitrate': 320, 'output_dir': 'MP3_320' } config_out = { 'album_art': album_art_dict, 'encoders': encoders_dict, 'output_prefix': "~/Music" } config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE) write_config(config_out, config_path)
def get_save_dir (): ''' Returns the path to the directory to save the maps to ''' if os.name == 'nt': savedir = os.path.join(os.path.expanduser('~'), '.labyrinth') if not os.access (savedir, os.W_OK): os.makedirs (savedir) return savedir old_savedir = os.path.join (os.path.expanduser('~'), ".gnome2", "labyrinth") savedir = BaseDirectory.save_data_path("labyrinth") # Migrate maps to the new save directory. if os.path.exists(old_savedir) and os.path.isdir(old_savedir): for m in os.listdir(old_savedir): try: os.rename(os.path.join(old_savedir, m), os.path.join(savedir, m)) except Exception as e: warnings.warn("Failed to migrate %s: %s" % (m, e)) # remove old dir try: os.rmdir(old_savedir) except Exception as e: warnings.warn("Could not remove old map dir (%s): %s" % (old_savedir, e)) return savedir
def get_load_path() -> Path: """Return the path to the database file. :return: The path to the database. :raise tp.exceptions.DatabaseNotFoundError: If the database isn't found. """ importlib.reload(BaseDirectory) for db_dir in BaseDirectory.load_data_paths(DB_FILE.parent): db_path = Path(db_dir, DB_FILE.name) if db_path.exists(): return db_path raise exceptions.DatabaseNotFoundError( 'Unable to find a database. A database should be present at one of ' 'the following paths: ' + ', '.join( (str(db_dir) for db_dir in BaseDirectory.load_data_paths(DB_FILE.parent))))
def write_empty_config(self, config, conffile): rootdir = BaseDirectory.save_config_path('tuyau') with file(conffile, 'wb') as fp: config.write(fp) g = GPG(gnupghome=os.path.join(rootdir, 'gnupg')) g.list_keys()
def __init__(self): self.key_sequence = KeySequence() self.nag_interval = 300 self.nag_header = '\nReminders:' self.use_git = True os.environ.pop('GIT_DIR', None) # for path in xdgbase.load_config_paths(APP_NAME, 'config.py'): # with file(path) as stream: # exec stream in self.__dict__ self.nag_home = xdgbase.save_config_path(APP_NAME) self.nag_file_dir = xdgbase.save_config_path(APP_NAME, 'files') self.runtime = os.path.join(xdgbase.get_runtime_dir(), APP_NAME) self.timestamp = os.path.join(self.runtime, 'timestamp')
def get_data_file(filename, package=PACKAGE_NAME): """ Return path to @filename if it exists anywhere in the data paths, else raise ResourceLookupError. """ data_paths = [] try: from . import version_subst except ImportError: first_datadir = os.path.abspath("%s/../data" % (os.path.dirname(__file__))) else: first_datadir = os.path.join(version_subst.DATADIR, package) data_paths.append(first_datadir) for data_path in base.load_data_paths(package): if not data_path in data_paths: data_paths.append(data_path) for direc in data_paths: file_path = os.path.join(direc, filename) if os.path.exists(file_path): return file_path if package == PACKAGE_NAME: raise ResourceLookupError("Resource %s not found" % filename) else: raise ResourceLookupError("Resource %s in package %s not found" % (filename, package))
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises pulp_smash.config.base.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileNotFoundError( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG configuration paths, such as ' '"~/.config/{1}/".'.format(xdg_config_file, xdg_config_dir) )
def _show_captcha(self): xdg_captcha_cache = './cap.png' if (self.platform == 'win32') \ else BaseDirectory.save_cache_path('slt-usage') + '/cap.png' if self.platform != 'win32': self.spinner.start() self.browser.get(_SLT_URL) elem = self.browser.find_element_by_css_selector('tr > td > img') with open(xdg_captcha_cache, 'w+b') as f: f.write(elem.screenshot_as_png) if self.platform != 'win32': self.spinner.stop() try: call([ 'termpix', xdg_captcha_cache, '--true-colour', '--width', '97', '--height', '19' ]) except FileNotFoundError: init() print( Fore.RED + Style.BRIGHT + '\nInstall termpix (https://github.com/hopey-dishwasher/termpix)' ' to view captcha inline on the terminal!') Image.open(xdg_captcha_cache).show()
def get_auth(): def check_auth(auth): return requests.head(full_repo_url, auth=auth).status_code != httplib.UNAUTHORIZED # config file init config_file = os.path.join(BaseDirectory.save_config_path("malucrawl_reportificate"), "settings.ini") config = configparser.SafeConfigParser() config.read(config_file) if not config.has_section('auth'): config.add_section('auth') try: username = config.get('auth', 'username') except configparser.NoOptionError: username = raw_input("Username: "******"Authorization Failed" username = raw_input("Username: ") password = getpass.getpass() keyring.set_password(github_url, username, password) config.set('auth', 'username', username) config.write(open(config_file, 'w')) return (username, password)
def __init__(self, platform='default', old_skills_dir=None, skills_dir=None, repo=None, versioned=True): self.platform = platform # Keep this variable alive for a while, is used to move skills from the # old config based location to XDG self.old_skills_dir = path.expanduser(old_skills_dir or '') or None self.skills_dir = (skills_dir or BaseDirectory.save_data_path('mycroft/skills')) self.repo = repo or SkillRepo() self.versioned = versioned self.lock = MsmProcessLock() # Property placeholders self._all_skills = None self._default_skills = None self._local_skills = None self._device_skill_state = None self.saving_handled = False self.device_skill_state_hash = '' with self.lock: self._init_skills_data()
def load(self, *, config_fd: TextIO = None) -> None: config = "" if config_fd: config = config_fd.read() else: # Local configurations (per project) are supposed to be static. # That's why it's only checked for 'loading' and never written to. # Essentially, all authentication-related changes, like # login/logout or macaroon-refresh, will not be persisted for the # next runs. file_path = "" if os.path.exists(LOCAL_CONFIG_FILENAME): file_path = LOCAL_CONFIG_FILENAME # FIXME: We don't know this for sure when loading the config. # Need a better separation of concerns. logger.warn( "Using local configuration ({!r}), changes will not be " "persisted.".format(file_path) ) else: file_path = BaseDirectory.load_first_config( "snapcraft", "snapcraft.cfg" ) if file_path and os.path.exists(file_path): with open(file_path, "r") as f: config = f.read() if config: _load_potentially_base64_config(self.parser, config)
def get_save_dir(): ''' Returns the path to the directory to save the maps to ''' if os.name == 'nt': savedir = os.path.join(os.path.expanduser('~'), '.labyrinth') if not os.access(savedir, os.W_OK): os.makedirs(savedir) return savedir old_savedir = os.path.join(os.path.expanduser('~'), ".gnome2", "labyrinth") savedir = BaseDirectory.save_data_path("labyrinth") # Migrate maps to the new save directory. if os.path.exists(old_savedir) and os.path.isdir(old_savedir): for m in os.listdir(old_savedir): try: os.rename(os.path.join(old_savedir, m), os.path.join(savedir, m)) except Exception as e: warnings.warn("Failed to migrate %s: %s" % (m, e)) # remove old dir try: os.rmdir(old_savedir) except Exception as e: warnings.warn("Could not remove old map dir (%s): %s" % (old_savedir, e)) return savedir
def locker(init): config = os.path.join( BaseDirectory.save_config_path('cinnamon-udev-locker'), 'config.yml') try: with open(config) as f: conditions = yaml.load(f) except FileNotFoundError as e: logger.error('File not found {0}'.format(e.filename)) return except PermissionError as e: logger.error('Unable to read file: {0}'.format(e.filename)) return cs = CScreensaver.ScreenSaverProxy.new_for_bus_sync( Gio.BusType.SESSION, Gio.DBusProxyFlags.NONE, 'org.cinnamon.ScreenSaver', '/org/cinnamon/ScreenSaver', None) def lock(device): logger.info('Lock: {0}'.format(device)) cs.call_lock('{0} removed'.format( device.get_property('ID_MODEL_FROM_DATABASE'))) def wakeup(device): logger.info('Wakeup: {0}'.format(device)) cs.call_simulate_user_activity() actions = { 'lock': lock, 'wakeup': wakeup, } def match_device_properties(device, d): result = [ re.match(p, device.get_property(k)) for k, p in d.items() if device.has_property(k) ] return result and all(result) def event(client, action, device): if init: props = map(lambda k: '{0}: {1}'.format(k, device.get_property(k)), device.get_property_keys()) print('{0}:\n * {1}'.format(action, '\n * '.join(props))) return for condition in conditions: try: result = [ match_device_properties(device, d) for d in condition['devices'] ] if result and any(result): if action in condition: actions[condition[action]](device) except KeyError as e: logger.error('Invalid configuration') c = GUdev.Client(subsystems=[]) c.connect('uevent', event) GLib.MainLoop().run()
def load_config(config_override): conf_path = None if config_override is None: for dir in BaseDirectory.load_config_paths('evdevremapkeys'): conf_path = Path(dir) / 'config.yaml' print(Path(dir)) if conf_path.is_file(): break if conf_path is None: raise NameError('No config.yaml found') else: conf_path = Path(config_override) if not conf_path.is_file(): raise NameError('Cannot open %s' % config_override) with open(conf_path.as_posix(), 'r') as fd: config = yaml.safe_load(fd) for device in config['devices']: device['remappings'] = normalize_config(device['remappings']) device['remappings'] = resolve_ecodes(device['remappings']) if 'modifier_groups' in device: for group in device['modifier_groups']: device['modifier_groups'][group] = \ normalize_config(device['modifier_groups'][group]) device['modifier_groups'][group] = \ resolve_ecodes(device['modifier_groups'][group]) return config
def write_ripper_config(): album_art_dict = { 'album_art_dir': "~/Pictures/album_art", 'embeded_art': True, 'folder_art': False } encoders_dict = {} encoders_dict[0] = {'codec': 'flac', 'output_dir': 'FLAC'} encoders_dict[1] = { 'codec': 'mp3', 'bitrate': 320, 'output_dir': 'MP3_320' } config_out = { 'album_art': album_art_dict, 'encoders': encoders_dict, 'output_prefix': "~/Music" } config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE) write_config(config_out, config_path)
def read_config(args): config = os.path.join(xdg.save_config_path(myname), "%s.conf" % myname) username = "" password = "" hostnames = [] # Read log.debug("Reading settings from '%s'", config) try: with open(config, 'r') as fd: username, password = fd.readline().strip().split('\t') for line in fd: hostnames.append(line.strip()) except IOError as e: log.warn(e) except ValueError as e: log.error("Error in config file, check credentials at '%s'", config) # Save if args.username or args.password or args.hostnames: log.info("Saving settings to '%s'", config) try: with open(config, 'w') as fd: fd.write("%s\t%s\n" % (args.username or username, args.password or password,)) for hostname in (args.hostnames or hostnames): fd.write("%s\n" % hostname) os.chmod(config, 0600) except IOError as e: log.error(e) return dict(username=username, password=password, hostnames=hostnames)
def get_state_path(): """Get complete path for skill state file. Returns: (str) path to skills.json """ return join(BaseDirectory.save_data_path('mycroft'), 'skills.json')
def __init__( self, *, project, echoer, is_ephemeral: bool = False, build_provider_flags: Dict[str, str] = None, ) -> None: self.project = project self.echoer = echoer self._is_ephemeral = is_ephemeral self.instance_name = "snapcraft-{}".format(project._snap_meta.name) if project._snap_meta.version: self.snap_filename = "{}_{}_{}.snap".format( project._snap_meta.name, project._snap_meta.version, project.deb_arch) else: self.snap_filename = "{}_{}.snap".format(project._snap_meta.name, project.deb_arch) self.provider_project_dir = os.path.join( BaseDirectory.save_data_path("snapcraft"), "projects", project._snap_meta.name, self._get_provider_name(), ) if build_provider_flags is None: build_provider_flags = dict() self.build_provider_flags = build_provider_flags.copy()
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises hansei.exceptions.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ path = BaseDirectory.load_first_config(xdg_config_dir, xdg_config_file) if path and os.path.isfile(path): return path raise exceptions.ConfigFileNotFoundError( 'Hansei is unable to find a configuration file. The following ' '(XDG compliant) paths have been searched: ' + ', '.join([ os.path.join(config_dir, xdg_config_dir, xdg_config_file) for config_dir in BaseDirectory.xdg_config_dirs ]))
def _ensure_xdg_dirs(self): """Make sure we have the default resource. :return The path to the XDG resource. """ return xdgBaseDir.save_config_path(DEFAULT_XDG_RESOURCE, DEFAULT_LAVA_TOOL_RESOURCE)
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A ``str`` path to a configuration file. :raises nailgun.config.ConfigFileError: When no configuration file can be found. """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileError( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG configuration paths, such as ' '"~/.config/{1}/".'.format(xdg_config_file, xdg_config_dir) )
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ paths = [ os.path.join(config_dir, xdg_config_file) for config_dir in BaseDirectory.load_config_paths(xdg_config_dir) ] for path in paths: if os.path.isfile(path): return path raise exceptions.ConfigFileNotFoundError( 'Pulp Smash is unable to find a configuration file. The following ' '(XDG compliant) paths have been searched: ' + ', '.join(paths) )