Skip to content

Commit

Permalink
Add support for crate specific .env files
Browse files Browse the repository at this point in the history
This change will attempt to load an .env file from CARGO_MANIFEST_DIR, if it exists.

For backwards compatibility, if the .env file does not exist, we will fall back to default dotenv behaviour.

Resolves launchbadge#267
  • Loading branch information
xyzd committed Apr 19, 2020
1 parent 57f52ff commit 8dfd088
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions sqlx-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ macro_rules! async_macro (
let res: Result<proc_macro2::TokenStream> = block_on(async {
use sqlx::connection::Connect;

// If a .env file exists at CARGO_MANIFEST_DIR, load environment variables from this,
// otherwise fallback to default dotenv behaviour.
if let Ok(env_path) = std::env::var("CARGO_MANIFEST_DIR")
.map(|dir| std::path::PathBuf::from(dir).join(".env"))
{
if env_path.exists() {
dotenv::from_path(env_path.as_path())
.map_err(|e| format!("failed to load environment from {:?}, {}", env_path, e))?
}
}

let db_url = Url::parse(&dotenv::var("DATABASE_URL").map_err(|_| "DATABASE_URL not set")?)?;

match db_url.scheme() {
Expand Down

0 comments on commit 8dfd088

Please sign in to comment.