Beispiel #1
0
def init(config=None, directories=None, files=None, force=False):
    """
    Initialize the configuration manager
    :param config: `string` or `dict`
    :param directories: semi-colon separated `string` or `list` of director(y|es)
    :param files: semi-colon separated `string` or `list` of file(s)
    :param force: force initialization even if it's already initialized
   """
    global _settings

    if not force and _settings is not None:
        raise ConfigurationAlreadyInitializedException("Configuration manager object is already initialized.")

    context = {
        'user_config_dir': user_config_dir()
    }

    _settings = ConfigManager(__builtin_config, context=context)

    if config:
        _settings.merge(config)

    local_config_file = join(user_config_dir(), 'myrpi.yaml')
    if exists(local_config_file):
        print('Loading config file: %s' % local_config_file)
        _settings.load_files(local_config_file)

    if directories:
        _settings.load_dirs(directories)

    if files:
        _settings.load_files(files)

    return _settings
Beispiel #2
0
 def __init__(self, name):
     self.config = RawConfigParser()
     self.file_opts = {}
     if sys.version_info[0] >= 3:
         self.file_opts['encoding'] = 'utf-8'
     if hasattr(appdirs, 'user_config_dir'):
         data_dir = appdirs.user_config_dir('photini')
     else:
         data_dir = appdirs.user_data_dir('photini')
     if not os.path.isdir(data_dir):
         os.makedirs(data_dir, mode=0700)
     self.file_name = os.path.join(data_dir, '%s.ini' % name)
     if name == 'editor':
         for old_file_name in (os.path.expanduser('~/photini.ini'),
                               os.path.join(data_dir, 'photini.ini')):
             if os.path.exists(old_file_name):
                 self.config.read(old_file_name, **self.file_opts)
                 self.save()
                 os.unlink(old_file_name)
     self.config.read(self.file_name, **self.file_opts)
     self.timer = QtCore.QTimer()
     self.timer.setSingleShot(True)
     self.timer.setInterval(3000)
     self.timer.timeout.connect(self.save)
     self.has_section = self.config.has_section
Beispiel #3
0
def get_config_js():
    from appdirs import user_config_dir

    config_dir = user_config_dir(appname="edit-on-web", appauthor="inducer")

    from os.path import join

    from os import makedirs

    try:
        makedirs(config_dir)
    except FileExistsError:
        pass

    config_file = join(config_dir, "config.js")

    for iattempt in [0, 1]:
        try:
            with open(config_file, "r") as inf:
                return Response(inf.read(), "200", mimetype="application/javascript")
        except FileNotFoundError:
            pass

        with open(config_file, "w") as outf:
            outf.write(DEFAULT_CONFIG)

    raise RuntimeError("failed to get config file")
Beispiel #4
0
    def get_settings_file(self):
        usr_cfg_dir = appdirs.user_config_dir(appname="jupyterbar", appauthor="ccodes")
        if not os.path.isdir(usr_cfg_dir):
            os.mkdir(usr_cfg_dir)

        usr_cfg_file = os.path.join(usr_cfg_dir, "ccodes.jupyterbar.xml")
        return usr_cfg_file
Beispiel #5
0
def _get_new_directories(platform_type):
    directories = {}
    if platform_type == ANDROID:
        directories['data'] = '%s/lbrynet' % android_app_internal_storage_dir()
        directories['lbryum'] = '%s/lbryum' % android_app_internal_storage_dir()
        directories['download'] = '%s/Download' % android_internal_storage_dir()
    elif platform_type == WINDOWS:
        directories['data'] = user_data_dir('lbrynet', 'lbry')
        directories['lbryum'] = user_data_dir('lbryum', 'lbry')
        directories['download'] = get_path(FOLDERID.Downloads, UserHandle.current)
    elif platform_type == DARWIN:
        directories = _get_old_directories(platform_type)
    elif platform_type == LINUX:
        directories['data'] = user_data_dir('lbry/lbrynet')
        directories['lbryum'] = user_data_dir('lbry/lbryum')
        try:
            with open(os.path.join(user_config_dir(), 'user-dirs.dirs'), 'r') as xdg:
                down_dir = re.search(r'XDG_DOWNLOAD_DIR=(.+)', xdg.read()).group(1)
                down_dir = re.sub('\$HOME', os.getenv('HOME'), down_dir)
                directories['download'] = re.sub('\"', '', down_dir)
        except EnvironmentError:
            directories['download'] = os.getenv('XDG_DOWNLOAD_DIR')

        if not directories['download']:
            directories['download'] = os.path.expanduser('~/Downloads')
    else:
        raise ValueError('unknown platform value')
    return directories
Beispiel #6
0
    def __init__(self,
                 app_name,
                 log_name='__main__',
                 config_dir=None,
                 silent=False):

        self.silent = silent

        if not self.silent:
            self.logger   = logging.getLogger('%s.cletus_supp' % log_name)
            self.logger.debug('SuppressCheck starting now')

        self.app_name        = app_name
        if config_dir:
            self.config_dir  = os.path.join(config_dir, 'suppress')
            if not silent:
                self.logger.debug('config_dir derrived from arg: %s' % self.config_dir)
        else:
            self.config_dir  = os.path.join(appdirs.user_config_dir(app_name), 'suppress')
            if not silent:
                self.logger.debug('config_dir provided via user_config_dir: %s' % self.config_dir)

        try:
            os.makedirs(self.config_dir)
            if not silent:
                self.logger.info('Suppression dir created successfully')
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                msg = 'Unknown OSError on creating config dir'
                if not silent:
                    self.logger.critical(msg)
                raise
 def user_config_dir(self):
     """Return ``user_config_dir``."""
     directory = appdirs.user_config_dir(self.appname, self.appauthor,
                            version=self.version, roaming=self.roaming)
     if self.create:
         self._ensure_directory_exists(directory)
     return directory
Beispiel #8
0
def load_css(filename):
	import os
	css = None
	if filename is None or not isinstance(filename, str):
		return None
	if os.path.exists(filename):
		with open(filename, 'r') as f:
			css = f.read()
		return css
	f0 = "{}.css".format(filename)
	if os.path.exists(f0):
		with open(f0, 'r') as f:
			css = f.read()
		return css
	try:
		import appdirs
	except ImportError:
		pass
	else:
		f1 = os.path.join(appdirs.user_config_dir('Larch'), filename)
		if os.path.exists(f1):
			with open(f1, 'r') as f:
				css = f.read()
			return css
		f2 = "{}.css".format(f1)
		if os.path.exists(f2):
			with open(f2, 'r') as f:
				css = f.read()
			return css
	if '{' in filename and '}' in filename:
		return filename
	return css
