返回 CodeWhale
ask_rules.rs
根目录 / crates / tui / src / tui / approval / ask_rules.rs
1 //! Save-preview formatting for persistent permission rules.
2 //!
3 //! The rules themselves come from
4 //! `codewhale_engine::core::authority::persistent_rules`, shared with the
5 //! Runtime approval route. This module deliberately has no modal state or
6 //! rendering code: views consume the validated rules and their bounded text
7 //! preview without re-parsing tool inputs.
8
9 use codewhale_config::ToolAskRule;
10 use codewhale_execpolicy::PermissionAction;
11 use codewhale_localization::{Locale, MessageId, tr};
12
13 /// Human-readable preview of rules an approval action would append.
14 ///
15 /// This is intentionally derived from the already validated persistent-rule
16 /// candidates; the approval UI must not re-parse tool inputs such as patches.
17 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct PermissionRuleSavePreview {
19 pub action: PermissionAction,
20 pub rule_count: usize,
21 pub entries: Vec<String>,
22 pub patterns: Vec<String>,
23 pub omitted: usize,
24 }
25
26 impl PermissionRuleSavePreview {
27 /// What saving these rules does, in the words the person reads on the
28 /// card. The entries below it name each command or file, and `omitted`
29 /// counts the rest, so the summary does not repeat a rule count (#6566).
30 #[must_use]
31 pub fn summary(&self, locale: Locale) -> String {
32 let id = match self.action {
33 PermissionAction::Allow => MessageId::ApprovalSaveSummaryAllow,
34 PermissionAction::Ask => MessageId::ApprovalSaveSummaryAsk,
35 PermissionAction::Deny => MessageId::ApprovalSaveSummaryDeny,
36 };
37 tr(locale, id).into_owned()
38 }
39
40 #[must_use]
41 pub fn pattern_text(&self) -> String {
42 let mut out = self.patterns.join(", ");
43 if self.omitted > 0 {
44 out.push_str(&format!(" (+{} more)", self.omitted));
45 }
46 out
47 }
48 }
49
50 pub(super) const SAVE_PREVIEW_MAX_ENTRIES: usize = 4;
51
52 #[must_use]
53 pub(crate) fn format_allow_rules_pattern(rules: &[ToolAskRule]) -> Option<String> {
54 build_save_preview(rules, SAVE_PREVIEW_MAX_ENTRIES).map(|preview| preview.pattern_text())
55 }
56
57 #[must_use]
58 pub(super) fn build_save_preview(
59 rules: &[ToolAskRule],
60 max_entries: usize,
61 ) -> Option<PermissionRuleSavePreview> {
62 if rules.is_empty() {
63 return None;
64 }
65
66 let entries = rules
67 .iter()
68 .take(max_entries)
69 .map(format_save_entry)
70 .collect();
71 let patterns = rules
72 .iter()
73 .take(max_entries)
74 .map(format_rule_pattern)
75 .collect();
76 Some(PermissionRuleSavePreview {
77 action: rules[0].action,
78 rule_count: rules.len(),
79 entries,
80 patterns,
81 omitted: rules.len().saturating_sub(max_entries),
82 })
83 }
84
85 #[must_use]
86 fn format_rule_pattern(rule: &ToolAskRule) -> String {
87 if let Some(command) = rule.command.as_deref() {
88 let cmd = sanitize_preview_value(command);
89 if rule.command_exact {
90 cmd
91 } else {
92 format!("{cmd} *")
93 }
94 } else if let Some(path) = rule.path.as_deref() {
95 sanitize_preview_value(path)
96 } else {
97 sanitize_preview_value(&rule.tool)
98 }
99 }
100
101 /// One saved rule as a plain phrase: what it covers ("run cargo test",
102 /// "edit src/lib.rs") and where. The card used to print the rule's config
103 /// syntax (`tool=exec_shell command=… command_exact=true`), which is the
104 /// storage format, not something a person decides on (#6566).
105 #[must_use]
106 fn format_save_entry(rule: &ToolAskRule) -> String {
107 let verb = match rule.tool.as_str() {
108 "exec_shell" if rule.command_exact => Some("run exactly"),
109 "exec_shell" => Some("run"),
110 "write_file" => Some("write"),
111 "edit_file" => Some("edit"),
112 "apply_patch" => Some("change"),
113 _ => None,
114 };
115 let target = rule
116 .command
117 .as_deref()
118 .or(rule.path.as_deref())
119 .map(sanitize_preview_value);
120 let mut entry = match (verb, target) {
121 (Some(verb), Some(target)) => format!("{verb} {target}"),
122 (Some(verb), None) => format!("{verb} ({})", sanitize_preview_value(&rule.tool)),
123 (None, Some(target)) => format!("{} {target}", sanitize_preview_value(&rule.tool)),
124 (None, None) => sanitize_preview_value(&rule.tool),
125 };
126 if let Some(workspace) = &rule.workspace {
127 entry.push_str(" in ");
128 entry.push_str(&sanitize_preview_value(workspace));
129 }
130 entry
131 }
132
133 #[must_use]
134 fn sanitize_preview_value(value: &str) -> String {
135 value
136 .replace('\\', "\\\\")
137 .replace('\r', "\\r")
138 .replace('\n', "\\n")
139 .replace('\t', "\\t")
140 }
141
141 lines RUST