Python click.get_app_dir() Examples

The following are 26 code examples of click.get_app_dir(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: __main__.py    From mocktailsmixer with MIT License 6 votes vote down vote up
def setup_assistant():

    # Load credentials.
    try:
      credentials = os.path.join(
          click.get_app_dir(common_settings.ASSISTANT_APP_NAME),
          common_settings.ASSISTANT_CREDENTIALS_FILENAME
      )
      global creds
      creds = auth_helpers.load_credentials(credentials, scopes=[common_settings.ASSISTANT_OAUTH_SCOPE, common_settings.PUBSUB_OAUTH_SCOPE])
    except Exception as e:
      logging.error('Error loading credentials: %s', e)
      logging.error('Run auth_helpers to initialize new OAuth2 credentials.')
      return -1

    # Create gRPC channel
    grpc_channel = auth_helpers.create_grpc_channel(ASSISTANT_API_ENDPOINT, creds)
    logging.info('Connecting to %s', ASSISTANT_API_ENDPOINT)

    # Create Google Assistant API gRPC client.
    global assistant
    assistant = embedded_assistant_pb2.EmbeddedAssistantStub(grpc_channel)
    return 0 
Example #2
Source File: kraken.py    From kraken with Apache License 2.0 6 votes vote down vote up
def get(ctx, model_id):
    """
    Retrieves a model from the repository.
    """
    from kraken import repo

    try:
        os.makedirs(click.get_app_dir(APP_NAME))
    except OSError:
        pass

    message('Retrieving model ', nl=False)
    filename = repo.get_model(model_id, click.get_app_dir(APP_NAME),
                              partial(message, '.', nl=False))
    message('\b\u2713', fg='green', nl=False)
    message('\033[?25h')
    message(f'Model name: {filename}')
    ctx.exit(0) 
Example #3
Source File: common.py    From zotero-cli with MIT License 5 votes vote down vote up
def _get_config_path():
    return os.path.join(click.get_app_dir(APP_NAME), 'config.ini') 
Example #4
Source File: nixpkgs_repo.py    From nox with MIT License 5 votes vote down vote up
def __init__(self):
        nox_dir = Path(click.get_app_dir('nox', force_posix=True))
        if not nox_dir.exists():
            nox_dir.mkdir()

        nixpkgs = nox_dir / 'nixpkgs'
        self.path = str(nixpkgs)

        if not nixpkgs.exists():
            click.echo('==> Creating nixpkgs repo in {}'.format(nixpkgs))
            self.git(['init', '--quiet', self.path], cwd=False)
            self.git('remote add origin https://github.com/NixOS/nixpkgs.git')
            self.git('config user.email nox@example.com')
            self.git('config user.name nox')

        if (Path.cwd() / '.git').exists():
            git_version = self.git('version', output=True).strip()
            if git_version >= 'git version 2':
                click.echo("==> We're in a git repo, trying to fetch it")

                self.git(['fetch', str(Path.cwd()), '--update-shallow', '--quiet'])
            else:
                click.echo("==> Old version of git detected ({}, maybe on travis),"
                " not trying to fetch from local, fetch 50 commits from master"
                " instead".format(git_version))
                self.git('fetch origin master --depth 50') 
Example #5
Source File: __init__.py    From EasyStorj with MIT License 5 votes vote down vote up
def setup_logging():
    """Reads the Storj GUI logging configuration from logging.conf.
    If the file does not exist it will load a default configuration.

    Mac OS X (POSIX):
        ~/.storj-gui
    Unix (POSIX):
        ~/.storj-gui
    Win XP (not roaming):
        ``C:\Documents and Settings\<user>\Application Data\storj-gui``
    Win 7 (not roaming):
        ``C:\\Users\<user>\AppData\Local\storj-gui``
    """

    logging_conf = os.path.join(
        click.get_app_dir(APP_NAME, force_posix=True),
        'logging.conf')

    if not os.path.exists(logging_conf) or not os.path.isfile(logging_conf):
        load_default_logging()
        logging.getLogger(__name__).warning('%s logging configuration file does not exist', logging_conf)
        return

    try:
        config.fileConfig(logging_conf, disable_existing_loggers=False)
        logging.getLogger(__name__).info('%s configuration file was loaded.', logging_conf)

    except RuntimeError:
        load_default_logging()
        logging.getLogger(__name__).warning('failed to load configuration from %s', logging_conf)
        return

    logging.getLogger(__name__).info('using logging configuration from %s', logging_conf) 
Example #6
Source File: temci_completion.py    From temci with GNU General Public License v3.0 5 votes vote down vote up
def completion_dir() -> str:
    """ Get the name of the completion directory """
    return click.get_app_dir("temci") 
Example #7
Source File: settings.py    From temci with GNU General Public License v3.0 5 votes vote down vote up
def load_from_config_dir(self):
        """
        Load the config file from the application directory (e.g. in the users home folder) if it exists.
        """
        conf = os.path.join(click.get_app_dir("temci"), "config.yaml")
        if os.path.exists(conf) and os.path.isfile(conf):
            self.load_file(conf) 
Example #8
Source File: cli.py    From mygeotab-python with Apache License 2.0 5 votes vote down vote up
def _get_config_file():
        config_path = click.get_app_dir(mygeotab.__title__)
        if not os.path.exists(config_path):
            os.makedirs(config_path)
        return os.path.join(config_path, "config.ini") 
Example #9
Source File: util.py    From q2cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cache_dir():
    import os.path
    return os.path.join(get_app_dir(), 'cache') 
Example #10
Source File: util.py    From q2cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_app_dir():
    import os
    conda_prefix = os.environ.get('CONDA_PREFIX')
    if conda_prefix is not None and os.access(conda_prefix, os.W_OK | os.X_OK):
        return os.path.join(conda_prefix, 'var', 'q2cli')
    else:
        import click
        return click.get_app_dir('q2cli', roaming=False)


# NOTE: `get_cache_dir` and `get_completion_path` live here instead of
# `q2cli.cache` because `q2cli.cache` can be  slow to import.
# `get_completion_path` (which relies on `get_cache_dir`) is imported and
# executed by the Bash completion function each time the user hits <tab>, so it
# must be quick to import. 
Example #11
Source File: configuration.py    From storj-python-sdk with MIT License 5 votes vote down vote up
def read_config():
    """Reads configuration storj client configuration.

    Mac OS X (POSIX):
        ~/.foo-bar
    Unix (POSIX):
        ~/.foo-bar
    Win XP (not roaming):
        ``C:\Documents and Settings\<user>\Application Data\storj``
    Win 7 (not roaming):
        ``C:\\Users\<user>\AppData\Local\storj``

    Returns:
        (tuple[str, str]): storj account credentials (email, password).
    """

    # OSX: /Users/<username>/.storj
    cfg = os.path.join(
        click.get_app_dir(
            APP_NAME,
            force_posix=True),
        'storj.ini')

    parser = RawConfigParser()
    parser.read([cfg])

    return parser.get(APP_NAME, CFG_EMAIL), parser.get(APP_NAME, CFG_PASSWORD) 
Example #12
Source File: framework.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self._config_dir = click.get_app_dir('canari', False, True)
        self._config_file = os.path.join(self.config_dir, 'canari.conf')
        self._config = None
        self._project = None
        self._working_dir = None 
Example #13
Source File: backend.py    From zotero-cli with MIT License 5 votes vote down vote up
def __init__(self, api_key=None, library_id=None, library_type='user',
                 autosync=False):
        """ Service class for communicating with the Zotero API.

        This is mainly a thin wrapper around :py:class:`pyzotero.zotero.Zotero`
        that handles things like transparent HTML<->[edit-formt] conversion.

        :param api_key:     API key for the Zotero API, will be loaded from
                            the configuration if not specified
        :param library_id:  Zotero library ID the API key is valid for, will
                            be loaded from the configuration if not specified
        :param library_type: Type of the library, can be 'user' or 'group'
        """
        self._logger = logging.getLogger()
        idx_path = os.path.join(click.get_app_dir(APP_NAME), 'index.sqlite')
        self.config = load_config()
        self.note_format = self.config['zotcli.note_format']
        self.storage_dir = self.config.get('zotcli.storage_dir')

        api_key = api_key or self.config.get('zotcli.api_key')
        library_id = library_id or self.config.get('zotcli.library_id')

        if not api_key or not library_id:
            raise ValueError(
                "Please set your API key and library ID by running "
                "`zotcli configure` or pass them as command-line options.")
        self._zot = Zotero(library_id=library_id, api_key=api_key,
                           library_type=library_type)
        self._index = SearchIndex(idx_path)
        sync_interval = self.config.get('zotcli.sync_interval', 300)
        since_last_sync = int(time.time()) - self._index.last_modified
        if autosync and since_last_sync >= int(sync_interval):
            click.echo("{} seconds since last sync, synchronizing."
                       .format(since_last_sync))
            num_updated = self.synchronize()
            click.echo("Updated {} items".format(num_updated)) 
Example #14
Source File: config.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def _get_global_config_dir():
    """Return user's config directory."""
    return click.get_app_dir(APP_NAME, force_posix=True) 
Example #15
Source File: test_main_cli.py    From onedrived-dev with MIT License 5 votes vote down vote up
def setUp(self):
        self.tempdir = tempfile.TemporaryDirectory()
        click.get_app_dir = lambda x: self.tempdir.name + '/' + x
        od_main.context = od_main.load_context()
        od_main.context._create_config_dir_if_missing() 
Example #16
Source File: test_pref_cli.py    From onedrived-dev with MIT License 5 votes vote down vote up
def setUp(self):
        self.tempdir = tempfile.TemporaryDirectory()
        click.get_app_dir = lambda x: self.tempdir.name + '/' + x
        od_pref.context = od_pref.load_context()
        od_pref.context._create_config_dir_if_missing() 
Example #17
Source File: od_context.py    From onedrived-dev with MIT License 5 votes vote down vote up
def __init__(self, loop):
        """
        :param asyncio.AbstractEventLoop | None loop:
        """
        # Information about host and user.
        self.host_name = os.uname()[1]
        self.user_name = get_login_username()
        self.user_uid = getpwnam(self.user_name).pw_uid
        self.user_home = os.path.expanduser('~' + self.user_name)
        self.config_dir = click.get_app_dir('onedrived')
        self._create_config_dir_if_missing()
        self.config = self.DEFAULT_CONFIG
        self.loop = loop
        self._watcher = None 
Example #18
Source File: __init__.py    From pros-cli2 with Mozilla Public License 2.0 5 votes vote down vote up
def get_template_dir(depot, identifier):
    if isinstance(depot, DepotConfig):
        depot = depot.name
    elif isinstance(depot, DepotProvider):
        depot = depot.config.name
    elif not isinstance(depot, str):
        raise ValueError('Depot must a str, DepotConfig, or DepotProvider')
    assert isinstance(depot, str)
    return os.path.join(click.get_app_dir('PROS'), depot, '{}-{}'.format(identifier.name, identifier.version)) 
Example #19
Source File: __init__.py    From pros-cli2 with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self,
                 file=None, name=None, registrar=None, location=None,
                 registrar_options=None,
                 types=None,
                 root_dir=None):
        self.name = name  # type: str
        self.registrar = registrar  # type: str
        self.location = location  # type: str
        self.types = types if types is not None else []  # type: List[TemplateTypes]
        self.registrar_options = registrar_options if registrar_options is not None else dict()  # type: Dict[str, str]
        if not file:
            file = os.path.join((root_dir if root_dir is not None else click.get_app_dir('PROS')), name, 'depot.pros')
        super(DepotConfig, self).__init__(file) 
