|
1 | 1 | from __future__ import print_function |
2 | 2 | from .main import load_dotenv, find_dotenv |
3 | 3 |
|
| 4 | +from IPython.core.magic import Magics, magics_class, line_magic |
| 5 | +from IPython.core.magic_arguments import (argument, magic_arguments, |
| 6 | + parse_argstring) |
4 | 7 |
|
5 | | -def _magic(dotenv_path): |
6 | | - """ |
7 | | - dotenv [dotenv_path] |
8 | 8 |
|
9 | | - Search in increasingly higher folders for the `dotenv_path` |
10 | | - """ |
11 | | - # Locate the .env file |
12 | | - dotenv_path = dotenv_path or '.env' |
13 | | - try: |
14 | | - dotenv_path = find_dotenv(dotenv_path, True, True) |
15 | | - except IOError: |
16 | | - print("cannot find .env file") |
17 | | - return |
| 9 | +@magics_class |
| 10 | +class IPythonDotEnv(Magics): |
18 | 11 |
|
19 | | - # Load the .env file |
20 | | - load_dotenv(dotenv_path) |
| 12 | + @magic_arguments() |
| 13 | + @argument( |
| 14 | + '-o', '--override', action='store_true', |
| 15 | + help="Indicate to override existing variables" |
| 16 | + ) |
| 17 | + @argument( |
| 18 | + '-v', '--verbose', action='store_true', |
| 19 | + help="Indicate function calls to be verbose" |
| 20 | + ) |
| 21 | + @argument('dotenv_path', nargs='?', type=str, default='.env', |
| 22 | + help='Search in increasingly higher folders for the `dotenv_path`') |
| 23 | + @line_magic |
| 24 | + def dotenv(self, line): |
| 25 | + args = parse_argstring(self.dotenv, line) |
| 26 | + # Locate the .env file |
| 27 | + dotenv_path = args.dotenv_path |
| 28 | + try: |
| 29 | + dotenv_path = find_dotenv(dotenv_path, True, True) |
| 30 | + except IOError: |
| 31 | + print("cannot find .env file") |
| 32 | + return |
| 33 | + |
| 34 | + # Load the .env file |
| 35 | + load_dotenv(dotenv_path, verbose=args.verbose, override=args.override) |
21 | 36 |
|
22 | 37 |
|
23 | 38 | def load_ipython_extension(ipython): |
24 | 39 | """Register the %dotenv magic.""" |
25 | | - ipython.register_magic_function(_magic, magic_name='dotenv') |
| 40 | + ipython.register_magics(IPythonDotEnv) |
0 commit comments