1use std::ops::Range;
2
3use tree_sitter::{Query, QueryMatch};
4
5use crate::MigrationPatterns;
6
7pub const SETTINGS_PATTERNS: MigrationPatterns = &[(
8 SETTINGS_CONTEXT_SERVER_PATTERN,
9 migrate_context_server_settings,
10)];
11
12const SETTINGS_CONTEXT_SERVER_PATTERN: &str = r#"(document
13 (object
14 (pair
15 key: (string (string_content) @context-servers)
16 value: (object
17 (pair
18 key: (string (string_content) @server-name)
19 value: (object) @server-settings
20 )
21 )
22 )
23 )
24 (#eq? @context-servers "context_servers")
25)"#;
26
27fn migrate_context_server_settings(
28 contents: &str,
29 mat: &QueryMatch,
30 query: &Query,
31) -> Option<(Range<usize>, String)> {
32 let server_settings_index = query.capture_index_for_name("server-settings")?;
33 let server_settings = mat.nodes_for_capture_index(server_settings_index).next()?;
34
35 let mut has_command = false;
36 let mut has_settings = false;
37 let mut has_url = false;
38 let mut other_keys = 0;
39 let mut column = None;
40
41 // Parse the server settings to check what keys it contains
42 let mut cursor = server_settings.walk();
43 for child in server_settings.children(&mut cursor) {
44 if child.kind() == "pair"
45 && let Some(key_node) = child.child_by_field_name("key")
46 {
47 if let (None, Some(quote_content)) = (column, key_node.child(0)) {
48 column = Some(quote_content.start_position().column);
49 }
50 if let Some(string_content) = key_node.child(1) {
51 let key = &contents[string_content.byte_range()];
52 match key {
53 // If it already has a source key, don't modify it
54 "source" => return None,
55 "command" => has_command = true,
56 "settings" => has_settings = true,
57 "url" => has_url = true,
58 _ => other_keys += 1,
59 }
60 }
61 }
62 }
63
64 let source_type = if has_command { "custom" } else { "extension" };
65
66 // Insert the source key at the beginning of the object
67 let start = server_settings.start_byte() + 1;
68 let indent = " ".repeat(column.unwrap_or(12));
69
70 if !has_command && !has_settings && !has_url {
71 return Some((
72 start..start,
73 format!(
74 r#"
75{indent}"source": "{}",
76{indent}"settings": {{}}{}
77 "#,
78 source_type,
79 if other_keys > 0 { "," } else { "" }
80 ),
81 ));
82 }
83
84 Some((
85 start..start,
86 format!(
87 r#"
88{indent}"source": "{}","#,
89 source_type
90 ),
91 ))
92}