-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathmetadata.rs
More file actions
181 lines (154 loc) · 5.68 KB
/
metadata.rs
File metadata and controls
181 lines (154 loc) · 5.68 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use sqlx_core::config::Config;
use std::hash::{BuildHasherDefault, DefaultHasher};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::query::cache::{MtimeCache, MtimeCacheBuilder};
use sqlx_core::HashMap;
pub struct Metadata {
pub manifest_dir: PathBuf,
pub config: Config,
env: MtimeCache<Arc<MacrosEnv>>,
workspace_root: Arc<Mutex<Option<PathBuf>>>,
}
pub struct MacrosEnv {
pub database_url: Option<String>,
pub offline_dir: Option<PathBuf>,
pub offline: Option<bool>,
}
impl Metadata {
pub fn env(&self) -> crate::Result<Arc<MacrosEnv>> {
let workspace_root = self.workspace_root();
self.env.get_or_try_init(|builder| {
load_env(&self.manifest_dir, &workspace_root, &self.config, builder)
})
}
pub fn workspace_root(&self) -> PathBuf {
let mut root = self.workspace_root.lock().unwrap();
if root.is_none() {
use serde::Deserialize;
use std::process::Command;
let cargo = crate::env("CARGO").unwrap();
let output = Command::new(cargo)
.args(["metadata", "--format-version=1", "--no-deps"])
.current_dir(&self.manifest_dir)
.env_remove("__CARGO_FIX_PLZ")
.output()
.expect("Could not fetch metadata");
#[derive(Deserialize)]
struct CargoMetadata {
workspace_root: PathBuf,
}
let metadata: CargoMetadata =
serde_json::from_slice(&output.stdout).expect("Invalid `cargo metadata` output");
*root = Some(metadata.workspace_root);
}
root.clone().unwrap()
}
}
pub fn try_for_crate() -> crate::Result<Arc<Metadata>> {
/// The `MtimeCache` in this type covers the config itself,
/// any changes to which will indirectly invalidate the loaded env vars as well.
#[expect(clippy::type_complexity)]
static METADATA: Mutex<
HashMap<String, Arc<MtimeCache<Arc<Metadata>>>, BuildHasherDefault<DefaultHasher>>,
> = Mutex::new(HashMap::with_hasher(BuildHasherDefault::new()));
let manifest_dir = crate::env("CARGO_MANIFEST_DIR")?;
let cache = METADATA
.lock()
.expect("BUG: we shouldn't panic while holding this lock")
.entry_ref(&manifest_dir)
.or_insert_with(|| Arc::new(MtimeCache::new()))
.clone();
cache.get_or_try_init(|builder| {
let manifest_dir = PathBuf::from(manifest_dir);
let config_path = manifest_dir.join("sqlx.toml");
builder.add_path(config_path.clone());
let config = Config::try_from_path_or_default(config_path)?;
Ok(Arc::new(Metadata {
manifest_dir,
config,
env: MtimeCache::new(),
workspace_root: Default::default(),
}))
})
}
fn load_env(
manifest_dir: &Path,
workspace_root: &Path,
config: &Config,
builder: &mut MtimeCacheBuilder,
) -> crate::Result<Arc<MacrosEnv>> {
#[derive(thiserror::Error, Debug)]
#[error("error reading dotenv file {path:?}")]
struct DotenvError {
path: PathBuf,
#[source]
error: dotenvy::Error,
}
let mut from_dotenv = MacrosEnv {
database_url: None,
offline_dir: None,
offline: None,
};
// https://github.com/launchbadge/sqlx/issues/4276
let dirs = if manifest_dir.starts_with(workspace_root) {
// Often just `[manifest_dir, workspace_dir]` but project structures can absolutely
// be more complicated
manifest_dir
.ancestors()
.take_while(|dir| dir.starts_with(workspace_root))
.collect::<Vec<_>>()
} else {
// Thinking of edge cases, there's the possibility that the package directory
// isn't actually a child of the workspace directory. There isn't really any other sane
// thing to do here; we shouldn't traverse into unrelated paths.
[manifest_dir, workspace_root].to_vec()
};
for dir in dirs {
let path = dir.join(".env");
let dotenv = match dotenvy::from_path_iter(&path) {
Ok(iter) => {
builder.add_path(path.clone());
iter
}
Err(dotenvy::Error::Io(e)) if e.kind() == io::ErrorKind::NotFound => {
builder.add_path(dir.to_path_buf());
continue;
}
Err(e) => {
builder.add_path(path.clone());
return Err(DotenvError { path, error: e }.into());
}
};
for res in dotenv {
let (name, val) = res.map_err(|e| DotenvError {
path: path.clone(),
error: e,
})?;
match &*name {
"SQLX_OFFLINE_DIR" => from_dotenv.offline_dir = Some(val.into()),
"SQLX_OFFLINE" => from_dotenv.offline = Some(is_truthy_bool(&val)),
_ if name == config.common.database_url_var() => {
from_dotenv.database_url = Some(val)
}
_ => continue,
}
}
}
Ok(Arc::new(MacrosEnv {
// Make set variables take precedent
database_url: crate::env_opt(config.common.database_url_var())?
.or(from_dotenv.database_url),
offline_dir: crate::env_opt("SQLX_OFFLINE_DIR")?
.map(PathBuf::from)
.or(from_dotenv.offline_dir),
offline: crate::env_opt("SQLX_OFFLINE")?
.map(|val| is_truthy_bool(&val))
.or(from_dotenv.offline),
}))
}
/// Returns `true` if `val` is `"true"`,
fn is_truthy_bool(val: &str) -> bool {
val.eq_ignore_ascii_case("true") || val == "1"
}