envmnt/lib.rs
1#![deny(
2 absolute_paths_not_starting_with_crate,
3 ambiguous_associated_items,
4 anonymous_parameters,
5 arithmetic_overflow,
6 array_into_iter,
7 asm_sub_register,
8 bad_asm_style,
9 bindings_with_variant_name,
10 break_with_label_and_loop,
11 cenum_impl_drop_cast,
12 clashing_extern_declarations,
13 coherence_leak_check,
14 conflicting_repr_hints,
15 confusable_idents,
16 const_err,
17 const_evaluatable_unchecked,
18 const_item_mutation,
19 dead_code,
20 deprecated,
21 deprecated_cfg_attr_crate_type_name,
22 deprecated_in_future,
23 deprecated_where_clause_location,
24 deref_into_dyn_supertrait,
25 deref_nullptr,
26 drop_bounds,
27 duplicate_macro_attributes,
28 dyn_drop,
29 ellipsis_inclusive_range_patterns,
30 enum_intrinsics_non_enums,
31 explicit_outlives_requirements,
32 exported_private_dependencies,
33 forbidden_lint_groups,
34 function_item_references,
35 ill_formed_attribute_input,
36 illegal_floating_point_literal_pattern,
37 improper_ctypes,
38 improper_ctypes_definitions,
39 incomplete_features,
40 incomplete_include,
41 indirect_structural_match,
42 ineffective_unstable_trait_impl,
43 inline_no_sanitize,
44 invalid_atomic_ordering,
45 invalid_doc_attributes,
46 invalid_type_param_default,
47 invalid_value,
48 irrefutable_let_patterns,
49 keyword_idents,
50 large_assignments,
51 late_bound_lifetime_arguments,
52 legacy_derive_helpers,
53 macro_expanded_macro_exports_accessed_by_absolute_paths,
54 meta_variable_misuse,
55 missing_abi,
56 missing_copy_implementations,
57 missing_docs,
58 missing_fragment_specifier,
59 mixed_script_confusables,
60 mutable_transmutes,
61 named_arguments_used_positionally,
62 named_asm_labels,
63 no_mangle_const_items,
64 no_mangle_generic_items,
65 non_ascii_idents,
66 non_camel_case_types,
67 non_fmt_panics,
68 non_shorthand_field_patterns,
69 non_snake_case,
70 non_upper_case_globals,
71 nontrivial_structural_match,
72 noop_method_call,
73 order_dependent_trait_objects,
74 overflowing_literals,
75 overlapping_range_endpoints,
76 path_statements,
77 patterns_in_fns_without_body,
78 pointer_structural_match,
79 private_in_public,
80 proc_macro_back_compat,
81 proc_macro_derive_resolution_fallback,
82 pub_use_of_private_extern_crate,
83 redundant_semicolons,
84 repr_transparent_external_private_fields,
85 rust_2021_incompatible_closure_captures,
86 rust_2021_incompatible_or_patterns,
87 rust_2021_prefixes_incompatible_syntax,
88 rust_2021_prelude_collisions,
89 semicolon_in_expressions_from_macros,
90 soft_unstable,
91 stable_features,
92 suspicious_auto_trait_impls,
93 temporary_cstring_as_ptr,
94 text_direction_codepoint_in_comment,
95 text_direction_codepoint_in_literal,
96 trivial_bounds,
97 trivial_casts,
98 trivial_numeric_casts,
99 type_alias_bounds,
100 tyvar_behind_raw_pointer,
101 unaligned_references,
102 uncommon_codepoints,
103 unconditional_panic,
104 unconditional_recursion,
105 unexpected_cfgs,
106 uninhabited_static,
107 unknown_crate_types,
108 unnameable_test_items,
109 unreachable_code,
110 unreachable_patterns,
111 unreachable_pub,
112 unsafe_code,
113 unsafe_op_in_unsafe_fn,
114 unstable_features,
115 unstable_name_collisions,
116 unsupported_calling_conventions,
117 unused_allocation,
118 unused_assignments,
119 unused_assignments,
120 unused_attributes,
121 unused_braces,
122 unused_comparisons,
123 unused_crate_dependencies,
124 unused_doc_comments,
125 unused_extern_crates,
126 unused_features,
127 unused_import_braces,
128 unused_imports,
129 unused_labels,
130 unused_lifetimes,
131 unused_macro_rules,
132 unused_macros,
133 unused_must_use,
134 unused_mut,
135 unused_parens,
136 unused_qualifications,
137 unused_unsafe,
138 unused_variables,
139 useless_deprecated,
140 where_clauses_object_safety,
141 while_true
142)]
143#![warn(macro_use_extern_crate, unknown_lints)]
144#![allow(
145 bare_trait_objects,
146 box_pointers,
147 elided_lifetimes_in_paths,
148 missing_debug_implementations,
149 single_use_lifetimes,
150 unused_results,
151 variant_size_differences,
152 warnings,
153 renamed_and_removed_lints
154)]
155
156//! # envmnt
157//!
158//! Environment variables utility functions.
159//!
160//! This library has many helper functions to access/modify/check environment variables.
161//!
162//! # Examples
163//!
164//! ## Get/Set/Remove environment variables
165//!
166//! ```
167//! use envmnt::{ExpandOptions, ExpansionType};
168//!
169//! fn main() {
170//! if !envmnt::exists("MY_ENV_VAR") {
171//! envmnt::set("MY_ENV_VAR", "SOME VALUE");
172//! }
173//!
174//! let mut value = envmnt::get_or("MY_ENV_VAR", "DEFAULT_VALUE");
175//! println!("Env Value: {}", &value);
176//!
177//! value = envmnt::get_or_panic("MY_ENV_VAR");
178//! println!("Env Value: {}", &value);
179//!
180//! let pre_value = envmnt::get_set("MY_ENV_VAR", "SOME NEW VALUE");
181//!
182//! let value = envmnt::get_or("MY_ENV_VAR", "DEFAULT_VALUE");
183//! println!("New Env Value: {}", &value);
184//! println!("Previous Env Value: {:?}", &pre_value);
185//!
186//! let var_was_set = envmnt::set_optional("MY_ENV_VAR", &Some("OPTIONAL VALUE"));
187//! println!("Env Was Modified: {}", var_was_set);
188//!
189//! let all_vars = envmnt::vars(); // returned as Vec<(String, String)>
190//!
191//! for (key, value) in all_vars {
192//! println!("{}: {}", key, value);
193//! }
194//!
195//! envmnt::set("MY_ENV_VAR2", "SOME VALUE2");
196//!
197//! let value = envmnt::get_any(&vec!["MY_ENV_VAR1", "MY_ENV_VAR2"], "default");
198//! println!("MY_ENV_VAR1 exists: {}", envmnt::exists("MY_ENV_VAR1"));
199//! println!("MY_ENV_VAR2 exists: {}", envmnt::exists("MY_ENV_VAR2"));
200//! println!("Found value: {}", value);
201//!
202//! let mut options = ExpandOptions::new();
203//! options.expansion_type = Some(ExpansionType::Unix);
204//! let mut value = envmnt::expand("Env: MY_ENV value is: ${MY_ENV}", Some(options));
205//! println!("Expanded: {}", &value);
206//! options.expansion_type = Some(ExpansionType::UnixBracketsWithDefaults);
207//! value = envmnt::expand(
208//! "Env: MY_ENV_NOT_FOUND value is: ${MY_ENV_NOT_FOUND:default value}",
209//! Some(options),
210//! );
211//! println!("Expanded: {}", &value);
212//! }
213//! ```
214//!
215//! ## Get/Set boolean environment variables and other comparisons
216//!
217//! ```
218//! fn main() {
219//! envmnt::set_bool("FLAG_VAR", true);
220//! let mut flag_value = envmnt::is_or("FLAG_VAR", false);
221//! println!("Bool Flag: {}", &flag_value);
222//!
223//! flag_value = envmnt::is("FLAG_VAR");
224//! assert!(flag_value);
225//!
226//! envmnt::set_bool("FLAG_VAR", true);
227//! assert!(envmnt::is_equal("FLAG_VAR", "true"));
228//!
229//! envmnt::set("MY_ENV_VAR", "SOME VALUE");
230//! let same = envmnt::is_equal("MY_ENV_VAR", "SOME VALUE");
231//! println!("Value Is Same: {}", &same);
232//! let mut contains = envmnt::contains("MY_ENV_VAR", "_ENV_");
233//! println!("Value Contained: {}", &contains);
234//! contains = envmnt::contains_ignore_case("MY_ENV_VAR", "_env_");
235//! println!("Value Contained (case insensitive): {}", &contains);
236//! }
237//! ```
238//!
239//! ## Get/Set numeric environment variables
240//!
241//! ```
242//! fn main() {
243//! // all numeric data types: u8/i8/u16/i16/u32/i32/u64/i64/u128/i128/f32/f64/isize/usize
244//! // are supported by specific set/get functions.
245//! envmnt::set_u8("U8_TEST_ENV", 50);
246//! let mut value_u8 = envmnt::get_u8("U8_TEST_ENV", 5);
247//! println!("u8 value: {}", value_u8);
248//!
249//! envmnt::set_isize("ISIZE_TEST_ENV", -50);
250//! let mut value_isize = envmnt::get_isize("ISIZE_TEST_ENV", 5);
251//! println!("isize value: {}", value_isize);
252//!
253//! // increment/decrement values
254//! value_isize = envmnt::increment("U8_TEST_ENV");
255//! assert_eq!(value_isize, 51);
256//! value_u8 = envmnt::get_u8("U8_TEST_ENV", 5);
257//! assert_eq!(value_u8, 51);
258//! value_isize = envmnt::decrement("U8_TEST_ENV");
259//! assert_eq!(value_isize, 50);
260//! value_u8 = envmnt::get_u8("U8_TEST_ENV", 5);
261//! assert_eq!(value_u8, 50);
262//! }
263//! ```
264//!
265//! ## Get and parse any type T that implements FromStr
266//!
267//! ```
268//! fn main() {
269//! envmnt::set("ENV_VAR", "123");
270//!
271//! let value: i16 = envmnt::get_parse("ENV_VAR").unwrap();
272//! assert_eq!(value, 123);
273//!
274//! let value: String = envmnt::get_parse("ENV_VAR").unwrap();
275//! assert_eq!(value, "123");
276//!
277//! let value: i32 = envmnt::get_parse_or("ENV_VAR", 123).unwrap();
278//! assert_eq!(value, 123);
279//!
280//! let value: i64 = envmnt::get_parse_or("ENV_UNDEFINED", 321).unwrap();
281//! assert_eq!(value, 321);
282//! }
283//! ```
284//!
285//! ## Get/Set list environment variables
286//!
287//! ```
288//! fn main() {
289//! envmnt::set_list(
290//! "LIST_TEST_ENV",
291//! &vec!["1".to_string(), "2".to_string(), "3".to_string()],
292//! );
293//!
294//! let mut values = envmnt::get_list("LIST_TEST_ENV").unwrap();
295//! println!("List Values: {:?}", values);
296//!
297//! let mut same = envmnt::is_equal("LIST_TEST_ENV", "1;2;3");
298//! println!("Same: {}", same);
299//!
300//! let mut options = envmnt::ListOptions::new();
301//! options.separator = Some(",".to_string());
302//! envmnt::set_list_with_options(
303//! "LIST_TEST_ENV",
304//! &vec!["1".to_string(), "2".to_string(), "3".to_string()],
305//! &options,
306//! );
307//!
308//! values = envmnt::get_list_with_options("LIST_TEST_ENV", &options).unwrap();
309//! println!("List Values: {:?}", values);
310//!
311//! same = envmnt::is_equal("LIST_TEST_ENV", "1,2,3");
312//! println!("Same: {}", same);
313//! }
314//! ```
315//!
316//! ## Bulk Operations
317//!
318//! ```
319//! use indexmap::IndexMap;
320//!
321//! fn main() {
322//! let mut env: IndexMap<String, String> = IndexMap::new();
323//! env.insert("ENV_VAR1".to_string(), "MY VALUE".to_string());
324//! env.insert("ENV_VAR2".to_string(), "MY VALUE2".to_string());
325//!
326//! envmnt::set_all(&env);
327//!
328//! let value = envmnt::get_or_panic("ENV_VAR1");
329//! println!("Value Is: {}", &value);
330//!
331//! let mut found = envmnt::is_any_exists(&vec!["ENV_VAR1", "ENV_VAR2"]);
332//!
333//! println!("Any Found: {}", &found);
334//!
335//! found = envmnt::is_all_exists(&vec!["ENV_VAR1", "ENV_VAR2"]);
336//!
337//! println!("All Found: {}", &found);
338//!
339//! envmnt::remove_all(&vec!["ENV_VAR1", "ENV_VAR2"]);
340//!
341//! found = envmnt::is_any_exists(&vec!["ENV_VAR1", "ENV_VAR2"]);
342//!
343//! println!("Any Found: {}", &found);
344//!
345//! env = IndexMap::new();
346//! env.insert("ENV_VAR1".to_string(), "MY VALUE".to_string());
347//! env.insert("ENV_VAR2".to_string(), "MY VALUE2".to_string());
348//!
349//! let eval_env = |key: String, value: String| {
350//! let mut updated_key = String::from("KEY-");
351//! updated_key.push_str(&key);
352//! let mut updated_value = String::from("VALUE-");
353//! updated_value.push_str(&value);
354//! Some((updated_key, updated_value))
355//! };
356//!
357//! envmnt::evaluate_and_set_all(&env, eval_env);
358//!
359//! let value = envmnt::get_or_panic("KEY-ENV_VAR1");
360//! println!("Value Is: {}", &value);
361//! }
362//! ```
363//!
364//! ## File Operations
365//!
366//! ```
367//! fn main() {
368//! let mut output = envmnt::load_file("./src/test/var.env");
369//! assert!(output.is_ok());
370//!
371//! let eval_env = |key: String, value: String| {
372//! let mut updated_value = String::from("PREFIX-");
373//! updated_value.push_str(&value);
374//! Some((key, updated_value))
375//! };
376//!
377//! output = envmnt::evaluate_and_load_file("./src/test/var.env", eval_env);
378//! assert!(output.is_ok());
379//! }
380//! ```
381//!
382//! # Installation
383//! In order to use this library, just add it as a dependency:
384//!
385//! ```ini
386//! [dependencies]
387//! envmnt = "*"
388//! ```
389//!
390//! # Contributing
391//! See [contributing guide](https://github.com/sagiegurari/envmnt/blob/master/.github/CONTRIBUTING.md)
392//!
393//! # License
394//! Developed by Sagie Gur-Ari and licensed under the
395//! [Apache 2](https://github.com/sagiegurari/envmnt/blob/master/LICENSE) open source license.
396//!
397
398#[cfg(test)]
399#[path = "./lib_test.rs"]
400mod lib_test;
401
402#[cfg(doctest)]
403doc_comment::doctest!("../README.md");
404
405mod bulk;
406mod checkpoint;
407mod environment;
408pub mod errors;
409mod expansion;
410mod file;
411mod generic;
412mod numeric;
413pub mod types;
414mod util;
415
416use crate::checkpoint::Checkpoint;
417use crate::types::EnvmntResult;
418use indexmap::IndexMap;
419use std::ffi::OsStr;
420use std::fmt::Display;
421use std::str::FromStr;
422
423/// Get/Set list options
424pub type ListOptions = types::ListOptions;
425
426/// Expansion Type - unix/windows style
427pub type ExpansionType = types::ExpansionType;
428
429/// Expand options
430pub type ExpandOptions = types::ExpandOptions;
431
432/// Returns true environment variable is defined.
433///
434/// # Arguments
435///
436/// * `key` - The environment variable name
437///
438/// # Example
439///
440/// ```
441/// fn main() {
442/// if !envmnt::exists("MY_ENV_VAR") {
443/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
444/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
445/// }
446/// }
447/// ```
448pub fn exists<K: AsRef<OsStr>>(key: K) -> bool {
449 environment::exists(key)
450}
451
452/// Removes the provided environment variable.
453///
454/// # Arguments
455///
456/// * `key` - The environment variable to remove
457///
458/// # Example
459///
460/// ```
461/// fn main() {
462/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
463/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
464///
465/// envmnt::remove("MY_ENV_VAR");
466/// assert!(!envmnt::exists("MY_ENV_VAR"));
467/// }
468/// ```
469pub fn remove<K: AsRef<OsStr>>(key: K) {
470 environment::remove(key)
471}
472
473/// Removes the provided environment variable and returns its previous value (if any).
474///
475/// # Arguments
476///
477/// * `key` - The environment variable to remove
478///
479/// # Example
480///
481/// ```
482/// fn main() {
483/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
484/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
485///
486/// let value = envmnt::get_remove("MY_ENV_VAR");
487/// assert!(!envmnt::exists("MY_ENV_VAR"));
488/// assert_eq!(value.unwrap(), "SOME VALUE");
489/// }
490/// ```
491pub fn get_remove<K: AsRef<OsStr>>(key: K) -> Option<String> {
492 environment::get_remove(key)
493}
494
495/// Removes all provided environment variables.
496///
497/// # Arguments
498///
499/// * `keys` - A list of environment variables to remove
500///
501/// # Example
502///
503/// ```
504/// fn main() {
505/// envmnt::set("MY_ENV_VAR1", "SOME VALUE 1");
506/// envmnt::set("MY_ENV_VAR2", "SOME VALUE 2");
507/// assert!(envmnt::is_equal("MY_ENV_VAR1", "SOME VALUE 1"));
508/// assert!(envmnt::is_equal("MY_ENV_VAR2", "SOME VALUE 2"));
509///
510/// envmnt::remove_all(&vec!["MY_ENV_VAR1", "MY_ENV_VAR2"]);
511/// assert!(!envmnt::exists("MY_ENV_VAR1"));
512/// assert!(!envmnt::exists("MY_ENV_VAR2"));
513/// }
514/// ```
515pub fn remove_all<K: AsRef<OsStr>>(keys: &Vec<K>) {
516 bulk::remove_all(keys)
517}
518
519/// Returns the environment variable value or if is not defined, the default value will be returned.
520///
521/// # Arguments
522///
523/// * `key` - The environment variable name
524/// * `default_value` - In case the environment variable is not defined, this value will be returned.
525///
526/// # Example
527///
528/// ```
529/// fn main() {
530/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
531/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
532///
533/// let mut value = envmnt::get_or("MY_ENV_VAR", "DEFAULT_VALUE");
534/// assert_eq!(value, "SOME VALUE");
535///
536/// value = envmnt::get_or("ANOTHER_ENV_VAR", "DEFAULT_VALUE");
537/// assert_eq!(value, "DEFAULT_VALUE");
538/// }
539/// ```
540pub fn get_or<K: AsRef<OsStr>>(key: K, default_value: &str) -> String {
541 environment::get_or(key, default_value)
542}
543
544/// Returns the environment variable value.
545/// If the variable is not defined, this function will panic.
546///
547/// # Arguments
548///
549/// * `key` - The environment variable name
550///
551/// # Example
552///
553/// ```
554/// fn main() {
555/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
556/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
557///
558/// let value = envmnt::get_or_panic("MY_ENV_VAR");
559/// assert_eq!(value, "SOME VALUE");
560/// }
561/// ```
562pub fn get_or_panic<K: AsRef<OsStr>>(key: K) -> String {
563 environment::get_or_panic(key)
564}
565
566/// Returns the first environment variable found.
567///
568/// # Arguments
569///
570/// * `keys` - The environment variables to search
571/// * `default_value` - In case the environment variables are not defined, this value will be returned.
572///
573/// # Example
574///
575/// ```
576/// fn main() {
577/// envmnt::set("MY_ENV_VAR2", "SOME VALUE2");
578///
579/// let value = envmnt::get_any(&vec!["MY_ENV_VAR1", "MY_ENV_VAR2"], "default");
580/// assert!(!envmnt::exists("MY_ENV_VAR1"));
581/// assert!(envmnt::exists("MY_ENV_VAR2"));
582/// assert_eq!(value, "SOME VALUE2");
583/// }
584/// ```
585pub fn get_any<K: AsRef<OsStr>>(keys: &Vec<K>, default_value: &str) -> String {
586 environment::get_any(keys, default_value)
587}
588
589/// Returns false if environment variable value if falsy.<br>
590/// Any other value is returned as true.<br>
591/// The value is falsy if it is one of the following:
592/// * Empty string
593/// * "false" (case insensitive)
594/// * "no" (case insensitive)
595/// * "0"
596///
597/// # Arguments
598///
599/// * `key` - The environment variable name
600/// * `default_value` - In case the environment variable is not defined, this value will be returned.
601///
602/// # Example
603///
604/// ```
605/// fn main() {
606/// envmnt::set_bool("FLAG_VAR", true);
607/// assert!(envmnt::is_equal("FLAG_VAR", "true"));
608///
609/// let flag_value = envmnt::is_or("FLAG_VAR", false);
610/// assert!(flag_value);
611/// }
612/// ```
613pub fn is_or<K: AsRef<OsStr>>(key: K, default_value: bool) -> bool {
614 environment::is_or(key, default_value)
615}
616
617/// Returns false if environment variable value if falsy.
618/// The value is falsy if it is one of the following:
619/// * Empty string
620/// * "false" (case insensitive)
621/// * "no" (case insensitive)
622/// * "0"
623/// <br>
624/// Any other value is returned as true.
625/// This is same as calling is_or("varname", false)
626///
627/// # Arguments
628///
629/// * `key` - The environment variable name
630///
631/// # Example
632///
633/// ```
634/// fn main() {
635/// envmnt::set_bool("FLAG_VAR", true);
636/// assert!(envmnt::is_equal("FLAG_VAR", "true"));
637///
638/// let flag_value = envmnt::is("FLAG_VAR");
639/// assert!(flag_value);
640/// }
641/// ```
642pub fn is<K: AsRef<OsStr>>(key: K) -> bool {
643 environment::is(key)
644}
645
646/// Sets the environment variable value.
647///
648/// # Arguments
649///
650/// * `key` - The environment variable name
651/// * `value` - The environment variable value
652///
653/// # Example
654///
655/// ```
656/// fn main() {
657/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
658/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
659///
660/// let value = envmnt::get_or("MY_ENV_VAR", "DEFAULT_VALUE");
661/// assert_eq!(value, "SOME VALUE");
662/// }
663/// ```
664pub fn set<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
665 environment::set(key, value)
666}
667
668/// Sets the environment variable with a true/false value as string.
669///
670/// # Arguments
671///
672/// * `key` - The environment variable name
673/// * `value` - true/false boolean value which will be converted to string
674///
675/// # Example
676///
677/// ```
678/// fn main() {
679/// envmnt::set_bool("FLAG_VAR", true);
680/// assert!(envmnt::is_equal("FLAG_VAR", "true"));
681///
682/// let flag_value = envmnt::is_or("FLAG_VAR", false);
683/// assert!(flag_value);
684/// }
685/// ```
686pub fn set_bool<K: AsRef<OsStr>>(key: K, value: bool) {
687 environment::set_bool(key, value)
688}
689
690/// Sets the environment variable if the provided option contains a value.
691///
692/// # Arguments
693///
694/// * `key` - The environment variable name
695/// * `value` - The optional value to set
696///
697/// # Example
698///
699/// ```
700/// fn main() {
701/// let output = envmnt::set_optional("MY_ENV_VAR", &Some("OPTIONAL VALUE"));
702///
703/// assert!(output);
704/// assert!(envmnt::is_equal(
705/// "MY_ENV_VAR",
706/// "OPTIONAL VALUE"
707/// ));
708/// }
709/// ```
710pub fn set_optional<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: &Option<V>) -> bool {
711 environment::set_optional(key, value)
712}
713
714/// Sets the environment variable if the provided option contains a value.
715/// If no value was provided, the environment variable will be removed.
716///
717/// # Arguments
718///
719/// * `key` - The environment variable name
720/// * `value` - The optional value to set, none to remove
721///
722/// # Example
723///
724/// ```
725/// fn main() {
726/// let mut output = envmnt::set_or_remove("MY_ENV_VAR", &Some("OPTIONAL VALUE"));
727///
728/// assert!(output);
729/// assert!(envmnt::is_equal(
730/// "MY_ENV_VAR",
731/// "OPTIONAL VALUE"
732/// ));
733///
734/// output = envmnt::set_or_remove::<&str, &str>("MY_ENV_VAR", &None);
735///
736/// assert!(!output);
737/// assert!(!envmnt::exists("MY_ENV_VAR"));
738/// }
739/// ```
740pub fn set_or_remove<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: &Option<V>) -> bool {
741 environment::set_or_remove(key, value)
742}
743
744/// Sets the environment variable value and returns the previous value.
745///
746/// # Arguments
747///
748/// * `key` - The environment variable name
749/// * `value` - The environment variable value
750///
751/// # Example
752///
753/// ```
754/// fn main() {
755/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
756/// assert!(envmnt::is_equal("MY_ENV_VAR", "SOME VALUE"));
757///
758/// let pre_value = envmnt::get_set("MY_ENV_VAR", "NEW VALUE");
759///
760/// let value = envmnt::get_or("MY_ENV_VAR", "DEFAULT_VALUE");
761/// assert_eq!(value, "NEW VALUE");
762/// assert_eq!(pre_value.unwrap(), "SOME VALUE");
763/// }
764/// ```
765pub fn get_set<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) -> Option<String> {
766 environment::get_set(key, value)
767}
768
769/// Returns all environment variables as a vector.
770///
771/// # Example
772///
773/// ```
774/// fn main() {
775/// let all_vars = envmnt::vars();
776///
777/// for (key, value) in all_vars {
778/// println!("{}: {}", key, value);
779/// }
780/// }
781/// ```
782pub fn vars() -> Vec<(String, String)> {
783 environment::vars()
784}
785
786/// Returns true if the provided environment variable is defined and equals the provided value.
787///
788/// # Arguments
789///
790/// * `key` - The environment variable name
791/// * `value` - The value to check
792///
793/// # Example
794///
795/// ```
796/// fn main() {
797/// envmnt::set("MY_ENV_VAR", "SOME VALUE");
798///
799/// let same = envmnt::is_equal("MY_ENV_VAR", "SOME VALUE");
800/// assert!(same);
801/// }
802/// ```
803pub fn is_equal<K: AsRef<OsStr>>(key: K, value: &str) -> bool {
804 environment::is_equal(key, value)
805}
806
807/// Returns true if the provided environment variable is defined and contains the provided value.
808///
809/// # Arguments
810///
811/// * `key` - The environment variable name
812/// * `value` - The value to check
813///
814/// # Example
815///
816/// ```
817/// fn main() {
818/// envmnt::set("MY_ENV_VAR", "SOME TEST VALUE");
819///
820/// let contains = envmnt::contains("MY_ENV_VAR", "TEST");
821/// assert!(contains);
822/// }
823/// ```
824pub fn contains<K: AsRef<OsStr>>(key: K, value: &str) -> bool {
825 environment::contains(key, value)
826}
827
828/// Returns true if the provided environment variable is defined and contains the provided value regardless of the case.
829///
830/// # Arguments
831///
832/// * `key` - The environment variable name
833/// * `value` - The value to check
834///
835/// # Example
836///
837/// ```
838/// fn main() {
839/// envmnt::set("MY_ENV_VAR", "SOME TEST VALUE");
840///
841/// let contains = envmnt::contains_ignore_case("MY_ENV_VAR", "test");
842/// assert!(contains);
843/// }
844/// ```
845pub fn contains_ignore_case<K: AsRef<OsStr>>(key: K, value: &str) -> bool {
846 environment::contains_ignore_case(key, value)
847}
848
849/// Sets the provided string vector as an environment variable.
850///
851/// # Arguments
852///
853/// * `key` - The environment variable name
854/// * `values` - String vector of values
855///
856/// # Example
857///
858/// ```
859/// fn main() {
860/// envmnt::set_list(
861/// "LIST_TEST_ENV",
862/// &vec!["1".to_string(), "2".to_string(), "3".to_string()],
863/// );
864///
865/// let values = envmnt::get_list("LIST_TEST_ENV").unwrap();
866/// assert_eq!(
867/// values,
868/// vec!["1".to_string(), "2".to_string(), "3".to_string()]
869/// );
870/// }
871/// ```
872pub fn set_list<K: AsRef<OsStr>>(key: K, values: &Vec<String>) {
873 environment::set_list(key, values)
874}
875
876/// Returns the requested environment variable as a string vector.
877///
878/// # Arguments
879///
880/// * `key` - The environment variable name
881///
882/// # Example
883///
884/// ```
885/// fn main() {
886/// envmnt::set_list(
887/// "LIST_TEST_ENV",
888/// &vec!["1".to_string(), "2".to_string(), "3".to_string()],
889/// );
890///
891/// let values = envmnt::get_list("LIST_TEST_ENV").unwrap();
892/// assert_eq!(
893/// values,
894/// vec!["1".to_string(), "2".to_string(), "3".to_string()]
895/// );
896/// }
897/// ```
898pub fn get_list<K: AsRef<OsStr>>(key: K) -> Option<Vec<String>> {
899 environment::get_list(key)
900}
901
902/// Sets the provided string vector as an environment variable.
903///
904/// # Arguments
905///
906/// * `key` - The environment variable name
907/// * `values` - String vector of values
908/// * `options` - See ListOptions
909///
910/// # Example
911///
912/// ```
913/// fn main() {
914/// let mut options = envmnt::ListOptions::new();
915/// options.separator = Some(",".to_string());
916/// envmnt::set_list_with_options(
917/// "LIST_TEST_ENV",
918/// &vec!["1".to_string(), "2".to_string(), "3".to_string()],
919/// &options,
920/// );
921///
922/// let values = envmnt::get_list_with_options("LIST_TEST_ENV", &options).unwrap();
923/// println!("List Values: {:?}", values);
924///
925/// let same = envmnt::is_equal("LIST_TEST_ENV", "1,2,3");
926/// println!("Same: {}", same);
927/// }
928/// ```
929pub fn set_list_with_options<K: AsRef<OsStr>>(key: K, values: &Vec<String>, options: &ListOptions) {
930 environment::set_list_with_options(key, values, options)
931}
932
933/// Returns the requested environment variable as a string vector.
934///
935/// # Arguments
936///
937/// * `key` - The environment variable name
938/// * `options` - See ListOptions
939///
940/// # Example
941///
942/// ```
943/// fn main() {
944/// let mut options = envmnt::ListOptions::new();
945/// options.separator = Some(",".to_string());
946/// envmnt::set_list_with_options(
947/// "LIST_TEST_ENV",
948/// &vec!["1".to_string(), "2".to_string(), "3".to_string()],
949/// &options,
950/// );
951///
952/// let values = envmnt::get_list_with_options("LIST_TEST_ENV", &options).unwrap();
953/// println!("List Values: {:?}", values);
954///
955/// let same = envmnt::is_equal("LIST_TEST_ENV", "1,2,3");
956/// println!("Same: {}", same);
957/// }
958/// ```
959pub fn get_list_with_options<K: AsRef<OsStr>>(
960 key: K,
961 options: &ListOptions,
962) -> Option<Vec<String>> {
963 environment::get_list_with_options(key, options)
964}
965
966/// Sets all the provided env key/value pairs.
967///
968/// # Arguments
969///
970/// * `env` - The environment variables to set
971///
972/// # Example
973///
974/// ```
975/// use indexmap::IndexMap;
976///
977/// fn main() {
978/// let mut env: IndexMap<String, String> = IndexMap::new();
979/// env.insert("MY_ENV_VAR".to_string(), "MY VALUE".to_string());
980/// env.insert("MY_ENV_VAR2".to_string(), "MY VALUE2".to_string());
981///
982/// envmnt::set_all(&env);
983///
984/// let mut value = envmnt::get_or_panic("MY_ENV_VAR");
985/// assert_eq!(value, "MY VALUE");
986/// value = envmnt::get_or_panic("MY_ENV_VAR2");
987/// assert_eq!(value, "MY VALUE2");
988/// }
989/// ```
990pub fn set_all(env: &IndexMap<String, String>) {
991 bulk::set_all(&env)
992}
993
994/// Sets all the provided env key/value pairs.
995///
996/// # Arguments
997///
998/// * `env` - The environment variables to set
999/// * `evaluate` - Evalute function which will modify the key/value before it is loaded into the environment
1000///
1001/// # Example
1002///
1003/// ```
1004/// use indexmap::IndexMap;
1005///
1006/// fn main() {
1007/// let mut env: IndexMap<String, String> = IndexMap::new();
1008/// env.insert("MY_ENV_VAR".to_string(), "MY VALUE".to_string());
1009/// env.insert("MY_ENV_VAR2".to_string(), "MY VALUE2".to_string());
1010///
1011/// let eval_env = |key: String, value: String| {
1012/// let mut updated_key = String::from("KEY-");
1013/// updated_key.push_str(&key);
1014/// let mut updated_value = String::from("VALUE-");
1015/// updated_value.push_str(&value);
1016/// Some((updated_key, updated_value))
1017/// };
1018///
1019/// envmnt::evaluate_and_set_all(&env, eval_env);
1020///
1021/// let mut value = envmnt::get_or_panic("KEY-MY_ENV_VAR");
1022/// assert_eq!(value, "VALUE-MY VALUE");
1023/// value = envmnt::get_or_panic("KEY-MY_ENV_VAR2");
1024/// assert_eq!(value, "VALUE-MY VALUE2");
1025/// }
1026/// ```
1027pub fn evaluate_and_set_all<F>(env: &IndexMap<String, String>, evaluate: F)
1028where
1029 F: Fn(String, String) -> Option<(String, String)>,
1030{
1031 bulk::evaluate_and_set_all(&env, evaluate)
1032}
1033
1034/// Returns true if any of environment variables is defined.
1035///
1036/// # Arguments
1037///
1038/// * `keys` - The environment variable names
1039///
1040/// # Example
1041///
1042/// ```
1043/// fn main() {
1044/// envmnt::set("ENV_VAR1", "SOME VALUE");
1045/// envmnt::remove("ENV_VAR2");
1046///
1047/// let found = envmnt::is_any_exists(&vec![
1048/// "ENV_VAR1",
1049/// "ENV_VAR2",
1050/// ]);
1051///
1052/// assert!(found);
1053/// }
1054/// ```
1055pub fn is_any_exists<K: AsRef<OsStr>>(keys: &Vec<K>) -> bool {
1056 bulk::is_any_exists(keys)
1057}
1058
1059/// Returns true if all of environment variables are defined.
1060///
1061/// # Arguments
1062///
1063/// * `keys` - The environment variable names
1064///
1065/// # Example
1066///
1067/// ```
1068/// fn main() {
1069/// envmnt::set("ENV_VAR1", "SOME VALUE");
1070/// envmnt::set("ENV_VAR2", "SOME VALUE");
1071///
1072/// let mut found = envmnt::is_all_exists(&vec![
1073/// "ENV_VAR1",
1074/// "ENV_VAR2",
1075/// ]);
1076///
1077/// assert!(found);
1078///
1079/// envmnt::remove("ENV_VAR2");
1080///
1081/// found = envmnt::is_all_exists(&vec![
1082/// "ENV_VAR1",
1083/// "ENV_VAR2",
1084/// ]);
1085///
1086/// assert!(!found);
1087/// }
1088/// ```
1089pub fn is_all_exists<K: AsRef<OsStr>>(keys: &Vec<K>) -> bool {
1090 bulk::is_all_exists(keys)
1091}
1092
1093/// Parses the provided env file and loads all environment variables.
1094///
1095/// # Arguments
1096///
1097/// * `file` - The file path to load and parse
1098///
1099/// # Example
1100///
1101/// ```
1102/// fn main() {
1103/// let output = envmnt::load_file("./src/test/var.env");
1104///
1105/// assert!(output.is_ok());
1106/// }
1107/// ```
1108pub fn load_file(file: &str) -> EnvmntResult<()> {
1109 file::load_file(file)
1110}
1111
1112/// Parses the provided env file and loads all environment variables.
1113///
1114/// # Arguments
1115///
1116/// * `file` - The file path to load and parse
1117/// * `evaluate` - Evalute function which will modify the key and value before it is loaded into the environment
1118///
1119/// # Example
1120///
1121/// ```
1122/// fn main() {
1123/// let eval_env = |key: String, value: String| {
1124/// let mut updated_value = String::from("PREFIX-");
1125/// updated_value.push_str(&value);
1126/// Some((key, updated_value))
1127/// };
1128///
1129/// let output = envmnt::evaluate_and_load_file("./src/test/var.env", eval_env);
1130///
1131/// assert!(output.is_ok());
1132/// }
1133/// ```
1134pub fn evaluate_and_load_file<F>(file: &str, evaluate: F) -> EnvmntResult<()>
1135where
1136 F: Fn(String, String) -> Option<(String, String)>,
1137{
1138 file::evaluate_and_load_file(file, evaluate)
1139}
1140
1141/// Parses the provided env file and returns its content as a map of key/value.
1142///
1143/// # Arguments
1144///
1145/// * `file` - The file path to load and parse
1146///
1147/// # Example
1148///
1149/// ```
1150/// fn main() {
1151/// let env = envmnt::parse_file("./src/test/var.env").unwrap();
1152///
1153/// println!("Parsed Env: {:?}", &env);
1154/// }
1155/// ```
1156pub fn parse_file(file: &str) -> EnvmntResult<IndexMap<String, String>> {
1157 file::parse_file(file)
1158}
1159
1160/// Parses the provided content as a map of key/value.
1161/// The content should be in the form of an env file format.
1162///
1163/// # Arguments
1164///
1165/// * `env_content` - The string to parse in env file format
1166///
1167/// # Example
1168///
1169/// ```
1170/// fn main() {
1171/// let env = envmnt::parse_env_file_content(r#"
1172/// ENV_VAR1=1
1173/// # some comment
1174/// ENV_VAR2=2
1175/// "#);
1176///
1177/// println!("Parsed Env: {:?}", &env);
1178/// }
1179/// ```
1180pub fn parse_env_file_content(env_content: &str) -> IndexMap<String, String> {
1181 file::parse_env_file_content(env_content)
1182}
1183
1184/// Expands the provided string value by replacing the environment variables defined in it.
1185/// The syntax of the environment variables is based on the type requested.
1186///
1187/// # Arguments
1188///
1189/// * `value` - The value to expand
1190/// * `expansion_type` - The expanstion type (unix/windows/unix prefix/...)
1191///
1192/// # Example
1193///
1194/// ```
1195/// use envmnt::{ExpandOptions, ExpansionType};
1196///
1197/// fn main() {
1198/// envmnt::set("MY_ENV", "my expanded value");
1199/// let mut options = ExpandOptions::new();
1200/// options.expansion_type = Some(ExpansionType::Unix);
1201/// let value = envmnt::expand("Env: MY_ENV value is: ${MY_ENV}", Some(options));
1202/// assert_eq!("Env: MY_ENV value is: my expanded value", &value);
1203/// }
1204/// ```
1205pub fn expand(value: &str, options: Option<ExpandOptions>) -> String {
1206 environment::expand(&value, options)
1207}
1208
1209macro_rules! generate_get_numeric {
1210 ($fn_name:ident, $type:ty) => {
1211 /// Returns the environment variable value or a default value
1212 /// in case the variable is not defined or cannot be parsed.
1213 ///
1214 /// # Arguments
1215 ///
1216 /// * `key` - The environment variable name
1217 /// * `default_value` - Returned if the variable does not exist or cannot be parsed
1218 ///
1219 pub fn $fn_name<K: AsRef<OsStr>>(key: K, default_value: $type) -> $type {
1220 numeric::$fn_name(key, default_value)
1221 }
1222 };
1223}
1224
1225generate_get_numeric!(get_u8, u8);
1226generate_get_numeric!(get_i8, i8);
1227generate_get_numeric!(get_i16, i16);
1228generate_get_numeric!(get_u16, u16);
1229generate_get_numeric!(get_i32, i32);
1230generate_get_numeric!(get_u32, u32);
1231generate_get_numeric!(get_i64, i64);
1232generate_get_numeric!(get_u64, u64);
1233generate_get_numeric!(get_i128, i128);
1234generate_get_numeric!(get_u128, u128);
1235generate_get_numeric!(get_f32, f32);
1236generate_get_numeric!(get_f64, f64);
1237generate_get_numeric!(get_isize, isize);
1238generate_get_numeric!(get_usize, usize);
1239
1240macro_rules! generate_set_numeric {
1241 ($fn_name:ident, $type:ty) => {
1242 /// Sets the environment variable value.
1243 ///
1244 /// # Arguments
1245 ///
1246 /// * `key` - The environment variable name
1247 /// * `value` - The new variable value
1248 ///
1249 pub fn $fn_name<K: AsRef<OsStr>>(key: K, value: $type) {
1250 numeric::$fn_name(key, value)
1251 }
1252 };
1253}
1254
1255generate_set_numeric!(set_u8, u8);
1256generate_set_numeric!(set_i8, i8);
1257generate_set_numeric!(set_i16, i16);
1258generate_set_numeric!(set_u16, u16);
1259generate_set_numeric!(set_i32, i32);
1260generate_set_numeric!(set_u32, u32);
1261generate_set_numeric!(set_i64, i64);
1262generate_set_numeric!(set_u64, u64);
1263generate_set_numeric!(set_i128, i128);
1264generate_set_numeric!(set_u128, u128);
1265generate_set_numeric!(set_f32, f32);
1266generate_set_numeric!(set_f64, f64);
1267generate_set_numeric!(set_isize, isize);
1268generate_set_numeric!(set_usize, usize);
1269
1270/// Increments and returns the new value stored by the given environment variable key.
1271/// In case the variable does not exist, it will increment to 1.
1272/// The updated value will be returned.
1273///
1274/// # Arguments
1275///
1276/// * `key` - The environment variable name
1277///
1278/// # Example
1279///
1280/// ```
1281/// fn main() {
1282/// envmnt::set_u8("ENV_VAR", 5);
1283/// let value = envmnt::increment("ENV_VAR");
1284/// assert_eq!(value, 6);
1285/// }
1286/// ```
1287pub fn increment<K: AsRef<OsStr>>(key: K) -> isize {
1288 numeric::increment(key)
1289}
1290
1291/// Decrements and returns the new value stored by the given environment variable key.
1292/// In case the variable does not exist, it will decrement to -1.
1293/// The updated value will be returned.
1294///
1295/// # Arguments
1296///
1297/// * `key` - The environment variable name
1298///
1299/// # Example
1300///
1301/// ```
1302/// fn main() {
1303/// envmnt::set_u8("ENV_VAR", 5);
1304/// let value = envmnt::decrement("ENV_VAR");
1305/// assert_eq!(value, 4);
1306/// }
1307/// ```
1308pub fn decrement<K: AsRef<OsStr>>(key: K) -> isize {
1309 numeric::decrement(key)
1310}
1311
1312/// Returns the parsed environment variable value.
1313///
1314/// # Arguments
1315///
1316/// * `key` - The environment variable name
1317///
1318/// # Example
1319///
1320/// ```
1321/// fn main() {
1322/// envmnt::set("ENV_VAR", "123");
1323/// let value: i32 = envmnt::get_parse("ENV_VAR").unwrap();
1324/// assert_eq!(value, 123);
1325/// }
1326/// ```
1327pub fn get_parse<K, T, E>(key: K) -> EnvmntResult<T>
1328where
1329 K: AsRef<OsStr>,
1330 T: FromStr + FromStr<Err = E>,
1331 E: Display,
1332{
1333 generic::get_parse(key)
1334}
1335
1336/// Returns the parsed environment variable value or if is not defined, the default value will be returned.
1337///
1338/// # Arguments
1339///
1340/// * `key` - The environment variable name
1341/// * `default` - The default value to use in case env var is not set
1342///
1343/// # Example
1344///
1345/// ```
1346/// fn main() {
1347/// envmnt::set("ENV_VAR", "123");
1348///
1349/// let value: i32 = envmnt::get_parse_or("ENV_VAR", 321).unwrap();
1350/// assert_eq!(value, 123);
1351///
1352/// let value: i32 = envmnt::get_parse_or("ENV_MISSING_VAR", 321).unwrap();
1353/// assert_eq!(value, 321);
1354/// }
1355/// ```
1356pub fn get_parse_or<K, T, E>(key: K, default: T) -> EnvmntResult<T>
1357where
1358 K: AsRef<OsStr>,
1359 T: FromStr + FromStr<Err = E>,
1360 E: Display,
1361{
1362 generic::get_parse_or(key, default)
1363}
1364
1365/// Create a new checkpoint, for the current environment of the process,
1366/// at a later date a checkpoint can be restored using [`Checkpoint::restore`], which will rollback
1367/// the environment to all values present at the time this function was called.
1368///
1369/// # Example
1370///
1371/// ```
1372/// fn main() {
1373/// envmnt::set("ENV_VAR", "123");
1374/// envmnt::set("ENV_VAR2", "345");
1375///
1376/// assert!(envmnt::is_equal("ENV_VAR", "123"));
1377/// assert!(envmnt::is_equal("ENV_VAR2", "345"));
1378/// assert!(!envmnt::exists("ENV_VAR3"));
1379///
1380/// let chk = envmnt::checkpoint();
1381///
1382/// envmnt::set("ENV_VAR", "1234");
1383/// envmnt::remove("ENV_VAR2");
1384/// envmnt::set("ENV_VAR3", "654");
1385///
1386/// assert!(envmnt::is_equal("ENV_VAR", "1234"));
1387/// assert!(!envmnt::exists("ENV_VAR2"));
1388/// assert!(envmnt::is_equal("ENV_VAR3", "654"));
1389///
1390/// chk.restore();
1391///
1392/// assert!(envmnt::is_equal("ENV_VAR", "123"));
1393/// assert!(envmnt::is_equal("ENV_VAR2", "345"));
1394/// assert!(!envmnt::exists("ENV_VAR3"));
1395/// }
1396/// ```
1397pub fn checkpoint() -> Checkpoint {
1398 Checkpoint::new()
1399}