1use std::path::{Path, PathBuf};
2
3use jsonc_parser::errors::ParseError;
4use jsonc_parser::{parse_to_serde_value, parse_to_value};
5use serde_json::Value;
6
7use super::formats::{parse_toml_value, parse_yaml_value};
8use super::merge::parse_value_with_overrides;
9use super::schema_directive::{
10 JSONC_PARSE_OPTIONS, OFFICIAL_SCHEMA_PREFIX, OFFICIAL_SCHEMA_SUFFIX, resolve_schema_url,
11};
12use super::types::Configuration;
13use crate::config_error::{
14 CONFIGURATION_FILE_NAME, ConfigFileKind, ConfigSyntax, ConfigurationFileError, JsoncError,
15};
16use crate::resolved::{ConfigOverrides, ResolvedConfiguration};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum SchemaVersionStatus {
20 Missing,
21 Compatible {
22 url: String,
23 version: Option<String>,
24 },
25 NewerThanBinary {
26 url: String,
27 config_version: String,
28 binary_version: String,
29 },
30}
31
32#[derive(Debug)]
33pub enum ConfigurationInspection {
34 Missing {
35 path: PathBuf,
36 },
37 Valid {
38 kind: ConfigFileKind,
39 path: PathBuf,
40 schema: SchemaVersionStatus,
41 configuration: Box<Configuration>,
42 },
43 Invalid {
44 kind: Option<ConfigFileKind>,
45 path: PathBuf,
46 schema: Option<SchemaVersionStatus>,
47 error: ConfigurationFileError,
48 },
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct DiscoveredConfigFile {
53 pub kind: ConfigFileKind,
54 pub path: PathBuf,
55}
56
57pub fn read_configuration(repository_root: &Path) -> Result<Configuration, ConfigurationFileError> {
58 read_resolved_configuration(repository_root, &ConfigOverrides::default())
59 .map(|resolved| resolved.configuration)
60}
61
62pub fn parse_configuration_files(
63 files: &[(ConfigFileKind, &str)],
64) -> Result<Configuration, ConfigurationFileError> {
65 match files {
66 [] => Ok(Configuration::default()),
67 [(kind, text)] => parse_with_overrides(
68 *kind,
69 PathBuf::from(kind.file_name()),
70 true,
71 Some(text),
72 &ConfigOverrides::default(),
73 )
74 .map(|resolved| resolved.configuration),
75 many => Err(ConfigurationFileError::AmbiguousConfigFiles {
76 files: many.iter().map(|(kind, _)| *kind).collect(),
77 }),
78 }
79}
80
81fn path_exists_including_symlinks(
82 path: &Path,
83 file: ConfigFileKind,
84) -> Result<bool, ConfigurationFileError> {
85 match std::fs::symlink_metadata(path) {
86 Ok(_) => Ok(true),
87 Err(error)
88 if matches!(
89 error.kind(),
90 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
91 ) =>
92 {
93 Ok(false)
94 }
95 Err(source) => Err(ConfigurationFileError::Unreadable { file, source }),
96 }
97}
98
99pub fn discover_config_file(
100 repository_root: &Path,
101) -> Result<Option<DiscoveredConfigFile>, ConfigurationFileError> {
102 let mut found = Vec::new();
103 for kind in ConfigFileKind::ALL {
104 let path = repository_root.join(kind.file_name());
105 if path_exists_including_symlinks(&path, kind)? {
106 found.push(DiscoveredConfigFile { kind, path });
107 }
108 }
109 match found.len() {
110 0 => Ok(None),
111 1 => Ok(found.into_iter().next()),
112 _ => Err(ConfigurationFileError::AmbiguousConfigFiles {
113 files: found.into_iter().map(|entry| entry.kind).collect(),
114 }),
115 }
116}
117
118fn read_config_file(discovered: &DiscoveredConfigFile) -> Result<String, ConfigurationFileError> {
119 let file = discovered.kind;
120 match std::fs::read_to_string(&discovered.path) {
121 Ok(text) => Ok(text),
122 Err(error)
123 if error.kind() == std::io::ErrorKind::NotFound
124 && is_broken_symlink(&discovered.path) =>
125 {
126 Err(ConfigurationFileError::BrokenSymlink { file })
127 }
128 Err(source) => Err(ConfigurationFileError::Unreadable { file, source }),
129 }
130}
131
132fn jsonc_error_from_parse_error(error: &ParseError) -> JsoncError {
133 JsoncError {
134 message: error.kind().to_string(),
135 line: error.line_display(),
136 column: error.column_display(),
137 }
138}
139
140pub(crate) fn parse_jsonc(input: &str) -> Result<Value, JsoncError> {
141 let without_bom = input.strip_prefix('\u{FEFF}').unwrap_or(input);
142 let value: Value = parse_to_serde_value(without_bom, &JSONC_PARSE_OPTIONS)
143 .map_err(|error| jsonc_error_from_parse_error(&error))?;
144 if value.is_null()
145 && parse_to_value(without_bom, &JSONC_PARSE_OPTIONS)
146 .map_err(|error| jsonc_error_from_parse_error(&error))?
147 .is_none()
148 {
149 return Err(JsoncError {
150 message: "EOF while parsing a value".to_owned(),
151 line: 1,
152 column: 1,
153 });
154 }
155 Ok(value)
156}
157
158fn parse_config_document(
159 text: &str,
160 file: ConfigFileKind,
161) -> Result<Value, ConfigurationFileError> {
162 match file.syntax() {
163 ConfigSyntax::Json => parse_jsonc_value(text, file),
164 ConfigSyntax::Toml => parse_toml_value(text, file),
165 ConfigSyntax::Yaml => parse_yaml_value(text, file),
166 }
167}
168
169fn parse_jsonc_value(text: &str, file: ConfigFileKind) -> Result<Value, ConfigurationFileError> {
170 parse_jsonc(text).map_err(|source| ConfigurationFileError::InvalidJsonc { file, source })
171}
172
173pub fn is_broken_symlink(path: &Path) -> bool {
174 std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink())
175 && matches!(
176 std::fs::metadata(path),
177 Err(error) if error.kind() == std::io::ErrorKind::NotFound
178 )
179}
180
181pub fn read_resolved_configuration(
182 repository_root: &Path,
183 overrides: &ConfigOverrides,
184) -> Result<ResolvedConfiguration, ConfigurationFileError> {
185 match discover_config_file(repository_root)? {
186 Some(discovered) => {
187 let text = read_config_file(&discovered)?;
188 parse_with_overrides(
189 discovered.kind,
190 discovered.path,
191 true,
192 Some(&text),
193 overrides,
194 )
195 }
196 None => parse_with_overrides(
197 ConfigFileKind::Json,
198 repository_root.join(CONFIGURATION_FILE_NAME),
199 false,
200 None,
201 overrides,
202 ),
203 }
204}
205
206pub fn inspect_configuration(repository_root: &Path) -> ConfigurationInspection {
207 let discovered = match discover_config_file(repository_root) {
208 Ok(Some(discovered)) => discovered,
209 Ok(None) => {
210 return ConfigurationInspection::Missing {
211 path: repository_root.join(CONFIGURATION_FILE_NAME),
212 };
213 }
214 Err(error) => {
215 return ConfigurationInspection::Invalid {
216 kind: None,
217 path: repository_root.join(CONFIGURATION_FILE_NAME),
218 schema: None,
219 error,
220 };
221 }
222 };
223 let text = match read_config_file(&discovered) {
224 Ok(text) => text,
225 Err(error) => {
226 return ConfigurationInspection::Invalid {
227 kind: Some(discovered.kind),
228 path: discovered.path,
229 schema: None,
230 error,
231 };
232 }
233 };
234 let value = match parse_config_document(&text, discovered.kind) {
235 Ok(value) => value,
236 Err(error) => {
237 return ConfigurationInspection::Invalid {
238 kind: Some(discovered.kind),
239 path: discovered.path,
240 schema: None,
241 error,
242 };
243 }
244 };
245 let schema_url = match resolve_schema_url(discovered.kind, &text, &value) {
246 Ok(url) => url,
247 Err(error) => {
248 return ConfigurationInspection::Invalid {
249 kind: Some(discovered.kind),
250 path: discovered.path,
251 schema: None,
252 error,
253 };
254 }
255 };
256 let schema = inspect_schema_url(schema_url.as_deref(), env!("CARGO_PKG_VERSION"));
257 match parse_value_without_schema_version(discovered.kind, value) {
258 Ok(configuration) => ConfigurationInspection::Valid {
259 kind: discovered.kind,
260 path: discovered.path,
261 schema,
262 configuration: Box::new(configuration),
263 },
264 Err(error) => ConfigurationInspection::Invalid {
265 kind: Some(discovered.kind),
266 path: discovered.path,
267 schema: Some(schema),
268 error,
269 },
270 }
271}
272
273pub(super) fn parse_with_overrides(
274 config_file_kind: ConfigFileKind,
275 config_file: PathBuf,
276 config_file_present: bool,
277 text: Option<&str>,
278 overrides: &ConfigOverrides,
279) -> Result<ResolvedConfiguration, ConfigurationFileError> {
280 let raw = match text {
281 Some(text) => {
282 let value = parse_config_document(text, config_file_kind)?;
283 let schema_url = resolve_schema_url(config_file_kind, text, &value)?;
284 check_schema_url(schema_url.as_deref(), env!("CARGO_PKG_VERSION"))
285 .map_err(|error| error.with_file_kind(config_file_kind))?;
286 Some(value)
287 }
288 None => None,
289 };
290 parse_value_with_overrides(
291 config_file_kind,
292 config_file,
293 config_file_present,
294 raw,
295 overrides,
296 )
297 .map_err(|error| error.with_file_kind(config_file_kind))
298}
299
300fn parse_value_without_schema_version(
301 config_file_kind: ConfigFileKind,
302 value: Value,
303) -> Result<Configuration, ConfigurationFileError> {
304 parse_value_with_overrides(
305 config_file_kind,
306 PathBuf::from(config_file_kind.file_name()),
307 true,
308 Some(value),
309 &ConfigOverrides::default(),
310 )
311 .map(|resolved| resolved.configuration)
312 .map_err(|error| error.with_file_kind(config_file_kind))
313}
314
315fn inspect_schema_url(schema_url: Option<&str>, binary_version: &str) -> SchemaVersionStatus {
316 let Some(schema_url) = schema_url else {
317 return SchemaVersionStatus::Missing;
318 };
319 let Some(config_version) = extract_official_schema_version(schema_url) else {
320 return SchemaVersionStatus::Compatible {
321 url: schema_url.to_owned(),
322 version: None,
323 };
324 };
325 let (Some(cfg), Some(bin)) = (parse_semver(config_version), parse_semver(binary_version))
326 else {
327 return SchemaVersionStatus::Compatible {
328 url: schema_url.to_owned(),
329 version: Some(config_version.to_owned()),
330 };
331 };
332 if cfg > bin {
333 return SchemaVersionStatus::NewerThanBinary {
334 url: schema_url.to_owned(),
335 config_version: config_version.to_owned(),
336 binary_version: binary_version.to_owned(),
337 };
338 }
339 SchemaVersionStatus::Compatible {
340 url: schema_url.to_owned(),
341 version: Some(config_version.to_owned()),
342 }
343}
344
345fn check_schema_url(
346 schema_url: Option<&str>,
347 binary_version: &str,
348) -> Result<(), ConfigurationFileError> {
349 if let SchemaVersionStatus::NewerThanBinary {
350 config_version,
351 binary_version,
352 ..
353 } = inspect_schema_url(schema_url, binary_version)
354 {
355 return Err(ConfigurationFileError::NewerSchemaVersion {
356 file: ConfigFileKind::Json,
357 config_version,
358 binary_version,
359 });
360 }
361 Ok(())
362}
363
364#[cfg(test)]
365pub(super) fn check_schema_version(
366 value: &Value,
367 binary_version: &str,
368) -> Result<(), ConfigurationFileError> {
369 let schema_url = value.get("$schema").and_then(Value::as_str);
370 check_schema_url(schema_url, binary_version)
371}
372
373fn extract_official_schema_version(url: &str) -> Option<&str> {
374 url.strip_prefix(OFFICIAL_SCHEMA_PREFIX)?
375 .strip_suffix(OFFICIAL_SCHEMA_SUFFIX)
376}
377
378fn parse_semver(raw: &str) -> Option<(u64, u64, u64)> {
379 let core = raw.split(['-', '+']).next()?;
380 let mut parts = core.split('.');
381 let major = parts.next()?.parse().ok()?;
382 let minor = parts.next()?.parse().ok()?;
383 let patch = parts.next()?.parse().ok()?;
384 if parts.next().is_some() {
385 return None;
386 }
387 Some((major, minor, patch))
388}