Beispiel #9
0
def _find_config():
    # prefer config file in the following order:
    # 1) current directory, 2) user home directory, 3) bundled config
    config_dirs = (
        ['.'] + [appdirs.user_config_dir("bandit")] +
        appdirs.site_config_dir("bandit", multipath=True).split(':'))
    if _running_under_virtualenv():
        config_dirs.append(os.path.join(sys.prefix, 'etc', 'bandit'))
        config_dirs.append(
            os.path.join(sysconfig.get_paths().get('purelib', ''),
                         'bandit', 'config'))
    config_locations = [os.path.join(s, BASE_CONFIG) for s in config_dirs]

    # pip on Mac installs to the following path, but appdirs expects to
    # follow Mac's BPFileSystem spec which doesn't include this path so
    # we'll insert it. Issue raised as http://git.io/vOreU
    mac_pip_cfg_path = "/usr/local/etc/bandit/bandit.yaml"
    if mac_pip_cfg_path not in config_locations:
        config_locations.append(mac_pip_cfg_path)

    for config_file in config_locations:
        if os.path.isfile(config_file):
            return config_file  # Found a valid config
    else:
        # Failed to find any config, raise an error.
        raise utils.NoConfigFileFound(config_locations)
Beispiel #10
0
def default_config_directories(
        user_config_dir=None,
        system_config_dir=None,
        exedir=None,
        verbose=0):
    # Use configuration in the order (lowest to highest priority)
    # 1) same path as exe,
    # 2) system config (XDG compliant.  /etc/xdg/ct)
    # 3) user config   (XDG compliant. ~/.config/ct)
    # 4) environment variables
    # 5) given on the command line

    # These variables are settable to assist writing tests
    if user_config_dir is None:
        user_config_dir = appdirs.user_config_dir(appname='ct')
    if system_config_dir is None:
        system_config_dir = appdirs.site_config_dir(appname='ct')
    if exedir is None:
        exedir = ct.wrappedos.dirname(ct.wrappedos.realpath(sys.argv[0]))

    executable_config_dir = os.path.join(exedir, "ct.conf.d")
    results = [user_config_dir, system_config_dir, executable_config_dir]
    if verbose >= 9:
        print(" ".join(["Default config directories"] + results))

    return results
Beispiel #11
0
def gui_main():

    args = get_arguments()

    try:
        # todo: today we're redirecting api.abel.co so for this we need to go direct.  In the future have everything on AWS including DNS.
        sentry_dsn = requests.get('http://l3wp7vlxe8.execute-api.us-west-2.amazonaws.com/dev/apps/propmtime/sentrydsn').text
        if not (sentry_dsn.startswith('http') and '@sentry.io' in sentry_dsn):
            sentry_dsn = None
    except ConnectionError:
        sentry_dsn = None

    balsa = Balsa( __application_name__, __author__, gui=True, use_sentry=sentry_dsn is not None, sentry_dsn=sentry_dsn)
    balsa.init_logger_from_args(args)

    app_data_folder = appdirs.user_config_dir(appname=__application_name__, appauthor=__author__)
    init_preferences_db(app_data_folder)

    init_exit_control_event()

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # so popup dialogs don't close the system tray icon
    system_tray = PropMTimeSystemTray(app, app_data_folder, balsa.log_path)
    system_tray.show()
    app.exec_()
Beispiel #12
0
 def __init__(self, app, org=None, maxlen=20):
     """
     :param app: Application name
     :type app: str
     :param org: Organisation name (default: ``None``)
     :type org: str
     :param maxlen: Maxium number of paths to remember
     :type maxlen: int
     :return: Iterable collection of MRU paths
     """
     self.app = app
     self.org = org
     #: Full path of file for saving MRU paths
     self.file_path = os.path.join(appdirs.user_config_dir(app, org), self.FILE_NAME)
     try:
         os.makedirs(os.path.dirname(self.file_path))  # create folder in advance
     except OSError:
         if not os.path.isdir(os.path.dirname(self.file_path)):
             raise
     try:
         # Load paths from file if possible
         with open(self.file_path, 'r', encoding='utf-8') as f:
             data = [line.rstrip('\n') for line in f]
     except OSError:
         data = []
     deque.__init__(self, data, maxlen=maxlen)
Beispiel #13
0
    def run(self):
        import appdirs

        old_data_dir = appdirs.user_config_dir(appauthor='Counterparty', appname='counterpartyd', roaming=True)
        old_database = os.path.join(old_data_dir, 'counterpartyd.9.db')
        old_database_testnet = os.path.join(old_data_dir, 'counterpartyd.9.testnet.db')

        new_data_dir = appdirs.user_data_dir(appauthor=config.XCP_NAME, appname=config.APP_NAME, roaming=True)
        new_database = os.path.join(new_data_dir, '{}.db'.format(config.APP_NAME))
        new_database_testnet = os.path.join(new_data_dir, '{}.testnet.db'.format(config.APP_NAME))

        # User have an old version of `counterpartyd`
        if os.path.exists(old_data_dir):
            # Move database
            if not os.path.exists(new_data_dir):
                os.makedirs(new_data_dir)
                files_to_copy = {
                    old_database: new_database,
                    old_database_testnet: new_database_testnet
                }
                for src_file in files_to_copy:
                    if os.path.exists(src_file):
                        dest_file = files_to_copy[src_file]
                        print('Copy {} to {}'.format(src_file, dest_file))
                        shutil.copy(src_file, dest_file)
Beispiel #14
0
def init_config():
    config_dir = user_config_dir(lecli.__name__)
    config_file_path = os.path.join(config_dir, 'config.ini')

    if not os.path.exists(config_file_path):
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)

        dummy_config = ConfigParser.ConfigParser()
        config_file = open(config_file_path, 'w')
        dummy_config.add_section('Auth')
        dummy_config.set('Auth', 'account_resource_id', '')
        dummy_config.set('Auth', 'owner_api_key_id', '')
        dummy_config.set('Auth', 'owner_api_key', '')
        dummy_config.set('Auth', 'rw_api_key', '')

        dummy_config.add_section('LogNicknames')
        dummy_config.add_section("LogGroups")
        dummy_config.write(config_file)
        config_file.close()
        print "An empty config file created in path %s, please check and configure it. To learn " \
              "how to get necessary api keys, go to this Logentries documentation page: " \
              "https://docs.logentries.com/docs/api-keys" % \
              config_file_path
    else:
        print "Config file exists in the path: " + config_file_path

    exit(1)
def extract_counterparty_server_config():
    counterparty_server_config = {}

    # Figure out the path to the server.conf file
    configdir = appdirs.user_config_dir(appauthor=config.XCP_NAME, appname=config.COUNTERPARTY_APP_NAME, roaming=True)
    server_configfile = os.path.join(configdir, 'server.conf')

    # Extract contents of server.conf to build service_url
    if os.path.exists(server_configfile):
        conf = {}
        with open(server_configfile, 'r') as fd:
            for line in fd.readlines():
                if '#' in line or '=' not in line:
                    continue
                k, v = line.split('=', 1)
                conf[k.strip()] = v.strip()

            config_keys = {
                'backend-connect': 'backend-connect',
                'backend-port': 'backend-port',
                'backend-user': '******',
                'backend-password': '******',
                'rpc-port': 'counterparty-port',
                'rpc-user': '******',
                'rpc-password': '******',
            }

            for server_key in config_keys:
                if server_key in conf:
                    counterparty_key = config_keys[server_key]
                    counterparty_server_config[counterparty_key] = conf[server_key]

    return counterparty_server_config
