예제 #1
0
def clearenv(key, dotenv_path=None):  # pragma: no cover
    if dotenv_path is None:
        dotenv_path = Path('.env').resolve()
    opts = ctx_opts()
    if opts.dry_run or opts.verbose:
        click.secho(f'{const.LOG_ENV} unset {key}', fg='magenta', color=opts.color)
    if not opts.dry_run:
        dotenv.unset_key(dotenv_path, key, quote_mode='never')
예제 #2
0
def test_unset():
    sh.touch(dotenv_path)
    success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD')
    stored_value = dotenv.get_key(dotenv_path, 'HELLO')
    assert stored_value == 'WORLD'
    success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO')
    assert dotenv.get_key(dotenv_path, 'HELLO') is None
    sh.rm(dotenv_path)
    success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO')
    assert success is None
예제 #3
0
def test_unset():
    sh.touch(dotenv_path)
    success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD')
    stored_value = dotenv.get_key(dotenv_path, 'HELLO')
    assert stored_value == 'WORLD'
    success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO')
    assert dotenv.get_key(dotenv_path, 'HELLO') is None
    sh.rm(dotenv_path)
    success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO')
    assert success is None
예제 #4
0
    def write_to_dotenv(self):
        "Write the current values of self to the dotenv file"
        # Current status of the dotenv file
        dotenv_values = self.current_dotenv_values

        # Remove the keys that are not in the self
        for k in set(dotenv_values) - set(super().keys()):
            dotenv.unset_key(self.dotenv, k)

        # Update the values from self
        for k in super().keys():
            dotenv.set_key(self.dotenv, k, self[k])
예제 #5
0
 def take_action(self, parsed_args):
     super(SettingsUnset, self).take_action(parsed_args)
     self.validate_identifier(parsed_args.identifier, allow_private=False)
     env_file = settings.config.find_config()
     setting_name = parsed_args.identifier
     unset_key(env_file, setting_name)
     headers = [setting_name]
     records = [
         'Run "tapis settings get {0}" to see current value'.format(
             setting_name)
     ]
     return (tuple(headers), tuple(records))
예제 #6
0
    def delete_from_env_file(self) -> "EnvironmentVariableHelper":
        """
        Deletes the given environment file from the given dotenv file.

        .. warning::
            This method also delete the environment variable from the current
            environment.
        """

        self.delete()

        dotenv.unset_key(self.env_file_path, self.name)

        return self
예제 #7
0
    def unset(self, name: str, path: List[str], setting_def=None):
        if not setting_def:
            raise StoreNotSupportedError

        env_vars = self.setting_env_vars(setting_def)
        env_keys = [var.key for var in env_vars]

        with self.update_dotenv() as dotenv_file:
            if not dotenv_file.exists():
                return {}

            for key in env_keys:
                dotenv.unset_key(dotenv_file, key)
                self.log(f"Unset key '{key}' in `.env`")

        return {}
예제 #8
0
def auth_spotify():
    """Authenticate access to Spotify user information

    Returns:
        user_id: str
            A string that represents the Spotify ID for the user
    """
    # If REFRESH_TOKEN exists, user wanted to be remembered from last session, so refresh access token
    print('Recognizing Spotify user...')
    if REFRESH_TOKEN:
        print('User is recognized. Refreshing Spotify access token...')
        token = refresh_token()
    else:
        print('User is unrecognized. Requesting Spotify authorization code...')
        token = request_token()

    global access_token
    access_token = token['access_token']

    # Ask user if they would like to be remembered for next session
    print_hdiv()
    while True:
        remember_me = input(
            'Would you like your Spotify access information to be remembered next session (y/n)? '
        )
        # If yes, save the refresh token to environment variables
        if remember_me.lower() == 'y':
            try:
                print("We'll remember you next time! ;)")
                set_key(find_dotenv(), 'REFRESH_TOKEN', token['refresh_token'])
            except KeyError:
                pass
            break
        # If no, make sure refresh token is unset in environment variables
        elif remember_me.lower() == 'n':
            print('Erasing you from memory...bye! :(')
            unset_key(find_dotenv(), 'REFRESH_TOKEN')
            break
        else:
            pass
    print_hdiv()

    user_object = requests.get('https://api.spotify.com/v1/me',
                               headers={
                                   'Authorization': 'Bearer ' + access_token
                               }).json()
    return user_object['id']
예제 #9
0
def test_unset_ok(dotenv_file):
    with open(dotenv_file, "w") as f:
        f.write("a=b\nc=d")

    success, key_to_unset = dotenv.unset_key(dotenv_file, "a")

    assert success is True
    assert key_to_unset == "a"
    with open(dotenv_file, "r") as f:
        assert f.read() == "c=d"
예제 #10
0
def test_unset_ok(dotenv_file):
    with open(dotenv_file, "w") as f:
        f.write("a=b\nc=d")

    success, key_to_unset = dotenv.unset_key(dotenv_file, "a")

    assert success is True
    assert key_to_unset == "a"
    with open(dotenv_file, "r") as f:
        assert f.read() == "c=d"
예제 #11
0
def test_unset_no_value(dotenv_file):
    logger = logging.getLogger("dotenv.main")
    with open(dotenv_file, "w") as f:
        f.write("foo")

    with mock.patch.object(logger, "warning") as mock_warning:
        result = dotenv.unset_key(dotenv_file, "foo")

    assert result == (True, "foo")
    with open(dotenv_file, "r") as f:
        assert f.read() == ""
    mock_warning.assert_not_called()