Example #20
Source File: cliconfig.py    From pros-cli2 with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, file=None, ctx=None):
        if not file:
            file = os.path.join(click.get_app_dir('PROS'), 'cli.pros')
        self.default_libraries = []  # type: list(str)
        self.providers = []
        self.applyDefaultProviders()
        super(CliConfig, self).__init__(file, ctx=ctx) 
Example #21
Source File: selescrape.py    From anime-downloader with The Unlicense 5 votes vote down vote up
def get_data_dir():
    '''
    Gets the folder directory selescrape will store data, 
    such as cookies or browser extensions and logs.
    '''
    APP_NAME = 'anime downloader'
    return os.path.join(click.get_app_dir(APP_NAME), 'data') 
Example #22
Source File: test_watson.py    From Watson with MIT License 5 votes vote down vote up
def test_empty_config_dir():
    watson = Watson()
    assert watson._dir == get_app_dir('watson') 
Example #23
Source File: watson.py    From Watson with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        """
        :param frames: If given, should be a list representing the
                        frames.
                        If not given, the value is extracted
                        from the frames file.
        :type frames: list

        :param current: If given, should be a dict representing the
                        current frame.
                        If not given, the value is extracted
                        from the state file.
        :type current: dict

        :param config_dir: If given, the directory where the configuration
                           files will be
        """
        self._current = None
        self._old_state = None
        self._frames = None
        self._last_sync = None
        self._config = None
        self._config_changed = False

        self._dir = (kwargs.pop('config_dir', None) or
                     click.get_app_dir('watson'))

        self.config_file = os.path.join(self._dir, 'config')
        self.frames_file = os.path.join(self._dir, 'frames')
        self.state_file = os.path.join(self._dir, 'state')
        self.last_sync_file = os.path.join(self._dir, 'last_sync')

        if 'frames' in kwargs:
            self.frames = kwargs['frames']

        if 'current' in kwargs:
            self.current = kwargs['current']

        if 'last_sync' in kwargs:
            self.last_sync = kwargs['last_sync'] 