Beispiel #16
0
 def read_defaults(self):
     settings = {}
     try:
         from appdirs import user_config_dir
         config_file = to_path(user_config_dir('vdiff'), 'config')
         try:
             code = config_file.read_text()
             try:
                 compiled = compile(code, str(config_file), 'exec')
                 exec(compiled, settings)
             except Exception as e:
                 error(e, culprit=config_file)
         except FileNotFoundError:
             pass
         except OSError as e:
             warn(os_error(e))
         if self.useGUI is not None:
             settings['gui'] = self.useGUI
     except ImportError:
         pass
     if settings.get('gui', DEFAULT_GUI):
         if 'DISPLAY' not in os.environ:
             warn('$DISPLAY not set, ignoring request for gvim.')
         else:
             self.cmd = settings.get('gvimdiff', DEFAULT_GVIM)
             return
     self.cmd = settings.get('vimdiff', DEFAULT_VIM)
Beispiel #17
0
    def add_file(self,
                 app_name=None,
                 config_dir=None,
                 config_fn=None,
                 config_fqfn=None):

        # figure out the config_fqfn:
        if config_fqfn:
            self.cm_config_fqfn = config_fqfn
            self.cm_logger.debug('using config_fqn: %s' % config_fqfn)
        elif config_dir and config_fn:
            self.cm_config_fqfn = os.path.join(config_dir, config_fn)
            self.cm_logger.debug('using config_dir & config_fn: %s' % config_fqfn)
        elif app_name and config_fn:
            self.cm_config_fqfn = os.path.join(appdirs.user_config_dir(app_name), config_fn)
            self.cm_logger.debug('using app_name & config_fn: %s' % config_fqfn)
        else:
            self.cm_logger.critical('Invalid combination of args.  Provide either config_fqfn, config_dir + config_fn, or app_name + config_fn')
            raise ValueError('invalid config args')

        if not os.path.isfile(self.cm_config_fqfn):
            self.cm_logger.critical('config file missing: %s' % self.cm_config_fqfn)
            raise IOError('config file missing, was expecting %s' % self.cm_config_fqfn)

        self.cm_config_file = {}
        with open(self.cm_config_fqfn, 'r') as f:
            self.cm_config_file = yaml.safe_load(f)

        self._post_add_maintenance(self.cm_config_file)
Beispiel #18
0
def get_path(file):
    """ Assures the file is ready, or creates a new one from a default. """
    config_dir = user_config_dir("convey")
    if path.exists(file):
        # check the .ini file is at current location
        file = path.join(getcwd(), file)
    elif path.exists(path.join(path.dirname(sys.argv[0]), file)):
        # file at program folder (I.E. at downloaded github folder)
        file = path.join(path.dirname(sys.argv[0]), file)
    elif path.exists(path.join(config_dir, file)):
        # INIT file at user config folder
        file = path.join(config_dir, file)
    else:
        # create INI file at user config folder or at program directory
        default_path = "{}/defaults/".format(path.dirname(path.realpath(__file__)))
        program_path = path.abspath(path.dirname(sys.argv[0]))
        if input("It seems this is a first run, since file {} haven't been found."
                 "\nShould we create a default config files at user config folder ({})? "
                 "Otherwise, they'll be created at program folder: {} [Y/n] ".format(file, config_dir, program_path)) \
                in ["", "Y", "y"]:
            makedirs(config_dir, exist_ok=True)
        else:
            config_dir = program_path
        try:
            for filename in glob.glob(path.join(default_path, '*.*')):
                copy(filename, config_dir)
            file = "{}/{}".format(config_dir, file)
        except Exception as e:
            print(e)
            print("Error creating program file {}. Exiting.".format(file))
            exit()
    return file
Beispiel #19
0
def load_config():
    global config_keys
    paths = [os.path.join(appdirs.user_config_dir("", ""), "rettyt"),
             os.path.join(appdirs.user_config_dir("", ""), "rettytrc"),
             os.path.expanduser("~/.rettytrc"),
             os.path.expanduser("~/rettytrc"),
             os.path.abspath("rettytrc")]
    for path in paths:
        if os.path.isfile(path):
            fle = open(path, 'r')
            parser = shlex.shlex(fle)
            while True:
                (key, sep, val) = map(lambda x: parser.get_token(), range(0, 3))
                if key == '' or val == '':
                    break
                config_keys[key] = val
            fle.close()
Beispiel #20
0
def get_instances():
    paths = set()
    if sys.platform.startswith("win"):#check for installed factorio
        factorioappdata = join(appdirs.user_config_dir("Factorio", "", roaming=True), "mods")
        if os.path.exists(factorioappdata):
            paths.add(factorioappdata)
    #TODO add configured paths
    return paths
Beispiel #21
0
def load_profile(profile):
    try:
        import appdirs
    except ImportError:
        raise SystemExit('The appdirs module is required for profile support, but could not be imported.')
    config_dir = appdirs.user_config_dir('github')
    config = '{}/{}.yaml'.format(config_dir, profile)
    return load_config(config)
Beispiel #22
0
def arg_parse():
    parser = argparse.ArgumentParser(description="efficient and secure cloud-based folder sync")
    parser.add_argument('-a', '--appdatafolder', default=appdirs.user_config_dir(latus.const.NAME, latus.const.COMPANY),
                        help="app data folder (where preferences are stored)")
    parser.add_argument('-v', '--verbose', action='store_true', help="more verbose logging")
    parser.add_argument('-t', '--test', action='store_true', help="test mode")
    args = parser.parse_args()
    return args
Beispiel #23
0
def main():
    config_dir = appdirs.user_config_dir(
        PACKAGE + '-6a4d9d98-8e64-4a2a-b6c2-8a753ea61daf')
    try:
        retval = run(config_dir, sys.argv[1:])
    except BaseException as e:
        retval = e
    sys.exit(retval)
Beispiel #24
0
def get_configdir():
    """
    Definges a configdir for this package under $HOME/.pyevsel
    """
    config_dir = appdirs.user_config_dir(_appname)
    if not os.path.exists(config_dir):
        os.mkdir(config_dir)
    return config_dir
Beispiel #25
0
def loadUserConfiguration():
    config_path = os.path.join( appdirs.user_config_dir( 'jaminique' ), "config.json" )
    
    if os.path.isfile( config_path ):
        with open( config_path, 'rt' ) as configfile:
            return ArgumentTree( configfile )
    else:
       return ArgumentTree()
