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