1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Terminal lifecycle + event loop. Panic hook restores the terminal
//! before printing (PLAN.md §9: no stray output outside the draw path).
use clap::Parser;
use ratatui::crossterm::{
ExecutableCommand,
cursor::SetCursorStyle,
event::{self, Event},
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{Terminal, backend::CrosstermBackend};
use rootle::app::App;
use rootle::cli::{Cli, ProviderCommand};
use rootle::config::Config;
use std::io::{self, stdout};
use std::time::Duration;
fn main() -> io::Result<()> {
// clap handles --version/-V (release pipeline smoke check) and --help.
let cli = Cli::parse();
// Provider manager (plans/0010 M3): subcommands run and exit —
// the TUI never starts.
if let Some(cmd) = &cli.provider {
run_provider(cmd);
return Ok(());
}
// Self-update (plans/0017 M2, 0018 M1, 0019 M1): run-and-exit —
// app half then the provider sweep, all output owned by the flow
// (stages on stderr, outcome lines on stdout).
if cli.update {
if let Err(e) = rootle::update::update(cli.check) {
eprintln!("update: {e}");
std::process::exit(1);
}
return Ok(());
}
// Headless driver (plans/0023 M1): scripted, deterministic —
// run-and-exit before any terminal setup, like the subcommands.
if cli.headless.is_some() {
return rootle::headless::run_cli(&cli);
}
// A full-screen TUI's colors are semantic (mode chips, dirs vs
// files), not decoration — ignore NO_COLOR like vim/helix do.
ratatui::crossterm::style::Colored::set_ansi_color_disabled(false);
enable_raw_mode()?;
stdout().execute(EnterAlternateScreen)?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
// On panic: restore the terminal first, then let the hook print.
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = disable_raw_mode();
let _ = stdout().execute(SetCursorStyle::DefaultUserShape);
let _ = stdout().execute(LeaveAlternateScreen);
default_hook(info);
}));
let result = run(&mut terminal, cli);
disable_raw_mode()?;
// Restore the user's cursor shape — never leave it mutated (PLAN.md §5).
stdout().execute(SetCursorStyle::DefaultUserShape)?;
stdout().execute(LeaveAlternateScreen)?;
// 0018 M3: the restart trace lands on the real screen, after the
// alternate screen is gone.
match result {
Ok(Some(line)) => println!("{line}"),
Ok(None) => {}
Err(e) => return Err(e),
}
Ok(())
}
/// SIGTERM/SIGINT set this; the poll loop exits through the normal
/// cleanup path (terminal restore + App drop kills provider children).
fn terminated_flag() -> &'static std::sync::Arc<std::sync::atomic::AtomicBool> {
static FLAG: std::sync::OnceLock<std::sync::Arc<std::sync::atomic::AtomicBool>> =
std::sync::OnceLock::new();
FLAG.get_or_init(|| std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)))
}
fn run(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
cli: Cli,
) -> io::Result<Option<String>> {
{
use signal_hook::consts::{SIGINT, SIGTERM};
let _ = signal_hook::flag::register(SIGTERM, terminated_flag().clone());
let _ = signal_hook::flag::register(SIGINT, terminated_flag().clone());
}
let config = match &cli.config {
Some(path) => Config::load_from(path),
None => Config::load(),
};
let theme = cli.resolve_theme(&config);
let (tx, rx) = rootle::event::channel();
let mut app = App::new(tx, config, theme);
// `rootle owner/repo`: skip search, go straight to browsing.
// `owner/repo@ref` (plans/0016 M1a): open AT the revision — the ref
// lands first, so the tree spawn below reads it.
if let Some((owner, name, ref_)) = cli.repo_parts() {
if let Some(r) = ref_ {
app.handle_action(rootle::action::Action::RefsCommit(r));
}
app.handle_action(rootle::action::Action::RepoSelected { owner, name });
}
let mut last_cursor_style: Option<SetCursorStyle> = None;
loop {
// Drain worker outcomes before drawing so a completed fetch
// renders on this frame, not the next.
while let Ok(event) = rx.try_recv() {
app.handle_app_event(event);
}
// Full clear must precede the draw: Terminal::clear resets the
// diff buffers, so the next draw re-renders every cell. Clearing
// after a draw would leave the screen blank until the next event.
if app.force_redraw {
app.force_redraw = false;
terminal.clear()?;
}
terminal.draw(|frame| {
let area = frame.area();
app.render(frame, area);
})?;
// Cursor shape follows input mode (bar=INSERT, block=NORMAL).
// Emit only on CHANGE — repeating it every frame spams the
// stream and races ratatui's own hide/show bookkeeping.
let style = app.cursor_style();
let changed = !matches!(
(style, last_cursor_style),
(None, None)
| (
Some(SetCursorStyle::SteadyBar),
Some(SetCursorStyle::SteadyBar)
)
| (
Some(SetCursorStyle::SteadyBlock),
Some(SetCursorStyle::SteadyBlock)
)
| (
Some(SetCursorStyle::DefaultUserShape),
Some(SetCursorStyle::DefaultUserShape)
)
);
if changed {
if let Some(style) = style {
stdout().execute(style)?;
}
last_cursor_style = style;
}
if event::poll(Duration::from_millis(250))? {
// Resize: ratatui resizes its buffers automatically; the
// next draw rewrites every cell. No manual clear (blink).
if let Event::Key(key) = event::read()? {
app.handle_key(key);
}
}
// Yank: write to the clipboard outside the draw path.
if let Some(text) = app.take_clipboard() {
rootle::clipboard::copy(&text);
}
// Editor: suspend the terminal, run the editor to completion,
// resume with a full redraw (the one legitimate clear).
if let Some(job) = app.take_editor_job() {
run_editor(terminal, job)?;
last_cursor_style = None; // editor reset the shape
}
if app.should_quit || terminated_flag().load(std::sync::atomic::Ordering::Relaxed) {
// 0018 M3: compare the on-disk binary once, post-update
// sessions only — main prints it after terminal restore.
return Ok(app.update_exit_note());
}
}
}
fn run_editor(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
job: rootle::editor::EditorJob,
) -> io::Result<()> {
// Suspend: leave the alternate screen, raw mode off, cursor normal.
disable_raw_mode()?;
stdout().execute(LeaveAlternateScreen)?;
stdout().execute(SetCursorStyle::DefaultUserShape)?;
let status = std::process::Command::new(&job.program)
.args(&job.args)
.status();
rootle::app::trace(&format!(
"editor {} exited: {}",
job.program,
status
.map(|s| s.to_string())
.unwrap_or_else(|e| e.to_string())
));
// Resume: raw mode + alternate screen again, then a full clear —
// the editor scribbled on the screen, so the diff is unusable.
enable_raw_mode()?;
stdout().execute(EnterAlternateScreen)?;
terminal.clear()?;
// Drain input queued while suspended (editor residue, resizes).
while event::poll(Duration::from_millis(0))? {
let _ = event::read()?;
}
Ok(())
}
/// Dispatch the provider subcommand tree (plans/0010 M3).
fn run_provider(cmd: &ProviderCommand) {
use rootle::provider::manager::{Manager, Ref};
let manager = match Manager::new() {
Ok(m) => m,
Err(e) => {
eprintln!("rootle provider: {e}");
std::process::exit(1);
}
};
let result: std::result::Result<(), rootle::provider::manager::ManagerError> = match cmd {
ProviderCommand::Install {
ref_,
pin,
force,
path,
} => {
if let Some(path) = path {
// --path: local binary install (gh's `gh extension
// install .` model); ref_ carries the name.
manager.install_path(ref_, path).map(|_| ())
} else {
let mut r = match Ref::parse(ref_) {
Ok(r) => r,
Err(e) => {
eprintln!("{e}");
std::process::exit(1);
}
};
if *pin && r.tag.is_none() {
// Pin to the latest at install time.
eprintln!("--pin without @tag: pinning to the latest release");
}
r.tag = r.tag.take(); // no-op, keeps the Option alive
manager.install(&r, *force).map(|_| ())
}
}
ProviderCommand::List { json } => {
let installed = manager.list();
if *json {
let rows: Vec<serde_json::Value> = installed
.iter()
.map(|i| {
serde_json::json!({
"name": i.receipt.name,
"version": i.receipt.tag,
"pinned": i.receipt.pinned,
"source": i.receipt.source,
"active": i.active,
})
})
.collect();
println!("{}", serde_json::to_string_pretty(&rows).unwrap());
} else {
let ui = rootle::provider::ui::Ui::new();
if installed.is_empty() {
ui.empty_hint();
return;
}
for i in &installed {
ui.row(
&i.receipt.name,
&i.receipt.tag,
&i.receipt.source,
i.active,
i.receipt.pinned,
);
}
}
Ok(())
}
ProviderCommand::Update { name } => match manager.update(name.as_deref()) {
Ok(stale) => {
if stale.is_empty() {
println!("all providers current");
} else {
for (name, from, to) in stale {
println!(
" {name}: {from} → {to} (upgrade with `rootle provider upgrade {name}`)"
);
}
}
Ok(())
}
Err(e) => Err(e),
},
ProviderCommand::Upgrade {
name,
all,
dry_run,
force,
} => {
let target = if *all { None } else { name.as_deref() };
if !*all && name.is_none() {
eprintln!("specify a provider name or --all");
std::process::exit(1);
}
manager.upgrade(target, *dry_run, *force)
}
ProviderCommand::Pin { name, tag } => manager.pin(name, tag.clone()),
ProviderCommand::Unpin { name } => manager.unpin(name),
ProviderCommand::Remove { name } => manager.remove(name),
ProviderCommand::Use { name, extra } => manager.activate(name, extra),
};
if let Err(e) = result {
eprintln!("rootle provider: {e}");
std::process::exit(1);
}
}