Skip to content

set

Sets key to value in dotenv content and returns the new content.

The first existing assignment of key is replaced in place and any later ones are dropped; when there is none, a new line is appended. Every other line (comments, blank lines, other variables) is left untouched, and the replaced line keeps its line ending. value is quoted and escaped only when needed, so get reads it back exactly.

use helpers4::env::set;

Cargo feature env (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features env

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.5", default-features = false, features = ["env"] }
pub fn set(content: &str, key: &str, value: &str) -> Result<String, InvalidKeyError>
ParameterTypeDescription
content&strThe dotenv text to edit.
key&strThe variable name to set.
value&strThe value to assign to key.

Result<String, InvalidKeyError>Ok on success, otherwise an Err: see Errors.

Returns InvalidKeyError when key is not [A-Za-z_][A-Za-z0-9_]*.

use helpers4::env::set;

let updated = set("# config\nHOST=old\nPORT=80\n", "HOST", "example.com")?;
assert_eq!(updated, "# config\nHOST=example.com\nPORT=80\n");

assert_eq!(set("A=1\n", "B", "two words")?, "A=1\nB=\"two words\"\n");

The variable name passed to set is not a valid name ([A-Za-z_][A-Za-z0-9_]*).

use helpers4::env::InvalidKeyError;

pub struct InvalidKeyError { /* private fields */ }
pub fn key(&self) -> &str

The rejected name.

Returns

&str — The rejected variable name.

src/env/set.rs