gitu/lib.rs
1pub mod app;
2mod bindings;
3mod calling_process;
4mod capped_input;
5pub mod cli;
6mod cmd_log;
7pub mod config;
8mod config_edit;
9mod config_git;
10mod diff_renderer;
11pub mod error;
12mod file_watcher;
13mod git;
14mod gitu_diff;
15mod item_data;
16mod items;
17mod key_parser;
18mod menu;
19mod ops;
20mod picker;
21mod prompt;
22mod rebase_todo;
23mod screen;
24mod search;
25mod stream;
26mod style;
27pub mod term;
28#[cfg(test)]
29mod tests;
30mod text_input;
31mod ui;
32
33use bindings::Bindings;
34use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventState, KeyModifiers};
35use error::Error;
36use git2::Repository;
37use items::Item;
38use ops::Action;
39use std::{
40 env,
41 io::{self, IsTerminal},
42 path::Path,
43 rc::Rc,
44 sync::Arc,
45 time::Duration,
46};
47use term::Term;
48
49use crate::calling_process::GitCommand;
50use crate::capped_input::Capped;
51use crate::config::Config;
52use crate::screen::pager::Paged;
53
54pub const LOG_FILE_NAME: &str = "gitu.log";
55
56// An overview of Gitu's ui and terminology:
57//
58// Screen (src/screen/*)
59// │
60// ▼
61// ┌──────────────────────────────────────────────────────────────────┐
62// Item───┬─► Branch: master │
63// Item └─► Your branch is up to date with 'origin/master'. │
64// ... │ │
65// │ Untracked files │
66// │ src/tests/rebase.rs │
67// │ │
68// │ Unstaged changes (4) │
69// │▌modified src/keybinds.rs… │
70// │ modified src/ops/mod.rs… │
71// │ modified src/ops/rebase.rs… │
72// │ modified src/tests/mod.rs… │
73// │ │
74// │ Stashes │
75// │ stash@0 On master: scroll │
76// │ stash@1 WIP on fix/run-cmd-error-on-bad-exit: 098d14a feat: prom…│
77// │ │
78// │ Recent commits │
79// Ops (src/ops/*) ├──────────────────────────────────────────────────────────────────┤
80// │ │Help Submenu modified src/keybinds.r│
81// └─────┬───►g Refresh h Help ret Show │
82// └───►tab Toggle section b Branch K Discard │
83// │k p ↑ Move up c Commit s Stage │
84// │j n ↓ Move down f Fetch u Unstage │
85// Submenu ───────►│C-k C-p C-↑ Move up line l Log │
86// │C-j C-n C-↓ Move down line F Pull │
87// │C-u Half page up P Push │
88// │C-d Half page down r Rebase │
89// │y Show refs X Reset │
90// │ z Stash │
91// └──────────────────────────────────────────────────────────────────┘
92
93pub type Res<T> = Result<T, Error>;
94
95/// Run gitu, returning the status to exit with.
96pub fn run(config: Arc<Config>, args: &cli::Args, term: &mut Term) -> Res<i32> {
97 // Before anything slower, and before reading the input: the git process on
98 // the other end of a pipe exits as soon as its output fits in the pipe, and
99 // cannot be found once it has. Reading to EOF is always too late — EOF is
100 // git closing the pipe.
101 let git_argv = args.pager.then(calling_process::paging_for).flatten();
102 log::debug!("Paging the output of {git_argv:?}");
103
104 log::debug!("Opening repo");
105 let repo = open_repo_from_env()?;
106
107 let piped = args
108 .pager
109 .then(|| read_piped_input(git_argv, repo.workdir(), config.general.max_input_bytes))
110 .transpose()?;
111
112 let mut app = app::App::create(
113 Rc::new(repo),
114 term.size().map_err(Error::Term)?,
115 args,
116 Arc::clone(&config),
117 true,
118 piped,
119 )?;
120
121 if args.quit_if_one_screen && app.print_if_one_screen(term)? {
122 return Ok(app.state.exit_code);
123 }
124
125 if args.print {
126 return run_app(&mut app, args, term);
127 }
128
129 term.setup_term(&config).map_err(Error::Term)?;
130 let result = run_app(&mut app, args, term);
131 term.reset_term(&config).map_err(Error::Term)?;
132 result
133}
134
135fn run_app(app: &mut app::App, args: &cli::Args, term: &mut Term) -> Res<i32> {
136 if let Some(keys_string) = &args.keys {
137 let ("", keys) = key_parser::parse_keys(keys_string).expect("Couldn't parse keys") else {
138 panic!("Couldn't parse keys");
139 };
140
141 for event in keys_to_events(&keys) {
142 app.handle_event(term, event)?;
143 }
144 }
145
146 app.redraw_now(term)?;
147
148 if args.print {
149 return Ok(app.state.exit_code);
150 }
151
152 app.run(term, Duration::from_millis(100))?;
153
154 Ok(app.state.exit_code)
155}
156
157/// What git piped to us as its pager, alongside the command already found to
158/// have produced it. Reading the terminal instead would wait for input that is
159/// never coming, so that is refused outright.
160fn read_piped_input(
161 git_argv: Option<Vec<String>>,
162 workdir: Option<&Path>,
163 limit: u64,
164) -> Res<Paged> {
165 if io::stdin().is_terminal() {
166 return Err(Error::PagerWithoutInput);
167 }
168
169 paged(io::stdin(), git_argv, workdir, limit)
170}
171
172/// What git piped, unless gitu found the command that produced it: then gitu
173/// asks git again itself (see [`screen::pager`]), and reading the output would
174/// only wait for git to write what is discarded. git, left blocked on a full
175/// pipe, ends with SIGPIPE when gitu exits, as it does when less quits early.
176fn paged(
177 input: impl io::Read,
178 git_argv: Option<Vec<String>>,
179 workdir: Option<&Path>,
180 limit: u64,
181) -> Res<Paged> {
182 if git_argv.clone().and_then(GitCommand::of).is_some() {
183 return Ok(Paged {
184 text: String::new(),
185 truncated: false,
186 git_argv,
187 prefix: command_prefix(workdir),
188 });
189 }
190
191 let input = Capped::read(input, limit).map_err(Error::ReadPipedInput)?;
192 Ok(Paged {
193 text: input.text,
194 truncated: input.truncated,
195 git_argv,
196 prefix: String::new(),
197 })
198}
199
200/// Where git ran the command it is paging (see [`GitCommand::prefix`]). git
201/// runs its pager from the repository's root and says in `GIT_PREFIX` where it
202/// was run; in a shell pipeline, gitu runs where git did, in `workdir`.
203fn command_prefix(workdir: Option<&Path>) -> String {
204 if let Ok(prefix) = env::var("GIT_PREFIX") {
205 return prefix;
206 }
207
208 let relative = || {
209 let dir = env::current_dir().ok()?.canonicalize().ok()?;
210 let root = workdir?.canonicalize().ok()?;
211 Some(dir.strip_prefix(root).ok()?.to_str()?.to_owned())
212 };
213 match relative() {
214 Some(dir) if !dir.is_empty() => format!("{dir}/"),
215 _ => String::new(),
216 }
217}
218
219fn open_repo(dir: &Path) -> Res<Repository> {
220 log::debug!("Opening repo");
221 let repo = open_repo_from_env()?;
222 repo.set_workdir(dir, false).map_err(Error::OpenRepo)?;
223 Ok(repo)
224}
225
226fn open_repo_from_env() -> Res<Repository> {
227 match Repository::open_from_env() {
228 Ok(repo) => Ok(repo),
229 Err(err) => Err(Error::OpenRepo(err)),
230 }
231}
232
233fn keys_to_events(keys: &[(KeyModifiers, KeyCode)]) -> Vec<Event> {
234 keys.iter()
235 .map(|(mods, key)| {
236 Event::Key(KeyEvent {
237 code: *key,
238 modifiers: *mods,
239 kind: event::KeyEventKind::Press,
240 state: KeyEventState::NONE,
241 })
242 })
243 .collect::<Vec<_>>()
244}