def get_config():
    """Return a user configuration object."""
    config_filename = appdirs.user_config_dir(_SCRIPT_NAME, _COMPANY) + ".ini"
    config = _MyConfigParser()
    config.optionxform = str
    config.read(config_filename)
    config.set_filename(config_filename)
    return config
Beispiel #27
0
def getConfig():
    config_file = os.path.join(user_config_dir('adsquery'), 'adsqueryrc')
    config = configparser.ConfigParser()
    config['adsquery'] = {
        'data_dir': '~/ADS',
        'pdf_viewer': 'evince'
    }
    config.read(config_file)
    return config
Beispiel #28
0
def load_config():
    config_file = os.path.join(user_config_dir(lecli.__name__), 'config.ini')
    files_read = CONFIG.read(config_file)
    if len(files_read) != 1:
        print "Error: Config file '%s' not found" % config_file
        exit(1)
    if not CONFIG.has_section('Auth'):
        print "Error: Config file '%s' is missing Auth section" % config_file
        exit(1)
    def load(self):
        # Load static config from a file
        try:
            with open(os.path.join(user_config_dir('archivemymail', 'Darac'), 'config.yml'), 'r') as f:
                self.__dict__ = yaml.load(f)
        except (OSError, IOError) as e:
            pass

        # Override the config with command line args
        parser = argparse.ArgumentParser(description="Archive mail from IMAP to compressed mbox")
        parser.add_argument('-n', '--dry-run', dest='dry_run', action='store_true',
                            default=self.setdefault('dry_run', False),
                            help="show what WOULD have been done")
        parser.add_argument('-S', '--no-learn', dest='do_learning', action='store_false',
                            default=self.setdefault('do_learning', True),
                            help="don't pass messages to spamassassin")
        group = parser.add_mutually_exclusive_group(required=False)
        group.add_argument('-z', '--gzip', dest='compression', action='store_const', const='gz',
                           help="GZIP-compress mboxes")
        group.add_argument('-j', '--bzip2', dest='compression', action='store_const', const='bz2',
                           help="BZIP2-compress mboxes")
        group.add_argument('-J', '--xz', dest='compression', action='store_const', const='xz',
                           help="XZ-compress mboxes (default)")
        parser.add_argument('-d', '--target-dir', dest='target_dir', action='store',
                            default=self.setdefault('target_dir', '/var/mail/%u/archive/'),
                            help="root location for the mboxes")
        parser.add_argument('-b', '--bayes-dir', dest='bayes_dir', action='store',
                            default=self.setdefault('bayes_dir', '/var/lib/amavis/.spamassassin'),
                            help="location of spamassassin's bayes database")
        parser.add_argument('-H', '--server', dest='server', action='store',
                            default=self.setdefault('server', 'mail.darac.org.uk'),
                            help="hostname of mail server")
        parser.add_argument('--debug', dest='debug', action='store_true',
                            default=self.setdefault('debug', False),
                            help="output extra logging")
        parser.add_argument('-a', '--account', dest='accounts', action='append',
                            default=self.setdefault('accounts', []),
                            help="account to archive (can be specified multiple times)",
                            metavar="USER:PASSWORD")

        args, unknowns = parser.parse_known_args()

        # Consolidate the options
        self['dry_run'] = args.dry_run
        self['do_learning'] = args.do_learning
        if args.compression is None:
            if 'compression' not in self.__dict__ or self['compression'] is None:
                self['compression'] = 'xz'
                # Else keep with self.compression
        else:
            self['compression'] = args.compression

        self['target_dir'] = args.target_dir
        self['bayes_dir'] = args.bayes_dir
        self['server'] = args.server
        self['debug'] = args.debug
        self['accounts'] = args.accounts
def main(argv=None):
    # ----------------------------------------------------------------------------------------------
    # Setup
    #
    # Get entry_point name
    entry_point = __name__.split('.')[-1].split('_')[0]
    # If argv is None, set it to sys.argv
    if argv is None:
        argv = sys.argv
    # Parse command-line arguments
    args = parse_args(argv[1:])
    # Setup logging
    logging.basicConfig(level=args.log_level)  # set log level for root logger
    logger = logging.getLogger('app_deployer')  # get instance of logger
    coloredlogs.install(fmt='%(message)s')  # colorize logging output

    # ----------------------------------------------------------------------------------------------
    # Print out app inventory
    #
    if args.list_apps:
        logger.info(app_inventory)
        sys.exit()

    # ----------------------------------------------------------------------------------------------
    # Print out hosts inventory
    #
    if args.list_hosts:
        logger.info(host_inventory)
        sys.exit()

    # ----------------------------------------------------------------------------------------------
    # Make sure ansible is installed and can be executed
    #
    if ansible_exe is None:
        config_dir = appdirs.user_config_dir('app-deployer')
        logger.fatal('ansible not found - please set ansible.path in {}/config.yml'.format(
            config_dir))
        sys.exit(1)

    # ----------------------------------------------------------------------------------------------
    # Validate the positional args
    #
    # App
    if not app_inventory.is_app(args.app_name):
        logger.fatal('Can\'t {} {} - not found in the app inventory. Run {} --list-apps to print '
                     'out the app inventory'.format(entry_point, args.app_name, entry_point))
        sys.exit(1)
    # Host
    if not host_inventory.is_host(args.host):
        logger.fatal('{} is not a valid host - make sure it\'s defined in your inventory file - '
                     'see Ansible documentation online'.format(args.host))
        sys.exit(1)

    # ----------------------------------------------------------------------------------------------
    # Create an App instance
    #
    app = app_inventory.get_app(args.app_name)
Beispiel #31
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses/.

# Imports {{{1
from textwrap import dedent
from appdirs import user_config_dir, user_cache_dir

# Non-Config Settings {{{1
# These value can be accessed with get_settings,
# but should not be found in the config file
NONCONFIG_SETTINGS = {
    'config_file': 'config',
    'config_doc_file': 'config.doc',
    'settings_dir': user_config_dir('avendesora'),
    'cache_dir': user_cache_dir('avendesora'),
    'default_accounts_file': 'accounts.gpg',
    'default_stealth_accounts_file': 'stealth_accounts',
    'charsets_hash': 'a055240c4c498e1470f5f3e80b3ec599',
    'dict_hash': '5dbabd4114eae520c1de8963a8b8d09d',
    'mnemonic_hash': 'cafd522d6627011d78e576f2d0b6ed58',
    'secrets_hash': '269d5bed6b564471b6581bf3309a6209',
    'discard_logfile': False,
    'commonly_mistaken_attributes': {
        'url': 'urls',
        'alias': 'aliases',
        'description': 'desc',
    }
}
Beispiel #32
0
 def __init__(self):
     self.confdir = appdirs.user_config_dir(appname, appauthor)
     self.confname = os.path.join(self.confdir, 'hosts.cfg')
     self.config = configparser.ConfigParser()
     self.config.read(self.confname)
