Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 44 additions & 10 deletions crates/tw-adopt/src/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,32 +24,66 @@ use std::path::{Path, PathBuf};
use thiserror::Error;
use tw_types::{Msg, msg};

/// 往别人的配置文件里写的时候,哪一道没过。
///
/// **英文只写一遍**:`Display` 就是 [`ForeignError::msg`] 的原句,界面拿码去翻。
#[derive(Debug, Error)]
pub enum ForeignError {
#[error("{path} could not be read: {source}")]
#[error("{}", self.msg())]
Read {
path: PathBuf,
source: std::io::Error,
},
#[error("{path} could not be written: {source}")]
#[error("{}", self.msg())]
Write {
path: PathBuf,
source: std::io::Error,
},
#[error(
"{path} changed after it was confirmed, so nothing was written. Look at the change again"
)]
#[error("{}", self.msg())]
ChangedUnderUs { path: PathBuf },
#[error("the edited content did not pass its check, so nothing was written ({0})")]
/// 里面是解析器的原话,或者「和预期的改动对不上」那一句
#[error("{}", self.msg())]
VerifyFailed(String),
#[error(
"what was read back after writing is not what was expected; restored from the backup: {path}"
)]
#[error("{}", self.msg())]
Readback { path: PathBuf },
#[error("too many levels of symbolic link: {path}")]
#[error("{}", self.msg())]
LinkLoop { path: PathBuf },
}

impl ForeignError {
/// 给人看的那句话,带码。`Read` / `Write` 的 `detail` 是系统的原话。
pub fn msg(&self) -> Msg {
match self {
ForeignError::Read { path, source } => msg!(
"adopt.file.read_failed", path = path.display(), detail = source =>
"{path} could not be read: {detail}"
),
ForeignError::Write { path, source } => msg!(
"adopt.file.write_failed", path = path.display(), detail = source =>
"{path} could not be written: {detail}"
),
ForeignError::ChangedUnderUs { path } => msg!(
"adopt.file.changed", path = path.display() =>
"{path} changed after it was confirmed, so nothing was written. Look at the \
change again"
),
ForeignError::VerifyFailed(d) => msg!(
"adopt.file.verify_failed", detail = d =>
"the edited content did not pass its check, so nothing was written ({detail})"
),
ForeignError::Readback { path } => msg!(
"adopt.file.readback_mismatch", path = path.display() =>
"what was read back after writing is not what was expected; restored from the \
backup: {path}"
),
ForeignError::LinkLoop { path } => msg!(
"adopt.file.link_loop", path = path.display() =>
"too many levels of symbolic link: {path}"
),
}
}
}

/// 写完之后的交代。**每一项都要能在 UI 上说出来** —— 用户敢按「接管」
/// 的前提是相信能退回去,那就得让他看见退路在哪儿。
#[derive(Debug, Clone)]
Expand Down
56 changes: 44 additions & 12 deletions crates/tw-adopt/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,53 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use tw_types::Msg;
use tw_types::{Msg, msg};

use crate::clients::Format;
use crate::foreign::{self, Applied, Change, ForeignError};
use crate::json::Val;

/// 搬 MCP server 时的失败。
///
/// **英文只写一遍**:`Display` 就是 [`McpError::msg`] 的原句,界面拿码去翻。
#[derive(Debug, thiserror::Error)]
pub enum McpError {
#[error("{0} is not a client we know")]
#[error("{}", self.msg())]
UnknownClient(String),
#[error("the MCP configuration of {client} could not be parsed, so nothing was changed: {msg}")]
#[error("{}", self.msg())]
Parse { client: String, msg: String },
#[error("{0}")]
#[error(transparent)]
Write(#[from] ForeignError),
#[error("{client} has no MCP server named `{name}`")]
#[error("{}", self.msg())]
NotThere { client: String, name: String },
#[error(
"the MCP configuration format of {client} is unverified, so it is not written to ({why})"
)]
NotCopyable { client: String, why: String },
/// 不能写的那个理由,带码。见 [`Target::why_not`]
#[error("{}", self.msg())]
NotCopyable { client: String, why: Msg },
}

impl McpError {
/// 给人看的那句话,带码。
pub fn msg(&self) -> Msg {
match self {
McpError::UnknownClient(client) => msg!(
"adopt.mcp.unknown_client", client = client =>
"{client} is not a client we know"
),
McpError::Parse { client, msg } => msg!(
"adopt.mcp.parse_failed", client = client, detail = msg =>
"the MCP configuration of {client} could not be parsed, so nothing was changed: \
{detail}"
),
McpError::Write(e) => e.msg(),
McpError::NotThere { client, name } => msg!(
"adopt.mcp.not_there", client = client, name = name =>
"{client} has no MCP server named `{name}`"
),
// **理由那半句本来就有自己的码**(`adopt.mcp.unverified_format` 那几条),
// 套进一句「格式未验证」里就又成了英文 —— 直接说理由
McpError::NotCopyable { why, .. } => why.clone(),
}
}
}

/// 一个能被写入的 MCP 配置位置。
Expand Down Expand Up @@ -151,9 +178,14 @@ impl Target {
} else {
Err(McpError::NotCopyable {
client: self.client.to_string(),
// 这一条是护栏:界面对不能写的目标根本不给按钮。
// 英文原句就够了,控制面会把它当 detail 包进去
why: self.why_not.map(|(_, t)| t.to_string()).unwrap_or_default(),
// 这一条是护栏:界面对不能写的目标根本不给按钮
why: self.why_not().unwrap_or_else(|| {
msg!(
"adopt.mcp.not_copyable", client = self.client =>
"the MCP configuration format of {client} is unverified, so it is not \
written to"
)
}),
})
}
}
Expand Down
146 changes: 135 additions & 11 deletions crates/tw-adopt/src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,64 @@ use crate::foreign::{self, Applied, Change, ForeignError};
use crate::json::Val;
use crate::sentinel::{self, Original, SidecarRecord, Was};