Example #24
Source File: assistant.py    From google-assistant-hotword-raspi with MIT License 4 votes vote down vote up
def __init__(self):
        self.api_endpoint = ASSISTANT_API_ENDPOINT
        self.credentials = os.path.join(click.get_app_dir('google-oauthlib-tool'),
                                   'credentials.json')
        # Setup logging.
        logging.basicConfig() # filename='assistant.log', level=logging.DEBUG if self.verbose else logging.INFO)
        self.logger = logging.getLogger("assistant")
        self.logger.setLevel(logging.DEBUG)

        # Load OAuth 2.0 credentials.
        try:
            with open(self.credentials, 'r') as f:
                self.credentials = google.oauth2.credentials.Credentials(token=None,
                                                                    **json.load(f))
                self.http_request = google.auth.transport.requests.Request()
                self.credentials.refresh(self.http_request)
        except Exception as e:
            logging.error('Error loading credentials: %s', e)
            logging.error('Run google-oauthlib-tool to initialize '
                          'new OAuth 2.0 credentials.')
            return

        # Create an authorized gRPC channel.
        self.grpc_channel = google.auth.transport.grpc.secure_authorized_channel(
            self.credentials, self.http_request, self.api_endpoint)
        logging.info('Connecting to %s', self.api_endpoint)
        
        self.audio_sample_rate = audio_helpers.DEFAULT_AUDIO_SAMPLE_RATE
        self.audio_sample_width = audio_helpers.DEFAULT_AUDIO_SAMPLE_WIDTH
        self.audio_iter_size = audio_helpers.DEFAULT_AUDIO_ITER_SIZE
        self.audio_block_size = audio_helpers.DEFAULT_AUDIO_DEVICE_BLOCK_SIZE
        self.audio_flush_size = audio_helpers.DEFAULT_AUDIO_DEVICE_FLUSH_SIZE
        self.grpc_deadline = DEFAULT_GRPC_DEADLINE

        # Create Google Assistant API gRPC client.
        self.assistant = embedded_assistant_pb2.EmbeddedAssistantStub(self.grpc_channel)

        # Stores an opaque blob provided in ConverseResponse that,
        # when provided in a follow-up ConverseRequest,
        # gives the Assistant a context marker within the current state
        # of the multi-Converse()-RPC "conversation".
        # This value, along with MicrophoneMode, supports a more natural
        # "conversation" with the Assistant.
        self.conversation_state_bytes = None

        # Stores the current volument percentage.
        # Note: No volume change is currently implemented in this sample
        self.volume_percentage = 50 