Beispiel #33
0
def get_data_folder():
    image_tag_dirs = Path(user_config_dir("tox-via-docker"))
    if not image_tag_dirs.exists():
        image_tag_dirs.mkdir(parents=True)
    return image_tag_dirs
Beispiel #34
0
import appdirs
import os
from ruamel.yaml import YAML

# Config file order of precedence:
#  1. Current directory
#  2. User config directory
#  3. Site config directories
config_dirs = [os.getcwd()]
config_dirs.append(appdirs.user_config_dir('nbgallery'))
config_dirs += appdirs.site_config_dir('nbgallery', multipath=True).split(':')

# Load the first nbgallery.yml we find
yaml = YAML(typ='safe')
config = {}
for d in config_dirs:
    config_file = os.path.join(d, 'nbgallery.yml')
    if os.path.exists(config_file):
        with open(config_file) as f:
            config = yaml.load(f)
        break

if not config:
    raise ImportError(f"No nbgallery.yml config file found in the search path: {str(config_dirs)}")

# If the config lists a Rails config file, load that too and look for
# database configuration -- but our file takes precedence.
if config['nbgallery'].get('rails_config'):
    with open(config['nbgallery']['rails_config']) as f:
        rails_config = yaml.load(f)
    rails_mysql_config = rails_config.get('mysql', {})
Beispiel #35
0
 def get_global_config_dir():
     from appdirs import user_config_dir
     return user_config_dir(appname=Config.APPNAME,
                            appauthor=Config.APPAUTHOR)
Beispiel #36
0
 def get_default_dir() -> str:
     return appdirs.user_config_dir("ciphey")
Beispiel #37
0
def get_config_dir():
    config_dir = user_config_dir(appname='label-studio')
    if not os.path.exists(config_dir):
        os.makedirs(config_dir)
    return config_dir
Beispiel #38
0
def main():
    parser = argparse.ArgumentParser(
        description="Command-line frontend to the shreddit library."
    )
    parser.add_argument(
        "-c", "--config", help="Config file to use instead of the default shreddit.yml"
    )
    parser.add_argument(
        "-g",
        "--generate-configs",
        help="Write shreddit and praw config files to current directory.",
        action="store_true",
    )
    parser.add_argument(
        "-u",
        "--user",
        help="User section from praw.ini if not default",
        default="default",
    )
    args = parser.parse_args()

    if args.generate_configs:
        if not os.path.isfile("shreddit.yml"):
            print("Writing shreddit.yml file...")
            with open("shreddit.yml", "wb") as fout:
                fout.write(
                    pkg_resources.resource_string("shreddit", "shreddit.yml.example")
                )
        if not os.path.isfile("praw.ini"):
            print("Writing praw.ini file...")
            with open("praw.ini", "wb") as fout:
                fout.write(
                    pkg_resources.resource_string("shreddit", "praw.ini.example")
                )
        return

    config_dir = user_config_dir("shreddit/shreddit.yml")

    if args.config:
        config_filename = args.config
    elif os.path.exists(config_dir):
        config_filename = config_dir
    else:
        config_filename = "shreddit.yml"

    if not os.path.isfile(config_filename):
        print(
            "No shreddit configuration file was found or provided. Run this script with -g to generate one."
        )
        return

    with open(config_filename) as fh:
        # Not doing a simple update() here because it's preferable to only set attributes that are "whitelisted" as
        # configuration options in the form of default values.
        user_config = yaml.safe_load(fh)
        for option in default_config:
            if option in user_config:
                default_config[option] = user_config[option]

    shredder = Shredder(default_config, args.user)
    shredder.shred()
Beispiel #39
0
"""

# Total imports
import os

# Partial imports
from appdirs import user_config_dir, user_data_dir
from shutil import copy2 as copy

# Local imports
from plebnet.settings import setting

# File parameters
file_name = 'plebnet_setup.cfg'

conf_path = user_config_dir()
data_path = user_data_dir()
init_path = os.path.join(os.path.expanduser("~/PlebNet"),
                         'plebnet/settings/configuration')

init_file = os.path.join(init_path, file_name)
conf_file = os.path.join(conf_path, file_name)
""" DATE AND TIME VARIABLES """
TIME_IN_HOUR = 60.0 * 60.0
TIME_IN_DAY = TIME_IN_HOUR * 24.0
MAX_DAYS = 5
""" EXIT CODES """
FAILURE = 0
SUCCESS = 1
UNKNOWN = 2
Beispiel #40
0
from pathlib import Path

import click
from appdirs import user_config_dir, user_data_dir

from pixi.errors import PixiError

CONFIG_DIR = Path(user_config_dir("pixi", "azuline"))
DATA_DIR = Path(user_data_dir("pixi", "azuline"))


@click.group()
def commandgroup():
    pass


def make_app_directories():
    for name, dir_ in [("configuration", CONFIG_DIR), ("data", DATA_DIR)]:
        try:
            dir_.mkdir(mode=0o700, parents=True, exist_ok=True)
        except PermissionError:  # pragma: no cover
            raise PixiError(f"Could not create {name} directory.")
Beispiel #41
0
import pathlib
import os
from appdirs import user_config_dir

APP_NAME = "dexbot"
VERSION = '0.1.26'
AUTHOR = "codaone"
__version__ = VERSION


config_dir = user_config_dir(APP_NAME, appauthor=AUTHOR)
config_file = os.path.join(config_dir, "config.yml")

default_config = """
node: wss://bitshares.openledger.info/ws
workers: {}
"""

if not os.path.isfile(config_file):
    pathlib.Path(config_dir).mkdir(parents=True, exist_ok=True)
    with open(config_file, 'w') as f:
        f.write(default_config)
        print("Created default config file at {}".format(config_file))
Beispiel #42
0
 def file(self):
     return getattr(sys.modules[self.import_name], "__file__", appdirs.user_config_dir())
Beispiel #43
0
from functools import wraps
from datetime import datetime, timezone
from warnings import catch_warnings, filterwarnings
from pyrestcli.exceptions import ServerErrorException
from pandas.api.types import is_datetime64_any_dtype as is_datetime

from .logger import log
from ..exceptions import DOError

GEOM_TYPE_POINT = 'point'
GEOM_TYPE_LINE = 'line'
GEOM_TYPE_POLYGON = 'polygon'

PG_NULL = '__null'

USER_CONFIG_DIR = appdirs.user_config_dir('cartoframes')


def map_geom_type(geom_type):
    return {
        'Point': GEOM_TYPE_POINT,
        'MultiPoint': GEOM_TYPE_POINT,
        'LineString': GEOM_TYPE_LINE,
        'MultiLineString': GEOM_TYPE_LINE,
        'Polygon': GEOM_TYPE_POLYGON,
        'MultiPolygon': GEOM_TYPE_POLYGON
    }[geom_type]


def dict_items(indict):
    """function for iterating through dict items compatible with py2 and 3
Beispiel #44
0
# -*- coding: utf-8 -*-

import logging
import os

import anyconfig
import appdirs
from mbot.utils.packages import install_package

