-
-
Notifications
You must be signed in to change notification settings - Fork 770
Expand file tree
/
Copy pathmain.rs
More file actions
366 lines (318 loc) 路 8 KB
/
Copy pathmain.rs
File metadata and controls
366 lines (318 loc) 路 8 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//!
//! The gitui program is a text-based UI for working with a Git repository.
//! The main navigation occurs between a number of tabs.
//! When you execute commands, the program may use popups to communicate
//! with the user. It is possible to customize the keybindings.
//!
//!
//! ## Internal Modules
//! The top-level modules of gitui can be grouped as follows:
//!
//! - User Interface
//! - [tabs] for main navigation
//! - [components] for visual elements used on tabs
//! - [popups] for temporary dialogs
//! - [ui] for tooling like scrollbars
//! - Git Interface
//! - [asyncgit] (crate) for async operations on repository
//! - Distribution and Documentation
//! - Project files
//! - Github CI
//! - Installation files
//! - Usage guides
//!
//! ## Included Crates
//! Some crates are part of the gitui repository:
//! - [asyncgit] for Git operations in the background.
//! - git2-hooks (used by asyncgit).
//! - git2-testing (used by git2-hooks).
//! - invalidstring used by asyncgit for testing with invalid strings.
//! - [filetreelist] for a tree view of files.
//! - [scopetime] for measuring execution time.
//!
#![forbid(unsafe_code)]
#![deny(
mismatched_lifetime_syntaxes,
unused_imports,
unused_must_use,
dead_code,
unstable_name_collisions,
unused_assignments
)]
#![deny(clippy::all, clippy::perf, clippy::nursery, clippy::pedantic)]
#![deny(
clippy::unwrap_used,
clippy::filetype_is_file,
clippy::cargo,
clippy::panic,
clippy::match_like_matches_macro
)]
#![allow(
clippy::multiple_crate_versions,
clippy::bool_to_int_with_if,
clippy::module_name_repetitions,
clippy::empty_docs,
clippy::unnecessary_debug_formatting
)]
//TODO:
// #![deny(clippy::expect_used)]
mod app;
mod args;
mod bug_report;
mod clipboard;
mod cmdbar;
mod components;
mod gitui;
mod input;
mod keys;
mod notify_mutex;
mod options;
mod popup_stack;
mod popups;
mod queue;
mod spinner;
mod string_utils;
mod strings;
mod tabs;
mod ui;
mod watcher;
use crate::{
app::App,
args::{process_cmdline, CliArgs},
};
use anyhow::{anyhow, bail, Result};
use app::QuitState;
use asyncgit::{sync::RepoPath, AsyncGitNotification};
use backtrace::Backtrace;
use crossbeam_channel::{Receiver, Select};
use crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen,
LeaveAlternateScreen,
},
ExecutableCommand,
};
use gitui::Gitui;
use input::InputEvent;
use keys::KeyConfig;
use ratatui::backend::CrosstermBackend;
use scopeguard::defer;
use std::{
io::{self, Stdout},
panic,
path::Path,
time::{Duration, Instant},
};
use ui::style::Theme;
type Terminal = ratatui::Terminal<CrosstermBackend<io::Stdout>>;
static TICK_INTERVAL: Duration = Duration::from_secs(5);
static SPINNER_INTERVAL: Duration = Duration::from_millis(80);
///
#[derive(Clone)]
pub enum QueueEvent {
Tick,
Notify,
SpinnerUpdate,
AsyncEvent(AsyncNotification),
InputEvent(InputEvent),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SyntaxHighlightProgress {
Progress,
Done,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsyncAppNotification {
///
SyntaxHighlighting(SyntaxHighlightProgress),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsyncNotification {
///
App(AsyncAppNotification),
///
Git(AsyncGitNotification),
}
#[derive(Clone, Copy, PartialEq)]
enum Updater {
Ticker,
NotifyWatcher,
}
/// Do `log::error!` and `eprintln!` in one line.
macro_rules! log_eprintln {
( $($arg:tt)* ) => {{
log::error!($($arg)*);
eprintln!($($arg)*);
}};
}
fn main() -> Result<()> {
let app_start = Instant::now();
let mut cliargs = process_cmdline()?;
asyncgit::register_tracing_logging();
ensure_valid_path(&cliargs.repo_path)?;
// pin to the repo root so operations survive deletion of the cwd
cliargs.repo_path = cliargs.repo_path.resolve_root()?;
let key_config = KeyConfig::init(
cliargs.key_bindings_path.as_ref(),
cliargs.key_symbols_path.as_ref(),
)
.map_err(|e| log_eprintln!("KeyConfig loading error: {e}"))
.unwrap_or_default();
let theme = Theme::init(&cliargs.theme);
setup_terminal()?;
defer! {
shutdown_terminal();
}
set_panic_handler()?;
let mut terminal =
start_terminal(io::stdout(), &cliargs.repo_path)?;
let updater = if cliargs.notify_watcher {
Updater::NotifyWatcher
} else {
Updater::Ticker
};
let mut args = cliargs;
loop {
let quit_state = run_app(
app_start,
args.clone(),
theme.clone(),
&key_config,
updater,
&mut terminal,
)?;
match quit_state {
QuitState::OpenSubmodule(p) => {
args = CliArgs {
repo_path: p,
select_file: None,
theme: args.theme,
notify_watcher: args.notify_watcher,
key_bindings_path: args.key_bindings_path,
key_symbols_path: args.key_symbols_path,
}
}
_ => break,
}
}
Ok(())
}
fn run_app(
app_start: Instant,
cliargs: CliArgs,
theme: Theme,
key_config: &KeyConfig,
updater: Updater,
terminal: &mut Terminal,
) -> Result<QuitState, anyhow::Error> {
let mut gitui = Gitui::new(cliargs, theme, key_config, updater)?;
log::trace!("app start: {} ms", app_start.elapsed().as_millis());
gitui.run_main_loop(terminal)
}
fn setup_terminal() -> Result<()> {
enable_raw_mode()?;
io::stdout().execute(EnterAlternateScreen)?;
Ok(())
}
fn shutdown_terminal() {
let leave_screen =
io::stdout().execute(LeaveAlternateScreen).map(|_f| ());
if let Err(e) = leave_screen {
log::error!("leave_screen failed:\n{e}");
}
let leave_raw_mode = disable_raw_mode();
if let Err(e) = leave_raw_mode {
log::error!("leave_raw_mode failed:\n{e}");
}
}
fn draw<B: ratatui::backend::Backend>(
terminal: &mut ratatui::Terminal<B>,
app: &App,
) -> Result<(), B::Error> {
if app.requires_redraw() {
terminal.clear()?;
}
terminal.draw(|f| {
if let Err(e) = app.draw(f) {
log::error!("failed to draw: {e:?}");
}
})?;
Ok(())
}
fn ensure_valid_path(repo_path: &RepoPath) -> Result<()> {
match asyncgit::sync::repo_open_error(repo_path) {
Some(e) => {
log::error!("invalid repo path: {e}");
bail!("invalid repo path: {e}")
}
None => Ok(()),
}
}
fn select_event(
rx_input: &Receiver<InputEvent>,
rx_git: &Receiver<AsyncGitNotification>,
rx_app: &Receiver<AsyncAppNotification>,
rx_ticker: &Receiver<Instant>,
rx_notify: &Receiver<()>,
rx_spinner: &Receiver<Instant>,
) -> Result<QueueEvent> {
let mut sel = Select::new();
sel.recv(rx_input);
sel.recv(rx_git);
sel.recv(rx_app);
sel.recv(rx_ticker);
sel.recv(rx_notify);
sel.recv(rx_spinner);
let oper = sel.select();
let index = oper.index();
let ev = match index {
0 => oper.recv(rx_input).map(QueueEvent::InputEvent),
1 => oper.recv(rx_git).map(|e| {
QueueEvent::AsyncEvent(AsyncNotification::Git(e))
}),
2 => oper.recv(rx_app).map(|e| {
QueueEvent::AsyncEvent(AsyncNotification::App(e))
}),
3 => oper.recv(rx_ticker).map(|_| QueueEvent::Notify),
4 => oper.recv(rx_notify).map(|()| QueueEvent::Notify),
5 => oper.recv(rx_spinner).map(|_| QueueEvent::SpinnerUpdate),
_ => bail!("unknown select source"),
}?;
Ok(ev)
}
fn start_terminal(
buf: Stdout,
repo_path: &RepoPath,
) -> Result<Terminal> {
let mut path = repo_path.gitpath().canonicalize()?;
let home = dirs::home_dir().ok_or_else(|| {
anyhow!("failed to find the home directory")
})?;
if path.starts_with(&home) {
let relative_part = path
.strip_prefix(&home)
.expect("can't fail because of the if statement");
path = Path::new("~").join(relative_part);
}
let mut backend = CrosstermBackend::new(buf);
backend.execute(crossterm::terminal::SetTitle(format!(
"gitui ({})",
path.display()
)))?;
let mut terminal = Terminal::new(backend)?;
terminal.hide_cursor()?;
terminal.clear()?;
Ok(terminal)
}
fn set_panic_handler() -> Result<()> {
panic::set_hook(Box::new(|e| {
let backtrace = Backtrace::new();
shutdown_terminal();
log_eprintln!("\nGitUI was closed due to an unexpected panic.\nPlease file an issue on https://github.com/gitui-org/gitui/issues with the following info:\n\n{e}\n\ntrace:\n{backtrace:?}");
}));
// global threadpool
rayon_core::ThreadPoolBuilder::new()
.num_threads(4)
.build_global()?;
Ok(())
}