hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

environ.ha (1889B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use errors;
      5 use strings;
      6 
      7 // All currently supported target architectures. This enum will be extended
      8 // whenever support for a new architecture is added.
      9 export type arch = enum {
     10 	AARCH64,
     11 	RISCV64,
     12 	X86_64,
     13 };
     14 
     15 // Returns a portable string for an [[arch]].
     16 export fn arch_name(arch: arch) const str = {
     17 	switch (arch) {
     18 	case arch::AARCH64 =>
     19 		return "aarch64";
     20 	case arch::RISCV64 =>
     21 		return "riscv64";
     22 	case arch::X86_64 =>
     23 		return "x86_64";
     24 	};
     25 };
     26 
     27 let envp: []str = [];
     28 
     29 @fini fn envp() void = strings::freeall(envp);
     30 
     31 // Looks up an environment variable and returns its value, or void if unset.
     32 export fn getenv(name: const str) (str | void) = {
     33 	getenvs(); // populate envp
     34 	for (let ent .. envp) {
     35 		let (key, value) = strings::cut(ent, "=");
     36 		if (key == name) return value;
     37 	};
     38 };
     39 
     40 // Looks up an environment variable and returns its value, or a default value if
     41 // unset.
     42 export fn tryenv(name: const str, default: str) str = match (getenv(name)) {
     43 case let s: str => return s;
     44 case void => return default;
     45 };
     46 
     47 // Sets an environment variable, overwriting it if it's already set. The name
     48 // may not contain '=' or '\0', and the value may not contain '\0'.
     49 export fn setenv(name: const str, value: const str) (void | errors::invalid) = {
     50 	if (strings::contains(value, '\0')) return errors::invalid;
     51 	unsetenv(name)?;
     52 	append(envp, strings::join("=", name, value));
     53 };
     54 
     55 // Unsets an environment variable. Does nothing if the variable isn't set. The
     56 // name may not contain '=' or '\0'.
     57 export fn unsetenv(name: const str) (void | errors::invalid) = {
     58 	if (strings::contains(name, '=', '\0')) return errors::invalid;
     59 	getenvs(); // populate envp
     60 	for (let i = 0z; i < len(envp); i += 1) {
     61 		if (strings::cut(envp[i], "=").0 == name) {
     62 			free(envp[i]);
     63 			delete(envp[i]);
     64 			break;
     65 		};
     66 	};
     67 };