LOG = logging.getLogger(__name__)

__name__ = "mbot"
__author__ = "Michael Kuty"

DATA_PATH = appdirs.user_data_dir(__name__, __author__)
CONFIG_PATH = appdirs.user_config_dir(__name__, __author__)

CONFIG_FORMAT = "yaml"

DEFAULT_CONFIG = """
core:
  data_path: {data_path}
  config_path: {config_path}
  backends:
    - slack

slack:
  token: {slack_token}
  engine: mbot.backends.slack.Slack
  middlewares:
    - mbot.contrib.system.Config
Beispiel #45
0
import os
import pathlib
from time import strftime
from appdirs import user_config_dir, user_log_dir, user_data_dir

APPNAME = 'UniverseBot'

LOG_FILE = pathlib.Path(
    user_log_dir(APPNAME)) / (strftime('%Y-%m-%d') + '.log')

CONF_FILE = pathlib.Path(user_config_dir(APPNAME)) / 'config.yml'

PLUGIN_DIRS = [
    pathlib.Path(os.path.abspath(os.path.dirname(__file__))) / 'plugins',
    pathlib.Path(pathlib.Path(user_data_dir(APPNAME))) / 'plugins',
]

LOGGER_CONFIG = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'default': {
            'format':
            "[%(levelname)s] %(message)s (%(filename)s::%(funcName)s::%(lineno)d) -- %(asctime)s",
        },
        'console': {
            'format': "[%(levelname)s] %(message)s",
        },
        'default-backend': {
            'format':
            "[BACKEND] [%(levelname)s] %(message)s (%(filename)s::%(funcName)s::%(lineno)d) -- %(asctime)s",
Beispiel #46
0
def get_config_dir():
    config_dir = user_config_dir(appname=_DIR_APP_NAME)
    os.makedirs(config_dir, exist_ok=True)
    return config_dir
Beispiel #47
0
import pathlib

import sys, os
import virtualenv
from appdirs import user_config_dir, site_config_dir, user_cache_dir
import subprocess
import platform

op_sys = platform.system()
if op_sys == 'Darwin':  # User config dir incompatible with venv on darwin (space in path name conflicts)
    user_venv_dir = os.path.join(user_cache_dir(appname='xicam'), 'venvs')
else:
    user_venv_dir = os.path.join(user_config_dir(appname='xicam'), 'venvs')
site_venv_dir = os.path.join(site_config_dir(appname='xicam'), 'venvs')

venvs = {}
observers = []

# Python 2 style execfile function
execfile = lambda filename, globals=None, locals=None: exec(
    open(filename).read(), globals, locals)

# TODO: transition to http://virtualenvwrapper.readthedocs.io/en/latest/index.html


def create_environment(name: str):
    """
    Create a new virtual environment in the user_venv_dir with name name.

    Parameters
    ----------
Beispiel #48
0
from tkinter import filedialog
from pygubu import Builder as pgBuilder

# if dist fails to start because it's missing these, uncomment these two imports
# import pygubu.builder.ttkstdwidgets
# import pygubu.builder.widgets.dialog

from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

# check to see if we're running from stand-alone one-file executable:
if hasattr(sys, '_MEIPASS'):
    CURRENT_DIR = sys._MEIPASS
else:
    CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
USER_DIR = str(plPath.home())
CONFIG_DIR = appdirs.user_config_dir(APPNAME)
DATA_DIR = appdirs.user_data_dir(APPNAME)


class UserData:
    '''Class for storing current user's application data'''
    def __init__(self):
        self.__user_data_path = os.path.join(DATA_DIR, 'data.json')
        self.__data_defaults = {
            'filedialog_path': USER_DIR,
            'number_of_processed_files': 0,
        }
        self.__user_data = self.__get_user_data()

    @property
    def filedialog_path(self):
Beispiel #49
0
 def __init__(self):
     self._cookiejar_filepath = appdirs.user_config_dir(
         'charmcraft.credentials')
     self._cookiejar = None
     self._client = None
Beispiel #50
0
import sys

import appdirs

from hat import util
from hat.util import aio
from hat.util import json
import hat.event.client
import hat.event.common
import hat.gateway.common
import hat.gateway.engine
import hat.monitor.client
import hat.monitor.common


user_conf_dir = Path(appdirs.user_config_dir('hat'))
default_conf_path = user_conf_dir / 'gateway.yaml'


def main():
    """Main"""
    aio.init_asyncio()

    args = _create_parser().parse_args()
    conf = json.decode_file(args.conf)
    json_schema_repo = json.SchemaRepository(
        hat.gateway.common.json_schema_repo,
        *args.additional_json_schemas_paths)
    json_schema_repo.validate('hat://gateway/main.yaml#', conf)
    for device_conf in conf['devices']:
        module = importlib.import_module(device_conf['module'])
Beispiel #51
0
import appdirs
import os

APP_NAME = 'satan' # Smartphone As a Token Also Nonces
APP_VERBOSE_NAME = 'S.A.T.A.N.: Smartphone As a Token. Also, Nonces!'


PASSWORD_CHECK_NAME = 'password_check'
FILES_LIST_NAME = 'files.yml'
PC_KEYS_NAME = 'rsa_key_pc.bin'
PHONE_KEYS_NAME = 'rsa_key_phone.bin'
ENCRYPTED_FILE_KEY_NAME = 'enc_file_key.bin'
DECRYPTED_FILE_KEY_NAME = 'dec_file_key.bin'


CONFIG_DIRECTORY = appdirs.user_config_dir(APP_NAME)

PASSWORD_CHECK_PATH = os.path.join(CONFIG_DIRECTORY, PASSWORD_CHECK_NAME)
FILES_LIST_PATH = os.path.join(CONFIG_DIRECTORY, FILES_LIST_NAME)
PC_KEYS_PATH = os.path.join(CONFIG_DIRECTORY, PC_KEYS_NAME)
PHONE_KEYS_PATH = os.path.join(CONFIG_DIRECTORY, PHONE_KEYS_NAME)
ENCRYPTED_FILE_KEY_PATH = os.path.join(CONFIG_DIRECTORY, ENCRYPTED_FILE_KEY_NAME)
DECRYPTED_FILE_KEY_PATH = os.path.join(CONFIG_DIRECTORY, DECRYPTED_FILE_KEY_NAME)

CONFIG_FILES = [
    PASSWORD_CHECK_PATH,
    PC_KEYS_PATH,
    PHONE_KEYS_PATH,
    ENCRYPTED_FILE_KEY_PATH,
]
Beispiel #52
0
 def getPreferencesFileName():
     from appdirs import user_config_dir
     preferences_file = os.path.join(
         user_config_dir(A2P2ClientPreferences.appname), "prefs.ini")
     return preferences_file
Beispiel #53
0
    def get_data_dir():
        '''
		Determines the path of the application's data directory.
		'''
        return appdirs.user_config_dir(APPLICATION_NAME, False, roaming=True)
