1 //! Config used by the language server.
3 //! We currently get this config from `initialize` LSP request, which is not the
4 //! best way to do it, but was the simplest thing we could implement.
6 //! Of particular interest is the `feature_flags` hash map: while other fields
7 //! configure the server itself, feature flags are passed into analysis, and
8 //! tweak things like automatic insertion of `()` in completions.
10 use std::{ffi::OsString, iter, path::PathBuf};
12 use flycheck::FlycheckConfig;
14 use ide::{AssistConfig, CompletionConfig, DiagnosticsConfig, HoverConfig, InlayHintsConfig};
15 use ide_db::helpers::{
16 insert_use::{InsertUseConfig, MergeBehavior},
19 use itertools::Itertools;
20 use lsp_types::{ClientCapabilities, MarkupKind};
21 use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest};
22 use rustc_hash::FxHashSet;
23 use serde::{de::DeserializeOwned, Deserialize};
26 use crate::{caps::completion_item_edit_resolve, diagnostics::DiagnosticsMapConfig};
30 /// The strategy to use when inserting new imports or merging imports.
31 assist_importMergeBehavior |
32 assist_importMergeBehaviour: MergeBehaviorDef = "\"full\"",
33 /// The path structure for newly inserted paths to use.
34 assist_importPrefix: ImportPrefixDef = "\"plain\"",
36 /// Show function name and docs in parameter hints.
37 callInfo_full: bool = "true",
39 /// Automatically refresh project info via `cargo metadata` on
40 /// `Cargo.toml` changes.
41 cargo_autoreload: bool = "true",
42 /// Activate all available features (`--all-features`).
43 cargo_allFeatures: bool = "false",
44 /// List of features to activate.
45 cargo_features: Vec<String> = "[]",
46 /// Run `cargo check` on startup to get the correct value for package
48 cargo_loadOutDirsFromCheck: bool = "false",
49 /// Do not activate the `default` feature.
50 cargo_noDefaultFeatures: bool = "false",
51 /// Compilation target (target triple).
52 cargo_target: Option<String> = "null",
53 /// Internal config for debugging, disables loading of sysroot crates.
54 cargo_noSysroot: bool = "false",
56 /// Run specified `cargo check` command for diagnostics on save.
57 checkOnSave_enable: bool = "true",
58 /// Check with all features (`--all-features`).
59 /// Defaults to `#rust-analyzer.cargo.allFeatures#`.
60 checkOnSave_allFeatures: Option<bool> = "null",
61 /// Check all targets and tests (`--all-targets`).
62 checkOnSave_allTargets: bool = "true",
63 /// Cargo command to use for `cargo check`.
64 checkOnSave_command: String = "\"check\"",
65 /// Do not activate the `default` feature.
66 checkOnSave_noDefaultFeatures: Option<bool> = "null",
67 /// Check for a specific target. Defaults to
68 /// `#rust-analyzer.cargo.target#`.
69 checkOnSave_target: Option<String> = "null",
70 /// Extra arguments for `cargo check`.
71 checkOnSave_extraArgs: Vec<String> = "[]",
72 /// List of features to activate. Defaults to
73 /// `#rust-analyzer.cargo.features#`.
74 checkOnSave_features: Option<Vec<String>> = "null",
75 /// Advanced option, fully override the command rust-analyzer uses for
76 /// checking. The command should include `--message-format=json` or
78 checkOnSave_overrideCommand: Option<Vec<String>> = "null",
80 /// Whether to add argument snippets when completing functions.
81 completion_addCallArgumentSnippets: bool = "true",
82 /// Whether to add parenthesis when completing functions.
83 completion_addCallParenthesis: bool = "true",
84 /// Whether to show postfix snippets like `dbg`, `if`, `not`, etc.
85 completion_postfix_enable: bool = "true",
86 /// Toggles the additional completions that automatically add imports when completed.
87 /// Note that your client must specify the `additionalTextEdits` LSP client capability to truly have this feature enabled.
88 completion_autoimport_enable: bool = "true",
90 /// Whether to show native rust-analyzer diagnostics.
91 diagnostics_enable: bool = "true",
92 /// Whether to show experimental rust-analyzer diagnostics that might
93 /// have more false positives than usual.
94 diagnostics_enableExperimental: bool = "true",
95 /// List of rust-analyzer diagnostics to disable.
96 diagnostics_disabled: FxHashSet<String> = "[]",
97 /// List of warnings that should be displayed with info severity.\n\nThe
98 /// warnings will be indicated by a blue squiggly underline in code and
99 /// a blue icon in the `Problems Panel`.
100 diagnostics_warningsAsHint: Vec<String> = "[]",
101 /// List of warnings that should be displayed with hint severity.\n\nThe
102 /// warnings will be indicated by faded text or three dots in code and
103 /// will not show up in the `Problems Panel`.
104 diagnostics_warningsAsInfo: Vec<String> = "[]",
106 /// Controls file watching implementation.
107 files_watcher: String = "\"client\"",
109 /// Whether to show `Debug` action. Only applies when
110 /// `#rust-analyzer.hoverActions.enable#` is set.
111 hoverActions_debug: bool = "true",
112 /// Whether to show HoverActions in Rust files.
113 hoverActions_enable: bool = "true",
114 /// Whether to show `Go to Type Definition` action. Only applies when
115 /// `#rust-analyzer.hoverActions.enable#` is set.
116 hoverActions_gotoTypeDef: bool = "true",
117 /// Whether to show `Implementations` action. Only applies when
118 /// `#rust-analyzer.hoverActions.enable#` is set.
119 hoverActions_implementations: bool = "true",
120 /// Whether to show `Run` action. Only applies when
121 /// `#rust-analyzer.hoverActions.enable#` is set.
122 hoverActions_run: bool = "true",
123 /// Use markdown syntax for links in hover.
124 hoverActions_linksInHover: bool = "true",
126 /// Whether to show inlay type hints for method chains.
127 inlayHints_chainingHints: bool = "true",
128 /// Maximum length for inlay hints. Default is unlimited.
129 inlayHints_maxLength: Option<usize> = "null",
130 /// Whether to show function parameter name inlay hints at the call
132 inlayHints_parameterHints: bool = "true",
133 /// Whether to show inlay type hints for variables.
134 inlayHints_typeHints: bool = "true",
136 /// Whether to show `Debug` lens. Only applies when
137 /// `#rust-analyzer.lens.enable#` is set.
138 lens_debug: bool = "true",
139 /// Whether to show CodeLens in Rust files.
140 lens_enable: bool = "true",
141 /// Whether to show `Implementations` lens. Only applies when
142 /// `#rust-analyzer.lens.enable#` is set.
143 lens_implementations: bool = "true",
144 /// Whether to show `Run` lens. Only applies when
145 /// `#rust-analyzer.lens.enable#` is set.
146 lens_run: bool = "true",
147 /// Whether to show `Method References` lens. Only applies when
148 /// `#rust-analyzer.lens.enable#` is set.
149 lens_methodReferences: bool = "false",
150 /// Whether to show `References` lens. Only applies when
151 /// `#rust-analyzer.lens.enable#` is set.
152 lens_references: bool = "false",
154 /// Disable project auto-discovery in favor of explicitly specified set
155 /// of projects.\n\nElements must be paths pointing to `Cargo.toml`,
156 /// `rust-project.json`, or JSON objects in `rust-project.json` format.
157 linkedProjects: Vec<ManifestOrProjectJson> = "[]",
159 /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
160 lruCapacity: Option<usize> = "null",
162 /// Whether to show `can't find Cargo.toml` error message.
163 notifications_cargoTomlNotFound: bool = "true",
165 /// Enable Proc macro support, `#rust-analyzer.cargo.loadOutDirsFromCheck#` must be
167 procMacro_enable: bool = "false",
168 /// Internal config, path to proc-macro server executable (typically,
169 /// this is rust-analyzer itself, but we override this in tests).
170 procMacro_server: Option<PathBuf> = "null",
172 /// Command to be executed instead of 'cargo' for runnables.
173 runnables_overrideCargo: Option<String> = "null",
174 /// Additional arguments to be passed to cargo for runnables such as
175 /// tests or binaries.\nFor example, it may be `--release`.
176 runnables_cargoExtraArgs: Vec<String> = "[]",
178 /// Path to the rust compiler sources, for usage in rustc_private projects.
179 rustcSource : Option<PathBuf> = "null",
181 /// Additional arguments to `rustfmt`.
182 rustfmt_extraArgs: Vec<String> = "[]",
183 /// Advanced option, fully override the command rust-analyzer uses for
185 rustfmt_overrideCommand: Option<Vec<String>> = "null",
189 impl Default for ConfigData {
190 fn default() -> Self {
191 ConfigData::from_json(serde_json::Value::Null)
195 #[derive(Debug, Clone)]
197 caps: lsp_types::ClientCapabilities,
199 pub discovered_projects: Option<Vec<ProjectManifest>>,
200 pub root_path: AbsPathBuf,
203 #[derive(Debug, Clone, Eq, PartialEq)]
204 pub enum LinkedProject {
205 ProjectManifest(ProjectManifest),
206 InlineJsonProject(ProjectJson),
209 impl From<ProjectManifest> for LinkedProject {
210 fn from(v: ProjectManifest) -> Self {
211 LinkedProject::ProjectManifest(v)
215 impl From<ProjectJson> for LinkedProject {
216 fn from(v: ProjectJson) -> Self {
217 LinkedProject::InlineJsonProject(v)
221 #[derive(Clone, Debug, PartialEq, Eq)]
222 pub struct LensConfig {
225 pub implementations: bool,
226 pub method_refs: bool,
227 pub refs: bool, // for Struct, Enum, Union and Trait
231 pub fn any(&self) -> bool {
232 self.implementations || self.runnable() || self.references()
235 pub fn none(&self) -> bool {
239 pub fn runnable(&self) -> bool {
240 self.run || self.debug
243 pub fn references(&self) -> bool {
244 self.method_refs || self.refs
248 #[derive(Debug, Clone)]
249 pub struct FilesConfig {
250 pub watcher: FilesWatcher,
251 pub exclude: Vec<String>,
254 #[derive(Debug, Clone)]
255 pub enum FilesWatcher {
260 #[derive(Debug, Clone)]
261 pub struct NotificationsConfig {
262 pub cargo_toml_not_found: bool,
265 #[derive(Debug, Clone)]
266 pub enum RustfmtConfig {
267 Rustfmt { extra_args: Vec<String> },
268 CustomCommand { command: String, args: Vec<String> },
271 /// Configuration for runnable items, such as `main` function or tests.
272 #[derive(Debug, Clone)]
273 pub struct RunnablesConfig {
274 /// Custom command to be executed instead of `cargo` for runnables.
275 pub override_cargo: Option<String>,
276 /// Additional arguments for the `cargo`, e.g. `--release`.
277 pub cargo_extra_args: Vec<String>,
281 pub fn new(root_path: AbsPathBuf, caps: ClientCapabilities) -> Self {
282 Config { caps, data: ConfigData::default(), discovered_projects: None, root_path }
284 pub fn update(&mut self, json: serde_json::Value) {
285 log::info!("updating config from JSON: {:#}", json);
286 if json.is_null() || json.as_object().map_or(false, |it| it.is_empty()) {
289 self.data = ConfigData::from_json(json);
292 pub fn json_schema() -> serde_json::Value {
293 ConfigData::json_schema()
299 || -> _ { Some($expr) }()
302 macro_rules! try_or {
303 ($expr:expr, $or:expr) => {
304 try_!($expr).unwrap_or($or)
309 pub fn linked_projects(&self) -> Vec<LinkedProject> {
310 if self.data.linkedProjects.is_empty() {
311 self.discovered_projects
316 .map(LinkedProject::from)
322 .filter_map(|linked_project| {
323 let res = match linked_project {
324 ManifestOrProjectJson::Manifest(it) => {
325 let path = self.root_path.join(it);
326 ProjectManifest::from_manifest_file(path)
327 .map_err(|e| log::error!("failed to load linked project: {}", e))
331 ManifestOrProjectJson::ProjectJson(it) => {
332 ProjectJson::new(&self.root_path, it.clone()).into()
341 pub fn did_save_text_document_dynamic_registration(&self) -> bool {
343 try_or!(self.caps.text_document.as_ref()?.synchronization.clone()?, Default::default());
344 caps.did_save == Some(true) && caps.dynamic_registration == Some(true)
346 pub fn did_change_watched_files_dynamic_registration(&self) -> bool {
348 self.caps.workspace.as_ref()?.did_change_watched_files.as_ref()?.dynamic_registration?,
353 pub fn location_link(&self) -> bool {
354 try_or!(self.caps.text_document.as_ref()?.definition?.link_support?, false)
356 pub fn line_folding_only(&self) -> bool {
357 try_or!(self.caps.text_document.as_ref()?.folding_range.as_ref()?.line_folding_only?, false)
359 pub fn hierarchical_symbols(&self) -> bool {
366 .hierarchical_document_symbol_support?,
370 pub fn code_action_literals(&self) -> bool {
377 .code_action_literal_support
381 pub fn work_done_progress(&self) -> bool {
382 try_or!(self.caps.window.as_ref()?.work_done_progress?, false)
384 pub fn code_action_resolve(&self) -> bool {
398 .any(|it| it == "edit")
400 pub fn signature_help_label_offsets(&self) -> bool {
407 .signature_information
409 .parameter_information
411 .label_offset_support?,
416 fn experimental(&self, index: &'static str) -> bool {
417 try_or!(self.caps.experimental.as_ref()?.get(index)?.as_bool()?, false)
419 pub fn code_action_group(&self) -> bool {
420 self.experimental("codeActionGroup")
422 pub fn hover_actions(&self) -> bool {
423 self.experimental("hoverActions")
425 pub fn status_notification(&self) -> bool {
426 self.experimental("statusNotification")
429 pub fn publish_diagnostics(&self) -> bool {
430 self.data.diagnostics_enable
432 pub fn diagnostics(&self) -> DiagnosticsConfig {
434 disable_experimental: !self.data.diagnostics_enableExperimental,
435 disabled: self.data.diagnostics_disabled.clone(),
438 pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
439 DiagnosticsMapConfig {
440 warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
441 warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
444 pub fn lru_capacity(&self) -> Option<usize> {
445 self.data.lruCapacity
447 pub fn proc_macro_srv(&self) -> Option<(PathBuf, Vec<OsString>)> {
448 if !self.data.procMacro_enable {
452 let path = self.data.procMacro_server.clone().or_else(|| std::env::current_exe().ok())?;
453 Some((path, vec!["proc-macro".into()]))
455 pub fn files(&self) -> FilesConfig {
457 watcher: match self.data.files_watcher.as_str() {
458 "notify" => FilesWatcher::Notify,
459 "client" | _ => FilesWatcher::Client,
464 pub fn notifications(&self) -> NotificationsConfig {
465 NotificationsConfig { cargo_toml_not_found: self.data.notifications_cargoTomlNotFound }
467 pub fn cargo_autoreload(&self) -> bool {
468 self.data.cargo_autoreload
470 pub fn cargo(&self) -> CargoConfig {
471 let rustc_source = self.data.rustcSource.as_ref().map(|it| self.root_path.join(&it));
474 no_default_features: self.data.cargo_noDefaultFeatures,
475 all_features: self.data.cargo_allFeatures,
476 features: self.data.cargo_features.clone(),
477 load_out_dirs_from_check: self.data.cargo_loadOutDirsFromCheck,
478 target: self.data.cargo_target.clone(),
480 no_sysroot: self.data.cargo_noSysroot,
483 pub fn rustfmt(&self) -> RustfmtConfig {
484 match &self.data.rustfmt_overrideCommand {
485 Some(args) if !args.is_empty() => {
486 let mut args = args.clone();
487 let command = args.remove(0);
488 RustfmtConfig::CustomCommand { command, args }
491 RustfmtConfig::Rustfmt { extra_args: self.data.rustfmt_extraArgs.clone() }
495 pub fn flycheck(&self) -> Option<FlycheckConfig> {
496 if !self.data.checkOnSave_enable {
499 let flycheck_config = match &self.data.checkOnSave_overrideCommand {
500 Some(args) if !args.is_empty() => {
501 let mut args = args.clone();
502 let command = args.remove(0);
503 FlycheckConfig::CustomCommand { command, args }
505 Some(_) | None => FlycheckConfig::CargoCommand {
506 command: self.data.checkOnSave_command.clone(),
511 .or(self.data.cargo_target.clone()),
512 all_targets: self.data.checkOnSave_allTargets,
513 no_default_features: self
515 .checkOnSave_noDefaultFeatures
516 .unwrap_or(self.data.cargo_noDefaultFeatures),
519 .checkOnSave_allFeatures
520 .unwrap_or(self.data.cargo_allFeatures),
523 .checkOnSave_features
525 .unwrap_or(self.data.cargo_features.clone()),
526 extra_args: self.data.checkOnSave_extraArgs.clone(),
529 Some(flycheck_config)
531 pub fn runnables(&self) -> RunnablesConfig {
533 override_cargo: self.data.runnables_overrideCargo.clone(),
534 cargo_extra_args: self.data.runnables_cargoExtraArgs.clone(),
537 pub fn inlay_hints(&self) -> InlayHintsConfig {
539 type_hints: self.data.inlayHints_typeHints,
540 parameter_hints: self.data.inlayHints_parameterHints,
541 chaining_hints: self.data.inlayHints_chainingHints,
542 max_length: self.data.inlayHints_maxLength,
545 fn insert_use_config(&self) -> InsertUseConfig {
547 merge: match self.data.assist_importMergeBehavior {
548 MergeBehaviorDef::None => None,
549 MergeBehaviorDef::Full => Some(MergeBehavior::Full),
550 MergeBehaviorDef::Last => Some(MergeBehavior::Last),
552 prefix_kind: match self.data.assist_importPrefix {
553 ImportPrefixDef::Plain => PrefixKind::Plain,
554 ImportPrefixDef::ByCrate => PrefixKind::ByCrate,
555 ImportPrefixDef::BySelf => PrefixKind::BySelf,
559 pub fn completion(&self) -> CompletionConfig {
561 enable_postfix_completions: self.data.completion_postfix_enable,
562 enable_imports_on_the_fly: self.data.completion_autoimport_enable
563 && completion_item_edit_resolve(&self.caps),
564 add_call_parenthesis: self.data.completion_addCallParenthesis,
565 add_call_argument_snippets: self.data.completion_addCallArgumentSnippets,
566 insert_use: self.insert_use_config(),
567 snippet_cap: SnippetCap::new(try_or!(
580 pub fn assist(&self) -> AssistConfig {
582 snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
584 insert_use: self.insert_use_config(),
587 pub fn call_info_full(&self) -> bool {
588 self.data.callInfo_full
590 pub fn lens(&self) -> LensConfig {
592 run: self.data.lens_enable && self.data.lens_run,
593 debug: self.data.lens_enable && self.data.lens_debug,
594 implementations: self.data.lens_enable && self.data.lens_implementations,
595 method_refs: self.data.lens_enable && self.data.lens_methodReferences,
596 refs: self.data.lens_enable && self.data.lens_references,
599 pub fn hover(&self) -> HoverConfig {
601 implementations: self.data.hoverActions_enable
602 && self.data.hoverActions_implementations,
603 run: self.data.hoverActions_enable && self.data.hoverActions_run,
604 debug: self.data.hoverActions_enable && self.data.hoverActions_debug,
605 goto_type_def: self.data.hoverActions_enable && self.data.hoverActions_gotoTypeDef,
606 links_in_hover: self.data.hoverActions_linksInHover,
618 .contains(&MarkupKind::Markdown),
621 pub fn semantic_tokens_refresh(&self) -> bool {
622 try_or!(self.caps.workspace.as_ref()?.semantic_tokens.as_ref()?.refresh_support?, false)
624 pub fn code_lens_refresh(&self) -> bool {
625 try_or!(self.caps.workspace.as_ref()?.code_lens.as_ref()?.refresh_support?, false)
629 #[derive(Deserialize, Debug, Clone)]
631 enum ManifestOrProjectJson {
633 ProjectJson(ProjectJsonData),
636 #[derive(Deserialize, Debug, Clone)]
637 #[serde(rename_all = "snake_case")]
638 enum MergeBehaviorDef {
644 #[derive(Deserialize, Debug, Clone)]
645 #[serde(rename_all = "snake_case")]
646 enum ImportPrefixDef {
652 macro_rules! _config_data {
653 (struct $name:ident {
655 $(#[doc=$doc:literal])*
656 $field:ident $(| $alias:ident)?: $ty:ty = $default:expr,
659 #[allow(non_snake_case)]
660 #[derive(Debug, Clone)]
661 struct $name { $($field: $ty,)* }
663 fn from_json(mut json: serde_json::Value) -> $name {
668 None$(.or(Some(stringify!($alias))))?,
674 fn json_schema() -> serde_json::Value {
677 let field = stringify!($field);
678 let ty = stringify!($ty);
679 (field, ty, &[$($doc),*], $default)
685 fn manual() -> String {
688 let field = stringify!($field);
689 let ty = stringify!($ty);
690 (field, ty, &[$($doc),*], $default)
697 use _config_data as config_data;
699 fn get_field<T: DeserializeOwned>(
700 json: &mut serde_json::Value,
702 alias: Option<&'static str>,
705 let default = serde_json::from_str(default).unwrap();
707 // XXX: check alias first, to work-around the VS Code where it pre-fills the
708 // defaults instead of sending an empty object.
711 .chain(iter::once(field))
712 .find_map(move |field| {
713 let mut pointer = field.replace('_', "/");
714 pointer.insert(0, '/');
715 json.pointer_mut(&pointer).and_then(|it| serde_json::from_value(it.take()).ok())
720 fn schema(fields: &[(&'static str, &'static str, &[&str], &str)]) -> serde_json::Value {
721 for ((f1, ..), (f2, ..)) in fields.iter().zip(&fields[1..]) {
722 fn key(f: &str) -> &str {
723 f.splitn(2, "_").next().unwrap()
725 assert!(key(f1) <= key(f2), "wrong field order: {:?} {:?}", f1, f2);
730 .map(|(field, ty, doc, default)| {
731 let name = field.replace("_", ".");
732 let name = format!("rust-analyzer.{}", name);
733 let props = field_props(field, ty, doc, default);
736 .collect::<serde_json::Map<_, _>>();
740 fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json::Value {
741 let doc = doc.iter().map(|it| it.trim()).join(" ");
743 doc.ends_with('.') && doc.starts_with(char::is_uppercase),
744 "bad docs for {}: {:?}",
748 let default = default.parse::<serde_json::Value>().unwrap();
750 let mut map = serde_json::Map::default();
752 ($($key:literal: $value:tt),*$(,)?) => {{$(
753 map.insert($key.into(), serde_json::json!($value));
756 set!("markdownDescription": doc);
757 set!("default": default);
760 "bool" => set!("type": "boolean"),
761 "String" => set!("type": "string"),
762 "Vec<String>" => set! {
764 "items": { "type": "string" },
766 "FxHashSet<String>" => set! {
768 "items": { "type": "string" },
771 "Option<usize>" => set! {
772 "type": ["null", "integer"],
775 "Option<String>" => set! {
776 "type": ["null", "string"],
778 "Option<PathBuf>" => set! {
779 "type": ["null", "string"],
781 "Option<bool>" => set! {
782 "type": ["null", "boolean"],
784 "Option<Vec<String>>" => set! {
785 "type": ["null", "array"],
786 "items": { "type": "string" },
788 "MergeBehaviorDef" => set! {
790 "enum": ["none", "full", "last"],
791 "enumDescriptions": [
793 "Merge all layers of the import trees",
794 "Only merge the last layer of the import trees"
797 "ImportPrefixDef" => set! {
804 "enumDescriptions": [
805 "Insert import paths relative to the current module, using up to one `super` prefix if the parent module contains the requested item.",
806 "Prefix all import paths with `self` if they don't begin with `self`, `super`, `crate` or a crate name.",
807 "Force import paths to be absolute by always starting them with `crate` or the crate name they refer to."
810 "Vec<ManifestOrProjectJson>" => set! {
812 "items": { "type": ["string", "object"] },
814 _ => panic!("{}: {}", ty, default),
821 fn manual(fields: &[(&'static str, &'static str, &[&str], &str)]) -> String {
824 .map(|(field, _ty, doc, default)| {
825 let name = format!("rust-analyzer.{}", field.replace("_", "."));
826 format!("[[{}]]{} (default: `{}`)::\n{}\n", name, name, default, doc.join(" "))
835 use test_utils::project_dir;
840 fn schema_in_sync_with_package_json() {
841 let s = Config::json_schema();
842 let schema = format!("{:#}", s);
843 let mut schema = schema
844 .trim_start_matches('{')
845 .trim_end_matches('}')
847 .replace("\n", "\n ")
848 .trim_start_matches('\n')
851 schema.push_str(",\n");
853 let package_json_path = project_dir().join("editors/code/package.json");
854 let mut package_json = fs::read_to_string(&package_json_path).unwrap();
856 let start_marker = " \"$generated-start\": false,\n";
857 let end_marker = " \"$generated-end\": false\n";
859 let start = package_json.find(start_marker).unwrap() + start_marker.len();
860 let end = package_json.find(end_marker).unwrap();
861 let p = remove_ws(&package_json[start..end]);
862 let s = remove_ws(&schema);
865 package_json.replace_range(start..end, &schema);
866 fs::write(&package_json_path, &mut package_json).unwrap();
867 panic!("new config, updating package.json")
872 fn schema_in_sync_with_docs() {
873 let docs_path = project_dir().join("docs/user/generated_config.adoc");
874 let current = fs::read_to_string(&docs_path).unwrap();
875 let expected = ConfigData::manual();
877 if remove_ws(¤t) != remove_ws(&expected) {
878 fs::write(&docs_path, expected).unwrap();
879 panic!("updated config manual");
883 fn remove_ws(text: &str) -> String {
884 text.replace(char::is_whitespace, "")