Removes a given key from the given `.env` file. If the .env path given doesn't exist, fails. If the given key doesn't exist in the .env, fails. This function doesn't follow symlinks by default, to avoid accidentally modifying a file at a potentially untrusted path. If you don'
(
dotenv_path: StrPath,
key_to_unset: str,
quote_mode: str = "always",
encoding: Optional[str] = "utf-8",
follow_symlinks: bool = False,
)
| 246 | |
| 247 | |
| 248 | def unset_key( |
| 249 | dotenv_path: StrPath, |
| 250 | key_to_unset: str, |
| 251 | quote_mode: str = "always", |
| 252 | encoding: Optional[str] = "utf-8", |
| 253 | follow_symlinks: bool = False, |
| 254 | ) -> Tuple[Optional[bool], str]: |
| 255 | """ |
| 256 | Removes a given key from the given `.env` file. |
| 257 | |
| 258 | If the .env path given doesn't exist, fails. |
| 259 | If the given key doesn't exist in the .env, fails. |
| 260 | |
| 261 | This function doesn't follow symlinks by default, to avoid accidentally |
| 262 | modifying a file at a potentially untrusted path. If you don't need this |
| 263 | protection and need symlinks to be followed, use `follow_symlinks`. |
| 264 | """ |
| 265 | if not os.path.exists(dotenv_path): |
| 266 | logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path) |
| 267 | return None, key_to_unset |
| 268 | |
| 269 | removed = False |
| 270 | with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as ( |
| 271 | source, |
| 272 | dest, |
| 273 | ): |
| 274 | for mapping in with_warn_for_invalid_lines(parse_stream(source)): |
| 275 | if mapping.key == key_to_unset: |
| 276 | removed = True |
| 277 | else: |
| 278 | dest.write(mapping.original.string) |
| 279 | |
| 280 | if not removed: |
| 281 | logger.warning( |
| 282 | "Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path |
| 283 | ) |
| 284 | return None, key_to_unset |
| 285 | |
| 286 | return removed, key_to_unset |
| 287 | |
| 288 | |
| 289 | def resolve_variables( |
no test coverage detected
searching dependent graphs…