Beispiel #54
0
                      rf"    \incfig{{{name}}}", rf"    \caption{{{title}}}",
                      rf"    \label{{fig:{name}}}", r"\end{figure}"))


# From https://stackoverflow.com/a/67692
def import_file(name, path):
    import importlib.util as util
    spec = util.spec_from_file_location(name, path)
    module = util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


# Load user config

user_dir = Path(user_config_dir("inkscape-figures", "Castel"))

if not user_dir.is_dir():
    user_dir.mkdir()

roots_file = user_dir / 'roots'
template = user_dir / 'template.svg'
config = user_dir / 'config.py'

if not roots_file.is_file():
    roots_file.touch()

if not template.is_file():
    source = str(Path(__file__).parent / 'template.svg')
    destination = str(template)
    copy(source, destination)
Beispiel #55
0
# Here's how it is decided upon:

# 1. Is there an environment variable KYMATIO_BACKEND_1D?
# 2. Is there an environment variable KYMATIO_BACKEND?
# 3. Is there a config file? If so, go and find the backend entry
# 4. Set the backend to DEFAULT_BACKEND

import os
import configparser
import appdirs

DEFAULT_BACKEND = "torch"

# find config file
config_file = os.path.join(appdirs.user_config_dir("kymatio"), "kymatio.cfg")
cp = configparser.ConfigParser()

if os.path.exists(config_file):
    cp.read(config_file)
    BACKEND = cp.get('general',
                     'backend_1d',
                     fallback=cp.get('general', 'backend', fallback=None))
    if BACKEND is None:
        BACKEND = DEFAULT_BACKEND
        if 'general' not in cp.sections():
            cp.add_section('general')
        cp['general']['backend_1d'] = BACKEND
        try:
            with open(config_file, "w") as f:
                cp.write(f)
Beispiel #56
0
import os
from appdirs import user_config_dir

SECTION_IDF = 'IDFs'
SECTION_APP = 'Apps'

CONFIG_DIR = user_config_dir("espy-cli")
CONFIG_FILE = os.path.join(CONFIG_DIR, 'config.json')
Beispiel #57
0
        "linestyle": ["none"],
        "padding": [0.05, 0.02, 1, 1],
    },
    # The colors for each dataset member used in table and show functions
    "colors": {
        "coords": "#dde9af",
        "data": "#ffe680",
        "labels": "#afdde9",
        "attrs": "#ff8080",
        "masks": "#cccccc",
        "hover": "#d6eaf8",
    },
    "table_max_size": 50,
}

config_directory = appdirs.user_config_dir('scipp')
config_filename = os.path.join(config_directory, 'config.yaml')


