8000 Add dotenv read support · adafruit/circuitpython@a30de85 · GitHub
[go: up one dir, main page]

Skip to content

Commit a30de85

Browse files
committed
Add dotenv read support
os.getenv() will use it (when available) to load variables from /.env This will also be useful when we need secrets or config for CircuitPython outside of the VM (like WiFi credentials.) Fixes #4212
1 parent 1dce806 commit a30de85

File tree

9 files changed

+435
-0
lines changed

9 files changed

+435
-0
lines changed

py/circuitpy_defns.mk

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,9 @@ endif
158158
ifeq ($(CIRCUITPY_DISPLAYIO),1)
159159
SRC_PATTERNS += displayio/%
160160
endif
161+
ifeq ($(CIRCUITPY_DOTENV),1)
162+
SRC_PATTERNS += dotenv/%
163+
endif
161164
ifeq ($(CIRCUITPY_PARALLELDISPLAY),1)
162165
SRC_PATTERNS += paralleldisplay/%
163166
endif
@@ -548,6 +551,7 @@ SRC_SHARED_MODULE_ALL = \
548551
displayio/TileGrid.c \
549552
displayio/area.c \
550553
displayio/__init__.c \
554+
dotenv/__init__.c \
551555
floppyio/__init__.c \
552556
fontio/BuiltinFont.c \
553557
fontio/__init__.c \

py/circuitpy_mpconfig.mk

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,9 @@ CFLAGS += -DCIRCUITPY_BITMAPTOOLS=$(CIRCUITPY_BITMAPTOOLS)
199199
CFLAGS += -DCIRCUITPY_FRAMEBUFFERIO=$(CIRCUITPY_FRAMEBUFFERIO)
200200
CFLAGS += -DCIRCUITPY_VECTORIO=$(CIRCUITPY_VECTORIO)
201201

202+
CIRCUITPY_DOTENV ?= $(CIRCUITPY_FULL_BUILD)
203+
CFLAGS += -DCIRCUITPY_DOTENV=$(CIRCUITPY_DOTENV)
204+
202205
CIRCUITPY_DUALBANK ?= 0
203206
CFLAGS += -DCIRCUITPY_DUALBANK=$(CIRCUITPY_DUALBANK)
204207

shared-bindings/dotenv/__init__.c

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
* This file is part of the Micro Python project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#include <string.h>
28+
29+
#include "extmod/vfs.h"
30+
#include "lib/oofatfs/ff.h"
31+
#include "lib/oofatfs/diskio.h"
32+
#include "py/mpstate.h"
33+
#include "py/obj.h"
34+
#include "py/objstr.h"
35+
#include "py/runtime.h"
36+
#include "shared-bindings/dotenv/__init__.h"
37+
38+
//| """Functions to manage environment variables from a .env file.
39+
//|
40+
//| A subset of the CPython `dotenv library <https://saurabh-kumar.com/python-dotenv/>`_. It does
41+
//| not support variables or double quotes.
42+
//|
43+
//| The simplest way to define keys and values is to put them in single quotes. \ and ' are
44+
//| escaped by \ in single quotes. Newlines can occur in quotes for multiline values. Comments
45+
//| start with # and apply for the rest of the line.
46+
//|
47+
//| File format example:
48+
//|
49+
//| .. code-block::
50+
//|
51+
//| key=value
52+
//| key2 = value2
53+
//| 'key3' = 'value with spaces'
54+
//| # comment
55+
// 1E79 | key4 = value3 # comment 2
56+
//| 'key5'=value4
57+
//| key=value5 # overrides the first one
58+
//| multiline = 'hello
59+
//| world
60+
//| how are you?'
61+
//|
62+
//| """
63+
//|
64+
//| import typing
65+
66+
//| def get_key(dotenv_path: str, key_to_get: str) -> Optional[str]:
67+
//| """Get the value for the given key from the given .env file. If the key occurs multiple
68+
//| times in the file, then the last value will be returned.
69+
//|
70+
//| Returns None if the key isn't found or doesn't have a value."""
71+
//| ...
72+
//|
73+
STATIC mp_obj_t _dotenv_get_key(mp_obj_t path_in, mp_obj_t key_to_get_in) {
74+
return common_hal_dotenv_get_key(mp_obj_str_get_str(path_in),
75+
mp_obj_str_get_str(key_to_get_in));
76+
}
77+
MP_DEFINE_CONST_FUN_OBJ_2(dotenv_get_key_obj, _dotenv_get_key);
78+
79+
//| def load_dotenv() -> None:
80+
//| """Does nothing in CircuitPython because os.getenv will automatically read .env when
81+
//| available.
82+
//|
83+
//| Present in CircuitPython so CPython-compatible code can use it without error."""
84+
//| ...
85+
//|
86+
STATIC mp_obj_t dotenv_load_dotenv(void) {
87+
return mp_const_none;
88+
}
89+
MP_DEFINE_CONST_FUN_OBJ_0(dotenv_load_dotenv_obj, dotenv_load_dotenv);
90+
91+
STATIC const mp_rom_map_elem_t dotenv_module_globals_table[] = {
92+
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_dotenv) },
93+
94+
{ MP_ROM_QSTR(MP_QSTR_get_key), MP_ROM_PTR(&dotenv_get_key_obj) },
95+
{ MP_ROM_QSTR(MP_QSTR_load_dotenv), MP_ROM_PTR(&dotenv_load_dotenv_obj) },
96+
};
97+
98+
STATIC MP_DEFINE_CONST_DICT(dotenv_module_globals, dotenv_module_globals_table);
99+
100+
const mp_obj_module_t dotenv_module = {
101+
.base = { &mp_type_module },
102+
.globals = (mp_obj_dict_t *)&dotenv_module_globals,
103+
};
104+
105+
MP_REGISTER_MODULE(MP_QSTR_dotenv, dotenv_module, CIRCUITPY_DOTENV);

