1use std::ffi::OsStr;
4use std::path::Path;
5use std::path::PathBuf;
6use std::sync::Mutex;
7use std::sync::MutexGuard;
8
9use anyhow::Context as _;
10use anyhow::Result;
11use anyhow::bail;
12use cargo_util::collections::HashMap;
13use cargo_util::collections::HashSet;
14use cargo_util::is_glob_pattern;
15use cargo_util::paths;
16use cargo_util_terminal::Shell;
17use cargo_util_terminal::report::Level;
18
19use super::ConfigValue;
20use super::Scope;
21use super::schema::{DetailedIncludeConfig, IncludeConfig};
22use super::{ConfigKey, ConfigReader, ConfigStore};
23
24use ConfigValue as CV;
25
26#[derive(Clone, Copy)]
28pub struct ConfigLoader<'a> {
29 shell: &'a Mutex<Shell>,
30 current_dir: &'a Path,
31 cargo_home: &'a Path,
32 search_stop_path: Option<&'a Path>,
33}
34
35impl<'a> ConfigLoader<'a> {
36 pub fn new(shell: &'a Mutex<Shell>, current_dir: &'a Path, cargo_home: &'a Path) -> Self {
41 Self {
42 shell,
43 current_dir,
44 cargo_home,
45 search_stop_path: None,
46 }
47 }
48
49 #[must_use]
53 pub fn search_stop_path(mut self, path: Option<&'a Path>) -> Self {
54 self.search_stop_path = path;
55 self
56 }
57
58 pub fn load_layers(&self, path: &Path) -> Result<Vec<ConfigStore>> {
62 let mut result = Vec::new();
63 self.walk_tree(path, |path| {
64 let mut layers = Vec::new();
65 self.load_file_layers(path, &mut HashSet::default(), Scope::Path, &mut layers)?;
66 result.splice(..0, layers);
70 Ok(())
71 })
72 .context("could not load Cargo configuration")?;
73 Ok(result)
74 }
75
76 fn load_file_layers(
78 &self,
79 path: &Path,
80 seen: &mut HashSet<PathBuf>,
81 scope: Scope,
82 output: &mut Vec<ConfigStore>,
83 ) -> Result<()> {
84 if !seen.insert(path.to_path_buf()) {
85 bail!(
86 "config `include` cycle detected with path `{}`",
87 path.display()
88 );
89 }
90 tracing::debug!(?path, ?scope, "load config from file");
91 let config = ConfigStore::read_layer(path, scope)?;
92 self.load_include_layers(&config, seen, output)?;
93 output.push(config);
94 Ok(())
95 }
96
97 fn load_include_layers(
99 &self,
100 config: &ConfigStore,
101 seen: &mut HashSet<PathBuf>,
102 output: &mut Vec<ConfigStore>,
103 ) -> Result<()> {
104 for include in self.include_paths(config)? {
105 let Some(abs_path) = include.resolve_path(self.current_dir) else {
106 continue;
107 };
108 self.load_file_layers(&abs_path, seen, config.definition().scope(), output)
109 .with_context(|| {
110 format!(
111 "failed to load config include `{}` from `{}`",
112 include.path,
113 include.path.definition()
114 )
115 })?;
116 }
117 Ok(())
118 }
119
120 fn include_paths(&self, config: &ConfigStore) -> Result<Vec<DetailedIncludeConfig>> {
122 let entries: Vec<IncludeConfig> = ConfigReader::new(self.shell)
123 .config(config)
124 .get(ConfigKey::from_parts(["include"]))?;
125 let includes: Vec<_> = entries
126 .into_iter()
127 .map(IncludeConfig::into_detailed)
128 .collect();
129
130 for include in &includes {
131 let path = &include.path;
132 if path.extension() != Some(OsStr::new("toml")) {
133 bail!(
134 "expected a config include path ending with `.toml`, \
135 but found `{}` from `{}`",
136 path,
137 path.definition(),
138 )
139 }
140
141 if is_glob_pattern(path.as_str()) {
142 bail!(
143 "expected a config include path without glob patterns, \
144 but found `{}` from `{}`",
145 path,
146 path.definition(),
147 )
148 }
149 if path.as_str().contains(&['{', '}']) {
150 bail!(
151 "expected a config include path without template braces, \
152 but found `{}` from `{}`",
153 path,
154 path.definition(),
155 )
156 }
157 }
158
159 Ok(includes)
160 }
161
162 pub fn load_cli_args_layer(&self, cli_args: &[String]) -> Result<ConfigStore> {
167 let mut loaded_args = ConfigStore::default();
168 let mut seen = HashSet::default();
169 for arg in cli_args {
170 let mut layers = Vec::new();
171 let arg_as_path = self.current_dir.join(arg);
172 if !arg.is_empty() && arg_as_path.exists() {
173 self.load_file_layers(&arg_as_path, &mut seen, Scope::Cli, &mut layers)
175 .with_context(|| {
176 format!("failed to load config from `{}`", arg_as_path.display())
177 })?;
178 } else {
179 let config = ConfigStore::parse_cli_key_value(arg)?;
180 self.load_include_layers(&config, &mut HashSet::default(), &mut layers)
181 .context("failed to load --config include")?;
182 layers.push(config);
183 }
184 loaded_args = ConfigStore::from_layers(std::iter::once(loaded_args).chain(layers))
185 .with_context(|| format!("failed to merge --config argument `{arg}`"))?;
186 }
187 Ok(loaded_args)
188 }
189
190 pub fn get_file_path(
196 &self,
197 dir: &Path,
198 file_stem: &str,
199 warn: bool,
200 ) -> Result<Option<PathBuf>> {
201 let possible = dir.join(file_stem);
202 let possible_with_extension = dir.join(format!("{}.toml", file_stem));
203
204 if let Ok(possible_handle) = same_file::Handle::from_path(&possible) {
205 if warn {
206 if let Ok(possible_with_extension_handle) =
207 same_file::Handle::from_path(&possible_with_extension)
208 {
209 if possible_handle != possible_with_extension_handle {
215 self.shell().warn(format!(
216 "both `{}` and `{}` exist. Using `{}`",
217 possible.display(),
218 possible_with_extension.display(),
219 possible.display()
220 ))?;
221 }
222 } else {
223 self.shell().print_report(&[
224 Level::WARNING.secondary_title(
225 format!(
226 "`{}` is deprecated in favor of `{file_stem}.toml`",
227 possible.display(),
228 )).element(Level::HELP.message(
229 format!("if you need to support cargo 1.38 or earlier, you can symlink `{file_stem}` to `{file_stem}.toml`")))
230 ], false)?;
231 }
232 }
233
234 Ok(Some(possible))
235 } else if possible_with_extension.exists() {
236 Ok(Some(possible_with_extension))
237 } else {
238 Ok(None)
239 }
240 }
241
242 fn walk_tree<F>(&self, pwd: &Path, mut walk: F) -> Result<()>
243 where
244 F: FnMut(&Path) -> Result<()>,
245 {
246 let home = self.cargo_home;
247 let mut seen_dir = HashSet::default();
248
249 for current in paths::ancestors(pwd, self.search_stop_path) {
250 let config_root = current.join(".cargo");
251 if let Some(path) = self.get_file_path(&config_root, "config", true)? {
252 walk(&path)?;
253 }
254
255 let canonical_root = config_root.canonicalize().unwrap_or(config_root);
256 seen_dir.insert(canonical_root);
257 }
258
259 let canonical_home = home.canonicalize().unwrap_or(home.to_path_buf());
260
261 if !seen_dir.contains(&canonical_home) && !seen_dir.contains(home) {
265 if let Some(path) = self.get_file_path(home, "config", true)? {
266 walk(&path)?;
267 }
268 }
269
270 Ok(())
271 }
272
273 pub fn load_credentials(&self) -> Result<ConfigStore> {
275 let Some(credentials) = self.get_file_path(self.cargo_home, "credentials", true)? else {
276 return Ok(ConfigStore::default());
277 };
278
279 let mut config = ConfigStore::read_layer(&credentials, Scope::Path)?;
280 {
282 let def = config.definition().clone();
283 let value_map = config.values_mut();
284
285 if let Some(token) = value_map.remove("token") {
286 value_map.entry("registry".into()).or_insert_with(|| {
287 let map = HashMap::from_iter([("token".into(), token)]);
288 CV::Table(map, def.clone())
289 });
290 }
291 }
292
293 Ok(config)
294 }
295
296 fn shell(&self) -> MutexGuard<'_, Shell> {
297 self.shell.lock().unwrap()
298 }
299}