返回 CodeWhale
legacy_root.rs
根目录 / crates / config / src / legacy_root.rs
1 //! Canonicalize the legacy top-level `base_url` / `api_key` into
2 //! `[providers.<name>]` tables (#6394).
3 //!
4 //! Older releases kept DeepSeek's endpoint and key at the root of
5 //! `config.toml`, and every reader then decided for itself which routes
6 //! inherited them. Those readers disagreed. This module is now the only place
7 //! that interprets the root keys: every parse runs [`apply_to_table`] before
8 //! the typed structs see the document (which no longer have root fields), and
9 //! every user-started write runs [`apply_to_document`], so memory and disk
10 //! follow one rule.
11 //!
12 //! Where the top-level `base_url` goes, per scope (the file itself and each
13 //! `[profiles.<name>]`):
14 //!
15 //! 1. `provider = "custom"` with no `[providers.custom]` table: the endpoint,
16 //! key and a copy of the model become `[providers.custom]`.
17 //! 2. An endpoint on another vendor's official host moves to that vendor's
18 //! table, so a DeepSeek route never dispatches to it.
19 //! 3. Anything else belongs to `[providers.deepseek]`, its historical owner.
20 //!
21 //! The key goes with DeepSeek (or the literal custom route). It follows the
22 //! endpoint to another vendor only when the same table explicitly selects that
23 //! vendor, the host is that vendor's own, and the vendor's table has no key.
24 //!
25 //! When the root and the table disagree, memory resolves it (the table's
26 //! `base_url` wins; the root `api_key` wins, because that is the key the TUI
27 //! sent) but disk never does: both keys stay where they are until the user
28 //! runs `codewhale config migrate --prefer ...` or writes that value.
29
30 use std::collections::HashSet;
31 use std::fmt;
32 use std::sync::{Mutex, OnceLock};
33
34 use anyhow::{Context as _, Result};
35
36 use crate::ProviderKind;
37
38 /// The root key names older releases accepted, canonical name first.
39 const BASE_URL_KEYS: [&str; 2] = ["base_url", "baseUrl"];
40 const API_KEY_KEYS: [&str; 2] = ["api_key", "apiKey"];
41
42 /// Hosts whose root `base_url` belongs to a non-DeepSeek vendor even when the
43 /// path is not one of that vendor's exact official endpoints. This is the list
44 /// the DeepSeek route used to refuse at dispatch time.
45 const FOREIGN_HOST_NEEDLES: &[(&str, ProviderKind)] = &[
46 ("integrate.api.nvidia.com", ProviderKind::NvidiaNim),
47 ("api.openai.com", ProviderKind::Openai),
48 ("api.atlascloud.ai", ProviderKind::Atlascloud),
49 ("maas-openapi.wanjiedata.com", ProviderKind::WanjieArk),
50 ("volces.com", ProviderKind::Volcengine),
51 ("openrouter.ai", ProviderKind::Openrouter),
52 ("xiaomimimo.com", ProviderKind::XiaomiMimo),
53 ("novita.ai", ProviderKind::Novita),
54 ("fireworks.ai", ProviderKind::Fireworks),
55 ("siliconflow", ProviderKind::Siliconflow),
56 ("arcee.ai", ProviderKind::Arcee),
57 ("moonshot.ai", ProviderKind::Moonshot),
58 ("api.kimi.com", ProviderKind::Moonshot),
59 ];
60
61 /// Which field a note is about.
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub enum LegacyRootField {
64 BaseUrl,
65 ApiKey,
66 }
67
68 impl LegacyRootField {
69 #[must_use]
70 pub fn key(self) -> &'static str {
71 match self {
72 Self::BaseUrl => "base_url",
73 Self::ApiKey => "api_key",
74 }
75 }
76 }
77
78 /// How a conflicting pair is resolved on disk by `codewhale config migrate`.
79 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
80 pub enum LegacyRootPrefer {
81 /// Keep the top-level value; it replaces the table value.
82 TopLevel,
83 /// Keep the table value; the top-level value is removed.
84 Table,
85 }
86
87 /// One thing the canonicalizer did or found. Never carries a value.
88 #[derive(Debug, Clone, PartialEq, Eq)]
89 pub enum LegacyRootNote {
90 /// A top-level key moved into a table.
91 Moved {
92 scope: Option<String>,
93 field: LegacyRootField,
94 to: String,
95 },
96 /// The table already held the same value; the top-level copy was removed.
97 Merged {
98 scope: Option<String>,
99 field: LegacyRootField,
100 to: String,
101 },
102 /// An empty top-level value was removed.
103 DroppedEmpty {
104 scope: Option<String>,
105 field: LegacyRootField,
106 },
107 /// The top-level key was copied into `[vision_model]`, which inherited it.
108 CopiedToVision { scope: Option<String> },
109 /// The literal custom route's model was copied into `[providers.custom]`.
110 CopiedModel { scope: Option<String> },
111 /// `provider` was written because older releases guessed it from the URL.
112 GuessedProvider {
113 scope: Option<String>,
114 provider: &'static str,
115 },
116 /// The top-level value and the table value differ.
117 Conflict {
118 scope: Option<String>,
119 field: LegacyRootField,
120 table: String,
121 /// Whether the conflict was resolved (in memory, or by `--prefer`).
122 resolved: bool,
123 },
124 }
125
126 /// Receipt for one canonicalization pass.
127 #[derive(Debug, Clone, Default, PartialEq, Eq)]
128 pub struct LegacyRootMigration {
129 pub notes: Vec<LegacyRootNote>,
130 }
131
132 impl LegacyRootMigration {
133 #[must_use]
134 pub fn is_empty(&self) -> bool {
135 self.notes.is_empty()
136 }
137
138 /// Whether anything in the file changed (or would change).
139 #[must_use]
140 pub fn changes_file(&self) -> bool {
141 self.notes.iter().any(|note| match note {
142 LegacyRootNote::Conflict { resolved, .. } => *resolved,
143 _ => true,
144 })
145 }
146
147 /// Conflicts that are still present in the file.
148 pub fn unresolved_conflicts(&self) -> impl Iterator<Item = &LegacyRootNote> {
149 self.notes.iter().filter(|note| {
150 matches!(
151 note,
152 LegacyRootNote::Conflict {
153 resolved: false,
154 ..
155 }
156 )
157 })
158 }
159
160 /// Whether the file still has legacy top-level keys to move.
161 #[must_use]
162 pub fn has_pending_moves(&self) -> bool {
163 self.notes.iter().any(|note| {
164 matches!(
165 note,
166 LegacyRootNote::Moved { .. }
167 | LegacyRootNote::Merged { .. }
168 | LegacyRootNote::DroppedEmpty { .. }
169 )
170 })
171 }
172
173 /// Whether the top-level (not per-profile) `api_key` moved into
174 /// `[providers.<table>]`, where that table had no key of its own.
175 #[must_use]
176 pub fn moved_root_api_key_to(&self, table: &str) -> bool {
177 self.notes.iter().any(|note| {
178 matches!(
179 note,
180 LegacyRootNote::Moved {
181 scope: None,
182 field: LegacyRootField::ApiKey,
183 to,
184 } if to.strip_prefix("providers.") == Some(table)
185 )
186 })
187 }
188
189 /// One line per note, suitable for CLI output and doctor.
190 #[must_use]
191 pub fn lines(&self) -> Vec<String> {
192 self.notes.iter().map(ToString::to_string).collect()
193 }
194
195 /// Short one-line summary of what moved.
196 #[must_use]
197 pub fn summary(&self) -> Option<String> {
198 let moved: Vec<String> = self
199 .notes
200 .iter()
201 .filter_map(|note| match note {
202 LegacyRootNote::Moved { scope, field, to }
203 | LegacyRootNote::Merged { scope, field, to } => {
204 Some(format!("{}{} to [{to}]", scope_prefix(scope), field.key()))
205 }
206 _ => None,
207 })
208 .collect();
209 (!moved.is_empty()).then(|| format!("moved top-level {}", moved.join(", ")))
210 }
211 }
212
213 fn scope_prefix(scope: &Option<String>) -> String {
214 scope
215 .as_deref()
216 .map(|name| format!("profiles.{name}."))
217 .unwrap_or_default()
218 }
219
220 impl fmt::Display for LegacyRootNote {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 match self {
223 Self::Moved { scope, field, to } => write!(
224 f,
225 "moved top-level {}{} to [{to}]",
226 scope_prefix(scope),
227 field.key()
228 ),
229 Self::Merged { scope, field, to } => write!(
230 f,
231 "removed top-level {}{}; [{to}] already has the same value",
232 scope_prefix(scope),
233 field.key()
234 ),
235 Self::DroppedEmpty { scope, field } => write!(
236 f,
237 "removed empty top-level {}{}",
238 scope_prefix(scope),
239 field.key()
240 ),
241 Self::CopiedToVision { scope } => write!(
242 f,
243 "copied top-level {}api_key into [{}vision_model], which used it",
244 scope_prefix(scope),
245 scope_prefix(scope)
246 ),
247 Self::CopiedModel { scope } => write!(
248 f,
249 "copied the {}custom route's model into [{}providers.custom]",
250 scope_prefix(scope),
251 scope_prefix(scope)
252 ),
253 Self::GuessedProvider { scope, provider } => write!(
254 f,
255 "set {}provider = \"{provider}\" (older releases inferred it from base_url)",
256 scope_prefix(scope)
257 ),
258 Self::Conflict {
259 scope,
260 field,
261 table,
262 resolved,
263 } => {
264 let in_use = match field {
265 LegacyRootField::BaseUrl => format!("[{table}] {}", field.key()),
266 LegacyRootField::ApiKey => format!("top-level {}", field.key()),
267 };
268 if *resolved {
269 write!(
270 f,
271 "resolved conflicting top-level {}{} and [{table}] {}",
272 scope_prefix(scope),
273 field.key(),
274 field.key()
275 )
276 } else {
277 write!(
278 f,
279 "top-level {}{} differs from [{table}] {}; {in_use} is in use \
280 (run `codewhale config migrate --prefer top-level|table`)",
281 scope_prefix(scope),
282 field.key(),
283 field.key()
284 )
285 }
286 }
287 }
288 }
289 }
290
291 /// A primitive edit, shared by the in-memory and on-disk appliers.
292 #[derive(Debug, Clone, PartialEq)]
293 enum Op {
294 Set(Vec<String>, toml::Value),
295 /// Set `to`, then remove `from` only if the set landed.
296 Move {
297 from: Vec<String>,
298 to: Vec<String>,
299 value: toml::Value,
300 },
301 /// A conflicting pair left in place on disk (no-op for both appliers).
302 KeepConflict {
303 root: Vec<String>,
304 table: Vec<String>,
305 },
306 /// Set only when the destination is absent.
307 SetIfAbsent(Vec<String>, toml::Value),
308 Remove(Vec<String>),
309 }
310
311 #[derive(Debug, Clone, PartialEq)]
312 struct PlannedOp {
313 op: Op,
314 note: Option<LegacyRootNote>,
315 }
316
317 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
318 enum Mode {
319 Memory,
320 Document(Option<LegacyRootPrefer>),
321 }
322
323 /// The vendor whose official host a root `base_url` names, if it is not
324 /// DeepSeek's. Loopback hosts and Codewhale's own env-dependent endpoint never
325 /// count: a local server is not another vendor.
326 #[must_use]
327 pub fn legacy_root_owner(base_url: &str) -> Option<ProviderKind> {
328 let trimmed = base_url.trim();
329 if trimmed.is_empty() || crate::base_url_uses_local_host(trimmed) {
330 return None;
331 }
332 let lower = trimmed.to_ascii_lowercase();
333 if crate::device_code::url_scheme_and_host(trimmed).is_ok_and(|(scheme, host, credentials)| {
334 scheme == "https" && host == "chatgpt.com" && !credentials
335 }) {
336 return Some(ProviderKind::OpenaiCodex);
337 }
338 if lower.contains("integrate.api.nvidia.com") {
339 return Some(ProviderKind::NvidiaNim);
340 }
341 ProviderKind::ALL
342 .iter()
343 .copied()
344 .filter(|kind| {
345 !matches!(
346 kind,
347 ProviderKind::Deepseek | ProviderKind::Custom | ProviderKind::Codewhale
348 )
349 })
350 .find(|kind| crate::provider_base_url_is_official(*kind, trimmed))
351 .or_else(|| {
352 FOREIGN_HOST_NEEDLES
353 .iter()
354 .find(|(needle, _)| lower.contains(needle))
355 .map(|(_, kind)| *kind)
356 })
357 }
358
359 /// Whether `base_url` is on `provider`'s own host family.
360 fn host_belongs_to(provider: ProviderKind, base_url: &str) -> bool {
361 if crate::base_url_uses_local_host(base_url) {
362 return false;
363 }
364 let lower = base_url.trim().to_ascii_lowercase();
365 crate::provider_base_url_is_official(provider, base_url)
366 || FOREIGN_HOST_NEEDLES
367 .iter()
368 .any(|(needle, kind)| *kind == provider && lower.contains(needle))
369 }
370
371 fn string_at<'a>(table: &'a toml::Table, key: &str) -> Option<&'a str> {
372 table.get(key).and_then(toml::Value::as_str)
373 }
374
375 fn table_at<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Table> {
376 table.get(key).and_then(toml::Value::as_table)
377 }
378
379 fn nonempty(value: Option<&str>) -> Option<&str> {
380 value.map(str::trim).filter(|value| !value.is_empty())
381 }
382
383 /// First present key of an alias pair: `(key name, value)`.
384 fn root_entry<'a>(
385 table: &'a toml::Table,
386 keys: &[&'static str],
387 ) -> Option<(&'static str, &'a toml::Value)> {
388 keys.iter()
389 .find_map(|key| table.get(*key).map(|value| (*key, value)))
390 }
391
392 fn is_blank(value: &toml::Value) -> bool {
393 value.as_str().is_some_and(|value| value.trim().is_empty())
394 }
395
396 struct Scope<'a> {
397 name: Option<String>,
398 /// Path prefix of this scope's table (empty for the file itself).
399 prefix: Vec<String>,
400 table: &'a toml::Table,
401 /// The base file's table when this scope is a profile.
402 base: Option<&'a toml::Table>,
403 }
404
405 impl Scope<'_> {
406 fn path(&self, parts: &[&str]) -> Vec<String> {
407 let mut path = self.prefix.clone();
408 path.extend(parts.iter().map(|part| (*part).to_string()));
409 path
410 }
411
412 fn label(&self, parts: &[&str]) -> String {
413 self.path(parts).join(".")
414 }
415
416 fn provider(&self) -> Option<&str> {
417 nonempty(string_at(self.table, "provider")).or_else(|| {
418 self.base
419 .and_then(|base| nonempty(string_at(base, "provider")))
420 })
421 }
422
423 fn own_provider_kind(&self) -> Option<ProviderKind> {
424 nonempty(string_at(self.table, "provider")).and_then(ProviderKind::parse_config_identity)
425 }
426
427 fn provider_table(&self, key: &str) -> Option<&toml::Table> {
428 table_at(self.table, "providers").and_then(|providers| table_at(providers, key))
429 }
430
431 fn has_literal_custom_table(&self) -> bool {
432 let has = |table: &toml::Table| {
433 table_at(table, "providers").is_some_and(|providers| {
434 providers
435 .keys()
436 .any(|key| key.trim().eq_ignore_ascii_case("custom"))
437 })
438 };
439 has(self.table) || self.base.is_some_and(has)
440 }
441
442 fn selects_literal_custom(&self) -> bool {
443 self.provider()
444 .is_some_and(|provider| provider.eq_ignore_ascii_case("custom"))
445 }
446 }
447
448 fn plan(root: &toml::Table, mode: Mode) -> Vec<PlannedOp> {
449 let mut ops = Vec::new();
450 plan_scope(
451 &Scope {
452 name: None,
453 prefix: Vec::new(),
454 table: root,
455 base: None,
456 },
457 mode,
458 &mut ops,
459 );
460 if let Some(profiles) = table_at(root, "profiles") {
461 for (name, profile) in profiles {
462 let Some(profile) = profile.as_table() else {
463 continue;
464 };
465 plan_scope(
466 &Scope {
467 name: Some(name.clone()),
468 prefix: vec!["profiles".to_string(), name.clone()],
469 table: profile,
470 base: Some(root),
471 },
472 mode,
473 &mut ops,
474 );
475 }
476 }
477 ops
478 }
479
480 fn plan_scope(scope: &Scope<'_>, mode: Mode, ops: &mut Vec<PlannedOp>) {
481 let base_url = root_entry(scope.table, &BASE_URL_KEYS);
482 let api_key = root_entry(scope.table, &API_KEY_KEYS);
483 if base_url.is_none() && api_key.is_none() {
484 return;
485 }
486 let name = scope.name.clone();
487
488 let base_url_str = base_url.and_then(|(_, value)| nonempty(value.as_str()));
489 let literal_custom = scope.selects_literal_custom() && !scope.has_literal_custom_table();
490
491 // Provider guesses that `api_provider()` used to make from the URL.
492 if scope.provider().is_none()
493 && let Some(url) = base_url_str
494 {
495 let lower = url.to_ascii_lowercase();
496 let guess = if lower.contains("integrate.api.nvidia.com") {
497 Some("nvidia-nim")
498 } else if lower.contains("api.deepseeki.com") {
499 Some("deepseek-cn")
500 } else {
501 None
502 };
503 if let Some(provider) = guess {
504 ops.push(PlannedOp {
505 op: Op::Set(
506 scope.path(&["provider"]),
507 toml::Value::String(provider.to_string()),
508 ),
509 note: Some(LegacyRootNote::GuessedProvider {
510 scope: name.clone(),
511 provider,
512 }),
513 });
514 }
515 }
516
517 let url_owner = base_url_str.and_then(legacy_root_owner);
518 let base_url_dest = if literal_custom {
519 "custom".to_string()
520 } else if let Some(explicit) = scope
521 .own_provider_kind()
522 .filter(|kind| base_url_str.is_some_and(|url| host_belongs_to(*kind, url)))
523 .filter(|kind| *kind != ProviderKind::Deepseek && *kind != ProviderKind::Custom)
524 {
525 explicit.provider().provider_config_key().to_string()
526 } else if let Some(owner) = url_owner {
527 owner.provider().provider_config_key().to_string()
528 } else {
529 "deepseek".to_string()
530 };
531
532 if let Some((key, value)) = base_url {
533 plan_move(
534 scope,
535 mode,
536 key,
537 value,
538 LegacyRootField::BaseUrl,
539 &base_url_dest,
540 ops,
541 );
542 }
543
544 if let Some((key, value)) = api_key {
545 let key_dest = if literal_custom {
546 "custom".to_string()
547 } else if let Some(explicit) = scope.own_provider_kind().filter(|kind| {
548 *kind != ProviderKind::Deepseek
549 && *kind != ProviderKind::Custom
550 && base_url_str.is_some_and(|url| host_belongs_to(*kind, url))
551 && nonempty(
552 scope
553 .provider_table(kind.provider().provider_config_key())
554 .and_then(|table| string_at(table, "api_key")),
555 )
556 .is_none()
557 }) {
558 explicit.provider().provider_config_key().to_string()
559 } else {
560 "deepseek".to_string()
561 };
562
563 // `[vision_model]` without a key of its own used the top-level key.
564 if !is_blank(value)
565 && let Some(vision) = table_at(scope.table, "vision_model")
566 && vision.get("api_key").is_none()
567 {
568 ops.push(PlannedOp {
569 op: Op::Set(scope.path(&["vision_model", "api_key"]), value.clone()),
570 note: Some(LegacyRootNote::CopiedToVision {
571 scope: name.clone(),
572 }),
573 });
574 }
575
576 plan_move(
577 scope,
578 mode,
579 key,
580 value,
581 LegacyRootField::ApiKey,
582 &key_dest,
583 ops,
584 );
585 }
586
587 if literal_custom
588 && name.is_none()
589 && base_url_str.is_some()
590 && let Some(windows @ toml::Value::Table(_)) = scope.table.get("model_context_windows")
591 {
592 ops.push(PlannedOp {
593 op: Op::Move {
594 from: scope.path(&["model_context_windows"]),
595 to: scope.path(&["providers", "custom", "model_context_windows"]),
596 value: windows.clone(),
597 },
598 note: None,
599 });
600 }
601
602 if literal_custom
603 && base_url_str.is_some()
604 && let Some(model) = ["default_text_model", "model"]
605 .iter()
606 .find_map(|key| nonempty(string_at(scope.table, key)))
607 .or_else(|| {
608 scope.base.and_then(|base| {
609 ["default_text_model", "model"]
610 .iter()
611 .find_map(|key| nonempty(string_at(base, key)))
612 })
613 })
614 && scope
615 .provider_table("custom")
616 .and_then(|table| table.get("model"))
617 .is_none()
618 {
619 ops.push(PlannedOp {
620 op: Op::SetIfAbsent(
621 scope.path(&["providers", "custom", "model"]),
622 toml::Value::String(model.to_string()),
623 ),
624 note: Some(LegacyRootNote::CopiedModel {
625 scope: name.clone(),
626 }),
627 });
628 }
629
630 // A `[providers.custom]` table is an OpenAI-compatible custom route; the
631 // top-level shape it replaces always was one.
632 let moved_key = api_key.is_some_and(|(_, value)| !is_blank(value));
633 if literal_custom && (base_url_str.is_some() || moved_key) {
634 ops.push(PlannedOp {
635 op: Op::SetIfAbsent(
636 scope.path(&["providers", "custom", "kind"]),
637 toml::Value::String("openai-compatible".to_string()),
638 ),
639 note: None,
640 });
641 }
642 }
643
644 #[allow(clippy::too_many_arguments)]
645 fn plan_move(
646 scope: &Scope<'_>,
647 mode: Mode,
648 key: &str,
649 value: &toml::Value,
650 field: LegacyRootField,
651 dest: &str,
652 ops: &mut Vec<PlannedOp>,
653 ) {
654 let name = scope.name.clone();
655 let root_path = scope.path(&[key]);
656 let dest_path = scope.path(&["providers", dest, field.key()]);
657 let dest_label = scope.label(&["providers", dest]);
658 if is_blank(value) {
659 ops.push(PlannedOp {
660 op: Op::Remove(root_path),
661 note: Some(LegacyRootNote::DroppedEmpty { scope: name, field }),
662 });
663 return;
664 }
665 let existing = scope
666 .provider_table(dest)
667 .and_then(|table| table.get(field.key()))
668 .filter(|existing| !is_blank(existing));
669 let Some(existing) = existing else {
670 ops.push(PlannedOp {
671 op: Op::Move {
672 from: root_path,
673 to: dest_path,
674 value: value.clone(),
675 },
676 note: Some(LegacyRootNote::Moved {
677 scope: name,
678 field,
679 to: dest_label,
680 }),
681 });
682 return;
683 };
684 let same = match (existing.as_str(), value.as_str()) {
685 (Some(a), Some(b)) => a.trim() == b.trim(),
686 _ => existing == value,
687 };
688 if same {
689 ops.push(PlannedOp {
690 op: Op::Remove(root_path),
691 note: Some(LegacyRootNote::Merged {
692 scope: name,
693 field,
694 to: dest_label,
695 }),
696 });
697 return;
698 }
699 // A real conflict. Memory applies the precedence the runtime always had;
700 // disk changes only on an explicit `--prefer`.
701 let top_level_wins = match mode {
702 Mode::Memory => Some(field == LegacyRootField::ApiKey),
703 Mode::Document(Some(LegacyRootPrefer::TopLevel)) => Some(true),
704 Mode::Document(Some(LegacyRootPrefer::Table)) => Some(false),
705 Mode::Document(None) => None,
706 };
707 let op = match top_level_wins {
708 Some(true) => Op::Move {
709 from: root_path,
710 to: dest_path,
711 value: value.clone(),
712 },
713 Some(false) => Op::Remove(root_path),
714 None => Op::KeepConflict {
715 root: root_path,
716 table: dest_path,
717 },
718 };
719 ops.push(PlannedOp {
720 op,
721 note: Some(LegacyRootNote::Conflict {
722 scope: name,
723 field,
724 table: dest_label,
725 resolved: matches!(mode, Mode::Document(Some(_))),
726 }),
727 });
728 }
729
730 /// Canonicalize a parsed document in memory. Every parse of `config.toml`
731 /// (and of profile, managed and imported configs) runs this before
732 /// deserializing, so no reader ever sees a top-level `base_url` or `api_key`.
733 pub fn apply_to_table(root: &mut toml::Table) -> LegacyRootMigration {
734 apply_planned_to_table(root, plan(root, Mode::Memory))
735 }
736
737 fn apply_planned_to_table(root: &mut toml::Table, planned: Vec<PlannedOp>) -> LegacyRootMigration {
738 let mut receipt = LegacyRootMigration::default();
739 for PlannedOp { op, note } in planned {
740 if apply_op_to_table(root, op)
741 && let Some(note) = note
742 {
743 receipt.notes.push(note);
744 }
745 }
746 receipt
747 }
748
749 /// Canonicalize `contents` as text, for callers that then deserialize it.
750 ///
751 /// Going through `toml::Value` would turn datetimes in unknown keys into
752 /// strings, so the edit is made on the document and re-rendered instead.
753 /// Returns `contents` unchanged (borrowed) when there is nothing to move.
754 pub fn canonicalize_text(
755 contents: &str,
756 ) -> Result<(std::borrow::Cow<'_, str>, LegacyRootMigration), toml::de::Error> {
757 let might_have_keys = BASE_URL_KEYS
758 .iter()
759 .chain(API_KEY_KEYS.iter())
760 .any(|key| contents.contains(key));
761 if !might_have_keys {
762 return Ok((
763 std::borrow::Cow::Borrowed(contents),
764 LegacyRootMigration::default(),
765 ));
766 }
767 let table = toml::from_str::<toml::Table>(contents)?;
768 if !has_legacy_root_keys(&table) {
769 return Ok((
770 std::borrow::Cow::Borrowed(contents),
771 LegacyRootMigration::default(),
772 ));
773 }
774 let planned = plan(&table, Mode::Memory);
775 match contents.parse::<toml_edit::DocumentMut>() {
776 Ok(mut doc) => {
777 let receipt = apply_planned_to_document(&mut doc, planned);
778 Ok((std::borrow::Cow::Owned(doc.to_string()), receipt))
779 }
780 Err(_) => {
781 let mut table = table;
782 let receipt = apply_planned_to_table(&mut table, planned);
783 let text = toml::to_string(&table).unwrap_or_else(|_| contents.to_string());
784 Ok((std::borrow::Cow::Owned(text), receipt))
785 }
786 }
787 }
788
789 /// What [`try_apply_to_document`] would do, without doing it.
790 pub fn try_preview_document(
791 doc: &toml_edit::DocumentMut,
792 prefer: Option<LegacyRootPrefer>,
793 ) -> Result<LegacyRootMigration> {
794 let mut cloned = doc.clone();
795 try_apply_to_document(&mut cloned, prefer)
796 }
797
798 /// What [`apply_to_document`] would do, without doing it.
799 #[must_use]
800 pub fn preview_document(
801 doc: &toml_edit::DocumentMut,
802 prefer: Option<LegacyRootPrefer>,
803 ) -> LegacyRootMigration {
804 try_preview_document(doc, prefer).unwrap_or_default()
805 }
806
807 /// Canonicalize a document on disk, keeping comments and layout. Conflicting
808 /// pairs are left untouched unless `prefer` says which one to keep.
809 pub fn apply_to_document(
810 doc: &mut toml_edit::DocumentMut,
811 prefer: Option<LegacyRootPrefer>,
812 ) -> LegacyRootMigration {
813 let Some(table) = document_table(doc) else {
814 return LegacyRootMigration::default();
815 };
816 apply_planned_to_document(doc, plan(&table, Mode::Document(prefer)))
817 }
818
819 pub fn try_apply_to_document(
820 doc: &mut toml_edit::DocumentMut,
821 prefer: Option<LegacyRootPrefer>,
822 ) -> Result<LegacyRootMigration> {
823 let Some(table) = document_table(doc) else {
824 return Ok(LegacyRootMigration::default());
825 };
826 let mut staged = doc.clone();
827 let mut receipt = LegacyRootMigration::default();
828 for PlannedOp { op, note } in plan(&table, Mode::Document(prefer)) {
829 if apply_op_to_document(&mut staged, op)?
830 && let Some(note) = note
831 {
832 receipt.notes.push(note);
833 }
834 }
835 *doc = staged;
836 Ok(receipt)
837 }
838
839 fn warn_once_skipped_migration_op(err: &anyhow::Error) {
840 static WARNED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
841 const MAX_WARNED_ENTRIES: usize = 64;
842 let message = format!("{err:#}");
843 let seen = WARNED
844 .get_or_init(|| Mutex::new(HashSet::new()))
845 .lock()
846 .map(|mut set| {
847 if set.contains(&message) {
848 true
849 } else {
850 if set.len() < MAX_WARNED_ENTRIES {
851 set.insert(message.clone());
852 }
853 false
854 }
855 })
856 .unwrap_or(false);
857 if !seen {
858 tracing::warn!("skipping legacy root migration op: {message}");
859 }
860 }
861
862 fn apply_planned_to_document(
863 doc: &mut toml_edit::DocumentMut,
864 planned: Vec<PlannedOp>,
865 ) -> LegacyRootMigration {
866 let mut receipt = LegacyRootMigration::default();
867 for PlannedOp { op, note } in planned {
868 match apply_op_to_document(doc, op) {
869 Ok(true) => {
870 if let Some(note) = note {
871 receipt.notes.push(note);
872 }
873 }
874 Ok(false) => {}
875 Err(err) => {
876 warn_once_skipped_migration_op(&err);
877 }
878 }
879 }
880 receipt
881 }
882
883 fn document_table(doc: &toml_edit::DocumentMut) -> Option<toml::Table> {
884 toml::from_str::<toml::Table>(&doc.to_string()).ok()
885 }
886
887 /// `raw` with its legacy top-level keys moved (conflicts left in place), or
888 /// `None` when there is nothing to move or `raw` does not parse.
889 #[must_use]
890 pub fn migrated_document_text(raw: &str) -> Option<String> {
891 let mut doc = raw.parse::<toml_edit::DocumentMut>().ok()?;
892 apply_to_document(&mut doc, None)
893 .changes_file()
894 .then(|| doc.to_string())
895 }
896
897 /// Whether a raw document still holds legacy top-level keys anywhere.
898 #[must_use]
899 pub fn has_legacy_root_keys(root: &toml::Table) -> bool {
900 let scope_has = |table: &toml::Table| {
901 BASE_URL_KEYS
902 .iter()
903 .chain(API_KEY_KEYS.iter())
904 .any(|key| table.contains_key(*key))
905 };
906 scope_has(root)
907 || table_at(root, "profiles").is_some_and(|profiles| {
908 profiles
909 .values()
910 .filter_map(toml::Value::as_table)
911 .any(scope_has)
912 })
913 }
914
915 fn apply_op_to_table(root: &mut toml::Table, op: Op) -> bool {
916 match op {
917 Op::Set(path, value) => set_in_table(root, &path, value, true),
918 Op::SetIfAbsent(path, value) => set_in_table(root, &path, value, false),
919 Op::KeepConflict { .. } => true,
920 Op::Move { from, to, value } => {
921 if set_in_table(root, &to, value, true) {
922 apply_op_to_table(root, Op::Remove(from))
923 } else {
924 false
925 }
926 }
927 Op::Remove(path) => {
928 let Some((last, parents)) = path.split_last() else {
929 return false;
930 };
931 let mut current = root;
932 for part in parents {
933 match current.get_mut(part).and_then(toml::Value::as_table_mut) {
934 Some(next) => current = next,
935 None => return false,
936 }
937 }
938 current.remove(last).is_some()
939 }
940 }
941 }
942
943 fn set_in_table(
944 root: &mut toml::Table,
945 path: &[String],
946 value: toml::Value,
947 overwrite: bool,
948 ) -> bool {
949 let Some((last, parents)) = path.split_last() else {
950 return false;
951 };
952 let mut current = root;
953 for part in parents {
954 let entry = current
955 .entry(part.clone())
956 .or_insert_with(|| toml::Value::Table(toml::Table::new()));
957 match entry.as_table_mut() {
958 Some(next) => current = next,
959 None => return false,
960 }
961 }
962 if overwrite || !current.contains_key(last) {
963 current.insert(last.clone(), value);
964 true
965 } else {
966 false
967 }
968 }
969
970 fn apply_op_to_document(doc: &mut toml_edit::DocumentMut, op: Op) -> Result<bool> {
971 let (path, value) = match op {
972 Op::Move { from, to, value } => {
973 // Move the value as written, trailing comment included.
974 let carried = comment_travelling_with(doc, &from);
975 let written = document_value(doc, &from)
976 .or_else(|| toml_value_to_edit(&value))
977 .with_context(|| format!("cannot represent `{}` as a TOML value", to.join(".")))?;
978 let segments: Vec<&str> = to.iter().map(String::as_str).collect();
979 crate::set_config_document_value(doc, &segments, written).with_context(|| {
980 format!("cannot move `{}` to `{}`", from.join("."), to.join("."))
981 })?;
982 apply_op_to_document(doc, Op::Remove(from))?;
983 if let Some(comment) = carried {
984 set_key_comment(doc, &to, &comment);
985 }
986 return Ok(true);
987 }
988 Op::Set(path, value) => (path, value),
989 Op::SetIfAbsent(path, value) if !document_has(doc, &path) => (path, value),
990 Op::SetIfAbsent(..) => return Ok(false),
991 Op::KeepConflict { .. } => return Ok(true),
992 Op::Remove(path) => {
993 let segments: Vec<&str> = path.iter().map(String::as_str).collect();
994 crate::unset_config_document_value(doc, &segments)
995 .with_context(|| format!("cannot remove `{}`", path.join(".")))?;
996 return Ok(true);
997 }
998 };
999 let segments: Vec<&str> = path.iter().map(String::as_str).collect();
1000 let value = toml_value_to_edit(&value)
1001 .with_context(|| format!("cannot represent `{}` as a TOML value", path.join(".")))?;
1002 crate::set_config_document_value(doc, &segments, value)
1003 .with_context(|| format!("cannot set `{}`", path.join(".")))?;
1004 Ok(true)
1005 }
1006
1007 /// Conflicting pairs `(root path, table path)` a document still holds.
1008 fn conflict_sites(root: &toml::Table) -> Vec<(Vec<String>, Vec<String>)> {
1009 plan(root, Mode::Document(None))
1010 .into_iter()
1011 .filter_map(|planned| match planned.op {
1012 Op::KeepConflict { root, table } => Some((root, table)),
1013 _ => None,
1014 })
1015 .collect()
1016 }
1017
1018 fn value_at<'a>(root: &'a toml::Table, path: &[String]) -> Option<&'a toml::Value> {
1019 let (last, parents) = path.split_last()?;
1020 let mut current = root;
1021 for part in parents {
1022 current = current.get(part)?.as_table()?;
1023 }
1024 current.get(last)
1025 }
1026
1027 fn set_document_value(doc: &mut toml_edit::DocumentMut, path: &[String], value: &toml::Value) {
1028 let segments: Vec<&str> = path.iter().map(String::as_str).collect();
1029 if let Some(value) = toml_value_to_edit(value) {
1030 let _ = crate::set_config_document_value(doc, &segments, value);
1031 }
1032 }
1033
1034 /// Put back conflicting pairs that a typed save dropped.
1035 ///
1036 /// A typed save writes the in-memory view, where the conflict was already
1037 /// resolved and the top-level key is gone. Unless the user changed that exact
1038 /// value during the session, both keys go back exactly as they were in
1039 /// `original_raw`. Returns whether the document changed.
1040 pub fn restore_conflicts(doc: &mut toml_edit::DocumentMut, original_raw: &str) -> bool {
1041 let Ok(original) = toml::from_str::<toml::Table>(original_raw) else {
1042 return false;
1043 };
1044 let sites = conflict_sites(&original);
1045 if sites.is_empty() {
1046 return false;
1047 }
1048 let mut canonical = original.clone();
1049 apply_to_table(&mut canonical);
1050 let Some(current) = document_table(doc) else {
1051 return false;
1052 };
1053 let mut changed = false;
1054 for (root_path, table_path) in sites {
1055 if value_at(&current, &table_path) != value_at(&canonical, &table_path) {
1056 // The user wrote this value during the session: their write wins
1057 // and the top-level key stays gone.
1058 continue;
1059 }
1060 if let (Some(table_value), Some(root_value)) = (
1061 value_at(&original, &table_path),
1062 value_at(&original, &root_path),
1063 ) {
1064 set_document_value(doc, &table_path, table_value);
1065 set_document_value(doc, &root_path, root_value);
1066 changed = true;
1067 }
1068 }
1069 changed
1070 }
1071
1072 /// Table values of the conflicting pairs in `doc`, taken before a targeted
1073 /// write so [`settle_conflicts_after_write`] can tell what the user changed.
1074 pub(crate) type ConflictSnapshot = Vec<(Vec<String>, Vec<String>, Option<toml::Value>)>;
1075
1076 pub(crate) fn conflict_snapshot(doc: &toml_edit::DocumentMut) -> ConflictSnapshot {
1077 let Some(table) = document_table(doc) else {
1078 return Vec::new();
1079 };
1080 conflict_sites(&table)
1081 .into_iter()
1082 .map(|(root, path)| {
1083 let value = value_at(&table, &path).cloned();
1084 (root, path, value)
1085 })
1086 .collect()
1087 }
1088
1089 /// After a targeted write: when the write changed (or removed) the table side
1090 /// of a conflicting pair, that explicit choice ends the conflict and the
1091 /// top-level key is removed.
1092 pub(crate) fn settle_conflicts_after_write(
1093 doc: &mut toml_edit::DocumentMut,
1094 snapshot: ConflictSnapshot,
1095 ) {
1096 if snapshot.is_empty() {
1097 return;
1098 }
1099 let Some(current) = document_table(doc) else {
1100 return;
1101 };
1102 for (root_path, table_path, before) in snapshot {
1103 if value_at(&current, &table_path) != before.as_ref()
1104 && let Err(err) = apply_op_to_document(doc, Op::Remove(root_path))
1105 {
1106 tracing::warn!("failed to remove settled legacy conflict key: {err:#}");
1107 }
1108 }
1109 }
1110
1111 static PENDING_NOTICES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
1112
1113 /// Queue the one-line notice for a write that moved legacy top-level keys.
1114 pub(crate) fn queue_notice(receipt: &LegacyRootMigration, backup: &std::path::Path) {
1115 let Some(summary) = receipt.summary() else {
1116 return;
1117 };
1118 let line = format!("{summary}; backup at {}", backup.display());
1119 if let Ok(mut pending) = PENDING_NOTICES.lock()
1120 && !pending.contains(&line)
1121 {
1122 pending.push(line);
1123 }
1124 }
1125
1126 /// Drain the notices queued by writes that moved legacy top-level keys. Each
1127 /// notice is returned exactly once.
1128 #[must_use]
1129 pub fn take_notices() -> Vec<String> {
1130 PENDING_NOTICES
1131 .lock()
1132 .map(|mut pending| std::mem::take(&mut *pending))
1133 .unwrap_or_default()
1134 }
1135
1136 fn table_like_at<'a>(
1137 doc: &'a toml_edit::DocumentMut,
1138 parents: &[String],
1139 ) -> Option<&'a dyn toml_edit::TableLike> {
1140 let mut current: &dyn toml_edit::TableLike = doc.as_table();
1141 for part in parents {
1142 current = current.get(part)?.as_table_like()?;
1143 }
1144 Some(current)
1145 }
1146
1147 /// The comment written directly above the key at `path`, when removing the
1148 /// key would otherwise drop it: the next key already has a comment of its
1149 /// own, or there is no next key. (When the next key has none, removal hands
1150 /// the comment to it, which keeps a file header at the top.)
1151 fn comment_travelling_with(doc: &toml_edit::DocumentMut, path: &[String]) -> Option<String> {
1152 let (key, parents) = path.split_last()?;
1153 let table = table_like_at(doc, parents)?;
1154 let prefix = table.key(key)?.leaf_decor().prefix()?.as_str()?.to_string();
1155 if !prefix.contains('#') {
1156 return None;
1157 }
1158 let mut found = false;
1159 let next_prefix_empty = table
1160 .iter()
1161 .find_map(|(candidate, _)| {
1162 if found {
1163 Some(candidate.to_owned())
1164 } else {
1165 found = candidate == key.as_str();
1166 None
1167 }
1168 })
1169 .and_then(|next| {
1170 table.key(&next).map(|next| {
1171 next.leaf_decor()
1172 .prefix()
1173 .and_then(|prefix| prefix.as_str())
1174 .is_none_or(str::is_empty)
1175 })
1176 })
1177 .unwrap_or(false);
1178 (!next_prefix_empty).then(|| prefix.trim_start_matches(['\n', '\r']).to_string())
1179 }
1180
1181 fn set_key_comment(doc: &mut toml_edit::DocumentMut, path: &[String], comment: &str) {
1182 let Some((key, parents)) = path.split_last() else {
1183 return;
1184 };
1185 let mut current: &mut dyn toml_edit::TableLike = doc.as_table_mut();
1186 for part in parents {
1187 match current
1188 .get_mut(part)
1189 .and_then(toml_edit::Item::as_table_like_mut)
1190 {
1191 Some(next) => current = next,
1192 None => return,
1193 }
1194 }
1195 if let Some(mut key) = current.key_mut(key) {
1196 key.leaf_decor_mut().set_prefix(comment);
1197 }
1198 }
1199
1200 fn document_value(doc: &toml_edit::DocumentMut, path: &[String]) -> Option<toml_edit::Value> {
1201 let (key, parents) = path.split_last()?;
1202 let mut value = table_like_at(doc, parents)?.get(key)?.as_value()?.clone();
1203 // The destination key supplies its own leading spacing.
1204 value.decor_mut().set_prefix(" ");
1205 Some(value)
1206 }
1207
1208 fn document_has(doc: &toml_edit::DocumentMut, path: &[String]) -> bool {
1209 let mut item: &toml_edit::Item = doc.as_item();
1210 for part in path {
1211 match item.get(part) {
1212 Some(next) => item = next,
1213 None => return false,
1214 }
1215 }
1216 true
1217 }
1218
1219 fn toml_value_to_edit(value: &toml::Value) -> Option<toml_edit::Value> {
1220 match value {
1221 toml::Value::String(text) => Some(toml_edit::Value::from(text.as_str())),
1222 other => other.to_string().parse::<toml_edit::Value>().ok(),
1223 }
1224 }
1225
1226 #[cfg(test)]
1227 mod tests;
1228
1228 lines RUST