Skip to main content

codeint_config/config_file/
schema_directive.rs

1use std::ops::Range;
2
3use jsonc_parser::{CollectOptions, ParseOptions, parse_to_ast};
4use serde_json::Value;
5
6use super::formats::{parse_toml_value, parse_yaml_value};
7use crate::config_error::{ConfigFileKind, ConfigSyntax, ConfigurationFileError};
8
9pub(super) const OFFICIAL_SCHEMA_PREFIX: &str =
10    "https://raw.githubusercontent.com/avidianity/codeint/v";
11pub(super) const OFFICIAL_SCHEMA_SUFFIX: &str = "/schema/codeint.schema.json";
12const OFFICIAL_TAG_URL_PREFIX: &str = "https://raw.githubusercontent.com/avidianity/codeint/";
13
14pub(super) const JSONC_PARSE_OPTIONS: ParseOptions = ParseOptions {
15    allow_comments: true,
16    allow_trailing_commas: true,
17    allow_loose_object_property_names: false,
18    allow_missing_commas: false,
19    allow_single_quoted_strings: false,
20    allow_hexadecimal_numbers: false,
21    allow_unary_plus_numbers: false,
22    allow_bare_decimal_point_numbers: false,
23    allow_non_finite_numbers: false,
24    allow_extended_string_escapes: false,
25};
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SchemaValueSpan {
29    pub span: Range<usize>,
30    pub value: String,
31}
32
33pub fn schema_value_span(text: &str) -> Option<SchemaValueSpan> {
34    let without_bom = text.strip_prefix('\u{FEFF}').unwrap_or(text);
35    let bom_len = text.len() - without_bom.len();
36    let parsed = parse_to_ast(
37        without_bom,
38        &CollectOptions::default(),
39        &JSONC_PARSE_OPTIONS,
40    )
41    .ok()?;
42    let value = parsed.value?;
43    let object = value.as_object()?;
44    let property = object
45        .properties
46        .iter()
47        .rev()
48        .find(|property| property.name.as_str() == "$schema")?;
49    let jsonc_parser::ast::Value::StringLit(schema) = &property.value else {
50        return None;
51    };
52    Some(SchemaValueSpan {
53        span: (schema.range.start + bom_len)..(schema.range.end + bom_len),
54        value: schema.value.to_string(),
55    })
56}
57
58pub(super) fn resolve_schema_url(
59    kind: ConfigFileKind,
60    text: &str,
61    value: &Value,
62) -> Result<Option<String>, ConfigurationFileError> {
63    let directives = extract_schema_directives(kind, text)?;
64    let directive_url = directives.first().map(|span| span.value.as_str());
65    let key_url = value.get("$schema").and_then(Value::as_str);
66    match (directive_url, key_url) {
67        (Some(directive), Some(key)) if directive != key => {
68            Err(ConfigurationFileError::ConflictingSchemaDirectives {
69                file: kind,
70                first_label: "its leading schema comment",
71                first_url: directive.to_owned(),
72                second_label: "$schema key",
73                second_url: key.to_owned(),
74            })
75        }
76        (Some(directive), _) => Ok(Some(directive.to_owned())),
77        (None, Some(key)) => Ok(Some(key.to_owned())),
78        (None, None) => Ok(None),
79    }
80}
81
82fn extract_schema_directives(
83    kind: ConfigFileKind,
84    text: &str,
85) -> Result<Vec<SchemaValueSpan>, ConfigurationFileError> {
86    let syntax = kind.syntax();
87    if syntax == ConfigSyntax::Json {
88        return Ok(Vec::new());
89    }
90    let without_bom = text.strip_prefix('\u{FEFF}').unwrap_or(text);
91    let mut offset = text.len() - without_bom.len();
92    let mut found: Vec<SchemaValueSpan> = Vec::new();
93    for raw_line in without_bom.split_inclusive('\n') {
94        let line = raw_line.trim_end_matches(['\r', '\n']);
95        let trimmed = line.trim_start();
96        if trimmed.is_empty() {
97            offset += raw_line.len();
98            continue;
99        }
100        if !trimmed.starts_with('#') {
101            break;
102        }
103        let line_start = offset + (line.len() - trimmed.len());
104        if let Some(span) = parse_directive_line(syntax, trimmed, line_start) {
105            record_directive(kind, &mut found, span)?;
106        }
107        offset += raw_line.len();
108    }
109    Ok(found)
110}
111
112fn record_directive(
113    file: ConfigFileKind,
114    found: &mut Vec<SchemaValueSpan>,
115    next: SchemaValueSpan,
116) -> Result<(), ConfigurationFileError> {
117    if let Some(existing) = found.first()
118        && existing.value != next.value
119    {
120        return Err(ConfigurationFileError::ConflictingSchemaDirectives {
121            file,
122            first_label: "a leading schema comment",
123            first_url: existing.value.clone(),
124            second_label: "another leading schema comment",
125            second_url: next.value,
126        });
127    }
128    found.push(next);
129    Ok(())
130}
131
132fn parse_directive_line(
133    syntax: ConfigSyntax,
134    trimmed: &str,
135    line_start: usize,
136) -> Option<SchemaValueSpan> {
137    match syntax {
138        ConfigSyntax::Toml => parse_toml_schema_directive(trimmed, line_start),
139        ConfigSyntax::Yaml => parse_yaml_schema_directive(trimmed, line_start),
140        ConfigSyntax::Json => None,
141    }
142}
143
144fn parse_toml_schema_directive(trimmed: &str, line_start: usize) -> Option<SchemaValueSpan> {
145    let after_prefix = trimmed.strip_prefix("#:schema")?;
146    if !after_prefix.chars().next()?.is_whitespace() {
147        return None;
148    }
149    extract_url_token(trimmed, after_prefix, line_start)
150}
151
152fn parse_yaml_schema_directive(trimmed: &str, line_start: usize) -> Option<SchemaValueSpan> {
153    let after_hash = trimmed.strip_prefix('#')?.trim_start();
154    let after_ls = after_hash
155        .strip_prefix("yaml-language-server:")?
156        .trim_start();
157    let after_key = after_ls.strip_prefix("$schema=")?;
158    extract_url_token(trimmed, after_key, line_start)
159}
160
161fn strip_inline_hash_comment(text: &str) -> &str {
162    let bytes = text.as_bytes();
163    for (index, &byte) in bytes.iter().enumerate() {
164        if byte == b'#' && index > 0 && matches!(bytes[index - 1], b' ' | b'\t') {
165            return text[..index].trim_end();
166        }
167    }
168    text.trim_end()
169}
170
171fn extract_url_token(
172    full_trimmed: &str,
173    after_marker: &str,
174    line_start: usize,
175) -> Option<SchemaValueSpan> {
176    let value_slice = strip_inline_hash_comment(after_marker.trim_start());
177    if value_slice.is_empty() || value_slice.chars().any(char::is_whitespace) {
178        return None;
179    }
180    let rel_start = value_slice.as_ptr() as usize - full_trimmed.as_ptr() as usize;
181    let start = line_start + rel_start;
182    Some(SchemaValueSpan {
183        span: start..(start + value_slice.len()),
184        value: value_slice.to_owned(),
185    })
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum RewrittenSchemaForm {
190    JsonKey,
191    TomlDirective,
192    TomlKey,
193    TomlDirectiveAndKey,
194    YamlDirective,
195    YamlKey,
196    YamlDirectiveAndKey,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct RewrittenSchema {
201    pub text: String,
202    pub url: String,
203    pub form: RewrittenSchemaForm,
204}
205
206struct Replacement {
207    span: Range<usize>,
208    text: String,
209}
210
211pub fn rewrite_schema_tag(
212    kind: ConfigFileKind,
213    text: &str,
214    target_tag: &str,
215) -> Option<RewrittenSchema> {
216    match kind.syntax() {
217        ConfigSyntax::Json => rewrite_json_schema_tag(text, target_tag),
218        ConfigSyntax::Toml | ConfigSyntax::Yaml => {
219            rewrite_toml_or_yaml_schema_tag(kind, text, target_tag)
220        }
221    }
222}
223
224fn updated_official_url(current_url: &str, target_tag: &str) -> Option<String> {
225    let rest = current_url.strip_prefix(OFFICIAL_TAG_URL_PREFIX)?;
226    let current_ref = rest.strip_suffix(OFFICIAL_SCHEMA_SUFFIX)?;
227    if current_ref.is_empty() || current_ref.contains('/') || current_ref == target_tag {
228        return None;
229    }
230    Some(format!(
231        "{OFFICIAL_TAG_URL_PREFIX}{target_tag}{OFFICIAL_SCHEMA_SUFFIX}"
232    ))
233}
234
235fn rewrite_json_schema_tag(text: &str, target_tag: &str) -> Option<RewrittenSchema> {
236    let schema = schema_value_span(text)?;
237    let new_url = updated_official_url(&schema.value, target_tag)?;
238    let updated = apply_replacements(
239        text,
240        vec![Replacement {
241            span: schema.span,
242            text: format!("\"{new_url}\""),
243        }],
244    )?;
245    Some(RewrittenSchema {
246        text: updated,
247        url: new_url,
248        form: RewrittenSchemaForm::JsonKey,
249    })
250}
251
252fn parse_structured_document(kind: ConfigFileKind, text: &str) -> Option<Value> {
253    match kind.syntax() {
254        ConfigSyntax::Toml => parse_toml_value(text, kind).ok(),
255        ConfigSyntax::Yaml => parse_yaml_value(text, kind).ok(),
256        ConfigSyntax::Json => None,
257    }
258}
259
260fn rewrite_toml_or_yaml_schema_tag(
261    kind: ConfigFileKind,
262    text: &str,
263    target_tag: &str,
264) -> Option<RewrittenSchema> {
265    let value = parse_structured_document(kind, text)?;
266    let active_url = resolve_schema_url(kind, text, &value).ok()??;
267    let new_url = updated_official_url(&active_url, target_tag)?;
268    let (replacements, form) = collect_structured_replacements(kind, text, &value, &new_url)?;
269    let updated = apply_replacements(text, replacements)?;
270    let reparsed = parse_structured_document(kind, &updated)?;
271    let verified = resolve_schema_url(kind, &updated, &reparsed).ok()??;
272    (verified == new_url).then_some(RewrittenSchema {
273        text: updated,
274        url: new_url,
275        form,
276    })
277}
278
279fn collect_structured_replacements(
280    kind: ConfigFileKind,
281    text: &str,
282    value: &Value,
283    new_url: &str,
284) -> Option<(Vec<Replacement>, RewrittenSchemaForm)> {
285    let directives = extract_schema_directives(kind, text).ok()?;
286    let has_directive = !directives.is_empty();
287    let mut replacements: Vec<Replacement> = directives
288        .into_iter()
289        .map(|span| Replacement {
290            span: span.span,
291            text: new_url.to_owned(),
292        })
293        .collect();
294    let mut has_key = false;
295    if let Some(expected_key_url) = value.get("$schema").and_then(Value::as_str) {
296        let key_span = unique_top_level_key_schema_span(kind.syntax(), text, expected_key_url)?;
297        let original = text.get(key_span.span.clone())?;
298        replacements.push(Replacement {
299            span: key_span.span,
300            text: format_scalar_replacement(original, new_url),
301        });
302        has_key = true;
303    }
304    let form = structured_schema_form(kind.syntax(), has_directive, has_key)?;
305    Some((replacements, form))
306}
307
308fn structured_schema_form(
309    syntax: ConfigSyntax,
310    has_directive: bool,
311    has_key: bool,
312) -> Option<RewrittenSchemaForm> {
313    match (syntax, has_directive, has_key) {
314        (ConfigSyntax::Toml, true, true) => Some(RewrittenSchemaForm::TomlDirectiveAndKey),
315        (ConfigSyntax::Toml, true, false) => Some(RewrittenSchemaForm::TomlDirective),
316        (ConfigSyntax::Toml, false, true) => Some(RewrittenSchemaForm::TomlKey),
317        (ConfigSyntax::Yaml, true, true) => Some(RewrittenSchemaForm::YamlDirectiveAndKey),
318        (ConfigSyntax::Yaml, true, false) => Some(RewrittenSchemaForm::YamlDirective),
319        (ConfigSyntax::Yaml, false, true) => Some(RewrittenSchemaForm::YamlKey),
320        _ => None,
321    }
322}
323
324fn format_scalar_replacement(original: &str, new_url: &str) -> String {
325    if original.starts_with('"') && original.ends_with('"') {
326        format!("\"{new_url}\"")
327    } else if original.starts_with('\'') && original.ends_with('\'') {
328        format!("'{new_url}'")
329    } else {
330        new_url.to_owned()
331    }
332}
333
334fn unique_top_level_key_schema_span(
335    syntax: ConfigSyntax,
336    text: &str,
337    expected_value: &str,
338) -> Option<SchemaValueSpan> {
339    let without_bom = text.strip_prefix('\u{FEFF}').unwrap_or(text);
340    let mut offset = text.len() - without_bom.len();
341    let mut matched: Option<SchemaValueSpan> = None;
342    for raw_line in without_bom.split_inclusive('\n') {
343        let line = raw_line.trim_end_matches(['\r', '\n']);
344        if syntax == ConfigSyntax::Toml && line.trim_start().starts_with('[') {
345            break;
346        }
347        if let Some(span) = parse_top_level_schema_key_line(syntax, line, offset)
348            && span.value == expected_value
349        {
350            if matched.is_some() {
351                return None;
352            }
353            matched = Some(span);
354        }
355        offset += raw_line.len();
356    }
357    matched
358}
359
360fn parse_top_level_schema_key_line(
361    syntax: ConfigSyntax,
362    line: &str,
363    line_offset: usize,
364) -> Option<SchemaValueSpan> {
365    let rest = match syntax {
366        ConfigSyntax::Toml => strip_toml_schema_assignment(line)?,
367        ConfigSyntax::Yaml => strip_yaml_schema_assignment(line)?,
368        ConfigSyntax::Json => return None,
369    };
370    let trimmed = rest.trim_start();
371    let value_start = line_offset + (trimmed.as_ptr() as usize - line.as_ptr() as usize);
372    extract_scalar_span(trimmed, value_start)
373}
374
375fn strip_toml_schema_assignment(line: &str) -> Option<&str> {
376    let trimmed = line.trim_start();
377    let after_key = trimmed
378        .strip_prefix("\"$schema\"")
379        .or_else(|| trimmed.strip_prefix("'$schema'"))?;
380    after_key.trim_start().strip_prefix('=')
381}
382
383fn strip_yaml_schema_assignment(line: &str) -> Option<&str> {
384    if line.starts_with(|c: char| c.is_whitespace()) {
385        return None;
386    }
387    let after_key = line
388        .strip_prefix("\"$schema\"")
389        .or_else(|| line.strip_prefix("'$schema'"))
390        .or_else(|| line.strip_prefix("$schema"))?;
391    after_key.trim_start().strip_prefix(':')
392}
393
394fn extract_scalar_span(trimmed: &str, value_start: usize) -> Option<SchemaValueSpan> {
395    if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
396        return None;
397    }
398    if let Some(quote) = trimmed.chars().next().filter(|c| *c == '"' || *c == '\'') {
399        let end_quote = trimmed[1..].find(quote)? + 1;
400        let inner = &trimmed[1..end_quote];
401        let trailing = trimmed[end_quote + 1..].trim_start();
402        if !trailing.is_empty() && !trailing.starts_with('#') {
403            return None;
404        }
405        return Some(SchemaValueSpan {
406            span: value_start..(value_start + end_quote + 1),
407            value: inner.to_owned(),
408        });
409    }
410    let without_comment = strip_inline_hash_comment(trimmed);
411    if without_comment.is_empty() || without_comment.chars().any(char::is_whitespace) {
412        return None;
413    }
414    Some(SchemaValueSpan {
415        span: value_start..(value_start + without_comment.len()),
416        value: without_comment.to_owned(),
417    })
418}
419
420fn apply_replacements(text: &str, mut replacements: Vec<Replacement>) -> Option<String> {
421    if replacements.is_empty() {
422        return None;
423    }
424    replacements.sort_by_key(|left| std::cmp::Reverse(left.span.start));
425    let mut updated = text.to_owned();
426    for replacement in replacements {
427        updated.get(replacement.span.clone())?;
428        updated.replace_range(replacement.span, &replacement.text);
429    }
430    Some(updated)
431}