def load():
    # Create the user configuration directory if it does not exist
    if not os.path.exists(config_directory):
        os.makedirs(config_directory)

    # Save a default configuration if no user coniguration file exists
    if not os.path.exists(config_filename):
        with open(config_filename, 'w+') as f:
            f.write(yaml.dump(defaults))

    # Load user configuration
    return config.config(
Beispiel #58
0
import json
import os
from http import server
from oauthlib.oauth2 import WebApplicationClient
from requests_oauthlib import OAuth2Session
import webbrowser
from .exceptions import SavedTokenError, AuthError
from urllib.parse import urlparse, parse_qs
from appdirs import user_config_dir

TOKEN_FILE_PATH = os.path.join(user_config_dir('fit_classification'),
                               'saved_token')


def get_session_from_token(client_id, client_secret, callback_host,
                           callback_port, token_url):
    if not os.path.isfile(TOKEN_FILE_PATH):
        raise SavedTokenError('File does not exist')

    token = None

    try:
        token = load_token()

    except Exception as e:
        raise SavedTokenError(f'Error reading token from file: {e}')

    if 'access_token' not in token \
            or 'refresh_token' not in token:
        raise SavedTokenError('Invalid format: '
                              'missing some required fields - '
Beispiel #59
0
"""
Helper functions.
"""
import keyword
import gzip
import os
import re

from appdirs import user_config_dir, user_data_dir
from collections import namedtuple
from six import BytesIO, string_types, Iterator

APP_NAME = "QuiltCli"
APP_AUTHOR = "QuiltData"
BASE_DIR = user_data_dir(APP_NAME, APP_AUTHOR)
CONFIG_DIR = user_config_dir(APP_NAME, APP_AUTHOR)
PYTHON_IDENTIFIER_RE = re.compile(r'^[a-zA-Z_]\w*$')
EXTENDED_PACKAGE_RE = re.compile(
    r'^((?:\w+:)?\w+/[\w/]+)(?::h(?:ash)?:(.+)|:v(?:ersion)?:(.+)|:t(?:ag)?:(.+))?$'
)

#return type for parse_package_extended
PackageInfo = namedtuple(
    "PackageInfo", "full_name, team, user, name, subpath, hash, version, tag")


def parse_package_extended(identifier):
    """
    Parses the extended package syntax and returns a tuple of (package, hash, version, tag).
    """
    match = EXTENDED_PACKAGE_RE.match(identifier)
Beispiel #60
0
def _main(argv=None):
    if sys.version_info < (3, 5):
        print("Error: Your version of Python is too old, 3.5+ is required: %d.%d.%d" % sys.version_info[:3])
        return -1

    try:
        check_runtime_requirements()
    except RuntimeError as e:
        print("Error: %s" % (e,))
        return -1

    # Protect access token and potentially encryption keys
    block_tracing()

    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()
    userspacefs.add_cli_arguments(parser)
    parser.add_argument("-c", "--config-file",
                        help="config file path")
    parser.add_argument("-e", "--encrypted-folder",
                        dest='encrypted_folders',
                        type=parse_encrypted_folder_arg,
                        default=[], action='append',
                        help="relative paths of encrypted folders, can be used multiple times. requires safefs")
    parser.add_argument("--print-default-config-file", action='store_true',
                        help="print default config file path to standard out and quit")
    parser.add_argument("mount_point", nargs='?')
    args = parser.parse_args(argv[1:])

    try:
        version = pkg_resources.require("dbxfs")[0].version
    except Exception:
        log.warning("Failed to get version", exc_info=True)
        version = ''

    if version:
        try:
            with urllib.request.urlopen("https://pypi.org/pypi/dbxfs/json") as f:
                rversion = json.load(io.TextIOWrapper(f))['info']['version']
                if rversion != version:
                    print("\033[0;31m\033[1mWarning: dbxfs is out of date (%s vs %s), upgrade with 'pip3 install --upgrade dbxfs'\033[0;0m" %
                          (rversion, version))
        except Exception:
            log.warning("Failed to get most recent version", exc_info=True)

    config_dir = appdirs.user_config_dir(APP_NAME)

    if args.config_file is not None:
        config_file = args.config_file
    else:
        config_file = os.path.join(config_dir, "config.json")

    if args.print_default_config_file:
        print(config_file)
        return 0

    try:
        os.makedirs(config_dir, exist_ok=True)
    except OSError as e:
        print("Unable to create configuration directory: %s" % (e,))
        return -1

    config = {}
    try:
        f = open(config_file)
    except IOError as e:
        if e.errno != errno.ENOENT: raise
    else:
        try:
            with f:
                config = json.load(f)
        except ValueError as e:
            print("Config file %r is not valid json: %s" % (config_file, e))
            return -1

    mount_point = args.mount_point
    if mount_point is None:
        mount_point = config.get("mount_point")

    if not args.smb_no_mount and mount_point is None:
        parser.print_usage()
        print("%s: error: please provide the mount_point argument" % (os.path.basename(argv[0]),))
        return 1

    encrypted_folders = config.get("encrypted_folders", []) + args.encrypted_folders
    if safefs_wrap_create_fs is None and encrypted_folders:
        print("safefs not installed, can't transparently decrypt encrypted folders")
        return 1

    access_token = None
    save_access_token = False
    save_config = False

    access_token_command = config.get("access_token_command", None)
    if access_token_command is not None:
        print("Running %r for access token" % (' '.join(access_token_command),))
        try:
            access_token = subprocess.check_output(access_token_command).decode("utf-8")
        except UnicodeDecodeError:
            print("Access token command output is not utf-8 encoded")
            return -1
        except TypeError:
            print("Bad access token command: %r, " % (access_token_command,))
            return -1

    if access_token is None:
        keyring_user = config.get("keyring_user", None)

        if keyring_user is not None:
            try:
                access_token = keyring.get_password(APP_NAME, keyring_user)
            except KeyringError as e:
                print("Failed to get access token from keyring: %s" % (e,))

    if access_token is None:
        access_token_privy = config.get("access_token_privy", None)
        if access_token_privy is not None:
            passwd = None
            while True:
                passwd = getpass.getpass("Enter access token passphrase (not your Dropbox password) (Ctrl-C to quit): ")
                try:
                    access_token = privy.peek(access_token_privy, passwd).decode('utf-8')
                except ValueError:
                    if not yes_no_input("Incorrect password, create new access token?"):
                        continue
                break
            del passwd

    try_directly = False
    while True:
        if access_token is None:
            save_access_token = True

        if (access_token is None and
            try_directly and
            yes_no_input("Want to try entering the access token directly?")):
            print("Go to https://dropbox.com/developers/apps to "
                  "create an app and generate a personal access token.")

            while True:
                access_token = getpass.getpass("Enter Access token (Ctrl-C to quit): ")
                if not access_token:
                    print("Access tokens cannot be empty")
                    continue
                break

        if access_token is None:
            auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
            authorize_url = auth_flow.start()
            print("We need an access token. Perform the following steps:")
            print("1. Go to " + authorize_url)
            print("2. Click \"Allow\" (you may have to log in first)")
            print("3. Copy the authorization code.")

            while True:
                auth_code = input("Enter authorization code (Ctrl-C to quit): ")
                if not auth_code:
                    print("Authorization code cannot be empty")
                    continue
                break

            try:
                oauth_result = auth_flow.finish(auth_code)
            except Exception as e:
                print("Authorization code was invalid!")
                try_directly = True
                continue

            access_token = oauth_result.access_token

        # test out access token
        try:
            dropbox.Dropbox(access_token).users_get_current_account()
        except (dropbox.exceptions.BadInputError,
                dropbox.exceptions.AuthError,
                ValueError) as e:
            print("Error using access token: %s" % (e,))
            access_token = None
            try_directly = True
        except OSError:
            if not yes_no_input("Error connecting to Dropbox, Try again?"):
                return 1
        else:
            break

    if save_access_token and yes_no_input("We're all connected. Do you want to save your credentials for future runs?", default_yes=True):
        keyring_user = ''.join([random.choice("asdfghjklzxcvbnmqwertyuiop")
                                for _ in range(24)])
        try:
            keyring.set_password(APP_NAME, keyring_user, access_token)
        except (KeyringError, RuntimeError) as e:
            print("We need a passphrase to encrypt your access token before we can save it.")
            print("Warning: Your access token passphrase must contain enough randomness to be resistent to hacking. You can read this for more info: https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/")
            while True:
                pass_ = getpass.getpass("Enter new access token passphrase: ")
                pass2_ = getpass.getpass("Enter new access token passphrase (again): ")
                if pass_ != pass2_:
                    print("Passphrases didn't match, please re-enter")
                else:
                    del pass2_
                    break
            config.pop('keyring_user', None)
            config['access_token_privy'] = privy.hide(access_token.encode('utf-8'), pass_, server=False)
            del pass_
            save_config = True
        else:
            config.pop('access_token_privy', None)
            config['keyring_user'] = keyring_user
            save_config = True

    if not config.get("asked_send_error_reports", False):
        if yes_no_input("Would you like to help us improve %s by providing anonymous error reports?" % (APP_NAME,), default_yes=True):
            config['send_error_reports'] = True
        config['asked_send_error_reports'] = True
        save_config = True

    if save_access_token and yes_no_input("Do you want \"%s\" to be the default mount point?" % (mount_point,), default_yes=True):
        config['mount_point'] = mount_point
        save_config = True

    if save_config:
        with open(config_file, "w") as f:
            json.dump(config, f)

    log.info("Starting %s...", APP_NAME)

    if config.get('send_error_reports', False):
        try:
            sentry_sdk.init("https://[email protected]/1293235",
                            release='%s@%s' % (APP_NAME, version),
                            with_locals=False)
        except Exception:
            log.warning("Failed to initialize sentry", exc_info=True)

    cache_folder = os.path.join(appdirs.user_cache_dir(APP_NAME), "file_cache")
    try:
        os.makedirs(cache_folder, exist_ok=True)
    except OSError:
        log.warning("Failed to create cache folder, running without file cache")
        cache_folder = None

    def create_fs():
        fs = CachingFileSystem(DropboxFileSystem(access_token), cache_folder=cache_folder)

        # From a purity standpoint the following layer ideally would
        # go between the caching fs and dropbox fs, but because the
        # contract between those two is highly specialized, just put
        # it on top
        fs = TranslateIgnoredFilesFileSystem(fs)

        if sys.platform == 'darwin':
            fs = DisableQuickLookFileSystem(fs)

        return fs

    if safefs_wrap_create_fs is not None:
        create_fs = safefs_wrap_create_fs(create_fs, encrypted_folders)

    if not os.path.exists(mount_point):
        if yes_no_input("Mount point \"%s\" doesn't exist, do you want to create it?" % (mount_point,), default_yes=True):
            try:
                os.makedirs(mount_point, exist_ok=True)
            except OSError as e:
                print("Unable to create mount point: %s" % (e,))
                return -1

    return userspacefs.simple_main(mount_point, "dbxfs", create_fs, args,
                                   on_new_process=None if BLOCK_TRACING_INHERITS else block_tracing)