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
367
368
369
370
371
372
373
374
375
376
377
378
pub mod amend;
pub mod bug_report;
pub mod gc;
pub mod hide;
pub mod hooks;
pub mod init;
pub mod r#move;
pub mod navigation;
pub mod restack;
pub mod reword;
pub mod smartlog;
pub mod sync;
pub mod undo;
pub mod wrap;
use std::any::Any;
use std::convert::TryInto;
use std::ffi::OsString;
use std::path::PathBuf;
use std::time::SystemTime;
use clap::Parser;
use eyre::Context;
use itertools::Itertools;
use tracing_chrome::ChromeLayerBuilder;
use tracing_error::ErrorLayer;
use tracing_subscriber::fmt as tracing_fmt;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
use crate::opts::ColorSetting;
use crate::opts::Command;
use crate::opts::Opts;
use crate::opts::WrappedCommand;
use lib::core::config::env_vars::get_path_to_git;
use lib::core::effects::Effects;
use lib::core::formatting::Glyphs;
use lib::git::GitRunInfo;
use lib::git::NonZeroOid;
use self::reword::InitialCommitMessages;
use self::smartlog::SmartlogOptions;
fn rewrite_args(args: Vec<OsString>) -> Vec<OsString> {
let first_arg = match args.first() {
None => return args,
Some(first_arg) => first_arg,
};
let exe_path = PathBuf::from(first_arg);
let exe_name = match exe_path.file_name().and_then(|arg| arg.to_str()) {
Some(exe_name) => exe_name,
None => return args,
};
let exe_name = match exe_name.strip_suffix(std::env::consts::EXE_SUFFIX) {
Some(exe_name) => exe_name,
None => exe_name,
};
match exe_name.strip_prefix("git-branchless-") {
Some(subcommand) => {
let mut new_args = vec![OsString::from("git-branchless"), OsString::from(subcommand)];
new_args.extend(args.into_iter().skip(1));
new_args
}
None => args,
}
}
fn do_main_and_drop_locals() -> eyre::Result<i32> {
let _tracing_guard = install_tracing();
let args = rewrite_args(std::env::args_os().collect_vec());
let Opts {
working_directory,
command,
color,
} = Opts::parse_from(args);
if let Some(working_directory) = working_directory {
std::env::set_current_dir(&working_directory).wrap_err_with(|| {
format!(
"Could not set working directory to: {:?}",
&working_directory
)
})?;
}
let path_to_git = get_path_to_git().unwrap_or_else(|_| PathBuf::from("git"));
let path_to_git = PathBuf::from(&path_to_git);
let git_run_info = GitRunInfo {
path_to_git,
working_directory: std::env::current_dir()?,
env: std::env::vars_os().collect(),
};
let color = match color {
Some(ColorSetting::Always) => Glyphs::pretty(),
Some(ColorSetting::Never) => Glyphs::text(),
Some(ColorSetting::Auto) | None => Glyphs::detect(),
};
let effects = Effects::new(color);
let exit_code = match command {
Command::Amend { move_options } => amend::amend(&effects, &git_run_info, &move_options)?,
Command::BugReport => bug_report::bug_report(&effects, &git_run_info)?,
Command::Checkout { checkout_options } => {
navigation::checkout(&effects, &git_run_info, &checkout_options)?
}
Command::Gc | Command::HookPreAutoGc => {
gc::gc(&effects)?;
0
}
Command::Hide { commits, recursive } => hide::hide(&effects, commits, recursive)?,
Command::HookDetectEmptyCommit { old_commit_oid } => {
let old_commit_oid: NonZeroOid = old_commit_oid.parse()?;
hooks::hook_drop_commit_if_empty(&effects, old_commit_oid)?;
0
}
Command::HookPostCheckout {
previous_commit,
current_commit,
is_branch_checkout,
} => {
hooks::hook_post_checkout(
&effects,
&previous_commit,
¤t_commit,
is_branch_checkout,
)?;
0
}
Command::HookPostCommit => {
hooks::hook_post_commit(&effects)?;
0
}
Command::HookPostMerge { is_squash_merge } => {
hooks::hook_post_merge(&effects, is_squash_merge)?;
0
}
Command::HookPostRewrite { rewrite_type } => {
hooks::hook_post_rewrite(&effects, &git_run_info, &rewrite_type)?;
0
}
Command::HookReferenceTransaction { transaction_state } => {
hooks::hook_reference_transaction(&effects, &transaction_state)?;
0
}
Command::HookRegisterExtraPostRewriteHook => {
hooks::hook_register_extra_post_rewrite_hook()?;
0
}
Command::HookSkipUpstreamAppliedCommit { commit_oid } => {
let commit_oid: NonZeroOid = commit_oid.parse()?;
hooks::hook_skip_upstream_applied_commit(&effects, commit_oid)?;
0
}
Command::Init {
uninstall: false,
main_branch_name,
} => {
init::init(&effects, &git_run_info, main_branch_name.as_deref())?;
0
}
Command::Init {
uninstall: true,
main_branch_name: _,
} => {
init::uninstall(&effects)?;
0
}
Command::Move {
source,
dest,
base,
move_options,
} => r#move::r#move(&effects, &git_run_info, source, dest, base, &move_options)?,
Command::Next {
traverse_commits_options,
} => navigation::traverse_commits(
&effects,
&git_run_info,
navigation::Command::Next,
&traverse_commits_options,
)?,
Command::Prev {
traverse_commits_options,
} => navigation::traverse_commits(
&effects,
&git_run_info,
navigation::Command::Prev,
&traverse_commits_options,
)?,
Command::Restack {
commits,
move_options,
} => restack::restack(&effects, &git_run_info, commits, &move_options)?,
Command::Reword {
commits,
messages,
discard,
} => {
let messages = if discard {
InitialCommitMessages::Discard
} else {
InitialCommitMessages::Messages(messages)
};
reword::reword(&effects, commits, messages, &git_run_info)?
}
Command::Smartlog {
show_hidden_commits,
only_show_branches,
} => {
smartlog::smartlog(
&effects,
&git_run_info,
&SmartlogOptions {
show_hidden_commits,
only_show_branches,
},
)?;
0
}
Command::Sync {
update_refs,
force,
move_options,
commits,
} => sync::sync(
&effects,
&git_run_info,
update_refs,
force,
&move_options,
commits,
)?,
Command::Undo { interactive } => undo::undo(&effects, &git_run_info, interactive)?,
Command::Unhide { commits, recursive } => hide::unhide(&effects, commits, recursive)?,
Command::Wrap {
git_executable: explicit_git_executable,
command: WrappedCommand::WrappedCommand(args),
} => {
let git_run_info = match explicit_git_executable {
Some(path_to_git) => GitRunInfo {
path_to_git,
..git_run_info
},
None => git_run_info,
};
let exit_code = wrap::wrap(&git_run_info, args.as_slice())?;
exit_code
}
};
let exit_code: i32 = exit_code.try_into()?;
Ok(exit_code)
}
pub fn main() {
color_eyre::install().expect("Could not install panic handler");
let exit_code = do_main_and_drop_locals().expect("A fatal error occurred");
std::process::exit(exit_code)
}
#[must_use = "This function returns a guard object to flush traces. Dropping it immediately is probably incorrect. Make sure that the returned value lives until tracing has finished."]
fn install_tracing() -> eyre::Result<impl Drop> {
let (filter_layer, fmt_layer) = match EnvFilter::try_from_default_env() {
Ok(filter_layer) => {
let fmt_layer = tracing_fmt::layer()
.with_span_events(tracing_fmt::format::FmtSpan::CLOSE)
.with_target(false);
(Some(filter_layer), Some(fmt_layer))
}
Err(_) => {
(None, None)
}
};
let (profile_layer, flush_guard): (_, Box<dyn Any>) = {
const NESTING_LEVEL_KEY: &str = "RUST_LOGGING_NESTING_LEVEL";
let nesting_level = match std::env::var(NESTING_LEVEL_KEY) {
Ok(nesting_level) => nesting_level.parse::<usize>().unwrap_or_default(),
Err(_) => 0,
};
std::env::set_var(NESTING_LEVEL_KEY, (nesting_level + 1).to_string());
let should_include_function_args = match std::env::var("RUST_PROFILE_INCLUDE_ARGS") {
Ok(value) if !value.is_empty() => true,
Ok(_) | Err(_) => false,
};
let filename = match std::env::var("RUST_PROFILE") {
Ok(value) if value == "1" || value == "true" => {
let filename = format!(
"trace-{}.json-{}",
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs(),
nesting_level,
);
Some(filename)
}
Ok(value) if !value.is_empty() => Some(format!("{}-{}", value, nesting_level)),
Ok(_) | Err(_) => None,
};
match filename {
Some(filename) => {
let (layer, flush_guard) = ChromeLayerBuilder::new()
.file(filename)
.include_args(should_include_function_args)
.build();
(Some(layer), Box::new(flush_guard))
}
None => {
struct TrivialDrop;
(None, Box::new(TrivialDrop))
}
}
};
tracing_subscriber::registry()
.with(ErrorLayer::default())
.with(filter_layer)
.with(fmt_layer)
.with(profile_layer)
.try_init()?;
Ok(flush_guard)
}