Skip to content

Commit a776ab5

Browse files
committed
Add environment variable override for cookie configuration
Cookies can now be overridden using LEETCODE_CSRF, LEETCODE_SESSION, and LEETCODE_SITE environment variables when loading configuration.
1 parent f422206 commit a776ab5

File tree

2 files changed

+36
-7
lines changed

2 files changed

+36
-7
lines changed

src/config/cookies.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,27 @@ impl Display for Cookies {
6262
)
6363
}
6464
}
65+
66+
/// Override cookies from environment variables
67+
pub const LEETCODE_CSRF_ENV: &str = "LEETCODE_CSRF";
68+
pub const LEETCODE_SESSION_ENV: &str = "LEETCODE_SESSION";
69+
pub const LEETCODE_SITE_ENV: &str = "LEETCODE_SITE";
70+
71+
impl Cookies {
72+
/// Load cookies from environment variables, overriding any existing values
73+
/// if the environment variables are set.
74+
pub fn with_env_override(mut self) -> Self {
75+
if let Ok(csrf) = std::env::var(LEETCODE_CSRF_ENV) {
76+
self.csrf = csrf;
77+
}
78+
if let Ok(session) = std::env::var(LEETCODE_SESSION_ENV) {
79+
self.session = session;
80+
}
81+
if let Ok(site) = std::env::var(LEETCODE_SITE_ENV) {
82+
if let Ok(leetcode_site) = LeetcodeSite::from_str(&site) {
83+
self.site = leetcode_site;
84+
}
85+
}
86+
self
87+
}
88+
}

src/config/mod.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,19 @@ impl Config {
4646

4747
let s = fs::read_to_string(&conf)?;
4848
match toml::from_str::<Config>(&s) {
49-
Ok(config) => match config.cookies.site {
50-
cookies::LeetcodeSite::LeetcodeCom => Ok(config),
51-
cookies::LeetcodeSite::LeetcodeCn => {
52-
let mut config = config;
53-
config.sys.urls = sys::Urls::new_with_leetcode_cn();
54-
Ok(config)
49+
Ok(mut config) => {
50+
// Override config.cookies with environment variables
51+
config.cookies = config.cookies.with_env_override();
52+
53+
match config.cookies.site {
54+
cookies::LeetcodeSite::LeetcodeCom => Ok(config),
55+
cookies::LeetcodeSite::LeetcodeCn => {
56+
let mut config = config;
57+
config.sys.urls = sys::Urls::new_with_leetcode_cn();
58+
Ok(config)
59+
}
5560
}
56-
},
61+
}
5762
Err(e) => {
5863
let tmp = Self::root()?.join("leetcode.tmp.toml");
5964
Self::write_default(tmp)?;

0 commit comments

Comments
 (0)