shared-bindings/dotenv/__init__.h

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* This file is part of the MicroPython project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2022 Scott Shawcroft for Adafruit Industries
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#ifndef MICROPY_INCLUDED_SHARED_BINDINGS_DOTENV___INIT___H
28+
#define MICROPY_INCLUDED_SHARED_BINDINGS_DOTENV___INIT___H
29+
30+
#include <stdint.h>
31+
#include <stdbool.h>
32+
33+
#include "py/objtuple.h"
34+
35+
#include "shared-module/dotenv/__init__.h"
36+
37+
mp_obj_t common_hal_dotenv_get_key(const char *path, const char *key);
38+
39+
#endif // MICROPY_INCLUDED_SHARED_BINDINGS_DOTENV___INIT___H

shared-bindings/os/__init__.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,25 @@ STATIC mp_obj_t os_getcwd(void) {
8383
}
8484
MP_DEFINE_CONST_FUN_OBJ_0(os_getcwd_obj, os_getcwd);
8585

86+
//| def getenv(key: str, default: Optional[str] = None) -> Optional[str]:
87+
//| """Get the environment variable value for the given key or return ``default``.
88+
//|
89+
//| This may load values from disk so cache the result instead of calling this often."""
90+
//| ...
91+
//|
92+
STATIC mp_obj_t os_getenv(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
93+
enum { ARG_key, ARG_default };
94+
static const mp_arg_t allowed_args[] = {
95+
{ MP_QSTR_key, MP_ARG_REQUIRED | MP_ARG_OBJ },
96+
{ MP_QSTR_default, MP_ARG_OBJ, {.u_obj = mp_const_none} },
97+
};
98+
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
99+
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
100+
101+
return common_hal_os_getenv(mp_obj_str_get_str(args[ARG_key].u_obj), args[ARG_default].u_obj);
102+
}
103+
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(os_getenv_obj, 1, os_getenv);
104+
86105
//| def listdir(dir: str) -> str:
87106
//| """With no argument, list the current directory. Otherwise list the given directory."""
88107
//| ...
@@ -220,6 +239,7 @@ STATIC const mp_rom_map_elem_t os_module_globals_table[] = {
220239

221240
{ MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&os_chdir_obj) },
222241
{ MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&os_getcwd_obj) },
242+
{ MP_ROM_QSTR(MP_QSTR_getenv), MP_ROM_PTR(&os_getenv_obj) },
223243
{ MP_ROM_QSTR(MP_QSTR_listdir), MP_ROM_PTR(&os_listdir_obj) },
224244
{ MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&os_mkdir_obj) },
225245
{ MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&os_remove_obj) },

shared-bindings/os/__init__.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ extern const mp_rom_obj_tuple_t common_hal_os_uname_info_obj;
3737
mp_obj_t common_hal_os_uname(void);
3838
void common_hal_os_chdir(const char *path);
3939
mp_obj_t common_hal_os_getcwd(void);
40+
mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_);
4041
mp_obj_t common_hal_os_listdir(const char *path);
4142
void common_hal_os_mkdir(const char *path);
4243
void common_hal_os_remove(const char *path);

0 commit comments

Comments
 (0)
0