1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//! # Overview
//! This crate allows you to load .env files in your compilation step.
//! It is built to be used in your **[build.rs](https://doc.rust-lang.org/cargo/reference/build-scripts.html)** file.
//!
//! # Usage
//!
//! 1. Ensure you have build scripts enabled via the `build` configuration in your `Cargo.toml`
//! 1. Add `dotenv-build` as a build dependency
//! 1. Create a `build.rs` file that uses `dotenv-build` to generate `cargo:` instructions.
//! 1. Use the [`env!`](std::env!) or [`option_env!`](std::option_env!) macro in your code
//!
//! ### Cargo.toml
//! ```toml
//! [package]
//! #..
//! build = "build.rs"
//!
//! [dependencies]
//! #..
//!
//! [build-dependencies]
//! dotenv-build = "0.1"
//! ```
//!
//! ### build.rs
//! ```
//! // in build.rs
//! fn main() {
//!     dotenv_build::output(dotenv_build::Config::default()).unwrap();
//! }
//! ```
//!
//! ### Use in code
//! ```ignore
//! println!("Your environment variable in .env: {}", env!("TEST_VARIABLE"));
//! ```
//!
//! [build scripts]: https://doc.rust-lang.org/cargo/reference/build-scripts.html
//! [cargo:rustc-env]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-env
//! [cargo:rerun-if-changed]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed
//!
//! ### Configuration
//!
//! Read more about the available options here: [`Config`]
//! ```ignore
//! let config = dotenv_build::Config {
//!   recursive_search: false,
//!   fail_if_missing_dotenv: true,
//!    ..Default::default()
//! };
//!
//! dotenv_build::output(config).unwrap();
//! ```

mod errors;
mod find;
mod iter;
mod parse;

use std::io;
use std::io::Write;
use std::path::Path;

use crate::errors::*;

/// Config for [`output`]
pub struct Config<'a> {
    /// The filename that is getting read for the environment variables. Defaults to `.env`
    pub filename: &'a Path,
    /// This specifies if we should search for the file recursively upwards in the file tree.
    /// Defaults to `true`.
    pub recursive_search: bool,
    /// This specifies if we should return an error if we don't find the file. Defaults to `false`.
    pub fail_if_missing_dotenv: bool,
}

impl<'a> Default for Config<'a> {
    fn default() -> Self {
        Config {
            filename: Path::new(".env"),
            recursive_search: true,
            fail_if_missing_dotenv: false,
        }
    }
}

/// Outputs the necessary [build.rs](https://doc.rust-lang.org/cargo/reference/build-scripts.html) instructions.
///
/// ## Example
///
/// _.env_:
/// ```text
/// RUST_LOG=debug
/// RUST_BACKTRACE=1
///
/// ## comment
/// TEST="hello world!"
/// ANOTHER_ONE=test
/// ```
///
/// _output_:
/// ```text
/// cargo:rustc-env=RUST_LOG=debug
/// cargo:rustc-env=RUST_BACKTRACE=1
/// cargo:rustc-env=TEST=hello world!
/// cargo:rustc-env=ANOTHER_ONE=test
/// cargo:rerun-if-changed=$PATH_TO_YOUR_FILE/.env
/// ```
pub fn output(config: Config) -> Result<()> {
    output_write_to(config, &mut io::stdout())
}

fn output_write_to<T>(config: Config, stdout: &mut T) -> Result<()>
where
    T: Write,
{
    let (path, lines) = match find::find(&config) {
        Ok(res) => res,
        Err(err) if err.not_found() => {
            return if config.fail_if_missing_dotenv {
                eprintln!("[dotenv-build] .env file not found, err: {}", err);
                Err(err)
            } else {
                Ok(())
            };
        }
        Err(err) => return Err(err),
    };

    for line in lines {
        let (key, value) = match line {
            Ok(l) => l,
            Err(err) => {
                eprintln!("[dotenv-build] {}", err);
                return Err(err);
            }
        };

        writeln!(stdout, "cargo:rustc-env={}={}", key, value)?;
    }

    writeln!(stdout, "cargo:rerun-if-changed={}", path.to_str().unwrap())?;
    Ok(())
}