dotenv

Yet another dotenv utility for MoonBit.

dotenv
moonbit
moon add tonyfettes/dotenv@0.4.1
Download zip
Version
0.4.1
License
Apache-2.0
Last updated
last year
Downloads
23

Dependencies

README

#📄 dotenv-mbt: A MoonBit Environment Variable Loader

Build Status License codecov

dotenv-mbt is a utility library for loading environment variables from .env files in MoonBit applications. Inspired by Rust's dotenvy crate, it provides a simple and efficient way to manage configuration through environment files.

🚀 Key Features

  • 🔄 Environment Loading – Loads variables from .env files into your application
  • 🔍 Variable Substitution – Supports variable substitution in env files
  • đŸ› ī¸ Easy to Use – Simple API for quick integration
  • 🔒 Safe – Non-modifying API that doesn't affect the global environment
  • 🌟 MoonBit Native – Designed specifically for the MoonBit language


#đŸ“Ĩ Installation

moon add ShellWen/dotenv

#🚀 Usage Guide for dotenv-mbt

dotenv-mbt provides a simple way to load environment variables from files into your MoonBit applications.


#📝 What is an Environment File?

An environment file, or env file, is a plain text file consisting of key-value pairs:

.env

HOST=localhost PORT=3000 DATABASE_URL=mysql://user:pass@localhost/dbname

Common names for env files are .env, .env.dev, .env.prod, but any name can be used. The default path for this library is .env.


#🔍 Basic Usage

The simplest way to use dotenv-mbt is with the EnvLoader:

fn main {
let env_map = @dotenv.EnvLoader::new?().unwrap().load?().unwrap()
let host = env_map.get("HOST").unwrap()
println("HOST=\{host}")
}

#âš™ī¸ Configuration Options

dotenv-mbt offers several ways to configure the environment loader:

// Load from a specific file path
let loader1 = @dotenv.EnvLoader::from_path?("./.env.dev").unwrap()

// Default loader (equivalent to with_path("./.env"))
let loader2 = @dotenv.EnvLoader::new?().unwrap()


#🔄 Variable Access

After loading the environment, you can access variables using the get method:

let env_map = @dotenv.EnvLoader::new?().unwrap().load?().unwrap()

// Get a variable (returns Option)
let host = env_map.get("HOST").unwrap()

// Get with default value if not found
let port = match env_map.get("PORT") {
Some(p) => p
None => "8080"
}

// Check if a variable exists
if env_map.get("DATABASE_URL").is_some() {
// Do something with database URL
}


#🔀 Variable Substitution

dotenv-mbt supports variable substitution in env files:

.env

HOST=localhost URL=http://${HOST}:3000

When loaded, URL will contain http://localhost:3000.


#âš ī¸ Error Handling

dotenv-mbt uses MoonBit's Result type for error handling:

match @dotenv.EnvLoader::new?().unwrap().load?() {
Ok(env) =>
// Use environment variables
println("Loaded successfully")
Err(e) =>
// Handle error
println("Error loading .env file")
}


#đŸ› ī¸ Full Example

fn main {
// Load environment from .env file
let env = @dotenv.EnvLoader::new?().unwrap().load?().unwrap()

// Access variables
let host = env.get("HOST").unwrap()
let port = match env.get("PORT") {
Some(p) => p
None => "8080" // Default to 8080 if not set
}

// Use variables in your application
println("Server running at \{host}:\{port}")

// Check if a variable exists
if env.get("DEBUG").is_some() {
println("Debug mode enabled")
}
}

#đŸ“Ļ Project Structure

  1. dotenv-mbt - Core library for loading and parsing environment files.

#📚 Inspiration

This project is inspired by dotenvy, a well-maintained fork of the dotenv crate for Rust. While the API and implementation details are adapted for MoonBit, we follow similar principles and parsing rules.

The README of this project is inspired by NyaSearch.

#📜 License

This project is licensed under the Apache-2.0 License. See LICENSE for details.

#đŸ“ĸ Contact & Support

👋 If you like this project, give it a ⭐! Happy coding! 🚀

#
DotenvError

pub suberror DotenvError {
FileNotFound(String)
LineParseError(String, UInt)
Io(Error, String)
InvalidOp
}

#
ParseBufError

pub suberror ParseBufError {
LineParse(String, UInt)
}

#
EnvLoader

pub struct EnvLoader {
path : String?
// private fields
}

#
EnvLoader::from_path

fn EnvLoader::from_path(path : String) -> EnvLoader raise DotenvError

#
EnvLoader::from_string

fn EnvLoader::from_string(str : String) -> EnvLoader

#
EnvLoader::load

fn EnvLoader::load(self : EnvLoader) -> EnvMap raise DotenvError
Loads environment variables into a hash map.

This is the primary method for loading environment variables.

#
EnvLoader::load_and_modify

fn EnvLoader::load_and_modify(self : EnvLoader) -> EnvMap raise DotenvError
Loads environment variables into a hash map, modifying the existing environment.

This calls @sys.set_env_var internally.

#
EnvLoader::set_path

fn EnvLoader::set_path(self : EnvLoader, path : String?) -> EnvLoader
Sets the path to the specified path.

This is useful when constructing with a reader, but still desiring a path to be used in the error message context.

If a reader exists and a path is specified, loading will be done using the reader.

#
EnvLoader::set_sequence

fn EnvLoader::set_sequence(self : EnvLoader, sequence : EnvSequence) -> EnvLoader
Sets the sequence in which to load environment variables.

#
EnvMap

type EnvMap

#
EnvMap::get

fn EnvMap::get(self : EnvMap, name : String) -> String?

#
EnvSequence

pub(all) enum EnvSequence {
EnvOnly
EnvThenInput
InputOnly
InputThenEnv
}

#
load

fn load(path? : String, ignore_file_not_found? : Bool) -> EnvMap raise DotenvError
Shortcut for loading environment variables from a file.

#
load_and_modify

fn load_and_modify(path? : String, ignore_file_not_found? : Bool) -> EnvMap raise DotenvError
Shortcut for loading environment variables from a file and modifying the existing environment.

#
temp_env

fn[R, E : Error] temp_env(temp_envs : Map[String, String], f : () -> R raise E) -> R raise E
This function is for testing only. Do not use this in production code. It is not thread-safe.

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

Š 2026 mooncakes.io