예제 #12
0
def test_unset_non_existent_file(tmp_path):
    nx_file = str(tmp_path / "nx")
    logger = logging.getLogger("dotenv.main")

    with mock.patch.object(logger, "warning") as mock_warning:
        result = dotenv.unset_key(nx_file, "foo")

    assert result == (None, "foo")
    mock_warning.assert_called_once_with(
        "Can't delete from %s - it doesn't exist.",
        nx_file,
    )
예제 #13
0
    def set(self, name: str, path: List[str], value, setting_def=None):
        if not setting_def:
            raise StoreNotSupportedError

        primary_var, *other_vars = self.setting_env_vars(setting_def)
        primary_key = primary_var.key
        other_keys = [var.key for var in other_vars]

        with self.update_dotenv() as dotenv_file:
            if dotenv_file.exists():
                for key in other_keys:
                    dotenv.unset_key(dotenv_file, key)
                    self.log(f"Unset key '{key}' in `.env`")
            else:
                dotenv_file.touch()

            dotenv.set_key(dotenv_file, primary_key,
                           setting_def.stringify_value(value))

        self.log(f"Set key '{primary_key}' in `.env`: {value!r}")
        return {"env_var": primary_key}
예제 #14
0
async def delvar_(message: Message) -> None:
    """ del var """
    heroku = True
    if not Config.HEROKU_APP:
        heroku = False
        if os.path.exists("config.env"):
            pass
        else:
            await message.err(
                "`Heroku app and config.env both not detected...`")
            return
    if not message.input_str:
        await message.err("`Input not found...`")
        return
    var_key = message.input_str
    var_key = var_key.strip()
    if heroku:
        heroku_vars = Config.HEROKU_APP.config()
        if var_key in heroku_vars:
            await CHANNEL.log(f"#HEROKU_VAR #DELETED\n\n`{var_key}`")
            await message.edit(
                f"`Var {var_key} deleted and forwarded to log channel...`",
                del_in=3)
        else:
            await message.edit(f"`Var {var_key} doesn't exist...`", del_in=3)
            return
        del heroku_vars[var_key]
    else:
        file = "config.env"
        get = get_key(file, var_key)
        if get is not None:
            await message.edit(
                f"Var {var_key} deleted and forwarded to log channel...",
                del_in=3)
            await CHANNEL.log(f"#CONFIG_VAR #DELETED\n\n`{var_key}`")
        else:
            await message.edit(f"`Var {var_key} doesn't exist...`", del_in=3)
            return
        unset_key(file, var_key)
        load_dotenv(file, override=True)
예제 #15
0
def decrypt_env(env_path, password='', keyfile=''):
    """Decrypt a .env file.

    Args:
        env_path (string): Path to the .env file to load.
        password (string): Password used to encrypt the .env file.
        keyfile (string): File used to encrypt the .env file.

    Example:
        >>> import os
        >>> from env_crypt import decrypt_env
        >>> decrypt_env('test.env', password='******')
    """
    salt = dotenv.get_key(env_path, 'salt')
    dotenv.unset_key(env_path, 'salt')
    enc_key, _ = get_enc_key(password, keyfile, salt=salt)

    values = dotenv.main.dotenv_values(env_path)
    for key, value in values.items():
        dec_value = decrypt_string(value, enc_key)
        dotenv.set_key(env_path, key, dec_value)
    return
예제 #16
0
def test_unset_non_existing_file():
    success, key_to_unset = dotenv.unset_key('/non-existing', 'HELLO')

    assert success is None
예제 #17
0
 def test_unset_var(self):
     unset_key(self.dotenv_file, self.env_var)
     result = self.get_env_var_from_subprocess()
     self.assertEqual(result, None)
def set(key, value):
    if os.getenv(key):
        unset_key(str(env_path), key)
    set_key(str(env_path), key, value)
예제 #19
0
def unset_local_env(key: str):
    if key in environ:
        del environ[key]
    return unset_key(PurePath('config.env'), key)
예제 #20
0
def test_unset_non_existing_file():
    success, key_to_unset = dotenv.unset_key('/non-existing', 'HELLO')

    assert success is None
env_path = find_dotenv()
load_dotenv(env_path)

def set_variable(env_name, value):
    set_key(env_path, f"export {env_name.upper()}", str(value))
    print(f"Environment Variable set\n{env_name.upper()}={str(value)}\n at {env_path}")


while True:
    option = input("\n[1] Change environment config (Prod, Dev) or \n[2] Add custom environment varibale\n")
    if option == str(1):
        while True:
            value = input(f"\nWhat config to select?\n[1] Development\n[2] Production\n")
            print(dotenv_values())
            if value == str(1):
                unset_key(env_path, f"APP_SETTINGS")
                set_variable("APP_SETTINGS", "config.DevelopmentConfig")
                break
            elif value == str(2):
                unset_key(env_path, f"APP_SETTINGS")
                set_variable("APP_SETTINGS", "config.ProductionConfig")
                break
            else:
                print("Invalid choice, try 1 or 2")
        break
    elif option == str(2):
        env_name = input("What is the name of your environment variable?\n")
        value = input(f"\nWhat is the value to set for {env_name}\n")
        unset_key(env_path, env_name)
        set_variable(env_name, value)
        break