serenade_console/commands/
debug_config.rs1use std::io::stdout;
4
5use crossterm::ExecutableCommand;
6use crossterm::event::{self, Event, KeyCode, KeyEventKind};
7use crossterm::terminal::{
8 EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
9};
10use ratatui::prelude::{Constraint, CrosstermBackend, Layout, Rect, Style, Terminal};
11use ratatui::widgets::{Block, Borders, Paragraph, Row, Table};
12
13use crate::application::stdout_is_terminal;
14use crate::{Command, ConsoleError, Input};
15
16#[derive(Clone, Copy, Debug, Default)]
18pub struct DebugConfigCommand;
19
20impl Command for DebugConfigCommand {
21 fn name(&self) -> &'static str {
22 "debug:config"
23 }
24
25 fn description(&self) -> &'static str {
26 "Dump config parameters (debug only; secrets redacted unless --reveal)"
27 }
28
29 fn execute(&self, input: &Input) -> Result<(), ConsoleError> {
30 if !input.debug() {
31 return Err(ConsoleError::Failed(
32 "debug:config requires debug mode (omit --no-debug; refuse in non-debug prod)"
33 .to_owned(),
34 ));
35 }
36 let reveal = input.args().iter().any(|arg| arg == "--reveal");
37 let want_plain = input.args().iter().any(|arg| arg == "--plain");
38 let prefix = input
39 .args()
40 .iter()
41 .find(|arg| !arg.starts_with('-'))
42 .map(String::as_str);
43 let rows = collect_rows(input, prefix, reveal);
44 if want_plain || !stdout_is_terminal() {
45 print_plain(input, reveal, &rows);
46 return Ok(());
47 }
48 run_tui(input, reveal, &rows)
49 }
50}
51
52fn collect_rows(input: &Input, prefix: Option<&str>, reveal: bool) -> Vec<(String, String)> {
53 let Some(container) = input.container() else {
54 return Vec::new();
55 };
56 let mut rows: Vec<(String, String)> = container
57 .parameters()
58 .iter()
59 .filter(|(key, _)| prefix.is_none_or(|prefix| key.starts_with(prefix)))
60 .map(|(key, value)| {
61 let display = if reveal || !is_sensitive(key) {
62 value.to_owned()
63 } else {
64 "***".to_owned()
65 };
66 (key.to_owned(), display)
67 })
68 .collect();
69 rows.sort_by(|left, right| left.0.cmp(&right.0));
70 rows
71}
72
73fn is_sensitive(key: &str) -> bool {
74 let lower = key.to_ascii_lowercase();
75 [
76 "password",
77 "passwd",
78 "secret",
79 "token",
80 "api_key",
81 "apikey",
82 "private_key",
83 "credential",
84 "dsn",
85 "auth",
86 ]
87 .iter()
88 .any(|needle| lower.contains(needle))
89}
90
91fn print_plain(input: &Input, reveal: bool, rows: &[(String, String)]) {
92 println!("Environment: {}", input.environment());
93 println!("Debug: {}", input.debug());
94 println!("Reveal: {reveal}");
95 if rows.is_empty() {
96 println!("Parameters: (none - pass a container via Application::run_with)");
97 return;
98 }
99 println!("Parameters ({}):", rows.len());
100 for (key, value) in rows {
101 println!(" {key} = {value}");
102 }
103}
104
105fn run_tui(input: &Input, reveal: bool, rows: &[(String, String)]) -> Result<(), ConsoleError> {
106 enable_raw_mode()?;
107 stdout().execute(EnterAlternateScreen)?;
108 let result = draw_loop(input, reveal, rows);
109 stdout().execute(LeaveAlternateScreen)?;
110 disable_raw_mode()?;
111 result
112}
113
114fn draw_loop(input: &Input, reveal: bool, rows: &[(String, String)]) -> Result<(), ConsoleError> {
115 let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
116 loop {
117 terminal.draw(|frame| {
118 let area = frame.area();
119 render(frame, area, input, reveal, rows);
120 })?;
121
122 if event::poll(std::time::Duration::from_millis(200))?
123 && let Event::Key(key) = event::read()?
124 && key.kind == KeyEventKind::Press
125 && matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)
126 {
127 break;
128 }
129 }
130 Ok(())
131}
132
133fn render(
134 frame: &mut ratatui::Frame,
135 area: Rect,
136 input: &Input,
137 reveal: bool,
138 rows: &[(String, String)],
139) {
140 let chunks = Layout::vertical([Constraint::Length(3), Constraint::Min(3)]).split(area);
141 let header = Paragraph::new(format!(
142 "debug:config env={} debug={} reveal={} (q/Esc quit)",
143 input.environment(),
144 input.debug(),
145 reveal
146 ))
147 .block(Block::default().borders(Borders::ALL).title("Serenade"));
148 frame.render_widget(header, chunks[0]);
149
150 let table_rows: Vec<Row> = if rows.is_empty() {
151 vec![Row::new(vec!["(no parameters)".to_owned(), String::new()])]
152 } else {
153 rows.iter()
154 .map(|(key, value)| Row::new(vec![key.clone(), value.clone()]))
155 .collect()
156 };
157 let table = Table::new(
158 table_rows,
159 [Constraint::Percentage(45), Constraint::Percentage(55)],
160 )
161 .header(Row::new(vec!["Key", "Value"]).style(Style::new().bold()))
162 .block(Block::default().borders(Borders::ALL).title("Parameters"));
163 frame.render_widget(table, chunks[1]);
164}