/// 接管或还原算不出来、落不了盘的原因。
///
/// **英文只写一遍**:`Display` 就是 [`PlanError::msg`] 的原句,界面拿码去翻。
#[derive(Debug, thiserror::Error)]
pub enum PlanError {
#[error("the configuration of {client} could not be read: {source}")]
#[error("{}", self.msg())]
Read {
client: String,
source: ForeignError,
},
#[error("the configuration of {client} could not be parsed, so nothing was changed: {msg}")]
#[error("{}", self.msg())]
Parse { client: String, msg: String },
#[error("{0}")]
#[error(transparent)]
Write(#[from] ForeignError),
#[error("the record beside {path} belongs to {other}, not {client}, so nothing was changed")]
#[error("{}", self.msg())]
ForeignSidecar {
path: PathBuf,
other: String,
client: String,
},
#[error(
"there is no record for {client}, so there is nothing to restore from. To restore by hand, look at {path}"
)]
#[error("{}", self.msg())]
NoRecord { client: String, path: PathBuf },
#[error(
"the original value for {client} is a secret kept only in the full backup, and the backup {backup} is gone"
)]
SecretGone { client: String, backup: PathBuf },
}

impl PlanError {
/// 给人看的那句话,带码。
pub fn msg(&self) -> Msg {
match self {
// **读不到的那个文件本身就是该客户端的配置**,所以直接说文件那一句:
// 两句套在一起(「X 的配置读不出来:某文件读不出来:…」)只是把同一件
// 事说了两遍
PlanError::Read { client, source } => match source {
ForeignError::Read { path, source } => msg!(
"adopt.plan.read_failed", client = client, path = path.display(), detail = source =>
"the configuration of {client} could not be read: {path}: {detail}"
),
other => other.msg(),
},
PlanError::Parse { client, msg } => msg!(
"adopt.plan.parse_failed", client = client, detail = msg =>
"the configuration of {client} could not be parsed, so nothing was changed: {detail}"
),
PlanError::Write(e) => e.msg(),
PlanError::ForeignSidecar {
path,
other,
client,
} => msg!(
"adopt.plan.foreign_record", path = path.display(), other = other, client = client =>
"the record beside {path} belongs to {other}, not {client}, so nothing was changed"
),
PlanError::NoRecord { client, path } => msg!(
"adopt.plan.no_record", client = client, path = path.display() =>
"there is no record for {client}, so there is nothing to restore from. To restore \
by hand, look at {path}"
),
}
}
}

/// 这次改动对某条路径做了什么。写回校验的参照物就是它们叠出来的。
Expand Down Expand Up @@ -623,3 +656,94 @@ fn rollback(a: &Applied) -> std::io::Result<()> {
std::fs::write(&a.real, text)
}
}

#[cfg(test)]
mod msg_codes {
use super::*;
use crate::mcp::McpError;

#[test]
fn every_adopt_error_has_its_own_code() {
let p = || PathBuf::from("/h/.claude/settings.json");
let io = || std::io::Error::other("denied");
let foreign = || {
vec![
ForeignError::Read {
path: p(),
source: io(),
},
ForeignError::Write {
path: p(),
source: io(),
},
ForeignError::ChangedUnderUs { path: p() },
ForeignError::VerifyFailed("x".into()),
ForeignError::Readback { path: p() },
ForeignError::LinkLoop { path: p() },
]
};
let mut all: Vec<(Msg, String)> = foreign()
.into_iter()
.map(|e| (e.msg(), e.to_string()))
.collect();
for e in [
PlanError::Read {
client: "claude-code".into(),
source: ForeignError::Read {
path: p(),
source: io(),
},
},
PlanError::Parse {
client: "claude-code".into(),
msg: "x".into(),
},
PlanError::ForeignSidecar {
path: p(),
other: "codex".into(),
client: "claude-code".into(),
},
PlanError::NoRecord {
client: "claude-code".into(),
path: p(),
},
] {
all.push((e.msg(), e.to_string()));
}
for e in [
McpError::UnknownClient("x".into()),
McpError::Parse {
client: "zed".into(),
msg: "x".into(),
},
McpError::NotThere {
client: "zed".into(),
name: "fs".into(),
},
] {
all.push((e.msg(), e.to_string()));
}
let mut seen = std::collections::HashSet::new();
for (m, display) in &all {
assert!(m.code.starts_with("adopt."), "{m:?}");
assert!(!m.text.is_empty() && &m.text == display, "{m:?}");
assert!(seen.insert(m.code.clone()), "码重复了:{}", m.code);
}
// 包着的那几层用里面那一句的码
let w = PlanError::Write(ForeignError::LinkLoop { path: p() });
assert_eq!(w.msg().code, "adopt.file.link_loop");
let r = PlanError::Read {
client: "x".into(),
source: ForeignError::LinkLoop { path: p() },
};
assert_eq!(r.msg().code, "adopt.file.link_loop");
// 不能写的理由本来就有码,直接说它
let e = crate::mcp::target("zed").unwrap().why_not().unwrap();
let m = McpError::NotCopyable {
client: "zed".into(),
why: e.clone(),
}
.msg();
assert_eq!(m, e);
}
}
Loading
Loading