Example #25
Source File: kraken.py    From kraken with Apache License 2.0 4 votes vote down vote up
def ocr(ctx, model, pad, reorder, no_segmentation, serializer, text_direction, threads):
    """
    Recognizes text in line images.
    """
    from kraken.lib import models

    if ctx.meta['input_format_type'] != 'image' and no_segmentation:
        raise click.BadParameter('no_segmentation mode is incompatible with page/alto inputs')

    # first we try to find the model in the absolue path, then ~/.kraken, then
    # LEGACY_MODEL_DIR
    nm = {}  # type: Dict[str, models.TorchSeqRecognizer]
    ign_scripts = model.pop('ignore')
    for k, v in model.items():
        search = [v,
                  os.path.join(click.get_app_dir(APP_NAME), v),
                  os.path.join(LEGACY_MODEL_DIR, v)]
        location = None
        for loc in search:
            if os.path.isfile(loc):
                location = loc
                break
        if not location:
            raise click.BadParameter(f'No model for {k} found')
        message(f'Loading ANN {k}\t', nl=False)
        try:
            rnn = models.load_any(location, device=ctx.meta['device'])
            nm[k] = rnn
        except Exception:
            message('\u2717', fg='red')
            ctx.exit(1)
        message('\u2713', fg='green')

    if 'default' in nm:
        from collections import defaultdict

        nn = defaultdict(lambda: nm['default'])  # type: Dict[str, models.TorchSeqRecognizer]
        nn.update(nm)
        nm = nn
    # thread count is global so setting it once is sufficient
    nm[k].nn.set_num_threads(threads)

    # set output mode
    ctx.meta['mode'] = serializer
    ctx.meta['text_direction'] = text_direction
    return partial(recognizer,
                   model=nm,
                   pad=pad,
                   no_segmentation=no_segmentation,
                   bidi_reordering=reorder,
                   script_ignore=ign_scripts) 
Example #26
Source File: cli.py    From mapbox-cli-py with MIT License 4 votes vote down vote up
def main_group(ctx, verbose, quiet, access_token, config):
    """This is the command line interface to Mapbox web services.

    Mapbox web services require an access token. Your token is shown
    on the https://www.mapbox.com/studio/account/tokens/ page when you are
    logged in. The token can be provided on the command line

      $ mapbox --access-token MY_TOKEN ...

    as an environment variable named MAPBOX_ACCESS_TOKEN (higher
    precedence) or MapboxAccessToken (lower precedence).

    \b
      $ export MAPBOX_ACCESS_TOKEN=MY_TOKEN
      $ mapbox ...

    or in a config file

    \b
      ; configuration file mapbox.ini
      [mapbox]
      access-token = MY_TOKEN

    The OS-dependent default config file path is something like

    \b
      ~/Library/Application Support/mapbox/mapbox.ini
      ~/.config/mapbox/mapbox.ini
      ~/.mapbox/mapbox.ini

    """
    ctx.obj = {}
    config = config or os.path.join(click.get_app_dir('mapbox'), 'mapbox.ini')
    cfg = read_config(config)
    if cfg:
        ctx.obj['config_file'] = config
    ctx.obj['cfg'] = cfg
    ctx.default_map = cfg

    verbosity = (os.environ.get('MAPBOX_VERBOSE') or
                 ctx.lookup_default('mapbox.verbosity') or 0)
    if verbose or quiet:
        verbosity = verbose - quiet
    verbosity = int(verbosity)
    configure_logging(verbosity)

    access_token = (access_token or os.environ.get('MAPBOX_ACCESS_TOKEN') or
                    os.environ.get('MapboxAccessToken') or
                    ctx.lookup_default('mapbox.access-token'))

    ctx.obj['verbosity'] = verbosity
    ctx.obj['access_token'] = access_token


# mapbox commands are added here.